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
lib/rand/vendor/ocaml-derive/src/lib.rs
Et7f3/randoml
88b15e5493bf0fb8f82a36f8069c4b803c52e311
#![allow(clippy::manual_map)] extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; mod derive; fn check_func(item_fn: &mut syn::ItemFn) { if item_fn.sig.asyncness.is_some() { panic!("OCaml functions cannot be async"); } if item_fn.sig.variadic.is_some() { panic!("OCaml...
#![allow(clippy::manual_map)] extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; mod derive; fn check_func(item_fn: &mut syn::ItemFn) { if item_fn.sig.asyncness.is_some() { panic!("OCaml functions cannot be async"); } if item_fn.sig.variadic.is_some() { panic!("OCaml...
#[proc_macro_attribute] pub fn ocaml_func(attribute: TokenStream, item: TokenStream) -> TokenStream { let mut item_fn: syn::ItemFn = syn::parse(item).unwrap(); check_func(&mut item_fn); let name = &item_fn.sig.ident; let unsafety = &item_fn.sig.unsafety; let constness = &item_fn.sig.constness; ...
y::Public(_) => (), _ => panic!("OCaml functions must be public"), } if !item_fn.sig.generics.params.is_empty() { panic!("OCaml functions may not contain generics") } item_fn.sig.abi = Some(syn::Abi { extern_token: syn::token::Extern::default(), name: Some(syn::LitStr::...
function_block-function_prefixed
[ { "content": "#[ocaml::func]\n\npub fn rand_bytes(buf: &mut [u8]) {\n\n OsRng.fill_bytes(buf);\n\n}\n\n\n", "file_path": "lib/rand/src/lib.rs", "rank": 0, "score": 32047.693563243232 }, { "content": "#[ocaml::func]\n\npub fn rand_int32() -> i32 {\n\n OsRng.next_u32() as i32\n\n}\n\n\n"...
Rust
examples/lisp.rs
42triangles/combinedfun
adbe66011e0b3813bdad91247de89de1c49d8d9d
use std::fmt; use std::io::prelude::*; use std::convert::{TryFrom, TryInto}; use combinedfun as cf; use cf::types::VerboseError; use cf::str_parsers as sp; #[derive(Clone, Debug)] pub enum Value { Str(String), Int(i32), Float(f32), List(Vec<Value>), } impl fmt::Display for Value { fn fmt(&self, f...
use std::fmt; use std::io::prelude::*; use std::convert::{TryFrom, TryInto}; use combinedfun as cf; use cf::types::VerboseError; use cf::str_parsers as sp; #[derive(Clone, Debug)] pub enum Value { Str(String), Int(i32), Float(f32), List(Vec<Value>), } impl fmt::Display for Value { fn fmt(&self, f...
r(LispError::WrongArgCountQuote(elements.clone())) }, s => Err(LispError::UndefinedFunction(s.to_owned())), }, ref x => Err(LispError::ExpectedCommand(x.clone())), } } else { Err(LispError...
Ok(()) }, } } } type ParserInput<'a> = cf::Span<&'a str, cf::Pos>; pub type ParserError<'a> = VerboseError<'a, ParserInput<'a>, (), str>; type ParserResult<'a, Out> = Result<(ParserInput<'a>, Out), ParserError<'a>>; fn parse_partial(i: ParserInput) -> ParserResult<Value> { f...
random
[ { "content": "/// Outputs the result of the given parser without consuming it.\n\npub fn lookahead<I, F>(f: Parser<F, I>) -> parser!(<I, F::Output, F::Error>)\n\nwhere F: ParserImpl<I>, I: Clone {\n\n Parser::new(move |inp: I| {\n\n let left = inp.clone();\n\n f.0.apply(inp).map(|(_, out)| (lef...
Rust
paddlers-shared-lib/src/game_mechanics/town/defence.rs
jakmeier/paddlers-browser-game
6c7afbb1ac13467ed94c418a5515fcf98224149e
use super::town_layout::ITownLayout; use super::{TOWN_RESTING_X, TOWN_X}; use crate::shared_types::*; pub trait IAttackingHobo { fn max_hp(&self) -> u32; fn speed(&self) -> f32; fn hurried(&self) -> bool; fn start_of_fight(&self) -> Option<Timestamp>; fn released(&self) -> Option<Timestamp>;...
use super::town_layout::ITownLayout; use super::{TOWN_RESTING_X, TOWN_X}; use crate::shared_types::*; pub trait IAttackingHobo { fn max_hp(&self) -> u32; fn speed(&self) -> f32; fn hurried(&self) -> bool; fn start_of_fight(&self) -> Option<Timestamp>; fn released(&self) -> Option<Timestamp>;...
resting } }) } }
ce<HOBO: IAttackingHobo>(&self, attacker: &HOBO) -> Option<Timestamp> { if attacker.start_of_fight().is_none() { return None; } attacker.released().map(|released| { let f = self.path_to_rest_place().len() as f32 / attacker.speed(); let t = Timestamp::from_floa...
function_block-random_span
[]
Rust
src/lib.rs
Kerollmops/futures-stream-batch
62a6b8beab86755b1640f5fb812f769b8122d15d
use core::mem; use core::pin::Pin; use futures::stream::{Fuse, FusedStream, Stream}; use futures::task::{Context, Poll}; use futures::{StreamExt, FutureExt}; use futures::future::OptionFuture; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::time::Duration; use futures_timer::Delay; impl<T: ?Sized> ChunksT...
use core::mem; use core::pin::Pin; use futures::stream::{Fuse, FusedStream, Stream}; use futures::task::{Context, Poll}; use futures::{StreamExt, FutureExt}; use futures::future::OptionFuture; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::time::Duration; use futures_timer::Delay; impl<T: ?Sized> ChunksT...
} #[derive(Debug)] #[must_use = "streams do nothing unless polled"] pub struct ChunksTimeout<St: Stream> { stream: Fuse<St>, items: Vec<St::Item>, cap: usize, clock: OptionFuture<Delay>, duration: Duration, } impl<St: Unpin + Stream> Unpin for ChunksTimeout<St> {} impl<St: Stream> ChunksTim...
fn chunks_timeout(self, capacity: usize, duration: Duration) -> ChunksTimeout<Self> where Self: Sized, { ChunksTimeout::new(self, capacity, duration) }
function_block-full_function
[ { "content": "# tokio-batch\n\n\n\nAn adaptor that chunks up elements and flushes them after a timeout or when the buffer is full.\n\n\n\n## Description\n\n\n\nAn adaptor that chunks up elements in a vector.\n\n\n\nThis adaptor will buffer up a list of items in the stream and pass on the\n\nvector used for buff...
Rust
src/commands/view.rs
brian-dawn/jot
411acce3d7dd7c72954adf162d59fc3a15fb0184
use crate::config::Config; use crate::constants::*; use crate::jot::{stream_jots, Jot, MessageType}; use anyhow::Result; use colorful::Colorful; use regex::Regex; use std::collections::HashSet; fn search_string_to_regex(search: &str) -> String { search .to_ascii_lowercase() .chars() ....
use crate::config::Config; use crate::constants::*; use crate::jot::{stream_jots, Jot, MessageType}; use anyhow::Result; use colorful::Colorful; use regex::Regex; use std::collections::HashSet; fn search_string_to_regex(search: &str) -> String { search .to_ascii_lowercase() .chars() ....
} else { for re in greps { let found = re .find_iter(&formatted_msg) .collect::<Vec<_>>() .into_iter() .rev(); for m in fo...
) .map(|m| m.collect::<HashSet<&str>>()) .unwrap_or_default(); if !(tags.is_empty() || tags.iter().all(|tag| jot.tags.contains(*tag))) { continue; } let greps = sub_matches .values_of("GREP") .map(|m| {...
random
[ { "content": "pub fn delete_jot(config: Config, note_id_to_delete: &str) -> Result<()> {\n\n // If the user passed in a number we're checking the count (id) not the uuid.\n\n let maybe_check_id = note_id_to_delete.parse::<usize>().ok();\n\n let uuid = Some(note_id_to_delete.to_string());\n\n\n\n // ...
Rust
yongnuo-osc-server/src/server.rs
jstarpl/yongnuo-osc-btle-bridge
93c9cf28cfd88f3a2aa71c426596455bcdcfc80d
use num_traits::ToPrimitive; use rosc::decoder::decode as osc_decode; use rosc::{OscBundle, OscMessage, OscPacket, OscType}; use std::net::{SocketAddr, UdpSocket}; use std::str::FromStr; use std::sync::Mutex; use std::sync::{Arc, Condvar}; use std::thread; use std::time::Duration; use btleplug::api::{BDAddr, Central, ...
use num_traits::ToPrimitive; use rosc::decoder::decode as osc_decode; use rosc::{OscBundle, OscMessage, OscPacket, OscType}; use std::net::{SocketAddr, UdpSocket}; use std::str::FromStr; use std::sync::Mutex; use std::sync::{Arc, Condvar}; use std::thread; use std::time::Duration; use btleplug::api::{BDAddr, Central, ...
fn handle_packet(packet: OscPacket, state: &mut LightState) -> StateModification { match packet { OscPacket::Message(osc_message) => handle_message(osc_message, state), OscPacket::Bundle(osc_bundle) => handle_bundle(osc_bundle, state), } } pub fn serve(port: u16, mac: &str) { let socket =...
OscBundle, state: &mut LightState) -> StateModification { bundle .content .into_iter() .map(|p| handle_packet(p, state)) .into_iter() .last() .unwrap_or(StateModification::None) }
function_block-function_prefixed
[ { "content": "#[cfg(any(target_os = \"windows\", target_os = \"macos\"))]\n\nfn get_central(manager: &Manager) -> Adapter {\n\n let adapters = manager.adapters().unwrap();\n\n adapters.into_iter().nth(0).unwrap()\n\n}\n\n\n", "file_path": "yongnuo-osc-server/src/discover.rs", "rank": 6, "score...
Rust
src/lib.rs
marinewater/polyline-rust
d4002c36b6ea7df670011724124dfb8ee96e5c7b
mod chunks; #[derive(PartialEq, Debug)] pub struct Point { pub latitude: f64, pub longitude: f64 } impl Point { pub fn new(latitude: f64, longitude: f64) -> Point { return Point { latitude, longitude }; } } pub fn encode(points: Vec<Point>, precision: u3...
mod chunks; #[derive(PartialEq, Debug)] pub struct Point { pub latitude: f64, pub longitude: f64 } impl Point { pub fn new(l
} pub fn encode(points: Vec<Point>, precision: u32) -> String { let mut encoded = String::new(); let mut latitude: f64 = 0.; let mut longitude: f64 = 0.; for point in points.iter() { let poly_latitude = encode_element(point.latitude-latitude, precision); encoded += poly_latitude.as_s...
atitude: f64, longitude: f64) -> Point { return Point { latitude, longitude }; }
function_block-function_prefixed
[ { "content": "use std::convert::TryFrom;\n\n\n\npub struct Chunks {\n\n chunks: Vec<u32>\n\n}\n\n\n\nimpl Chunks {\n\n pub fn new() -> Chunks {\n\n return Chunks {\n\n chunks: vec![]\n\n };\n\n }\n\n\n\n /// splices an integer into chunks\n\n pub fn parse(&mut self, eleme...
Rust
src/crawler.rs
ronin13/finde-rs
e7b00b1ec3fa4a299d070c5c561dfaaeadd6bb8f
use crate::constants::{CHAN_TIMEOUT_S, INDEX_HEAP_SIZE, INIT_THREADS}; use crate::haslen::HasLen; use crate::indexer; use crate::resource::Resource; use crate::scheduler; use anyhow::{anyhow, Context, Result}; use crossbeam::channel::select; use log::{debug, info, trace}; use crate::resource::Response; use crossbeam:...
use crate::constants::{CHAN_TIMEOUT_S, INDEX_HEAP_SIZE, INIT_THREADS}; use crate::haslen::HasLen; use crate::indexer; use crate::resource::Resource; use crate::scheduler; use anyhow::{anyhow, Context, Result}; use crossbeam::channel::select; use log::{debug, info, trace}; use crate::resource::Response; use crossbeam:...
fn run_indexer( index_dir: String, heap_size: usize, ) -> (thread::JoinHandle<Result<()>>, Sender<String>) { let (file_chan, index_chan): (Sender<String>, Receiver<String>) = unbounded(); ( thread::spawn(move || -> Result<()> { match indexer::build_i...
pub fn new( _resource: Box<dyn Resource<T>>, _initial_threads: Option<usize>, _max_threads: Option<usize>, _index_dir: String, _indexer_heap_size: Option<usize>, ) -> Crawler<T> { let (_crawler_chan, _processor_chan): (Sender<T>, Receiver<T>) = unbounded(); le...
function_block-full_function
[ { "content": "pub trait Resource<T: FromStr + Send + Sync>: Send + Sync {\n\n fn get_dirs_and_leaves(&self, path: &T) -> Response<T>;\n\n fn get_path(&self) -> Result<T>;\n\n}\n\n\n\n// trait alias not stable yet!\n\n// trait StringyTVar = FromStr + Send + Sync + std::fmt::Debug;\n", "file_path": "src...
Rust
kimchi/src/tests/framework.rs
chee-chyuan/proof-systems
b883501b06375da79fc9965c1c17e02a72e9ded7
use crate::circuits::lookup::runtime_tables::{RuntimeTable, RuntimeTableCfg}; use crate::circuits::lookup::tables::LookupTable; use crate::circuits::{gate::CircuitGate, wires::COLUMNS}; use crate::proof::ProverProof; use crate::prover_index::testing::new_index_for_test_with_lookups; use crate::prover_index::ProverInd...
use crate::circuits::lookup::runtime_tables::{RuntimeTable, RuntimeTableCfg}; use crate::circuits::lookup::tables::LookupTable; use crate::circuits::{gate::CircuitGate, wires::COLUMNS}; use crate::proof::ProverProof; use crate::prover_index::testing::new_index_for_test_with_lookups; use crate::prover_index::ProverInd...
up_map, &self.0.verifier_index.unwrap(), &proof, ) .unwrap(); println!("- time to verify: {}ms", start.elapsed().as_millis()); } } pub fn print_witness<F>(cols: &[Vec<F>; COLUMNS], start_row: usize, end_row: usize) where F: PrimeField, { let rows = cols[0].le...
self } #[must_use] pub(crate) fn setup(mut self) -> TestRunner { let start = Instant::now(); let lookup_tables = mem::replace(&mut self.lookup_tables, vec![]); let runtime_tables_setup = mem::replace(&mut self.runtime_tables_setup, None); let index = new_index...
random
[ { "content": "/// generates a vector of `length` field elements\n\nfn rand_fields(rng: &mut impl Rng, length: u8) -> Vec<Fp> {\n\n let mut fields = vec![];\n\n for _ in 0..length {\n\n let fe = Fp::rand(rng);\n\n fields.push(fe)\n\n }\n\n fields\n\n}\n\n\n", "file_path": "oracle/ex...
Rust
src/commands.rs
Phraeyll/point-mass-ballistics-cli
20f383843e8507e3a0fb9a6ba63966d2c815bc75
use crate::{ args::{Args, SimulationKind}, printer::print_table, }; use std::{error::Error, file, line, ops::DerefMut, stringify, time::Instant}; use point_mass_ballistics::{ output::Measurements, projectiles::{self as bc, Projectile, ProjectileImpl}, simulation::{Simulation, SimulationBuilder}, ...
use crate::{ args::{Args, SimulationKind}, printer::print_table, }; use std::{error::Error, file, line, ops::DerefMut, stringify, time::Instant}; use point_mass_ballistics::{ output::Measurements, projectiles::{self as bc, Projectile, ProjectileImpl}, simulation::{Simulation, SimulationBuilder}, ...
} Ok(builder.init()) } }
(ref params) => params.run::<bc::G8>(), Self::GI(ref params) => params.run::<bc::GI>(), Self::GS(ref params) => params.run::<bc::GS>(), } } } impl Args { pub fn run<T>(&self) -> Result<(), Box<dyn Error>> where T: Projectile + From<ProjectileImpl> + DerefMut<Target =...
random
[ { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let cmd = SimulationKind::from_args();\n\n cmd.run()?;\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 0, "score": 58197.53884264095 }, { "content": "pub fn print_table<I>(table: I, output_tolerance: Length, pretty:...
Rust
src/devices/docker_provider.rs
tagantroy/marathon-benchmark
bd188315520da50d6eff45371c6e544b2432be88
use crate::devices::provider::Provider; use async_trait::async_trait; use port_scanner::request_open_port; use std::collections::HashMap; use std::io::{Error, ErrorKind}; use std::process::Stdio; use std::time::Duration; use tokio::process::Command; pub struct DockerProvider { image: String, tag: String, n...
use crate::devices::provider::Provider; use async_trait::async_trait; use port_scanner::request_open_port; use std::collections::HashMap; use std::io::{Error, ErrorKind}; use std::process::Stdio; use std::time::Duration; use tokio::process::Command; pub struct DockerProvider { image: String, tag: String, n...
} async fn stop_containers(&self) -> Result<(), Box<dyn std::error::Error>> { let ids: Vec<String> = self .running_containers .values() .map(|c| &c.id) .map(|id| short_docker_id(id)) .collect(); Command::new("docker") .arg...
if stdout.contains(&expected) { Ok(()) } else { Err(Box::new(Error::new( ErrorKind::ConnectionRefused, "Cannot connect to device", ))) }
if_condition
[ { "content": "fn wait_for_devices(expected: u32) {\n\n let host = mozdevice::Host::default();\n\n let mut devices: Vec<DeviceInfo> = host.devices().expect(\"Cannot get all devices\");\n\n while devices.len() < expected as usize {\n\n devices = host.devices().expect(\"Cannot get all devices\");\n...
Rust
day_2_corruption_checksum/rust/corruption_checksum/src/lib.rs
cjschneider2/advent_of_code_2017
db7907ecb7df22a1173ec4162676a71f4e5d45e8
pub fn row_difference(input: &str) -> u32 /* row difference */ { let digits: Vec<u32> = input.split_whitespace() .map(|s| s.parse::<u32>().unwrap()) .collect(); let mut max = 0; let mut min = std::u32::MAX; for digit in digits { if ...
pub fn row_difference(input: &str) -> u32 /* row difference */ { let digits: Vec<u32> = input.split_whitespace() .map(|s| s.parse::<u32>().unwrap()) .collect(); let mut max = 0; let mut min = std::u32::MAX; for digit in digits { if ...
pub fn row_division(input: &str) -> u32 /* row div */ { let digits: Vec<u32> = input.split_whitespace() .map(|s| s.parse::<u32>().unwrap()) .collect(); for (idx, digit) in digits.iter().enumerate() { for (idy, d) in digits.iter().enumerat...
pub fn checksum_matrix(input: &str) -> u32 /* matrix checksum */ { let checksum: u32 = input.split("\n") .fold(0, |acc, row| { acc + row_difference(row) }); checksum }
function_block-full_function
[ { "content": "pub fn inverse_captcha(input: &str) -> u32 {\n\n let digits: Vec<u32> = input.chars().map(|c| c.to_digit(10).unwrap() ).collect();\n\n let first: u32 = *(digits.first().unwrap());\n\n let mut sum = 0;\n\n let mut iter = digits.iter().peekable();\n\n while let Some(digit) = iter.next...
Rust
src/filesystem.rs
vladimyr/fcp
5e6dd145aff2abf8d879fa5475387c20df495f42
use nix::sys::stat::Mode; use nix::unistd; use std::convert::TryInto; use std::error::Error as BaseError; use std::fmt; use std::fs::{self, DirBuilder, File, Metadata, OpenOptions, Permissions, ReadDir}; use std::os::unix::fs::{self as unix, DirBuilderExt, FileTypeExt, OpenOptionsExt, PermissionsExt}; use std::path::...
use nix::sys::stat::Mode; use nix::unistd; use std::convert::TryInto; use std::error::Error as BaseError; use std::fmt; use std::fs::{self, DirBuilder, File, Metadata, OpenOptions, Permissions, ReadDir}; use std::os::unix::fs::{self as unix, DirBuilderExt, FileTypeExt, OpenOptionsExt, PermissionsExt}; use std::path::...
pub fn mkfifo<P: AsRef<Path>>(path: P, permissions: Permissions) -> Result<(), Error> { let path = path.as_ref(); let mode = Mode::from_bits_truncate(permissions.mode().try_into()?); unistd::mkfifo(path, mode).map_err(make_error_message!(path)) } #[derive(Debug)] pub enum FileType { Regular, Dire...
pub fn create<P: AsRef<Path>>(path: P, mode: u32) -> Result<File, Error> { let path = path.as_ref(); OpenOptions::new() .mode(mode) .truncate(true) .write(true) .create(true) .open(path) .map_err(make_error_message!(path)) }
function_block-full_function
[ { "content": "fn copy_directory(source: (&Path, Metadata), dest: &Path) -> Result<bool, Error> {\n\n let (source, metadata) = source;\n\n fs::create_dir(dest, metadata.permissions().mode())?;\n\n Ok(fs::read_dir(source)?\n\n .collect::<Box<_>>()\n\n .into_par_iter()\n\n .map(|entry...
Rust
src/solvers/mod.rs
jonasolovolsson/lp-solvers
4e9d37b928acf5ce5d276004568afa195d45111b
use std::collections::HashMap; use std::ffi::OsString; use std::fs::File; use std::marker::PhantomData; use std::path::{Path, PathBuf}; use std::process::Command; use crate::lp_format::LpProblem; pub use self::auto::*; pub use self::cbc::*; #[cfg(feature = "cplex")] pub use self::cplex::*; pub use self::glpk::*; pu...
use std::collections::HashMap; use std::ffi::OsString; use std::fs::File; use std::marker::PhantomData; use std::path::{Path, PathBuf}; use std::process::Command; use crate::lp_format::LpProblem; pub use self::auto::*; pub use self::cbc::*; #[cfg(feature = "cplex")] pub use self::cplex::*; pub use self::glpk::*; pu...
} pub trait WithMaxSeconds<T> { fn max_seconds(&self) -> Option<u32>; fn with_max_seconds(&self, seconds: u32) -> T; } pub trait WithNbThreads<T> { fn nb_threads(&self) -> Option<u32>; fn with_nb_threads(&self, threads: u32) -> T; } #[derive(Default, Copy, Clone)] pub struct Stat...
fn run<'a, P: LpProblem<'a>>(&self, problem: &'a P) -> Result<Solution, String> { let command_name = self.command_name(); let file_model = problem .to_tmp_file() .map_err(|e| format!("Unable to create {} problem file: {}", command_name, e))?; let temp_solution_file = if ...
function_block-full_function
[ { "content": "fn sol_file(file: &str) -> PathBuf {\n\n PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"tests\")\n\n .join(\"solution_files\")\n\n .join(file)\n\n}\n\n\n", "file_path": "tests/solvers.rs", "rank": 0, "score": 132935.86002717246 }, { "content": "...
Rust
src/read.rs
zeroeightysix/ozelot
22d5bdc5bfbdb73d92838174ac062d45c23bceb1
use errors::{Result, ResultExt}; use std::io::Read; use byteorder::{BigEndian, ReadBytesExt}; pub fn read_bool<R: Read>(reader: &mut R) -> Result<bool> { let byte = read_u8(reader)?; match byte { 0 => Ok(false), 1 => Ok(true), _ => bail!("Bool had invalid value {}", byte), } } /...
use errors::{Result, ResultExt}; use std::io::Read; use byteorder::{BigEndian, ReadBytesExt}; pub fn read_bool<R: Read>(reader: &mut R) -> Result<bool> { let byte = read_u8(reader)?; match byte { 0 => Ok(false), 1 => Ok(true), _ => bail!("Bool had invalid value {}", byte), } } /...
pub fn read_prefixed_bytearray<R: Read>(reader: &mut R) -> Result<Vec<u8>> { let length = read_varint(reader)?; let mut tmp = vec![0; length as usize]; reader.read_exact(&mut tmp)?; Ok(tmp) } pub fn read_prefixed_varintarray<R: Read>(reader: &mut R) -> Result<Vec<i32>> { let length = read_varint(...
4> { let mut result = 0; let msb: u8 = 0b10000000; let mask: u8 = !msb; for i in 0..10 { let read = reader.read_u8()?; result |= ((read & mask) as i64) << (7 * i); /* The last (10th) byte is only allowed to have the LSB set */ if i == 9 && ((read & (!0x1)) != 0) { ...
function_block-function_prefixed
[ { "content": "fn chat_to_str_parse_json(json: &Value, ret: &mut String) {\n\n match json.get(\"text\") {\n\n Some(&Value::String(ref x)) => ret.push_str(x),\n\n _ => (),\n\n }\n\n\n\n match json.get(\"extra\") {\n\n Some(&Value::Array(ref x)) => {\n\n for object in x {\n...
Rust
layout-engine/src/layout.rs
Oanakiaja/layout-engine-toy
52053c1408c19365f3c4b26200131d8b933ff919
use crate::css::{Unit, Value}; use crate::style::{Display, StyledNode}; #[derive(Default, Debug, Clone, Copy)] pub struct Dimensions { pub content: Rect, pub padding: EdgeSizes, pub border: EdgeSizes, pub margin: EdgeSizes, } #[derive(Default, Debug, Copy, Clone)] pub struct Rect { pub x: f32, ...
use crate::css::{Unit, Value}; use crate::style::{Display, StyledNode}; #[derive(Default, Debug, Clone, Copy)] pub struct Dimensions { pub content: Rect, pub padding: EdgeSizes, pub border: EdgeSizes, pub margin: EdgeSizes, } #[derive(Default, Debug, Copy, Clone)] pub struct Rect { pub x: f32, ...
fn layout_block_children(&mut self) { let d = &mut self.dimensions; for child in &mut self.children { child.layout(*d); d.content.height = d.content.height + child.dimensions.margin_box().height; } } fn calculate_block_height(&mut self) { if let Some...
fn calculate_block_position(&mut self, containing_block: Dimensions) { let style = self.get_style_node(); let d = &mut self.dimensions; let zero = Value::Length(0.0, Unit::Px); d.margin.top = style.lookup("margin-top", "margin", &zero).to_px(); d.margin.bottom = style.lookup("ma...
function_block-full_function
[ { "content": "pub fn element(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {\n\n Node {\n\n children: children,\n\n node_type: NodeType::Element(ElementData {\n\n tag_name: name,\n\n attributes: attrs,\n\n }),\n\n }\n\n}\n", "file_path": "layout-...
Rust
src/opcodes.rs
osmon-lang/bulut
53a68622bd63fd2c8456aff929575f6fbd06ecb6
use colored; use self::colored::Colorize; #[derive(Clone)] pub enum Instruction { LoadString(usize, String), LoadBool(usize, bool), LoadInt(usize, i32), LoadLong(usize, i64), LoadFloat(usize, f32), LoadDouble(usize, f...
use colored; use self::colored::Colorize; #[derive(Clone)] pub enum Instruction { LoadString(usize, String), LoadBool(usize, bool), LoadInt(usize, i32), LoadLong(usize, i64), LoadFloat(usize, f32), LoadDouble(usize, f...
} #[derive(Clone, Debug)] pub struct CodeBlock { pub code: Vec<Instruction>, pub ip: usize, } impl CodeBlock { pub fn new(ins: Vec<Instruction>) -> CodeBlock { CodeBlock { code: ins, ip: 0 } } }
fn toString(&self) -> String { let mut str = String::new(); for i in 0..self.len() { str.push_str(&format!("{:04} {}", i, format!("{}", self[i]).white())); str.push('\n'); } str }
function_block-full_function
[]
Rust
mark/src/tree.rs
dj2/Archive
dcece02a3764454b732d3f3ba2e3a022deb218b2
use std::fmt; #[derive(Debug)] pub struct Doc<'a> { blocks: Vec<Block<'a>>, } impl<'a> Doc<'a> { pub fn new(blocks: Vec<Block<'a>>) -> Self { Self { blocks } } } impl<'a> fmt::Display for Doc<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for idx in 0..self.blocks.l...
use std::fmt; #[derive(Debug)] pub struct Doc<'a> { blocks: Vec<Block<'a>>, } impl<'a> Doc<'a> { pub fn new(blocks: Vec<Block<'a>>) -> Self { Self { blocks } } } impl<'a> fmt::Display for Doc<'a> {
} #[derive(Copy, Clone, Debug, PartialEq)] pub enum Marker { Bullet, Dash, Plus, UpperAlpha, LowerAlpha, UpperRoman, LowerRoman, Numeric, } #[derive(Debug, PartialEq)] pub enum Block<'a> { Blockquote(Vec<Block<'a>>), Code(Option<&'a str>, Vec<Block<'a>>), He...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for idx in 0..self.blocks.len() { write!(f, "{}", self.blocks[idx].to_string())?; } Ok(()) }
function_block-full_function
[ { "content": "#[test]\n\npub fn list() {\n\n compare(\"data/list\")\n\n}\n\n\n", "file_path": "mark/tests/fixtures/mod.rs", "rank": 0, "score": 115371.05257245473 }, { "content": "#[test]\n\npub fn code() {\n\n compare(\"data/code\")\n\n}\n", "file_path": "mark/tests/fixtures/mod.r...
Rust
radiance/src/math/transform.rs
dontpanic92/radiance
bcc1a4f9a5f4a9eab06f518d5284b46ed920de5b
use super::mat::Mat44; use super::{vec::Vec3, Quaternion}; use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Transform { mat: Mat44, } impl Transform { const EPS: f32 = 0.0001; pub fn new() -> Self { Self { mat: Mat44::new_identity(), } ...
use super::mat::Mat44; use super::{vec::Vec3, Quaternion}; use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Transform { mat: Mat44, } impl Transform { const EPS: f32 = 0.0001; pub fn new() -> Self { Self { mat: Mat44::new_identity(), } ...
fn rotate_axis_angle_impl(&mut self, axis: &Vec3, radian: f32, local: bool) -> &mut Self { /* * http://en.wikipedia.org/wiki/Rotation_matrix * * c = cos(theta), s = sin(theta), v = (x, y, z), where x^2+y^2+z^2=0 * M(v, theta) = [c+(1-c)x^2 (1-c)xy-sz (1-c)xz+sy] ...
fn translate_impl(&mut self, vec: &Vec3, local: bool) -> &mut Self { let mut tm = Mat44::new_identity(); tm[0][3] = vec.x; tm[1][3] = vec.y; tm[2][3] = vec.z; self.apply(&tm, local) }
function_block-full_function
[ { "content": "#[cfg(target_os = \"windows\")]\n\npub fn instance_extension_names() -> Vec<*const i8> {\n\n vec![\n\n ash::extensions::khr::Surface::name().as_ptr(),\n\n ash::extensions::khr::Win32Surface::name().as_ptr(),\n\n ash::extensions::ext::DebugReport::name().as_ptr(),\n\n ...
Rust
src/bin/server.rs
Ryan-Git/sagittarius
4ed296e59d6a21ab9eef2ffd73e68d43c67b30f8
use std::env; use std::future::Future; use std::net::SocketAddr; use log::{debug, error, info, trace}; use lru::LruCache; use once_cell::sync::Lazy; use rand::distributions::{Distribution, Uniform}; use rand::prelude::*; use tokio::io::AsyncReadExt; use tokio::net::{lookup_host, TcpListener, TcpStream, ToSocketAddrs};...
use std::env; use std::future::Future; use std::net::SocketAddr; use log::{debug, error, info, trace}; use lru::LruCache; use once_cell::sync::Lazy; use rand::distributions::{Distribution, Uniform}; use rand::prelude::*; use tokio::io::AsyncReadExt; use tokio::net::{lookup_host, TcpListener, TcpStream, ToSocketAddrs};...
exact(&mut buf)).await?; trace!("size: {}, header: {:?}", size, &buf); let host = String::from_utf8(buf)?; let port = self.inbound.read_u16().await?; self.target_addr = Some(format!("{}:{}", host, port)); let remote_ip = match self.addr_cache.get(self.target_addr.as_ref().unwra...
it } async fn read_address(&mut self) -> Result<(), anyhow::Error> { let size = random_wait_on_fail(self.inbound.read_u8()).await?; let mut buf = Vec::new(); buf.resize(size as usize, 0); random_wait_on_fail(self.inbound.read_
random
[ { "content": "pub fn init_log() {\n\n const DEFAULT_LOG_LEVEL: &str = \"debug\";\n\n\n\n env_logger::from_env(Env::default().default_filter_or(DEFAULT_LOG_LEVEL))\n\n .format(|buf, record| {\n\n writeln!(\n\n buf,\n\n \"[{} {:<5} {}:{}] {}\",\n\n ...
Rust
rust/mynewt/src/libs/sensor_network.rs
FWeissenb/pinetime-logo-loader
a2ff22cc17ff8305391d3cb9227df15f6817f116
/* automatically generated by rust-bindgen */ use super::*; pub const SENSOR_NETWORK_SIZE: u32 = 5; pub type __uint8_t = ::cty::c_uchar; pub type __uint16_t = ::cty::c_ushort; #[repr(C)] pub struct oc_server_handle { _unused: [u8; 0], } #[mynewt_macros::safe_wrap(attr)] extern "C" { pub fn init_sensor_post(se...
/* automatically generated by rust-bindgen */ use super::*; pub const SENSOR_NETWORK_SIZE: u32 = 5; pub type __uint8_t = ::cty::c_uchar; pub type __uint16_t = ::cty::c_ushort; #[repr(C)] pub struct oc_server_handle { _unused: [u8; 0], } #[mynewt_macros::safe_wrap(attr)] extern "C" { pub fn init_sensor_post(se...
ttr)] extern "C" { pub fn do_collector_post() -> bool; } #[mynewt_macros::safe_wrap(attr)] extern "C" { pub fn sensor_network_do_post(iface_type: u8) -> bool; } #[mynewt_macros::safe_wrap(attr)] extern "C" { pub fn is_collector_node() -> bool; } #[mynewt_macros::safe_wrap(attr)] extern "C" { pub fn is_s...
{ #[doc = ""] pub fn start_server_transport() -> ::cty::c_int; } #[mynewt_macros::safe_wrap(attr)] extern "C" { pub fn start_collector_transport() -> ::cty::c_int; } #[mynewt_macros::safe_wrap(attr)] extern "C" { pub fn sensor_network_start_transport(iface_type: u8) -> ::cty::c_int; } #[mynewt_macros::...
random
[ { "content": "/// Write \"length\" number of bytes from \"buffer\" to the output buffer in hex format.\n\npub fn dump(buffer: *const u8, len: u32) {\n\n unsafe { console_dump(buffer, len); }\n\n}\n\n\n", "file_path": "rust/mynewt/src/sys/console.rs", "rank": 0, "score": 365215.7375841767 }, ...
Rust
mmids-gstreamer/src/endpoints/gst_transcoder/mod.rs
AircastDev/mmids
c304d67d1498f7526e5186d315f07986aade1984
mod transcoding_manager; use crate::encoders::EncoderFactory; use crate::endpoints::gst_transcoder::endpoint_futures::notify_manager_gone; use crate::endpoints::gst_transcoder::transcoding_manager::{ start_transcode_manager, TranscodeManagerRequest, TranscoderParams, }; use crate::GSTREAMER_INIT_RESULT; use future...
mod transcoding_manager; use crate::encoders::EncoderFactory; use crate::endpoints::gst_transcoder::endpoint_futures::notify_manager_gone; use crate::endpoints::gst_transcoder::transcoding_manager::{ start_transcode_manager, TranscodeManagerRequest, TranscoderParams, }; use crate::GSTREAMER_INIT_RESULT; use future...
let (outbound_media_sender, outbound_media_receiver) = unbounded_channel(); let pipeline_name = format!("transcode_pipeline_{}", id); let pipeline = Pipeline::new(Some(pipeline_name.as_str())); let video_encoder = self.encoder_factory.get_video_encoder( video_encoder_name...
if self.active_transcodes.contains_key(&id) { warn!( "Transcoding requested with id {}, but that id is already active", id ); let _ = notification_channel.send(GstTranscoderNotification::TranscodingStopped( GstTranscoderStoppedCause::Id...
if_condition
[ { "content": "fn stop_process(id: Uuid, mut process: FfmpegProcess) {\n\n info!(id = ?id, \"Killing ffmpeg process {}\", id);\n\n let _ = process.handle.kill();\n\n\n\n let _ = process\n\n .notification_channel\n\n .send(FfmpegEndpointNotification::FfmpegStopped);\n\n}\n\n\n\nasync fn wai...
Rust
kernel-rs/src/arch/arm/trap.rs
reverofx/rv6
52184515dfd02ff8a7242424ab68d1f827277de3
use core::{fmt, mem}; use cortex_a::registers::*; use tock_registers::interfaces::{Readable, Writeable}; use crate::{ addr::PGSIZE, arch::interface::{MemLayout, TrapManager}, arch::{ asm::{intr_get, intr_off, intr_on, r_fpsr, w_fpsr}, intr::INTERRUPT_CONTROLLER, memlayout::TIMER0...
use core::{fmt, mem}; use cortex_a::registers::*; use tock_registers::interfaces::{Readable, Writeable}; use crate::{ addr::PGSIZE, arch::interface::{MemLayout, TrapManager}, arch::{ asm::{intr_get, intr_off, intr_on, r_fpsr, w_fpsr}, intr::INTERRUPT_CONTROLLER, memlayout::TIMER0...
} } extern "C" { static mut trampoline: [u8; 0]; static mut userret: [u8; 0]; fn vectors(); } impl From<&IrqTypes> for IrqNum { fn from(item: &IrqTypes) -> Self { match item { IrqTypes::Uart => Armv8::UART0_IRQ, IrqTypes::Virtio => Armv8::VIRTIO0_IRQ, ...
match n { 0 => Self::SyncException, 1 => Self::IRQ, 2 => Self::FIQ, 3 => Self::SError, _ => panic!("invalud exception code"), }
if_condition
[ { "content": "pub fn r_fpsr() -> usize {\n\n let mut x;\n\n unsafe { asm! (\"mrs {x}, fpsr\", x = out(reg) x) };\n\n x\n\n}\n\n\n\n/// Write to Floating-point Status Register\n\n///\n\n/// # Safety\n\n///\n\n/// `x` must contain valid value for mdscr_el1 register.\n\npub unsafe fn w_fpsr(x: usize) {\n\...
Rust
src/simulator/mod.rs
stainless-steel/tempan
4de6baefcf8c2b0bc26c1c9d41bcfd58df2f2a9f
#![allow(non_snake_case)] use matrix::decomposition::SymmetricEigen; use matrix::format::{Compressed, Conventional}; use matrix::operation::{Multiply, MultiplyInto}; use matrix::{Matrix, Size}; use std::ops::{Deref, DerefMut}; use std::{mem, ptr}; use {Circuit, Config, Result}; #[cfg(test)] mod tests; pub struct Si...
#![allow(non_snake_case)] use matrix::decomposition::SymmetricEigen; use matrix::format::{Compressed, Conventional}; use matrix::operation::{Multiply, MultiplyInto}; use matrix::{Matrix, Size}; use std::ops::{Deref, DerefMut}; use std::{mem, ptr}; use {Circuit, Config, Result}; #[cfg(test)] mod tests; pub struct Si...
pub fn config(&self) -> &Config { &self.config } } impl State { fn new(nodes: usize) -> State { State(vec![0.0; 2 * nodes]) } fn next(&mut self, nodes: usize, steps: usize) { let buffer = &mut self.0; let current = buffer.len(); let required = (steps ...
4], Q: &mut [f64]) { let Config { ambience, .. } = self.config; let System { units, nodes, spots, ref C, ref E, ref F, ref mut S } = self.system; let steps = P.len() / units; debug_assert_eq!(P.len(), units * steps); debug_assert_eq!(Q.len(), spots * steps); S.next(nodes,...
function_block-function_prefixed
[ { "content": "pub fn setup(name: &str) -> Simulator {\n\n let circuit = HotSpot::new(find(&format!(\"{}.flp\", name)), find(\"hotspot.config\"));\n\n Simulator::new(circuit.unwrap(), Default::default()).unwrap()\n\n}\n\n\n", "file_path": "src/simulator/tests/hotspot/mod.rs", "rank": 2, "score"...
Rust
lib/value/src/value/target.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::collections::BTreeMap; use std::iter::Peekable; use lookup::{FieldBuf, LookupBuf, SegmentBuf}; use crate::Value; impl Value { ...
use std::collections::BTreeMap; use std::iter::Peekable; use lookup::{FieldBuf, LookupBuf, SegmentBuf}; use crate::Value; impl Value { ...
ed_rem_euclid(len) .and_then(move |i| array.get_mut(i as usize)) }), } } fn remove_by_segments<'a, T>( &mut self, mut segments: Peekable<T>, compact: bool, ) -> Option<Self> where T: Iterator<Item = &'a SegmentBuf> + Clone, { ...
t_mut() .and_then(|map| map.get_mut(name.as_str())), SegmentBuf::Coalesce(fields) => self.as_object_mut().and_then(|map| { fields .iter() .find(|field| map.contains_key(field.as_str())) .and_then(move |field| map.get...
function_block-random_span
[ { "content": "#[allow(clippy::needless_pass_by_value)] // impl Path is always a reference\n\npub fn remove<'a>(value: &mut Value, path: impl Path<'a>, prune: bool) -> Option<Value> {\n\n let path_iter = path.segment_iter().peekable();\n\n remove_rec(value, path_iter, prune).map(|(value, _)| value)\n\n}\n\...
Rust
src/s390x/eckd.rs
jldohmann/coreos-installer
76f7da8df668b2b605128405407a4b0b0d338335
use anyhow::{anyhow, bail, Context, Result}; use std::fs::{read_to_string, File}; use std::io::Write; use std::num::NonZeroU32; use std::os::unix::io::AsRawFd; use std::process::{Command, Stdio}; use crate::blockdev::{get_sector_size, udev_settle}; use crate::runcmd; use crate::s390x::dasd::{partitions_from_gpt_head...
use anyhow::{anyhow, bail, Context, Result}; use std::fs::{read_to_string, File}; use std::io::Write; use std::num::NonZeroU32; use std::os::unix::io::AsRawFd; use std::process::{Command, Stdio}; use crate::blockdev::{get_sector_size, udev_settle}; use crate::runcmd; use crate::s390x::dasd::{partitions_from_gpt_head...
fn bus_id(dasd: &str) -> Result<String> { let cmd = Command::new("lszdev") .arg("-n") .arg("-c") .arg("ID") .arg("--by-node") .arg(dasd) .stderr(Stdio::inherit()) .output() .with_context(|| format!("executing lszdev on {}", dasd))?; if !cmd.statu...
ing_lba * bytes_per_block, out_offset: start_track * blocks_per_track * bytes_per_block, length: blocks * bytes_per_block, }); let end_track = start_track + (blocks + blocks_per_track - 1) / blocks_per_track - 1; if idx == last { entries.push(format!("[{}, la...
function_block-function_prefixed
[ { "content": "/// Checks if underlying device is IBM DASD disk\n\npub fn is_dasd(device: &str, fd: Option<&mut File>) -> Result<bool> {\n\n let target =\n\n canonicalize(device).with_context(|| format!(\"getting absolute path to {}\", device))?;\n\n if target.to_string_lossy().starts_with(\"/dev/da...
Rust
src/chips/nrf51822/uart_old_2.rs
utkarshapets/tock
10e48d70a4ea6b4400a663a9ba8d228081d87609
use helpers::*; use core::mem; use hil::{uart, Controller}; use hil::uart::{Parity, Mode}; use nvic; use chip; #[repr(C, packed)] struct Registers { startrx: u32, stoprx: u32, starttx: u32, stoptx: u32, reserved0: [u32; 62], rxdrdy: u32, reserved1: [u32; 4], txdrdy: u32, error: ...
use helpers::*; use core::mem; use hil::{uart, Controller}; use hil::uart::{Parity, Mode}; use nvic; use chip; #[repr(C, packed)] struct Registers { startrx: u32, stoprx: u32, starttx: u32, stoptx: u32, reserved0: [u32; 62], rxdrdy: u32, reserved1: [u32; 4], txdrdy: u32, error: ...
(&mut regs.starttx, 1); } fn disable_tx(&mut self) { let regs : &mut Registers = unsafe { mem::transmute(self.regs) }; volatile_store(&mut regs.stoptx, 1); } } #[no_mangle] #[allow(non_snake_case)] pub unsafe extern fn UART0_Handler() { use common::Queue; nvic::disable(nvic::Nvic...
); } fn send_byte(&self, byte: u8) { while !self.tx_ready() {} let regs : &mut Registers = unsafe { mem::transmute(self.regs) }; volatile_store(&mut regs.txd, byte as u32); } fn send_bytes(&self, bytes: &'static mut [u8], len: usize) { unimplemented!(); } fn rx...
random
[ { "content": "pub fn generic_clock_enable(clock: GenericClock, \n\n source: ClockSource) {\n\n // Oscillator field is bits 12:9, bit 0 is enable\n\n let val = (source as u32) << 8 | 1;\n\n unsafe { match clock {\n\n GenericClock::GCLK0 => intrinsics::volatile_store(&m...
Rust
core/src/rpc.rs
HaoZeke/prest
eec6b34bde4e060f52a391662347918995ded245
use std; use std::io::{Read,Write,Stdout,Stdin,BufReader,BufWriter}; use std::result::Result; use std::fmt::Display; use codec::{self,Encode,Decode}; use estimation; use consistency; use simulation; use experiment_stats; use budgetary; #[derive(Debug)] pub enum ActionRequest { BudgetaryConsistency(budgetary::cons...
use std; use std::io::{Read,Write,Stdout,Stdin,BufReader,BufWriter}; use std::result::Result; use std::fmt::Display; use codec::{self,Encode,Decode}; use estimation; use consistency; use simulation; use experiment_stats; use budgetary; #[derive(Debug)] pub enum ActionRequest { BudgetaryConsistency(budgetary::cons...
From<E> for Error { fn from(e : E) -> Error { Error { error_message: format!("{}", e), error: codec::encode_to_memory(&e).unwrap(), } } } #[derive(Clone, Copy)] pub enum LogLevel { Debug, Info, Warning, Error, } impl Encode for LogLevel { fn encode<W...
Menus(Decode::decode(f)?)), "tuple-intrans-alts" => Ok(TupleIntransAlts(Decode::decode(f)?)), "estimation" => Ok(Estimation(Decode::decode(f)?)), "echo" => Ok(Echo(Decode::decode(f)?)), "crash" => Ok(Crash(Decode::decode(f)?)), "fail" => Ok(Fail(Decode::decode...
random
[ { "content": "pub fn decode_iterator<T : Decode, R : Read>(f : &mut R) -> Result<Vec<T>> {\n\n let mut result = Vec::new();\n\n while let Some(item) = Decode::decode(f)? {\n\n result.push(item);\n\n }\n\n Ok(result)\n\n}\n\n\n", "file_path": "core/src/codec.rs", "rank": 0, "score"...
Rust
src/main.rs
sandalbanditten/epoch-get
b169a1747f394e4fc0229d012ba462ed75f3a61e
use colored::Colorize; use std::{env, error}; use std::time::{SystemTime, UNIX_EPOCH}; enum Verbosity { Verbose, Quiet, } enum Mode { Seconds, Milliseconds, Microseconds, Nanoseconds, } enum Action { Help, Print, Version, } fn main() -> Result<(), Box<dyn error::Error>> { ...
use colored::Colorize; use std::{env, error}; use std::time::{SystemTime, UNIX_EPOCH}; enum Verbosity { Verbose, Quiet, } enum Mode { Seconds, Milliseconds, Microseconds, Nanoseconds, } enum Action { Help, Print, Version, } fn main() -> Result<(), Box<dyn error::Error>> { ...
fn print_help() { print_version(Verbosity::Verbose); println!(); println!("{}", "USAGE:".yellow()); println!(" epoch-get [OPTIONS]"); println!(); println!("{}", "OPTIONS:".yellow()); println!(" {}", "-h, --help".green()); println!(" Print this help menu."); println!(...
function_block-full_function
[ { "content": "# epoch-get\n\n\n\nA simple program to get the current time since the Unix Epoch.\n\n\n\n## Contributing\n\n\n\nI am new at rust programming, and somewhat new at programming in general, so all feedback and contribution is very welcome!\n\n\n\n## Version\n\n\n\nThis is version 0.4.1\n\n\n\n## Usage...
Rust
galaxy/main.rs
nwtnni/icfp-2020
0eeb7851cd70bdec9343d6a4257d7286275fa79f
use std::cmp; use std::env; use std::fmt::Write as _; use std::fs; use std::rc::Rc; use std::time; use minifb::Key; use minifb::KeyRepeat; use minifb::MouseButton; use minifb::MouseMode; use minifb::Window; use minifb::WindowOptions; use icfp::ast::Atom; use icfp::ast::AtomCache; use icfp::ast::Exp; const WIDTH: usi...
use std::cmp; use std::env; use std::fmt::Write as _; use std::fs; use std::rc::Rc; use std::time; use minifb::Key; use minifb::KeyRepeat; use minifb::MouseButton; use minifb::MouseMode; use minifb::Window; use minifb::WindowOptions; use icfp::ast::Atom; use icfp::ast::AtomCache; use icfp::ast::Exp; const WIDTH: usi...
?; } else { window.update(); } }; log::info!("[recv]: {}", &out_state); let _ = std::mem::replace(&mut state, out_state); } Ok(()) } fn redraw( window_buffer: &mut Vec<u32>, data_buffer: &[Vec<(i64, i64)>], current_x: i64, curren...
redraw( &mut window_buffer, &data_buffer, current_x, current_y, scale, filter, &mut window, )
call_expression
[ { "content": "fn demodulate_int<'v>(v: &'v str, cache: &mut AtomCache) -> (Rc<Exp>, &'v str) {\n\n let positive = &v[0..2] == \"01\";\n\n let index = v[2..]\n\n .find('0')\n\n .expect(\"Expected '0' in linear-encoded value\");\n\n let length = index * 4;\n\n let mut final_val = i64::fr...
Rust
src/lib.rs
akikoskinen/wide
56b76bff3eb7aba37c17cb74ea999a24faa8cf7e
#![warn(missing_docs)] #![cfg_attr(not(feature = "extern_crate_std"), no_std)] #![cfg_attr(feature = "toolchain_nightly", feature(stdsimd))] #![cfg_attr(feature = "toolchain_nightly", feature(core_intrinsics))] #![allow(clippy::replace_consts)] #![allow(clippy::inline_always)] #![allow(clippy::expl_impl_clone_on_copy)]...
#![warn(missing_docs)] #![cfg_attr(not(feature = "extern_crate_std"), no_std)] #![cfg_attr(feature = "toolchain_nightly", feature(stdsimd))] #![cfg_attr(feature = "toolchain_nightly", feature(core_intrinsics))] #![allow(clippy::replace_consts)] #![allow(clippy::inline_always)] #![allow(clippy::expl_impl_clone_on_copy)]...
#[inline(always)] #[must_use] pub fn tan_f32(x: f32) -> f32 { magic! { if #[cfg(target_feature = "sse")] { f32x4 { sse: m128::set0(x) }.tan().sse.extract0() } else { f32x4 { arr: [x, 0.0, 0.0, 0.0] }.tan().arr[0] } } }
4 { sse: m128::set0(x) }.cos().sse.extract0() } else { f32x4 { arr: [x, 0.0, 0.0, 0.0] }.cos().arr[0] } } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn m128i_round_f32() {\n\n let i: m128i = cast([-1, 23, 8, 6]);\n\n let out: [f32; 4] = cast(i.round_f32());\n\n assert_eq!(out, [-1.0_f32, 23.0, 8.0, 6.0]);\n\n}\n\n\n", "file_path": "tests/sse2.rs", "rank": 4, "score": 125182.39102974095 }, { "content": "#[inlin...
Rust
src/key_store/import_token.rs
ushkarev/rusty-kms
45fc974f5df65ddef86cb5ee6af28972ba909d0a
use std::convert::{TryFrom, TryInto}; use chrono::{DateTime, TimeZone, Utc}; use openssl::pkey::Private; use openssl::rsa::{Rsa, Padding}; use crate::misc::days_from_now; use crate::key_store::errors::*; lazy_static! { static ref IMPORT_KEY: Rsa<Private> = Rsa::generate(2048).expect("cannot genera...
use std::convert::{TryFrom, TryInto}; use chrono::{DateTime, TimeZone, Utc}; use openssl::pkey::Private; use openssl::rsa::{Rsa, Padding}; use crate::misc::days_from_now; use crate::key_store::errors::*; lazy_static! { static ref IMPORT_KEY: Rsa<Private> = Rsa::generate(2048).expect("cannot genera...
#[test] fn expiry() { let mut token = ImportToken::new("arn:aws:kms:eu-west-2:0000000:key/11111111-2222-3333-4444-555555555555", ImportMode::PKCS1); token.expiry_date = days_from_now(-1); let bytes: Vec<u8> = token.try_into().unwrap(); let result: Result<ImportToken, _> = bytes...
fn round_trip() { let token = ImportToken::new("arn:aws:kms:eu-west-2:0000000:key/11111111-2222-3333-4444-555555555555", ImportMode::PKCS1); let result = token.try_into(); assert!(result.is_ok(), "{:?}", result); let bytes: Vec<u8> = result.unwrap(); let result = bytes.as_slice()...
function_block-full_function
[ { "content": "pub fn raw_decrypt(data: &mut Vec<u8>, key: &KeyMaterial, context: &HashMap<&str, &str>) -> Result<(), RawDecryptError> {\n\n // NB: data must end with tag and nonce\n\n let len = data.len();\n\n if len < TAG_LEN + NONCE_LEN {\n\n return Err(RawDecryptError::Length);\n\n }\n\n ...
Rust
clocks/src/analog_clock.rs
nivpgir/epd-clock
f28c44a80759f6329402d452a7e73028d44ecd23
use chrono::{Local, Timelike}; use core::f32::consts::PI; use embedded_graphics::{ Drawable, pixelcolor::BinaryColor, prelude::*, primitives::{ Circle, Line, PrimitiveStyle, PrimitiveStyleBuilder, Rectangle, Sector }}; use embedded_graphics::geometry::AngleUnit; const MARGIN: u32 = 10; fn ...
use chrono::{Local, Timelike}; use core::f32::consts::PI; use embedded_graphics::{ Drawable, pixelcolor::BinaryColor, prelude::*, primitives::{ Circle, Line, PrimitiveStyle, PrimitiveStyleBuilder, Rectangle, Sector }}; use embedded_graphics::geometry::AngleUnit; const MARGIN: u32 = 10; fn ...
get)?; hours_inner.into_styled(PrimitiveStyle::with_fill(BinaryColor::Off)).draw(target)?; Ok(()) } }
osition = polar(clock_face, angle, length_delta); let decoration_style = PrimitiveStyleBuilder::new() .fill_color(BinaryColor::Off) .stroke_color(BinaryColor::On) .stroke_width(1) .build(); Circle::with_center(decoration_position, 11) .into_styled(decora...
random
[ { "content": "fn main() -> Result<()> {\n\n // let simulator = SimulatorDisplay::<BinaryColor>::new(Size::new(256, 256));\n\n let simulator = SimulatorDisplay::<BinaryColor>::new(Size::new(122, 250));\n\n let output_settings = OutputSettingsBuilder::new().scale(2).build();\n\n let mut screen = Windo...
Rust
rclrust-msg-gen/src/types/member.rs
HarukiUchito/rclrust
a00c65daa837ff72e437f17516705725c807a8c3
use quote::{quote, ToTokens}; use super::{primitives::*, sequences::*}; macro_rules! define_enum_from { ($into_t:ty, $from_t:ty, $path:path) => { impl From<$from_t> for $into_t { fn from(t: $from_t) -> Self { $path(t) } } }; } #[derive(Debug, Clone, Par...
use quote::{quote, ToTokens}; use super::{primitives::*, sequences::*}; macro_rules! define_enum_from { ($into_t:ty, $from_t:ty, $path:path) => { impl From<$from_t> for $into_t { fn from(t: $from_t) -> Self { $path(t) } } }; } #[derive(Debug, Clone, Par...
{ let token = t.type_tokens(package); quote! { #token } } } } pub fn raw_type_tokens(&self, package: &str) -> impl ToTokens { match self { Self::NestableType(t) => { let token = t.raw_type_tokens(package); q...
ens(&self, package: &str) -> impl ToTokens { match self { Self::NestableType(t) => { let token = t.type_tokens(package); quote! { #token } } Self::Array(t) => { let token = t.type_tokens(package); quote! { #token...
function_block-random_span
[ { "content": "pub fn string_literal_sequence(s: &str) -> IResult<&str, Vec<String>> {\n\n verify(rest, |v: &str| v.starts_with('[') && v.ends_with(']'))(s)?;\n\n\n\n delimited(\n\n space0,\n\n separated_list1(\n\n char(','),\n\n delimited(\n\n space0,\n\n...
Rust
src/main.rs
mocsy/tera_design
aa9aad754724f898c731ca66d7626eca0f0d67de
#![forbid(unsafe_code)] #[macro_use] extern crate tera; mod config; mod lock; use actix_files as fs; use actix_identity::Identity; use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_web::{ error, get, middleware, web, App, Error, FromRequest, HttpRequest, HttpResponse, HttpServer, }; use log::...
#![forbid(unsafe_code)] #[macro_use] extern crate tera; mod config; mod lock; use actix_files as fs; use actix_identity::Identity; use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_web::{ error, get, middleware, web, App, Error, FromRequest, HttpRequest, HttpResponse, HttpServer, }; use log::...
#[derive(Deserialize, Default)] pub(crate) struct MyAppState { secret: String, } fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_web=info,tera_design=debug"); env_logger::init(); let version = env!("CARGO_PKG_VERSION"); let cfg = config::load_config(); let port =...
cfg: web::Data<config::Config>, ) -> Result<HttpResponse, Error> { let state = state.lock().unwrap(); if !state.secret.is_empty() && id.identity().is_none() { return Ok(HttpResponse::Found().header("location", "/unlock").finish()); } let mut tmpl = tmpl.lock().unwrap(); if let Err(e) = tmpl....
function_block-function_prefix_line
[ { "content": "// fn default_template_dir() -> String {\n\n// String::new()\n\n// }\n\nfn default_port() -> u32 {\n\n 8080\n\n}\n\n\n\npub(crate) fn load_config() -> Config {\n\n if let Ok(conf_file) = File::open(\"./config.ron\") {\n\n match from_reader(&conf_file) {\n\n Ok(x) => x,\...
Rust
src/modules/style/styledobject.rs
iCiaran/crossterm
830eec7cc7140203085008e9159d5456f5d61740
use super::{Color, ObjectStyle}; use Screen; use std::fmt::Display; #[cfg(unix)] use super::Attribute; pub struct StyledObject<D: Display> { pub object_style: ObjectStyle, pub content: D, } impl<D: Display> StyledObject<D> { ...
use super::{Color, ObjectStyle}; use Screen; use std::fmt::Display; #[cfg(unix)] use super::Attribute; pub struct StyledObject<D: Display> { pub object_style: ObjectStyle, pub content: D, } impl<D: Display> StyledObject<D> { ...
}
pub fn paint(&self, screen: &Screen) { let colored_terminal = ::color(&screen); let mut reset = true; if let Some(bg) = self.object_style.bg_color { colored_terminal.set_bg(bg); reset = true; } if let Some(fg) = self.object_style.fg_color { ...
function_block-full_function
[ { "content": "/// Get an Terminal Color implementation whereon color related actions can be performed.\n\n/// Pass the reference to any screen you want this type to perform actions on.\n\npub fn color<'stdout>(screen: &'stdout Screen) -> TerminalColor<'stdout> {\n\n TerminalColor::new(&screen.stdout)\n\n}\n"...
Rust
src/node/src/main.rs
Talentica/simpleblockchain
c2cf10052ae852bdbb433fe69babf51d017c1ee0
extern crate consensus; extern crate controllers; extern crate ctrlc; extern crate db_service; extern crate p2plib; extern crate schema; #[macro_use] extern crate log; mod nodemsgprocessor; use consensus::consensus_interface; use controllers::client_controller::{ClientController, Controller}; use libloading::{Library...
extern crate consensus; extern crate controllers; extern crate ctrlc; extern crate db_service; extern crate p2plib; extern crate schema; #[macro_use] extern crate log; mod nodemsgprocessor; use consensus::consensus_interface; use controllers::client_controller::{ClientController, Controller}; use libloading::{Library...
(txn_sender); info!("Started api_service"); while !terminate.load(Ordering::SeqCst) { std::thread::park(); } info!("Stopping REST End Point"); api_service.stop(); } fn register_signals(terminate: Arc<AtomicBool>) { let thread = std::thread::current(); ctrlc::se...
ocess() { let config: &Configuration = &configreader::GLOBAL_CONFIG; let pk: PublicKey = PublicKey::Ed25519(config.node.public.clone()); let peer_id = PeerId::from_public_key(pk); let mut swarm = SimpleSwarm::new(); swarm.topic_list.push(String::from(constants::NODE.clone())); let mut node_msg_p...
function_block-random_span
[ { "content": "fn get_peer_url_using_pk(pk: &String) -> Option<String> {\n\n let public_key: PublicKey = match utils::keypair::PublicKey::from_string(pk) {\n\n Some(public_key) => PublicKey::Ed25519(public_key),\n\n None => return None,\n\n };\n\n let peer_id_string: String = PeerId::from_...
Rust
src/interop.rs
typst/hayagriva
9bbd3f00c07d78a88bdcee393be7469a70b34216
use biblatex as tex; use tex::{Chunk, ChunksExt, DateValue, Edition, EditorType}; use url::Url; use super::types::{ Date, EntryType, FmtString, NumOrStr, Person, PersonRole, QualifiedUrl, Title, }; use super::Entry; macro_rules! tex_kinds { ($self:expr, $mv_attr:expr, [$({$kind:pat, $new_kind:expr, $top_lev...
use biblatex as tex; use tex::{Chunk, ChunksExt, DateValue, Edition, EditorType}; use url::Url; use super::types::{ Date, EntryType, FmtString, NumOrStr, Person, PersonRole, QualifiedUrl, Title, }; use super::Entry; macro_rules! tex_kinds { ($self:expr, $mv_attr:expr, [$({$kind:pat, $new_kind:expr, $top_lev...
}) { if let Some(parent) = book(&mut item, parent) { parent.set_publisher(publisher); } else { item.set_publisher(publisher); } } if let Some(organization) = entry.organization().map(|d| { let mut format = String::new()...
rent) = book(&mut item, parent) { parent.set_location(location); } else { item.set_location(location); } } if let Some(publisher) = entry.publisher().map(|d| { let mut format = FmtString::new_empty(false, true, false); let ...
random
[ { "content": "#[cfg(feature = \"biblatex\")]\n\npub fn from_biblatex_str(biblatex: &str) -> Option<Vec<Entry>> {\n\n Bibliography::parse(biblatex).map(|b| from_biblatex(&b))\n\n}\n\n\n\n/// Parse a bibliography from a BibLaTeX [`Bibliography`].\n", "file_path": "src/io.rs", "rank": 2, "score": 19...
Rust
tests/f32x4.rs
akikoskinen/wide
56b76bff3eb7aba37c17cb74ea999a24faa8cf7e
#![allow(clippy::float_cmp)] use bytemuck::*; use wide::*; #[test] fn declaration_tests_f32x4() { use core::mem::{align_of, size_of}; assert_eq!(size_of::<f32x4>(), 16); assert_eq!(align_of::<f32x4>(), 16); } #[test] #[allow(non_snake_case)] fn declaration_tests_ConstUnionHack_f32x4() { use core::mem::{align_...
#![allow(clippy::float_cmp)] use bytemuck::*; use wide::*; #[test] fn declaration_tests_f32x4() { use core::mem::{align_of, size_of}; assert_eq!(size_of::<f32x4>(), 16); assert_eq!(align_of::<f32x4>(), 16); } #[test] #[allow(non_snake_case)] fn declaration_tests_ConstUnionHack_f32x4() { use core::mem::{align_...
#[test] fn f32x4_signum() { let a = f32x4::new(0.0, 1.0, 2.0, core::f32::INFINITY).signum(); assert_eq!(a[0], 1.0); assert_eq!(a[1], 1.0); assert_eq!(a[2], 1.0); assert_eq!(a[3], 1.0); let b = f32x4::new(-0.0, -1.0, -2.0, core::f32::NEG_INFINITY).signum(); assert_eq!(b[0], -1.0); assert_eq!(b[1], -1....
et mask = f.cmp_gt(f32x4::from(1.5)); assert_eq!(mask[0], 0.0); assert_eq!(mask[1], 0.0); assert!(mask[2].is_nan()); assert!(mask[3].is_nan()); let combined = mask.merge(f32x4::ONE, f32x4::ZERO); assert_eq!(combined[0], 0.0); assert_eq!(combined[1], 0.0); assert_eq!(combined[2], 1.0); assert_eq!(comb...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn m128d_move_mask() {\n\n let max = core::u64::MAX;\n\n for target_mask in 0..4 {\n\n let arr: [u64; 2] =\n\n [max * (target_mask & 0b1), max * ((target_mask & 0b10) >> 1)];\n\n let m: m128d = cast(arr);\n\n let out_mask: i32 = m.move_mask();\n\n assert_eq!(out_mask ...
Rust
integration-tests/src/backend/features/persistent_log.rs
input-output-hk/vit-testing
71e77212cd1e7c1833b656a925b614c67a4c9fb8
use crate::common::{load::build_load_config_count, vitup_setup}; use assert_fs::fixture::PathChild; use assert_fs::TempDir; use catalyst_toolbox::recovery::Replay; use iapyx::NodeLoad; use jcli_lib::utils::output_file::OutputFile; use jcli_lib::utils::output_format::{FormatVariant, OutputFormat}; use jormungandr_lib::i...
use crate::common::{load::build_load_config_count, vitup_setup}; use assert_fs::fixture::PathChild; use assert_fs::TempDir; use catalyst_toolbox::recovery::Replay; use iapyx::NodeLoad; use jcli_lib::utils::output_file::OutputFile; use jcli_lib::utils::output_format::{FormatVariant, OutputFormat}; use jormungandr_lib::i...
pub fn persistent_log_contains_all_sent_votes() { let testing_directory = TempDir::new().unwrap().into_persistent(); let endpoint = "127.0.0.1:8080"; let version = "2.0"; let no_of_threads = 1; let number_requests_to_per_threads = 50; let batch_size = 20; let no_of_wallets = 100; let v...
function_block-full_function
[ { "content": "pub fn vitup_setup(\n\n mut quick_setup: VitBackendSettingsBuilder,\n\n mut testing_directory: PathBuf,\n\n) -> (VitController, Controller, ValidVotePlanParameters, String) {\n\n let context = context(&testing_directory);\n\n\n\n testing_directory.push(quick_setup.title());\n\n if t...
Rust
src/mkvmuxer/seek_head.rs
rainliu/libwebm
4013030ffb25ce72c2547a2fcb26a2be96703c7f
use super::util; use super::writer::Writer; use crate::MkvId; const kSeekEntryCount: usize = 5; pub struct SeekHead { seek_entry_id_: Vec<u32>, seek_entry_pos_: Vec<u64>, start_pos_: u64, } impl SeekHead { pub fn new() -> SeekHead { SeekHead { seek_entry_id_: vec![0; k...
use super::util; use super::writer::Writer; use crate::MkvId; const kSeekEntryCount: usize = 5; pub struct SeekHead { seek_entry_id_: Vec<u32>, seek_entry_pos_: Vec<u64>, start_pos_: u64, } impl SeekHead { pub fn new() -> SeekHead { SeekHead { seek_entry_id_: vec![0; k...
on() - self.start_pos_); let bytes_written = util::WriteVoidElement(writer, size_left); if bytes_written == 0 { return false; } if writer.set_position(pos).is_err() { return false; } } true } }
] = id; self.seek_entry_pos_[i] = pos; return true; } } false } pub fn GetId(&self, index: usize) -> u32 { if index >= kSeekEntryCount { std::u32::MAX } else { self.seek_entry_id_[index] } } pub...
random
[ { "content": "pub fn WriteEbmlMasterElement(writer: &mut dyn Writer, t: MkvId, size: u64) -> bool {\n\n if WriteID(writer, t).is_err() {\n\n return false;\n\n }\n\n if WriteUInt(writer, size).is_err() {\n\n return false;\n\n }\n\n true\n\n}\n\n\n", "file_path": "src/mkvmuxer/uti...
Rust
src/model/dealer.rs
nakidixon/klondike-rs
b017ed3cc4645df7e48f137e0197252feef44b09
use std::fmt; use num_traits::ToPrimitive; use rand::{seq::SliceRandom, thread_rng}; use super::{area, area_list, settings, Card, Game, Rank, Suit}; pub trait Dealer { fn deal_game(&self, settings: &settings::GameSettings) -> Game; } pub fn create_dealer(mode: settings::DealerMode) -> Box<dyn Dealer> { matc...
use std::fmt; use num_traits::ToPrimitive; use rand::{seq::SliceRandom, thread_rng}; use super::{area, area_list, settings, Card, Game, Rank, Suit}; pub trait Dealer { fn deal_game(&self, settings: &settings::GameSettings) -> Game; } pub fn create_dealer(mode: settings::DealerMode) -> Box<dyn Dealer> { matc...
} #[derive(Debug)] struct StandardDealer<S> where S: Shuffle + fmt::Debug, { shuffle: S, } impl<S> Dealer for StandardDealer<S> where S: Shuffle + fmt::Debug, { fn deal_game(&self, settings: &settings::GameSettings) -> Game { let mut deck = S::create_deck(); let mut tableaux_areas = ...
let mut areas: Vec<Box<dyn area::UnselectedArea>> = vec![stock, talon]; areas.append(&mut foundation_areas); areas.append(&mut tableaux_areas); let areas = area_list::AreaList::new(areas).expect("Unable to create AreaList"); Game::new(areas) }
function_block-function_prefix_line
[ { "content": "pub trait SplitOffBounded {\n\n fn split_off_bounded(&mut self, len: usize) -> Self;\n\n}\n\n\n\nimpl<T> SplitOffBounded for Vec<T> {\n\n fn split_off_bounded(&mut self, len: usize) -> Self {\n\n let split_index = self.len().saturating_sub(len);\n\n self.split_off(split_index)\...
Rust
src/main.rs
thyrc/parallel-sh
86d158bf35e4ec7b0ca4ac0d18640c6d79eb0f98
extern crate chrono; extern crate clap; extern crate log; extern crate simplelog; use chrono::{DateTime, Duration, Local}; use clap::{value_t, values_t, App, Arg, ArgMatches}; use log::{debug, error, info, warn}; use simplelog::{ ColorChoice, CombinedLogger, ConfigBuilder, LevelFilter, SharedLogger, TermLogger, ...
extern crate chrono; extern crate clap; extern crate log; extern crate simplelog; use chrono::{DateTime, Duration, Local}; use clap::{value_t, values_t, App, Arg, ArgMatches}; use log::{debug, error, info, warn}; use simplelog::{ ColorChoice, CombinedLogger, ConfigBuilder, LevelFilter, SharedLogger, TermLogger, ...
; let mut clijobs = vec![]; if matches.is_present("clijobs") { for v in values_t!(matches, "clijobs", String).unwrap() { clijobs.push(v); } } let jobsfile = matches.value_of_os("jobsfile").map(PathBuf::from); if let Err(e) = add_jobs(clijobs, jobsfile, tx) { er...
start_workers( value_t!(matches, "threads", usize).unwrap_or_else(|_| num_cpus::get()), matches.is_present("dry_run"), rx, rtx, )
call_expression
[ { "content": "## Options\n\n```text\n\nparallel-sh 0.1.1\n\nExecute commands in parallel\n\n\n\nUSAGE:\n\n parallel-sh [FLAGS] [OPTIONS] [clijobs]...\n\n\n\nFLAGS:\n\n --dry-run Perform a trial run, only print what would be done (with -vv)\n\n --halt-on-error Stop execution if an er...
Rust
src/physics.rs
ethanxxxl/staws
2939d3ec80829b13ee3182ec5d74999176788a7b
use super::ships::{Engine, Throttle}; use bevy::prelude::*; use bevy_inspector_egui::Inspectable; pub struct PhysicsPlugin; impl Plugin for PhysicsPlugin { fn build(&self, app: &mut AppBuilder) { app.add_system(kinimatics_system.system()); } } #[derive(Inspectable, Default, Clone, Copy)] pub struct ...
use super::ships::{Engine, Throttle}; use bevy::prelude::*; use bevy_inspector_egui::Inspectable; pub struct PhysicsPlugin; impl Plugin for PhysicsPlugin { fn build(&self, app: &mut AppBuilder) { app.add_system(kinimatics_system.system()); } } #[derive(Inspectable, Default, Clone, Copy)] pub struct ...
pub fn kinimatics_system( mut k_bods: Query<(&mut Kinimatics, &mut Transform, Option<&Engine>)>, time: Res<Time>, ) { let num_bods = k_bods.iter_mut().count(); let mut all_forces: Vec<Vec<Vec3>> = Vec::new(); all_forces.reserve(num_bods); for _ in 0..num_bods { all_forces.push...
function_block-full_function
[ { "content": "/// Temporary init function.\n\n///\n\n/// Soon™ this will be unified into normal [startup_system()] system. Currently,\n\n/// this builds the UI.\n\npub fn init_ui(\n\n mut commands: Commands,\n\n mut materials: ResMut<Assets<ColorMaterial>>,\n\n asset_server: Res<AssetServer>,\n\n //...
Rust
src/opt/mod.rs
herzrasen/pkghist
ee67613d60c80f472fa24c9dda9600c04e9ff31d
use std::str::FromStr; use crate::error::Error; use crate::error::ErrorDetail; use chrono::NaiveDateTime; use clap::ArgMatches; use regex::Regex; pub mod cli; pub fn parse_args<'a>(argv: &[String]) -> ArgMatches<'a> { cli::build_cli().get_matches_from(argv) } #[derive(Debug, PartialOrd, PartialEq)] pub enum F...
use std::str::FromStr; use crate::error::Error; use crate::error::ErrorDetail; use chrono::NaiveDateTime; use clap::ArgMatches; use regex::Regex; pub mod cli; pub fn parse_args<'a>(argv: &[String]) -> ArgMatches<'a> { cli::build_cli().get_matches_from(argv) } #[derive(Debug, PartialOrd, PartialEq)] pub enum F...
false } ) } #[test] fn should_create_config_from_args_exclude() { let matches = parse_args(&[ String::from("pkghist"), String::from("--exclude"), String::from("^lib"), ]); let config = Config::from_arg_matches(&matches); ...
} ) } #[test] fn should_parse_format_json() { let format: Result<Format, Error> = "json".parse(); assert!(format.is_ok()); assert_eq!( format.unwrap(), Format::Json { without_details: false } ) } #[...
random
[ { "content": "pub fn is_relevant_package(filters: &[String], package: &str) -> bool {\n\n filters.is_empty() || filters.contains(&String::from(package))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::fs;\n\n use std::fs::File;\n\n use std::io::Write;\n\n use std::path::Path;\n\n\n\n use ...
Rust
src/lib.rs
kldtz/cistemrs
5a6bd9d86c0d94220ebe5732499d6e9cce78df0c
pub fn stem(word: &str, case_insensitive: bool) -> String { if word.len() == 0 { return "".into(); } let upper = word.chars().next().unwrap().is_uppercase(); let mut normalized = String::with_capacity(word.len()); let mut num_chars = 0; for ch in word.chars() { n...
pub fn stem(word: &str, case_insensitive: bool) -> String { if word.len() == 0 { return "".into(); } let upper = word.chars().next().unwrap().is_uppercase(); let mut normalized = String::with_capacity(word.len()); let mut num_chars = 0; for ch in word.chars() { n...
= stem(word, true); let (left, right) = segment(word, false); let (left_ic, right_ic) = segment(word, true); let actual_line = format!( "{}\t{}\t{}\t{}\t{}\t{}\t{}", word, stem_cs, stem_ci, left, right, left_ic, right_ic ); asse...
); repl = replxx(repl); num_chars -= word.len() - repl.len(); let mut end = word.len(); while num_chars > 3 { if num_chars > 5 && (repl.ends_with("em") || repl.ends_with("er") || repl.ends_with("nd")) { repl.truncate(repl.len() - 2); end -= 2; num_c...
random
[ { "content": "fn main() {\n\n let now = Instant::now();\n\n let file = File::open(\"data/de_wordlist_simple.txt\").unwrap();\n\n let reader = BufReader::new(file);\n\n\n\n let mut i = 0;\n\n for line in reader.lines() {\n\n let line = line.unwrap();\n\n let word = line.trim();\n\n ...
Rust
app/src/auth.rs
ericpan64/DuGuo-Chinese-Reading-App
c7e9993e80efcdba899fe469b4ebb46cbab9cd90
/* /// Module handling user authentication and cookies /// /// auth.rs /// ├── UserCredentials: Struct /// ├── UserToken: Struct /// | /// └── pub fn: /// └── generate_http_cookie /// └── add_user_cookie_to_context /// └── get_username_from_cookie /// └── str_to_hashed_string */ use blake2::{Blake2b, ...
/* /// Module handling user authentication and cookies /// /// auth.rs /// ├── UserCredentials: Struct /// ├── UserToken: Struct /// | /// └── pub fn: /// └── generate_http_cookie /// └── add_user_cookie_to_context /// └── get_username_from_cookie /// └── str_to_hashed_string */ use blake2::{Blake2b, ...
fn check_if_jwt_is_active(expiration_timestamp: i64) -> bool { let current_timestamp: i64 = Utc::now().timestamp(); return current_timestamp <= expiration_timestamp; } fn get_username_from_valid_user_credentials(db: &Database, cred: UserCredentials) -> Option<String> { let coll = (*db).collection(USER_CO...
fn validate_jwt_and_get_username(db: &Database, token: &str) -> Option<String> { let jwt_decoding_key: DecodingKey = DecodingKey::from_secret(JWT_SECRET); let jwt_validation_algorithm: Validation = Validation::new(Algorithm::HS256); let res = match jsonwebtoken::decode::<UserToken>(token, &jwt_decoding_ke...
function_block-full_function
[ { "content": "#[get(\"/u/<raw_username>/<doc_title>\")]\n\npub fn user_view_doc(cookies: Cookies, db: State<Database>, raw_username: &RawStr, doc_title: &RawStr) -> Template {\n\n let mut context: HashMap<&str, String> = HashMap::new(); // Note: <&str, String> makes more sense than <&str, &str> due to variab...
Rust
src/hazardous/hkdf.rs
ritalinn/orion
8ebdb41a3003ea4049ecca605392af9aed74d6e2
use clear_on_drop::clear::Clear; use core::options::ShaVariantOption; use core::{errors::*, util}; use hazardous::hmac::Hmac; pub struct Hkdf { pub salt: Vec<u8>, pub ikm: Vec<u8>, pub info: Vec<u8>, pub length: usize, pub hmac: ShaVariantOption, } impl Drop for Hkdf { fn drop(&mut self) { ...
use clear_on_drop::clear::Clear; use core::options::ShaVariantOption; use core::{errors::*, util}; use hazardous::hmac::Hmac; pub struct Hkdf { pub salt: Vec<u8>, pub ikm: Vec<u8>, pub info: Vec<u8>, pub length: usize, pub hmac: ShaVariantOption, } impl Drop for Hkdf { fn drop(&mut self) { ...
pub fn expand(&self, prk: &[u8]) -> Result<Vec<u8>, UnknownCryptoError> { if self.length > self.max_okmlen() { return Err(UnknownCryptoError); } if self.length < 1 { return Err(UnknownCryptoError); } let n_iter: usize = 1 + ((self.length - 1) /...
pub fn extract(&self, salt: &[u8], ikm: &[u8]) -> Vec<u8> { let prk = Hmac { secret_key: salt.to_vec(), data: ikm.to_vec(), sha2: self.hmac, }; prk.finalize() }
function_block-full_function
[ { "content": "fn fuzz_hkdf(salt: &[u8], ikm: &[u8], info: &[u8], len_max: usize, hmac: ShaVariantOption) {\n\n let mut rng = rand::thread_rng();\n\n let okm_len_rand = rng.gen_range(1, len_max + 1);\n\n\n\n let dk = Hkdf {\n\n salt: salt.to_vec(),\n\n ikm: ikm.to_vec(),\n\n info: i...
Rust
src/matrix.rs
ZippyMagician/mtrs
433fc606a3900e0e0c18bafa18b4458ff4756614
use crate::size::Size; use crate::Matrix; use std::io; use num_traits::Num; macro_rules! new { ($height:ident, $width:ident, $body:expr) => { Matrix { height: $height, width: $width, data: $body, } }; } impl<T: Num + Clone + Copy> Matrix<T> { ...
use crate::size::Size; use crate::Matrix; use std::io; use num_traits::Num; macro_rules! new { ($height:ident, $width:ident, $body:expr) => { Matrix { height: $height, width: $width, data: $body, } }; } impl<T: Num + Clone + Copy> Matrix<T> { ...
} } #[cfg(test)] mod matrix_tests { use super::Matrix; #[test] fn test_cols() { let matrix1: Matrix<i32> = Matrix::identity(1); let matrix2: Matrix<i32> = Matrix::identity(2); let matrix3: Matrix<i32> = Matrix::identity(3); assert_eq!(matrix1.get_col(0), Some(vec![1])...
if self.width != width { let mut new_dat = self.as_vec(); for entry in &mut new_dat { let len = entry.len(); entry.resize(len + width - self.width, T::zero()); } self.width = width; self.data = new_dat .iter() ...
if_condition
[ { "content": "/// Is implemented for both `usize` and `(usize, usize)`, which allows for a more flexible input\n\n/// when creating matrices\n\npub trait Size {\n\n fn dim(&self) -> (usize, usize);\n\n}\n\n\n\nimpl Size for usize {\n\n fn dim(&self) -> (usize, usize) {\n\n (*self, *self)\n\n }\n...
Rust
src/system/resource.rs
vn-ki/harsark.rs
e34a4419fcd9003cd1f436a01a3fde98d5a5f6d4
use core::cell::RefCell; use crate::kernel::tasks::{block_tasks, get_curr_tid, schedule, unblock_tasks}; use crate::system::pi_stack::PiStack; use crate::system::scheduler::{BooleanVector, Scheduler, TaskId}; use crate::utils::arch::{critical_section, Mutex}; use crate::system::spinlock::{spinlock, spinlock_try, spi...
use core::cell::RefCell; use crate::kernel::tasks::{block_tasks, get_curr_tid, schedule, unblock_tasks}; use crate::system::pi_stack::PiStack; use crate::system::scheduler::{BooleanVector, Scheduler, TaskId}; use crate::utils::arch::{critical_section, Mutex}; use crate::system::spinlock::{spinlock, spinlock_try, spi...
ernelError::AccessDenied); } if ceiling as i32 > pi_stack.system_ceiling { pi_stack.push_stack(ceiling)?; spinlock(&TASKMANAGER_LOCK); *self.blocked_mask.borrow_mut() = ...
s_mask) as TaskId, } } fn get_pi_mask(ceiling: TaskId) -> u32 { let mask; if ceiling < 31 { mask = (1 << (ceiling + 1)) - 1; } else { mask = 0xffffffff } mask } pub(crate) fn lock(&self) -> Result<&T, KernelError> { ...
random
[ { "content": "/// Returns the TaskId of the currently running task in the kernel.\n\npub fn get_curr_tid(task_manager: &'static Mutex<RefCell<Scheduler>>) -> TaskId {\n\n critical_section(|cs_token| {\n\n spinlock(&TASKMANAGER_LOCK);\n\n let tid = task_manager.borrow(cs_token).borrow().curr_tid...
Rust
src/device_discovery.rs
danielwippermann/async-resol-vbus.rs
c79410b3d719fc834363001603e9e611b3baa424
use std::{ collections::HashSet, net::{Ipv4Addr, SocketAddr, SocketAddrV4}, time::Duration, }; use async_std::net::UdpSocket; use crate::{device_information::DeviceInformation, error::Result}; #[derive(Debug)] pub struct DeviceDiscovery { broadcast_addr: SocketAddr, rounds: u8, broadcast_time...
use std::{ collections::HashSet, net::{Ipv4Addr, SocketAddr, SocketAddrV4}, time::Duration, }; use async_std::net::UdpSocket; use crate::{device_information::DeviceInformation, error::Result}; #[derive(Debug)] pub struct DeviceDiscovery { broadcast_addr: SocketAddr, rounds: u8, broadcast_time...
} impl Default for DeviceDiscovery { fn default() -> DeviceDiscovery { DeviceDiscovery::new() } } #[cfg(test)] mod tests { use async_std::net::{SocketAddr, TcpListener, UdpSocket}; use super::*; use crate::test_utils::create_webserver; #[test] fn test() -> Result<()> { ...
pub async fn discover_device_addresses(&self) -> Result<Vec<SocketAddr>> { let broadcast_socket = UdpSocket::bind("0.0.0.0:0").await?; broadcast_socket.set_broadcast(true)?; let query_bytes = b"---RESOL-BROADCAST-QUERY---"; let reply_bytes = b"---RESOL-BROADCAST-REPLY---"; let ...
function_block-full_function
[ { "content": "fn run_serial_read_loop(mut rx_port: Box<dyn SerialPort>, rx_port_sender: Sender<Vec<u8>>) -> Result<()> {\n\n let mut ldb = LiveDataBuffer::new(0);\n\n let mut buf = [0; 4096];\n\n loop {\n\n // trace!(\"Start reading from serial port...\");\n\n let size = match rx_port.rea...
Rust
src/entity/mod.rs
ndouglas/azymus
945736f15ebb886f1d3cba438818320ebe9073e4
use tcod::map::Map as FovMap; use crate::agent; use agent::Agent; use crate::body; use body::Body; use crate::component; use component::actor::Actor; use component::field_of_view::FieldOfView; use component::light_source::{LightSource, Factory as LightSourceFactory}; use component::position::Position; use component::re...
use tcod::map::Map as FovMap; use crate::agent; use agent::Agent; use crate::body; use body::Body; use crate::component; use component::actor::Actor; use component::field_of_view::FieldOfView; use component::light_source::{LightSource, Factory as LightSourceFactory}; use component::position::Position; use component::re...
pub fn get_player(map: &Map) -> Entity { trace!("Entering get_player()."); let mut player = Entity::new("Player".to_string()); player.actor = Some(Actor { time: 0, speed: 12, }); player.body = Some(Body { total_hit_points: 32767, current_hit_points: 32767, }); ...
function_block-full_function
[ { "content": "fn command_to_attack(id: usize, position: &Position, game: &Game) -> Option<Command> {\n\n if let Some(compass_direction) = get_direction_to(id, position, game) {\n\n return Some(Command::MeleeAttack(compass_direction));\n\n }\n\n None\n\n}\n", "file_path": "src/agent/mod.rs", ...
Rust
src/main.rs
Kondziowy/llama-bot
f3b69ba1b74fcd4115973bfe2dbacbd924fa8bf2
#![type_length_limit="1884939"] use std::{convert::Infallible, env, net::SocketAddr}; use hyper::{Body, Request, Response, Server, service::{make_service_fn, service_fn}}; use serenity::{ async_trait, model::{channel::Message, gateway::Ready}, prelude::*, }; use rand::Rng; use select::{document::Document, ...
#![type_length_limit="1884939"] use std::{convert::Infallible, env, net::SocketAddr}; use hyper::{Body, Request, Response, Server, service::{make_service_fn, service_fn}}; use serenity::{ async_trait, model::{channel::Message, gateway::Ready}, prelude::*, }; use rand::Rng; use select::{document::Document, ...
async fn ready(&self, _: Context, ready: Ready) { println!("{} is connected!", ready.user.name); } } fn get_absolute_uri(n: Node) -> Option<&str> { match n.attr("src") { Some(link) => { if link.starts_with("http") { return Some(link); } } ...
r() { HELP_COMMAND => { response = String::from(HELP_MESSAGE); } SHOW_COMMAND => { response = String::from(findimage().await.unwrap()); } &_ => { if msg.content.starts_with(YESNO_COMMAND) { le...
function_block-function_prefixed
[ { "content": "# llama-bot\n\nVirtual llama for use in Discord servers\n\n\n\nHow to run:\n\n\n\nFollow instructions on how to set up your Discord server [here](https://developers.facebook.com/blog/post/2020/09/30/build-discord-bot-with-rust-and-serenity/)\n\n\n\nRun with DISCORD_TOKEN=_<your_token>_ cargo run\n...
Rust
src/instruction.rs
8-sided-oregon/chip8emu
550e0d09cf965bec6f3466ee5ab4c543b4ef60ff
mod instructions { use crate::memory::EmuState; pub trait Instruction<E> { fn new() -> Self; fn extract_data(&mut self, ins: u16); fn execute(&self, state: &mut EmuState) -> Result<(), E>; } pub struct ClearScreen { } impl Instruction<()> for ClearScreen { fn n...
mod instructions { use crate::memory::EmuState; pub trait Instruction<E> { fn new() -> Self; fn extract_data(&mut self, ins: u16); fn execute(&self, state: &mut EmuState) -> Result<(), E>; } pub struct ClearScreen { } impl Instruction<()> for ClearScreen { fn n...
} pub struct VAndV { register_num1: u8, register_num2: u8, } impl Instruction<()> for VAndV { fn new() -> VAndV { VAndV { register_num1: 0, register_num2: 0 } } fn extract_data(&mut self, ins: u16) { (self.register_num1, self.register_n...
e) -> Result<(), ()> { state.registers.variables[self.register_num1 as usize] |= state.registers.variables[self.register_num2 as usize]; Ok(()) }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let v = video::VideoRam::new();\n\n \n\n}\n", "file_path": "src/main.rs", "rank": 18, "score": 22386.89231935665 }, { "content": "#[test]\n\nfn test_xor() {\n\n let mut v = VideoRam::new();\n\n\n\n let (x, y) = (10, 10);\n\n let (width, height) = ...
Rust
src/day04.rs
vipentti/advent-of-code-2018
66c92c020b05aae9d368ef9854de7f4ac9d127df
#[macro_use] extern crate lazy_static; extern crate regex; extern crate itertools; use itertools::Itertools; use std::collections::HashMap; use std::fmt; use std::str::FromStr; use regex::Regex; use std::error; use aoc::{read_input, Result}; #[derive(Debug, Clone, PartialEq, Eq)] struct CustomError(String); impl...
#[macro_use] extern crate lazy_static; extern crate regex; extern crate itertools; use itertools::Itertools; use std::collections::HashMap; use std::fmt; use std::str::FromStr; use regex::Regex; use std::error; use aoc::{read_input, Result}; #[derive(Debug, Clone, PartialEq, Eq)] struct CustomError(String); impl...
fn gather_2(events: &[LogEvent]) -> Result<(i32, i32)> { let mut sleeping_start = 0; let mut sleeping_end; let mut guard = 0; let mut map: HashMap<i32, Vec<i32>> = HashMap::new(); for event in events { match event.event { EventType::ShiftStart(id) => { guard =...
let mut sleeping = vec![0; 60]; for value in values { for index in value.start..value.end { sleeping[index as usize] += 1; } } let minute = sleeping .iter() .enumerate() .max_by(|(_, val), (_, v2)| val.cmp(&v2)) .ok_or_else::<Box<CustomError>, _>...
function_block-function_prefix_line
[ { "content": "fn part2(s: &str) -> Result<(i32, i32)> {\n\n let mut grid = read_grid(s)?;\n\n\n\n eprintln!(\"{}\", grid.draw());\n\n\n\n let mut tick = 0;\n\n\n\n let res: Option<(i32, i32)> = loop {\n\n if let Some(pos) = grid.tick_part2() {\n\n eprintln!(\"{} -> {:?}\", tick, po...
Rust
src/command/open.rs
gifnksm/rsrs
18261dce29fd96feef5809439cb3b37f3f783a27
use super::GlobalOpts; use crate::{ common, prelude::*, protocol, protocol::cli::{self, Request, Response}, Result, }; use nix::unistd; use passfd::tokio_02::FdPassingExt; use std::{ffi::OsString, fmt::Debug, os::unix::io::AsRawFd, process::Stdio}; use tokio::{ fs::File, net::{ unix:...
use super::GlobalOpts; use crate::{ common, prelude::*, protocol, protocol::cli::{self, Request, Response}, Result, }; use nix::unistd; use passfd::tokio_02::FdPassingExt; use std::{ffi::OsString, fmt::Debug, os::unix::io::AsRawFd, process::Stdio}; use tokio::{ fs::File, net::{ unix:...
#[tracing::instrument(skip(in_stream, out_stream, magic), err)] #[allow(clippy::unit_arg)] async fn forward_until_magic( mut in_stream: impl AsyncRead + Unpin, mut out_stream: impl AsyncWrite + Unpin, magic: &[u8], ) -> Result<()> { let mut whole_buf = vec![0u8; magic.len()]; let mut matched_len ...
async fn forward_until_interrupted( mut in_stream: impl AsyncRead + Unpin, mut out_stream: impl AsyncWrite + Unpin, mut rx: watch::Receiver<bool>, ) -> Result<()> { let mut buf = vec![0u8; 4096]; loop { tokio::select! { res = in_stream.read(&mut buf) => { let n = ...
function_block-full_function
[ { "content": "fn gen(out_dir: impl AsRef<Path>, name: &str) -> io::Result<()> {\n\n let out_dir = out_dir.as_ref();\n\n\n\n let mut src_path = PathBuf::from(\"data\");\n\n src_path.push(name);\n\n src_path.set_extension(\"txt\");\n\n println!(\"cargo:rerun-if-changed={}\", src_path.display());\n\...
Rust
backend/c/src/lib.rs
dan-zheng/telamon
de463284fdcea70ce29cf43a9c62f3aa2da14276
use std::fmt; use telamon::codegen::llir; use telamon::ir; pub trait C99Display { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; fn c99(&self) -> DisplayC99<'_, Self> { DisplayC99 { inner: self } }...
use std::fmt; use telamon::codegen::llir; use telamon::ir; pub trait C99Display { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; fn c99(&self) -> DisplayC99<'_, Self> { DisplayC99 { inner: self } }...
write!( fmt, "{}0x{:x}p{}{}", signchar, mantissa, exponent, floating_suffix ) } } } } impl<T: C99Display> C99Display for llir::ScalarOrVector<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt...
let floating_suffix = match bits { 32 => "f", 64 => "", _ => panic!("Cannot print floating point value with {} bits", bits), };
assignment_statement
[ { "content": "/// Checks the result of all valid candidates.\n\npub fn check_candidates<F>(space: SearchSpace, ctx: &Context, mut check: F)\n\nwhere\n\n F: FnMut(),\n\n{\n\n explorer::gen_space(\n\n ctx,\n\n space,\n\n |_| (),\n\n |candidate| {\n\n debug!(\"testing c...
Rust
src/render/object.rs
lolmaus/vange-rs
f47045fa5d0c34ca4e848c7eb032b95c3cb743d9
use crate::{ render::{ body::GpuBody, global::Context as GlobalContext, GpuTransform, Palette, PipelineSet, Shaders, COLOR_FORMAT, DEPTH_FORMAT, SHADOW_FORMAT, }, space::Transform, }; use bytemuck::{Pod, Zeroable}; use m3d::NUM_COLOR_IDS; use std::{mem, slice}; const COLOR_TABLE: [[u8; 2];...
use crate::{ render::{ body::GpuBody, global::Context as GlobalContext, GpuTransform, Palette, PipelineSet, Shaders, COLOR_FORMAT, DEPTH_FORMAT, SHADOW_FORMAT, }, space::Transform, }; use bytemuck::{Pod, Zeroable}; use m3d::NUM_COLOR_IDS; use std::{mem, slice}; const COLOR_TABLE: [[u8; 2];...
pub fn new( device: &wgpu::Device, queue: &wgpu::Queue, palette_data: &[[u8; 4]], global: &GlobalContext, ) -> Self { let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Object"), entries: &[ ...
Default::default() }); ( texture.create_view(&wgpu::TextureViewDescriptor::default()), sampler, ) }
function_block-function_prefix_line
[ { "content": "struct Pipelines {\n\n step: wgpu::ComputePipeline,\n\n gather: wgpu::ComputePipeline,\n\n push: wgpu::ComputePipeline,\n\n}\n\n\n\nimpl Pipelines {\n\n fn new(\n\n layout_step: &wgpu::PipelineLayout,\n\n layout_gather: &wgpu::PipelineLayout,\n\n layout_push: &wgpu...
Rust
suspend-channel/tests/channel.rs
andrewwhitehead/suspend-rs
8acdf983e10f56746a5c232101b1969ac8a78ecf
extern crate alloc; use alloc::sync::Arc; use core::{ pin::Pin, sync::atomic::{AtomicUsize, Ordering}, task::{Context, Poll}, }; #[cfg(feature = "std")] use std::thread; use futures_core::{FusedStream, Stream}; use futures_task::{waker_ref, ArcWake}; use suspend_channel::{channel, TrySendError}; #[cfg(f...
extern crate alloc; use alloc::sync::Arc; use core::{ pin::Pin, sync::atomic::{AtomicUsize, Ordering}, task::{Context, Poll}, }; #[cfg(feature = "std")] use std::thread; use futures_core::{FusedStream, Stream}; use futures_task::{waker_ref, ArcWake}; use suspend_channel::{channel, TrySendError}; #[cfg(f...
t ta = thread::spawn(move || { sender1 .try_send(block_on(receiver0.stream_next()).unwrap()) .unwrap() }); let tb = thread::spawn(move || sender0.try_send(1u32).unwrap()); assert_eq!(block_on(receiver1.stream_next()), Some(1u32)); ta.join().unwrap(); tb.join().unwrap(...
sender, mut receiver) = channel(); let ta = thread::spawn(move || sender.try_send(1u32).unwrap()); assert_eq!(block_on(receiver.stream_next()), Some(1u32)); ta.join().unwrap(); } #[cfg(feature = "std")] #[test] fn channel_send_receive_forward_thread() { let (mut sender0, mut receiver0) = channel(); ...
random
[ { "content": "pub fn poll_once<F, T>(mut fut: F) -> Poll<T>\n\nwhere\n\n F: Future<Output = T> + Unpin,\n\n{\n\n let waker = NullWaker::waker();\n\n let mut cx = Context::from_waker(&waker);\n\n Pin::new(&mut fut).poll(&mut cx)\n\n}\n", "file_path": "suspend-core/tests/utils/mod.rs", "rank":...
Rust
src/main.rs
ucarion/gaia_demo
924794feae523293101261e2687e96ae008d9ae9
#[macro_use] extern crate error_chain; extern crate cgmath; extern crate fps_counter; extern crate gaia; extern crate gaia_assetgen; extern crate gfx; extern crate hsl; extern crate piston; extern crate piston_window; mod camera_controller; use camera_controller::CameraController; use cgmath::{Angle, Matrix4, Persp...
#[macro_use] extern crate error_chain; extern crate cgmath; extern crate fps_counter; extern crate gaia; extern crate gaia_assetgen; extern crate gfx; extern crate hsl; extern crate piston; extern crate piston_window; mod camera_controller; use camera_controller::CameraController; use cgmath::{Angle, Matrix4, Persp...
} struct State { camera_controller: CameraController, map_mode: MapMode, labels_enabled: bool, } impl State { pub fn event<E>(&mut self, e: &E) where E: GenericEvent, { self.camera_controller.event(e); e.press(|button| match button { Button::Keyboard(Key::...
fn color(&self, properties: &Properties) -> [u8; 4] { match *self { MapMode::Terrain | MapMode::All | MapMode::Oecd => { let color_num = properties["MAPCOLOR13"].as_f64().unwrap() as u8; let (r, g, b) = HSL { h: 360.0 * (color_num as f64 / 13.0), ...
function_block-full_function
[ { "content": "fn main() {\n\n PrepareAssetsTask::new()\n\n .with_noaa_globe_dir(\"assets/noaa_globe\".into())\n\n .with_nasa_blue_marble_dir(\"assets/nasa_blue_marble\".into())\n\n .with_polygons_file(\"assets/ne_10m_admin_0_countries_lakes.geojson\".into())\n\n .with_points_file(...
Rust
src/cli/sudoku_puzzle.rs
xuanyan0x7c7/puzzle-solver
f5e96596e49cde5d6dc744250bd7ca65cbab39e0
use std::io::stdin; use std::process; use clap::ArgMatches; use puzzle_solver::PuzzleSolver; pub fn solve_sudoku_puzzle(subcommand: &ArgMatches) { let size_string = subcommand.value_of("size").unwrap(); let box_size = if size_string == "4" { (2, 2) } else if size_string == "9" { (3, 3) ...
use std::io::stdin; use std::process; use clap::ArgMatches; use puzzle_solver::PuzzleSolver; pub fn solve_sudoku_puzzle(subcommand: &ArgMatches) { let size_string = subcommand.value_of("size").unwrap(); let box_size = if size_string == "4" { (2, 2) } else if size_string == "9" { (3, 3) ...
print!("─"); } println!("─┤"); } print!("│ "); for column in 0..board_size { if column > 0 { print!(" "); if column % box_size.1 == 0 { print!("│ "); } ...
function_block-function_prefix_line
[ { "content": "pub fn solve_calendar_puzzle(subcommand: &ArgMatches) {\n\n let date_string = subcommand.value_of(\"date\").unwrap();\n\n let date = match NaiveDate::parse_from_str(date_string, \"%Y-%m-%d\") {\n\n Ok(date) => date,\n\n Err(_) => {\n\n eprintln!(\"Invalid date: {}\",...
Rust
src/render.rs
anjinl/rust_one_weekend
dae4c98f0f165bcbd7e8328329d65c6df7d055d5
use scoped_threadpool::Pool; use spiral::ChebyshevIterator; use crossbeam::atomic::AtomicCell; use crossbeam_channel::bounded; use crate::camera::*; use crate::scene::*; use crate::shared::*; pub struct RenderBlock { pub block_index: u32, pub x: u32, pub y: u32, pub width: u32, pub height: u32, ...
use scoped_threadpool::Pool; use spiral::ChebyshevIterator; use crossbeam::atomic::AtomicCell; use crossbeam_channel::bounded; use crate::camera::*; use crate::scene::*; use crate::shared::*; pub struct RenderBlock { pub block_index: u32, pub x: u32, pub y: u32, pub width: u32, pub height: u32, ...
while !self.channel_receiver.is_empty() { let res = self.channel_receiver.recv().unwrap(); results.push(res); limit -= 1; if limit == 0 { break; } } results } pub fn stop_render(&self) { self.ke...
let x = renderblock.x + index % renderblock.width; let y = renderblock.y + (index / renderblock.width) % renderblock.height; let mut color_accum = Color::ZERO; ...
random
[ { "content": "pub fn color_random(rng: &mut RayRng) -> Color {\n\n color_random_range(rng, 0.0..1.0)\n\n}\n\n\n", "file_path": "src/shared.rs", "rank": 1, "score": 181509.62839603328 }, { "content": "pub fn index_from_xy(image_width: u32, _image_height: u32, x: u32, y: u32) -> usize {\n\n...
Rust
examples/server.rs
belak/tokio-scgi
a23e428ed92d140ef3b10cefe290d0b292534b5e
#![deny(warnings, rust_2018_idioms)] use bytes::{BufMut, BytesMut}; use futures::{SinkExt, StreamExt}; use std::env; use std::fs; use std::io::{Error, ErrorKind}; use std::net::ToSocketAddrs; use std::path::Path; use std::time::SystemTime; use tokio; use tokio::net::{TcpListener, UnixListener}; use tokio::prelude::*; ...
#![deny(warnings, rust_2018_idioms)] use bytes::{BufMut, BytesMut}; use futures::{SinkExt, StreamExt}; use std::env; use std::fs; use std::io::{Error, ErrorKind}; use std::net::ToSocketAddrs; use std::path::Path; use std::time::SystemTime; use tokio; use tokio::net::{TcpListener, UnixListener}; use tokio::prelude::*; ...
struct SampleHandler { headers: Vec<(String, String)>, body: BytesMut, body_remaining: usize, } impl SampleHandler { pub fn new() -> SampleHandler { SampleHandler { headers: Vec::new(), body: BytesMut::new(), body_remaining: 0, ...
async fn serve<C>(conn: C) -> Result<(), Error> where C: AsyncRead + AsyncWrite + std::marker::Send + std::marker::Unpin + std::fmt::Debug, { let mut handler = SampleHandler::new(); let mut framed = Framed::new(conn, SCGICodec::new()); loop { match framed.next().await { None => { ...
function_block-full_function
[ { "content": "fn consume_header_string(bytes_with_nul: BytesMut) -> Result<String, io::Error> {\n\n // Omit trailing NUL to parse buffer as string.\n\n String::from_utf8(bytes_with_nul[..bytes_with_nul.len() - 1].to_vec())\n\n .or_else(|_| io_err!(\"Header key or value is not a UTF-8 string\"))\n\n...
Rust
proxy/src/telemetry/metrics/mod.rs
xiaods/conduit
bc16034fd6d3c88f20a4e7a6dc3f0baa0e3ce06f
use std::net; use std::sync::Arc; use std::time::Duration; use std::{u32, u64}; use http; use indexmap::IndexMap; use conduit_proxy_controller_grpc::common::{ TcpAddress, Protocol, }; use conduit_proxy_controller_grpc::telemetry::{ ClientTransport, eos_ctx, EosCtx, EosScope, ReportRequest,...
use std::net; use std::sync::Arc; use std::time::Duration; use std::{u32, u64}; use http; use indexmap::IndexMap; use conduit_proxy_controller_grpc::common::{ TcpAddress, Protocol, }; use conduit_proxy_controller_grpc::telemetry::{ ClientTransport, eos_ctx, EosCtx, EosScope, ReportRequest,...
|code| { ResponseCtx { http_status_code: u32::from(code.as_u16()), } }), ends: ends, response_latency_counts: res_stats.latencies .into_iter() ...
uestScope, ResponseCtx, ResponseScope, ServerTransport, TransportSummary, }; use ctx; use telemetry::event::Event; mod latency; pub mod prometheus; #[derive(Debug)] pub struct Metrics { sources: IndexMap<net::IpAddr, TransportStats>, destinations: IndexMap<net::SocketAddr, TransportStats>, ...
random
[ { "content": "\treq *http.Request\n", "file_path": "controller/api/public/http_server.go", "rank": 0, "score": 123774.43165109301 }, { "content": "/// Tries to make sure the `Uri` of the request is in a form needed by\n\n/// hyper's Client.\n\n///\n\n/// Also sets the `UriIsAbsoluteForm` ext...
Rust
day16/src/main.rs
pkusensei/adventofcode2020
116b462afa8f5d05d221d312644a7b870954fc92
use std::collections::HashMap; type Error = Box<dyn std::error::Error>; fn main() { let input = include_str!("..\\input.txt"); let (rules, ticket, nearby) = parse(input).unwrap(); assert_eq!(23044, scan_error_rate(&rules, &nearby)); assert_eq!(3765150732757, p2(&rules, &ticket, &nearby)); println!...
use std::collections::HashMap; type Error = Box<dyn std::error::Error>; fn main() { let input = include_str!("..\\input.txt"); let (rules, ticket, nearby) = parse(input).unwrap(); assert_eq!(23044, scan_error_rate(&rules, &nearby)); assert_eq!(3765150732757, p2(&rules, &ticket, &nearby)); println!...
#[cfg(test)] mod tests { use super::*; const SAMPLE1: &str = r#"class: 1-3 or 5-7 row: 6-11 or 33-44 seat: 13-40 or 45-50 your ticket: 7,1,14 nearby tickets: 7,3,47 40,4,50 55,2,20 38,6,12"#; const SAMPLE2: &str = r#"class: 0-1 or 4-19 row: 0-5 or 8-19 ...
fn parse_ticket(line: &str) -> Result<Vec<u32>, Error> { Ok(line .split(',') .map(|n| n.trim().parse()) .collect::<Result<Vec<u32>, _>>()?) }
function_block-full_function
[ { "content": "fn parse_rule(line: &str) -> Result<(u32, Rule), Error> {\n\n let rule_id: u32 = line\n\n .split(':')\n\n .next()\n\n .ok_or_else(|| \"Invalid line of rule\")?\n\n .parse()?;\n\n let rule_str = line\n\n .split(':')\n\n .skip(1)\n\n .next()\n\n...
Rust
src/audio/device.rs
NyantasticUwU/nstd
5e48969f2cb25bc19fb83fc87b61655c527f53cf
use super::{ def::{NSTDAudioSampleFormat, NSTDAudioStreamConfig}, stream::NSTDAudioStream, }; use crate::{ core::def::{NSTDAny, NSTDAnyConst, NSTDErrorCode}, string::NSTDString, }; use cpal::{ traits::*, BufferSize, BuildStreamError, Device, Sample, SampleFormat, SampleRate, Stream, StreamConfi...
use super::{ def::{NSTDAudioSampleFormat, NSTDAudioStreamConfig}, stream::NSTDAudioStream, }; use crate::{ core::def::{NSTDAny, NSTDAnyConst, NSTDErrorCode}, string::NSTDString, }; use cpal::{ traits::*, BufferSize, BuildStreamError, Device, Sample, SampleFormat, SampleRate, Stream, StreamConfi...
macro_rules! generate_device_default_config { ($name: ident, $method: ident) => { #[cfg_attr(feature = "clib", no_mangle)] pub unsafe extern "C" fn $name( device: NSTDAudioDevice, config: *mut NSTDAudioStreamConfig, ) -> NSTDErrorCode { if let O...
d::ptr::null_mut()); let null = crate::vec::nstd_vec_from_existing(0, &null); crate::string::nstd_string_from_existing(&null) }
function_block-function_prefixed
[ { "content": " NSTDStream stream;\n", "file_path": "include/nstd/io/output_stream.h", "rank": 0, "score": 75658.04851957448 }, { "content": " NSTDStream stream;\n", "file_path": "include/nstd/io/input_stream.h", "rank": 1, "score": 75658.04851957448 }, { "content": ...
Rust
src/lib.rs
aDotInTheVoid/h4x_re
3439be812221a024f2d7ed5867acf2edcfa53710
const START: u8 = b'^'; const DOT: u8 = b'.'; const END: u8 = b'$'; #[derive(PartialEq, Debug, Clone, Hash, Eq)] pub struct Regex { binds: Binds, pattern: Pattern, } #[derive(PartialEq, Debug, Clone, Hash, Eq)] enum Binds { Front, Back, Both, Neither, } #[derive(PartialEq, Debug, Clone, Hash,...
const START: u8 = b'^'; const DOT: u8 = b'.'; const END: u8 = b'$'; #[derive(PartialEq, Debug, Clone, Hash, Eq)] pub struct Regex { binds: Binds, pattern: Pattern, } #[derive(PartialEq, Debug, Clone, Hash, Eq)] enum Binds { Front, Back, Both, Neither, } #[derive(PartialEq, Debug, Clone, Hash,...
assert!(re.is_match($accpet)); )* $( assert!(!re.is_match($regect)); )* }; } #[test] fn cost_and_string() { for i in &[ "^win$", "^win", "^wi.", "wi.", "wi", "^wi", "win$", "win", "wi.$", ] { let reg = R...
rn false; } for i in 0..=text.len() - self.pattern.len() { if self.match_dots_pos(&text[i..i + self.pattern.len()]) { return true; } } false } } #[cfg(test)] mod tests { use super::*; #[test] fn create() { let ans_1 = Reg...
random
[ { "content": "#![no_main]\n\n\n\nuse h4x_re_fuzz::check_regex_same;\n\n\n\ncheck_regex_same!(\"win$\");", "file_path": "fuzz/fuzz_targets/literal_end.rs", "rank": 2, "score": 12712.897279644098 }, { "content": "#![no_main]\n\n\n\nuse h4x_re_fuzz::check_regex_same;\n\n\n\ncheck_regex_same!(\"...
Rust
src/macos/keyboard.rs
Byron/The-Fat-Controller
ec4b0c0f8e3c290f514b1732f06d72a0df707fdb
use crate::Key; use unicode_segmentation::UnicodeSegmentation; use core_graphics::event::{CGEvent, CGEventTapLocation}; use super::{ffi, Context, Error, SHIFT_BIT, OPTION_BIT}; enum GroupedKey { CapsLock, Modifier(u8, u32), Regular(u8), Media(u8), } fn to_key_code(key: Key) -> GroupedKey { use ffi...
use crate::Key; use unicode_segmentation::UnicodeSegmentation; use core_graphics::event::{CGEvent, CGEventTapLocation}; use super::{ffi, Context, Error, SHIFT_BIT, OPTION_BIT}; enum GroupedKey { CapsLock, Modifier(u8, u32), Regular(u8), Media(u8), } fn to_key_code(key: Key) -> GroupedKey { use ffi...
}
let event = match CGEvent::new_keyboard_event(self.event_source.clone(), 0, true) { Ok(e) => e, Err(()) => return Err(Error::Unknown), }; for grapheme in s.graphemes(true) { event.set_string(grapheme); event.post(CGEventTapLocation::HID); } ...
function_block-function_prefix_line
[]
Rust
src/bin/urllog-search.rs
sjm42/urlharvest-rs
823a7e757ec87af680b5ec7c3ee85eb62393ebae
use futures::TryStreamExt; use handlebars::{to_json, Handlebars}; use log::*; use regex::Regex; use serde::Deserialize; use sqlx::{Connection, SqliteConnection}; use std::fmt::Write as _; use std::net::SocketAddr; use structopt::StructOpt; use warp::Filter; use urlharvest::*; const INDEX_NAME: &str = "index"; cons...
use futures::TryStreamExt; use handlebars::{to_json, Handlebars}; use log::*; use regex::Regex; use serde::Deserialize; use sqlx::{Connection, SqliteConnection}; use std::fmt::Write as _; use std::net::SocketAddr; use structopt::StructOpt; use warp::Filter; use urlharvest::*; const INDEX_NAME: &str = "index"; cons...
const SQL_SEARCH: &str = "select min(u.id) as id, min(seen) as seen_first, max(seen) as seen_last, count(seen) as seen_count, \ group_concat(channel, ' ') as channels, group_concat(nick, ' ') as nicks, \ url, url_meta.title from url as u \ inner join url_meta on url_meta.url_id = u.id \ where lower(ch...
warp::http::Response::builder() .header("cache-control", "no-store") .header("content-type", resp_type.as_ref()) .body(resp_body.as_ref().into()) }
function_block-function_prefix_line
[ { "content": "pub fn ts_fmt<S: AsRef<str>>(fmt: S, ts: i64) -> String {\n\n Local\n\n .from_utc_datetime(&NaiveDateTime::from_timestamp(ts, 0))\n\n .format(fmt.as_ref())\n\n .to_string()\n\n}\n\n\n", "file_path": "src/str_util.rs", "rank": 0, "score": 92513.80934181523 }, ...
Rust
src/x11/glx.rs
yoanlcq/dmc
cf9b0b64e1f9fe2272007013fab21fcc56cbf65d
use std::ffi::{CStr, CString}; use std::os::raw::c_int; use std::mem; use super::x11::xlib as x; use super::x11::glx::*; use super::x11::glx::arb::*; use super::missing_bits::glx::*; use super::X11SharedContext; use gl::{GLPixelFormatSettings, GLContextSettings, GLVariant, GLContextResetNotificationStrategy, GLVersion,...
use std::ffi::{CStr, CString}; use std::os::raw::c_int; use std::mem; use super::x11::xlib as x; use super::x11::glx::*; use super::x11::glx::arb::*; use super::missing_bits::glx::*; use super::X11SharedContext; use gl::{GLPixelFormatSettings, GLContextSettings, GLVariant, GLContextResetNotificationStrategy, GLVersion,...
pub fn gen_arb_attribs(&self, settings: &GLContextSettings) -> [c_int; 11] { let &GLContextSettings { version, robust_access, debug, forward_compatible, profile, .. } = settings; #[allow(non_snake_case)] let &GlxExt { GLX_ARB_create_context_profi...
t, GLX_ACCUM_BLUE_SIZE, accum_blue_bits as c_int, GLX_ACCUM_ALPHA_SIZE, accum_alpha_bits as c_int, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, GLX_X_RENDERABLE, x::True, GLX_CONFI...
function_block-function_prefixed
[ { "content": "pub fn set<T: PropElement>(x_display: *mut x::Display, x_window: x::Window, prop: x::Atom, prop_type: PropType, mode: PropMode, data: &[T]) -> Result<()> {\n\n unsafe {\n\n xlib_error::sync_catch(x_display, || {\n\n x::XChangeProperty(x_display, x_window, prop, prop_type as _,...
Rust
healthyrig/src/main.rs
ktsol/pirig
a00833884394dffedf2b20da14c348113439bdc6
extern crate getopts; #[macro_use] extern crate serde_derive; extern crate tiny_http; extern crate toml; use getopts::Options; use tiny_http::{Server, Response}; use std::env; use std::fs::{read_dir, File}; use std::io::Read; use std::path::PathBuf; use std::process::Command; pub static HWDIR: &'static str = "/sys/c...
extern crate getopts; #[macro_use] extern crate serde_derive; extern crate tiny_http; extern crate toml; use getopts::Options; use tiny_http::{Server, Response}; use std::env; use std::fs::{read_dir, File}; use std::io::Read; use std::path::PathBuf; use std::process::Command; pub static HWDIR: &'static str = "/sys/c...
er(|r| r.is_ok()) .map(|r| r.unwrap() / 1000) .collect() } fn check_nw_temp() -> Vec<i32> { let mut res: Vec<i32> = Vec::new(); for gpu_id in 0..get_nv_gpu_count() { let rt = get_nv_temp(gpu_id); if rt.is_ok() { res.push(rt.unwrap()); } } res } fn ge...
(&r).unwrap()); return; } if let Some(p) = matches.opt_str("p").and_then(|v| v.parse::<usize>().ok()) { run_server(p, cfg); } } fn check_all(cfg: &Config) -> CheckResult { let temps = check_temp(); CheckResult { hostname: check_hostname(), service: check_servi...
random
[ { "content": "pub fn read_file(p: &PathBuf) -> Result<String, Error> {\n\n File::open(p).and_then(|mut f| {\n\n let mut s = String::new();\n\n f.read_to_string(&mut s).map(|_| s)\n\n })\n\n}\n\n\n", "file_path": "thorinpi/src/main.rs", "rank": 5, "score": 118564.54196593085 }, ...
Rust
src/adc14/adc14ifgr1.rs
klanmiko/msp432p401r
f21410cf79fa268fe78714b7e8a367c10374055a
#[doc = "Reader of register ADC14IFGR1"] pub type R = crate::R<u32, super::ADC14IFGR1>; #[doc = "Interrupt flag for ADC14MEMx within comparator window\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADC14INIFG_A { #[doc = "0: No interrupt pending"] ADC14INIFG_0 = 0, #[doc = "1: Inte...
#[doc = "Reader of register ADC14IFGR1"] pub type R = crate::R<u32, super::ADC14IFGR1>; #[doc = "Interrupt flag for ADC14MEMx within comparator window\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADC14INIFG_A { #[doc = "0: No interrupt pending"] ADC14INIFG_0 = 0, #[doc = "1: Inte...
#[doc = "Checks if the value of the field is `ADC14HIIFG_0`"] #[inline(always)] pub fn is_adc14hiifg_0(&self) -> bool { *self == ADC14HIIFG_A::ADC14HIIFG_0 } #[doc = "Checks if the value of the field is `ADC14HIIFG_1`"] #[inline(always)] pub fn is_adc14hiifg_1(&self) -> bool { ...
pub fn variant(&self) -> ADC14HIIFG_A { match self.bits { false => ADC14HIIFG_A::ADC14HIIFG_0, true => ADC14HIIFG_A::ADC14HIIFG_1, } }
function_block-full_function
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
mem4/src/divgridcontainer.rs
bestia-dev/mem4_game
fa6b702dbf840abefe8dbfa0f1aceb608a20143e
use crate::gamedata::{CardStatusCardFace, Size2d}; use crate::rootrenderingcomponent::RootRenderingComponent; use crate::statusplaybefore1stcard; use crate::statusplaybefore2ndcard; use crate::logmod; use crate::rootrenderingcomponent; use conv::{ConvUtil}; use dodrio::bumpalo::{self, Bump}; use dodrio::Node; use me...
use crate::gamedata::{CardStatusCardFace, Size2d}; use crate::rootrenderingcomponent::RootRenderingComponent; use crate::statusplaybefore1stcard; use crate::statusplaybefore2ndcard; use crate::logmod; use crate::rootrenderingcomponent; use conv::{ConvUtil}; use dodrio::bumpalo::{self, Bump}; use dodrio::Node; use me...
} pub fn grid_width() -> usize { let usize_inner_width = rootrenderingcomponent::usize_window_inner_width(); let grid_width: usize; if usize_inner_width < 300 { grid_width = 300; } else if usize_inner_width > 600 { grid_width = 600; } else { grid_width = usiz...
if game_status.as_ref() == GameStatus::PlayBefore2ndCard.as_ref() { statusplaybefore2ndcard::on_click_2nd_card(rrc, this_click_card_index) } else { panic!("this else must never be reached!"); }
if_condition
[ { "content": "///on click\n\npub fn on_click_2nd_card(rrc: &mut RootRenderingComponent, this_click_card_index: usize) {\n\n logmod::log1_str(\"on_click_2nd_card\");\n\n rrc.game_data.card_index_of_second_click = this_click_card_index;\n\n card_click_2nd_card(rrc);\n\n}\n\n\n", "file_path": "mem4/sr...
Rust
jakescript/src/interpreter/vm.rs
jakemarsden/JakeScript
7ac9bd6f2e1c822d139bdaab2950736da387fa88
use crate::interpreter::heap::Heap; use crate::interpreter::stack::CallStack; use crate::interpreter::value::Value; use std::assert_matches::assert_matches; use std::mem; #[derive(Default)] pub struct Vm { execution_state: ExecutionState, hidden_exception: Option<Value>, heap: Heap, stack: CallStack, }...
use crate::interpreter::heap::Heap; use crate::interpreter::stack::CallStack; use crate::interpreter::value::Value; use std::assert_matches::assert_matches; use std::mem; #[derive(Default)] pub struct Vm { execution_state: ExecutionState, hidden_exception: Option<Value>, heap: Heap, stack: CallStack, }...
} } pub fn restore_hidden_exception(&mut self) { if let Some(exception) = self.hidden_exception.take() { if !matches!(self.execution_state(), ExecutionState::Exception(..)) { self.set_execution_state(ExecutionState::Exception(exception)); ...
if let ExecutionState::Exception(ex) = self.reset_execution_state() { if self.hidden_exception.is_none() { self.hidden_exception = Some(ex); } } else { unreachable!(); }
if_condition
[ { "content": "pub fn init() {\n\n static INIT: sync::Once = sync::Once::new();\n\n INIT.call_once(|| {\n\n #[cfg(windows)]\n\n ansi_term::enable_ansi_support().ok();\n\n });\n\n}\n\n\n", "file_path": "jakescript/tests/harness/mod.rs", "rank": 0, "score": 129419.79569738172 }...
Rust
source/rust_verify/example/state_machines/tutorial/unverified_fifo.rs
secure-foundations/verus
c4477686a329c29ae4bd51dc9e19a38480f35081
use std::cell::UnsafeCell; use std::mem::MaybeUninit; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; struct Queue<T> { buffer: Vec<UnsafeCell<MaybeUninit<T>>>, head: AtomicU64, tail: AtomicU64, } pub struct Producer<T> { queue: Arc<Queue<T>>, tail: usize, } pub struct Consume...
use std::cell::UnsafeCell; use std::mem::MaybeUninit; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; struct Queue<T> { buffer: Vec<UnsafeCell<MaybeUninit<T>>>, head: AtomicU64, tail: AtomicU64, } pub struct Producer<T> { queue: Arc<Queue<T>>, tail: usize, } pub struct Consume...
safe { (*self.queue.buffer[self.tail].get()).write(t); } self.queue.tail.store(next_tail as u64, Ordering::SeqCst); self.tail = next_tail; return; } } } } impl<T> Consumer<T> ...
let len = self.queue.buffer.len(); let next_tail = if self.tail + 1 == len { 0 } else { self.tail + 1 }; let head = self.queue.head.load(Ordering::SeqCst); if head != next_t...
function_block-random_span
[ { "content": "pub fn replace_self_sm(sm: &mut SM) {\n\n let path = get_self_ty_turbofish_path(&*sm);\n\n for trans in sm.transitions.iter_mut() {\n\n match trans {\n\n Transition { name: _, kind: _, params, body } => {\n\n for param in params.iter_mut() {\n\n ...
Rust
src/display.rs
alonblade/snakeos
8a62357eab51f7ff18ecd999999fb90f581e6652
use bootloader::boot_info::{FrameBufferInfo, PixelFormat}; use core::{ fmt::{self, Write}, ptr, }; use font8x8::UnicodeFonts; const LINE_SPACING: usize = 2; pub const BLOCK_SIZE: usize = 8; #[derive(Debug, PartialEq, Clone, Copy)] pub enum Color { Black, White, Grey, Red, Green, Yello...
use bootloader::boot_info::{FrameBufferInfo, PixelFormat}; use core::{ fmt::{self, Write}, ptr, }; use font8x8::UnicodeFonts; const LINE_SPACING: usize = 2; pub const BLOCK_SIZE: usize = 8; #[derive(Debug, PartialEq, Clone, Copy)] pub enum Color { Black, White, Grey, Red, Green, Yello...
pub fn set_framebuffer(&mut self, framebuffer: &'static mut bootloader::boot_info::FrameBuffer) { self.info = Some(framebuffer.info().clone()); self.framebuffer = Some(framebuffer.buffer_mut()); } pub fn set_xy(&mut self, x: usize, y: usize) { self.x_pos = x; self.y_po...
pub fn new() -> Self { Display{ framebuffer: None, info: None, x_pos: 0, y_pos: 0, color: Color::Green, background_color: Color::Black, } }
function_block-full_function
[ { "content": "#[doc(hidden)]\n\npub fn _print(args: ::core::fmt::Arguments) {\n\n use core::fmt::Write;\n\n use x86_64::instructions::interrupts;\n\n\n\n interrupts::without_interrupts(|| {\n\n SERIAL1\n\n .lock()\n\n .write_fmt(args)\n\n .expect(\"Printing to se...
Rust
src/lib.rs
kpcyrd/ioprio-rs
c66d87b52489697bd35959c641e3cb8db04b6c5d
#![deny(missing_docs)] use std::cmp::Ordering; use std::convert::TryInto; use nix::errno::Errno; use nix::unistd::{Pid, Uid}; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Priority { inner: u16, } impl PartialOrd for Priority { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { ...
#![deny(missing_docs)] use std::cmp::Ordering; use std::convert::TryInto; use nix::errno::Errno; use nix::unistd::{Pid, Uid}; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Priority { inner: u16, } impl PartialOrd for Priority { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { ...
pub trait Sealed {} } impl private::Sealed for iou_::SQE<'_> {} pub trait SqeExt { fn priority(&self) -> Priority; fn set_priority(&mut self, priority: Priority); } impl SqeExt for iou_::SQE<'_> { fn priority(&self) -> Priority { ...
t fn lowest() -> Self { Self { inner: 7 } } pub const fn from_level(level: u8) -> Option<Self> { if level < 8 { Some(Self { inner: level }) } else { None } } pub const fn level(self) -> u8 { self.inner } fn data(...
random
[ { "content": "# `ioprio-rs`\n\n\n\nA crate for managing Linux I/O priorities, either globally for one or more\n\nprocesses, or in advanced interfaces such as io_uring and Linux AIO. It allows\n\nsetting the `ioprio` field of io_uring SQE:s directly when the `iou` Cargo\n\nfeature is enabled.\n", "file_path"...
Rust
14-cubecontroller/src/bridge.rs
Logenleedev/Toio_Control
f0cf7cea2e1db462ad0bfb79c6e9bbee7cbbbff9
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use crossbeam_channel::{Receiver, Sender}; use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr, TcpStream}; use std::{thread, time}; #[derive(Debug, Clone, Copy, PartialEq)] pub enum BridgeMode { Bridge, Scanner, Unknown, } #[de...
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use crossbeam_channel::{Receiver, Sender}; use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr, TcpStream}; use std::{thread, time}; #[derive(Debug, Clone, Copy, PartialEq)] pub enum BridgeMode { Bridge, Scanner, Unknown, } #[de...
, "battery" => Message::BatteryInfo(address, payload[0]), &_ => Message::Unknown, }; self.to_manager.send(message).unwrap(); } Ok(()) } fn send_message(&mut self, message: Message) { match message { Messa...
match payload[0] { 1 => { let mut p = &payload[1..]; let x = p.read_u16::<LittleEndian>().unwrap(); let y = p.read_u16::<LittleEndian>().unwrap(); let a = p.read_u16::<LittleEndian>().unwrap(); ...
if_condition
[ { "content": "class Address {\n\n public:\n\n static String ToString(ble_gap_addr_t &addr) {\n\n char tmp[18] = {0};\n\n sprintf(tmp, \"%02x:%02x:%02x:%02x:%02x:%02x\", addr.addr[5], addr.addr[4], addr.addr[3], addr.addr[2], addr.addr[1], addr.addr[0]);\n\n return String(tmp);\n\n }...
Rust
src/engine.rs
jcdyer/tablespanner
b6f0203f5e265a954604fa0f115535cbe6efbf95
use std::collections::HashMap; use std::hash::Hash; #[derive(Copy, Clone, PartialEq, Eq)] pub(crate) struct Span { rows: usize, cols: usize, } impl Span { pub(crate) fn new(rows: usize, cols: usize) -> Span { if rows == 0 { panic!("Error constructing Span. Ze...
use std::collections::HashMap; use std::hash::Hash; #[derive(Copy, Clone, PartialEq, Eq)] pub(crate) struct Span { rows: usize, cols: usize, } impl Span { pub(crate) fn new(rows: usize, cols: usize) -> Span { if rows == 0 { panic!("Error constructing Span. Ze...
} } } fn spanned(&self, col_index: usize) -> bool { self.0.get(&col_index).unwrap_or(&0) > &0 } fn max_spanned(&self) -> Option<usize> { self.0.keys().max().cloned() } } fn cell_fits(col: usize, col_count: usize, active_row_spans: &Row...
if *value > 1 { *value -= 1; } else { self.0.remove(&key); }
if_condition
[ { "content": "/// IntoIterator where Item=(x, y) will work with a HashMap, a BTreeMap, or a Vec.\n\n///\n\n/// # Panics\n\n///\n\n/// This panics if any of the usize values passed to `Span::new` are zero.\n\nfn simpledata_to_spaninfo<S, T>(data: S) -> HashMap<T, Span>\n\nwhere\n\n S: IntoIterator<Item = (T, ...
Rust
src/analysis/trg.rs
vjn0/llhd
b06135a5b351ec6ae4483d03d84fb20c480bd8c3
use crate::ir::prelude::*; use std::{ collections::{HashMap, HashSet, VecDeque}, ops::Index, }; #[derive(Debug)] pub struct TemporalRegionGraph { blocks: HashMap<Block, TemporalRegion>, regions: Vec<TemporalRegionData>, } impl TemporalRegionGraph { #[deprecated(since = "0.13.0", n...
use crate::ir::prelude::*; use std::{ collections::{HashMap, HashSet, VecDeque}, ops::Index, }; #[derive(Debug)] pub struct TemporalRegionGraph { blocks: HashMap<Block, TemporalRegion>, regions: Vec<TemporalRegionData>, } impl TemporalRegionGraph { #[deprecated(since = "0.13.0", n...
pub fn is_head(&self, bb: Block) -> bool { self[self[bb]].is_head(bb) } pub fn is_tail(&self, bb: Block) -> bool { self[self[bb]].is_tail(bb) } pub fn regions(&self) -> impl Iterator<Item = &TemporalRegionData> { self.regions.iter() } } impl Index<Temp...
while let Some(bb) = todo.pop_front() { let tr = blocks[&bb]; let term = unit.terminator(bb); if unit[term].opcode().is_temporal() { breaks.push(term); tail_blocks.insert(bb); continue; } for &target...
function_block-function_prefix_line
[]
Rust
src/reader.rs
estebank/galvanize
a9624a317d8664dced737b203d2712f4127eb90e
use helpers::{hash, unpack}; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use types::{Error, Result}; use writer::Writer; #[derive(Debug)] pub struct Reader<'a, F: Read + Seek + 'a> { file: &'a mut F, index: Vec<(u32, u32)>, table_start: usize, length: usize, } pub stru...
use helpers::{hash, unpack}; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use types::{Error, Result}; use writer::Writer; #[derive(Debug)] pub struct Reader<'a, F: Read + Seek + 'a> { file: &'a mut F, index: Vec<(u32, u32)>, table_start: usize, length: usize, } pub stru...
et _ = chunk.read_to_end(&mut val); } Some((key, val)) } } impl<'a, 'file: 'a, F: Read + Seek + 'file> IntoIterator for &'a mut Reader<'file, F> { type Item = (Vec<u8>, Vec<u8>); type IntoIter = ItemIterator<'a, 'file, F>; fn into_iter(self) -> Self::IntoIter { ...
u64 { return None; } } Err(_) => return None, } let mut buf: [u8; 8] = [0; 8]; { let mut chunk = self.reader.file.take(8); let _ = chunk.read(&mut buf); } let k = unpack([buf[0], buf[1], ...
function_block-random_span
[ { "content": "fn make_writer<'a, F: Write + Read + Seek>(file: &'a mut F, items: &[(&[u8], &[u8])]) -> Writer<'a, F> {\n\n // This is how you write into a CDB.\n\n let mut cdb_writer = Writer::new(file).ok().unwrap();\n\n\n\n for item in items.iter() {\n\n // Inserting returns a success or error...
Rust
src/macos/mod.rs
Byron/The-Fat-Controller
ec4b0c0f8e3c290f514b1732f06d72a0df707fdb
mod ffi; mod error; mod keyboard; mod mouse; mod screen; use error::PlatformError; type Error = crate::GenericError<PlatformError>; const SHIFT_BIT: u32 = 0; const OPTION_BIT: u32 = 1; #[derive(Copy, Clone)] struct KeyInfo { key_code: u8, modifiers: u8, } pub struct Context { hid_connect: ffi::io_connec...
mod ffi; mod error; mod keyboard; mod mouse; mod screen; use error::PlatformError; type Error = crate::GenericError<PlatformError>; const SHIFT_BIT: u32 = 0; const OPTION_BIT: u32 = 1; #[derive(Copy, Clone)] struct KeyInfo { key_code: u8, modifiers: u8, } pub struct Context { hid_connect: ffi::io_connec...
impl Context { pub fn new() -> Result<Self, Error> { use core_graphics::event_source::{CGEventSource, CGEventSourceStateID}; let key_map = create_key_map()?; let event_source = match CGEventSource::new(CGEventSourceStateID::Private) { Ok(s) => s, Err(()) => return...
d); } return Err(Error::Unknown); } let string_utf16 = &string[..length as usize]; let string_utf32 = std::char::decode_utf16(string_utf16.iter().cloned()) .collect::<Vec<_>>(); if string_utf32.len() == 1 { ...
function_block-function_prefixed
[]
Rust
src/editorview.rs
proegssilb/scrappy
fadaf9ff96b18957ed14b16b0598bf06ecd5aafd
use fltk::{ app, button, dialog, enums::{CallbackTrigger, Color, Event, Font, Shortcut}, input, menu, prelude::*, text, window, }; use std::{fs, path}; #[derive(Copy, Clone)] pub enum Message { Changed, New, Open, Save, SaveAs, Quit, Cut, Copy, Paste, About, ...
use fltk::{ app, button, dialog, enums::{CallbackTrigger, Color, Event, Font, Shortcut}, input, menu, prelude::*, text, window, }; use std::{fs, path}; #[derive(Copy, Clone)] pub enum Message { Changed, New, Open, Save, SaveAs, Quit, Cut, Copy, Paste, About, ...
pub fn filename(&self) -> String { self.filename.clone() } pub fn set_filename(&mut self, name: &str) { self.filename = String::from(name); } pub fn initialize(&mut self) { self.initialize_menu(); self.initialize_editor(); self.window.make_resizable(true);...
pub fn new() -> EditorView { let (s, r) = app::channel::<Message>(); let wind = window::Window::default() .with_size(800, 600) .center_screen() .with_label("Scrappy"); let mut editor = text::TextEditor::new(5, 40, wind.width() - 10, wind.height() - 45, ""); ...
function_block-full_function
[ { "content": "#![windows_subsystem = \"windows\"]\n\n\n\nuse fltk::app::*;\n\n\n\nmod editorview;\n\n\n\nuse editorview::EditorView;\n\n\n", "file_path": "src/main.rs", "rank": 13, "score": 10.439156730067529 }, { "content": "# scrappy\n\n\n\nA small, crappy text editor. Maybe it'll grow up ...
Rust
src/os/redox.rs
planet-s/gdbserver
4839ddbcef78209cd435a3689fa392debb259106
use super::{Target, Registers}; use crate::Result; use std::{ cell::{Cell, RefCell}, fs, io, mem, os::unix::ffi::OsStrExt, }; use gdb_remote_protocol::{Error, StopReason}; use log::error; use strace::{EventData, Flags, Tracer}; use syscall::flag::*; pub struct Os { pid: usize, last_status...
use super::{Target, Registers}; use crate::Result; use std::{ cell::{Cell, RefCell}, fs, io, mem, os::unix::ffi::OsStrExt, }; use gdb_remote_protocol::{Error, StopReason}; use log::error; use strace::{EventData, Flags, Tracer}; use syscall::flag::*; pub struct Os { pid: usize, last_status...
n pid(&self) -> u32 { return self.pid as _; } fn getregs(&self) -> Result<Registers> { let mut tracer = self.tracer.borrow_mut(); let int = e!(tracer.regs.get_int()).0; let float = e!(tracer.regs.get_float()).0; let mut registers = Registers::default(); register...
}, Err(err) => e!(Err(err)), } } } impl Target for Os { fn new(program: String, args: Vec<String>) -> Result<Self, Box<dyn std::error::Error>> { unsafe { let pid = e!(syscall::clone(CloneFlags::empty())); if pid == 0 { le...
random
[ { "content": "fn getmem<G, E>(mut src: usize, dest: &mut [u8], mut get: G) -> Result<usize, E>\n\nwhere\n\n G: FnMut(usize) -> Result<usize, E>,\n\n{\n\n for chunk in dest.chunks_mut(mem::size_of::<usize>()) {\n\n let bytes = get(src)?.to_ne_bytes();\n\n chunk.copy_from_slice(&bytes[..chunk....
Rust
cli/pg_datanymizer/src/options.rs
janmeier/datanymizer
84772997863aa990616aa4c9b5d9e7610612c7ff
use anyhow::{anyhow, Result}; use structopt::StructOpt; use url::Url; #[derive(StructOpt, Debug, Clone)] #[structopt(name = "pg_datanymizer")] pub struct Options { #[structopt(name = "DBNAME")] database: String, #[structopt( short, long, help = "Path to config file", defaul...
use anyhow::{anyhow, Result}; use structopt::StructOpt; use url::Url; #[derive(StructOpt, Debug, Clone)] #[structopt(name = "pg_datanymizer")] pub struct Options { #[structopt(name = "DBNAME")] database: String, #[structopt( short, long, help = "Path to config file", defaul...
} #[cfg(test)] mod tests { use super::*; #[test] fn parse_empty_config() { let cfg = Options { database: "postgres://hostname/test".to_string(), config: "./config.yml".to_string(), file: None, db_name: "test".to_string(), host: "localhos...
fn build_url(&self, override_db_name: Option<String>) -> Result<Url> { let db_name = override_db_name.unwrap_or_else(|| self.db_name.clone()); if db_name.is_empty() { return Err(anyhow!("No one database passed")); } let mut url = Url::parse(format!("postgres://{}", self.host...
function_block-full_function
[ { "content": "pub fn deserialize_phone_format<'de, D>(deserializer: D) -> Result<Option<PhoneFormat>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let s: Option<String> = Option::deserialize(deserializer)?;\n\n if let Some(s) = s {\n\n return Ok(Some(PhoneFormat::from_format(s)));\n\n ...
Rust
src/padding.rs
SalusaSecondus/CryptoPals-Rust
19968c5d4f21780a09ff56eb89aabfe7b89bbb64
use anyhow::{bail, ensure, Result}; use rand::{distributions::Uniform, Rng}; use rand_core::OsRng; pub enum Padding { Pkcs1PaddingSigning(u64), Pkcs1PaddingEncryption(u64), Pkcs7Padding(usize), } impl Padding { pub fn pad(&self, data: &[u8]) -> Result<Vec<u8>> { match self { Padding...
use anyhow::{bail, ensure, Result}; use rand::{distributions::Uniform, Rng}; use rand_core::OsRng; pub enum Padding { Pkcs1PaddingSigning(u64), Pkcs1PaddingEncryption(u64), Pkcs7Padding(usize), } impl Padding { pub fn pad(&self, data: &[u8]) -> Result<Vec<u8>> { match self { Padding...
#[cfg(test)] mod tests { use super::Padding; use anyhow::Result; use rand::RngCore; use rand_core::OsRng; #[test] fn challenge_9() -> Result<()> { let input = b"YELLOW SUBMARINE"; let expected = b"YELLOW SUBMARINE\x04\x04\x04\x04"; let padded = Padding::Pkcs7Padding(20...
pkcs1_sign_unpad(data: &[u8], padding_type: u8, bit_length: u64) -> Result<Vec<u8>> { let em_len: usize = ((bit_length + 7) / 8) as usize; let base_index = if data.len() == em_len { ensure!(data[0] == 0, "Invalid first byte"); 1 } else if data.len() == em_len - 1 { 0 } else { ...
random
[ { "content": "pub fn rsa_pkcs1_15_sign<H, K>(key: &K, data: &[u8]) -> Result<Vec<u8>>\n\nwhere\n\n K: RsaPrivateKey,\n\n H: Digest + DigestOneShot,\n\n{\n\n let keylength = key.modulus().bits();\n\n\n\n let asn1_struct = rsa_pkcs1_15_generate_asn1_struct::<H>(data)?;\n\n let padded = Padding::Pkc...
Rust
TuringDB/src/t_engine/engine.rs
charleschege/TuringDB
f884bdf1985fa6bac72c4ff6883e10b3278f18c3
use crate::{ Document, OpsOutcome, RepoPath, TuringDB, TuringDBDocumentOps, TuringDBFieldOps, TuringDBOps, TuringDbError, TuringResult, }; use anyhow::Result; use async_fs::{self, DirBuilder, ReadDir}; use async_lock::Mutex; use camino::{Utf8Path, Utf8PathBuf}; use dashmap::DashMap; use futures_lite::stream::St...
use crate::{ Document, OpsOutcome, RepoPath, TuringDB, TuringDBDocumentOps, TuringDBFieldOps, TuringDBOps, TuringDbError, TuringResult, }; use anyhow::Result; use async_fs::{self, DirBuilder, ReadDir}; use async_lock::Mutex; use camino::{Utf8Path, Utf8PathBuf}; use dashmap::DashMap; use futures_lite::stream::St...
pub async fn db_create(&mut self, ops: TuringDBOps) -> TuringResult<OpsOutcome> { let db_path = ops.get_db_name(); let db = TuringDB::new(); let dbop = db.db_create(&self.repo_dir, &db_path).await?; self.dbs.insert(db_path.into(), TuringDB::new()); Ok(dbop) } pu...
t<OpsOutcome> { let mut repo = async_fs::read_dir(&self.repo_dir).await?; while let Some(database_entry) = repo.try_next().await? { let database_name_raw = database_entry.file_name(); if database_entry.file_type().await?.is_dir() { let mut repo = async_fs::read_...
function_block-function_prefixed
[ { "content": "/// Converts a database operation from a header to `TuringOp` enum variant\n\npub fn to_op(value: &[u8]) -> TuringOp {\n\n match *value {\n\n [0x00] => TuringOp::RepoCreate,\n\n [0x01] => TuringOp::RepoDrop,\n\n [0x02] => TuringOp::DbCreate,\n\n [0x03] => TuringOp::D...
Rust
src/db.rs
bnclabs/ip-tools
05c7e7b7db30dced65ecd782d7971ffbc2951f33
use std::{borrow::Borrow, fmt, hash::Hash, ops::Bound}; #[allow(unused_imports)] use crate::data::{Diff, NoDiff}; use crate::{Error, LocalCborize}; pub trait BuildIndex<K, V, D, B> { type Err; fn build_index<I>( &mut self, iter: I, bitmap: B, seqno: ...
use std::{borrow::Borrow, fmt, hash::Hash, ops::Bound}; #[allow(unused_imports)] use crate::data::{Diff, NoDiff}; use crate::{Error, LocalCborize}; pub trait BuildIndex<K, V, D, B> { type Err; fn build_index<I>( &mut self, iter: I, bitmap: B, seqno: ...
pub fn merge(&self, other: &Self) -> Self where K: PartialEq + Clone, V: Clone + Diff<Delta = D>, D: Clone + From<V>, { if self.key != other.key { return self.clone(); } let mut values = self.to_values(); values.extend(other.to_values())...
pub fn contains(&self, other: &Self) -> bool where V: Clone + PartialEq + Diff<Delta = D>, D: Clone, { let values = self.to_values(); other.to_values().iter().all(|v| values.contains(v)) }
function_block-full_function
[ { "content": "/// Trait for diff-able values.\n\n///\n\n/// Version control is a necessary feature for non-destructive writes.\n\n/// Using this trait it is possible to generate concise older versions as\n\n/// deltas. Note that this version control follows centralized behavior, as\n\n/// apposed to distributed...
Rust
core/lib/circuit/benches/criterion/transfer.rs
euevew/zksync
0d8c7959fc2fbba3334dfda44bc9561237731e99
use crate::generate_accounts; use crate::utils::ZkSyncStateGenerator; use criterion::{black_box, criterion_group, Bencher, BenchmarkId, Criterion}; use num::BigUint; use zksync_circuit::witness::{utils::SigDataInput, Witness}; use zksync_crypto::franklin_crypto::bellman::pairing::bn256::Bn256; use zksync_types::{TokenI...
use crate::generate_accounts; use crate::utils::ZkSyncStateGenerator; use criterion::{black_box, criterion_group, Bencher, BenchmarkId, Criterion}; use num::BigUint; use zksync_circuit::witness::{utils::SigDataInput, Witness}; use zksync_crypto::franklin_crypto::bellman::pairing::bn256::Bn256; use zksync_types::{TokenI...
criterion_group!(transfer_benches, bench_transfer);
sfer get pubdata", transfer_get_pubdata); c.bench_function( "Transfer calculate operations", transfer_calculate_operations, ); }
function_block-function_prefixed
[ { "content": "/// Measures the time of close account apply tx\n\nfn close_account_apply_tx(b: &mut Bencher<'_>, number_of_accounts: &usize) {\n\n let accounts = generate_accounts(*number_of_accounts);\n\n let account = &accounts[0];\n\n let close_account_op = CloseOp {\n\n tx: account.zksync_acc...
Rust
src/errors.rs
mbenoukaiss/automate
4f1db11f2d6c405b2f8e97499983ba5bfee75d96
use std::{fmt, result}; use chrono::{NaiveDateTime, Local, DateTime, Utc}; #[derive(Debug)] pub enum Error { Gateway(String), Http(String), InvalidToken(TokenContext), NoPermission(TokenContext), RateLimited(RlContext), Json(JsonContext), Other(String), } #[derive(Debug)] pub struct TokenC...
use std::{fmt, result}; use chrono::{NaiveDateTime, Local, DateTime, Utc}; #[derive(Debug)] pub enum Error { Gateway(String), Http(String), InvalidToken(TokenContext), NoPermission(TokenContext), RateLimited(RlContext), Json(JsonContext), Other(String), } #[derive(Debug)] pub struct TokenC...
} impl<T: std::error::Error> From<T> for Error { fn from(err: T) -> Self { Error::new(err.to_string()) } }
Error::Json(s) => { #[cfg(feature = "backtrace")] write!(f, "{}\n{}", s.message, s.backtrace)?; #[cfg(not(feature = "backtrace"))] write!(f, "{}", s.message)?; Ok(()) }, Error::Other(s) => write!(f, "{}", s), } }
function_block-function_prefix_line
[ { "content": "/// Extends [Deref](std::ops::Deref) and [DerefMut](std::ops::DerefMut)\n\n/// on tuple struct of one element.\n\npub fn extend_with_deref(input: &ItemStruct, quote: &mut TokenStream2) -> Result<(), TokenStream> {\n\n let name = &input.ident;\n\n let (impl_generics, ty_generics, where_clause...
Rust
src/auth.rs
arthurbambou/sage_auth
533141aac07beb2a63aaa4a014f31d4ec201618d
use reqwest::{IntoUrl, StatusCode, Url}; use serde_derive::{Deserialize, Serialize}; use uuid::Uuid; use crate::consts::DEFAULT_SERVER; use crate::types::{Profile, User}; use crate::{Error, Result}; #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct AgentInfo<'a> { name: &'a str, version: i32, }...
use reqwest::{IntoUrl, StatusCode, Url}; use serde_derive::{Deserialize, Serialize}; use uuid::Uuid; use crate::consts::DEFAULT_SERVER; use crate::types::{Profile, User}; use crate::{Error, Result}; #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct AgentInfo<'a> { name: &'a str, version: i32, }...
n Err(Error::MissingField("password")); } if self.params.client_token.is_none() { self.params.client_token = Some(Uuid::new_v4()); } let client = reqwest::Client::new(); let response = client .post(self.server.join(self.endpoint)?) .json(&self...
eResponse> { if self.params.username.is_none() { return Err(Error::MissingField("username")); } if self.params.password.is_none() { retur
random
[ { "content": "/// Convert Mojang special key-value format to [HashMap]\n\n///\n\n/// Mojang account properties are given in the following format:\n\n///\n\n/// ```json\n\n/// [\n\n/// {\n\n/// \"name\": \"preferredLanguage\",\n\n/// \"value\": \"en\"\n\n/// },\n\n/// {\n\n/// ...
Rust
src/stream.rs
teymour-aldridge/sodium-rust
a3e17bae5d5b8807ee649b064c1fbc3257a8982c
use crate::cell::Cell; use crate::impl_::dep::Dep; use crate::impl_::stream::Stream as StreamImpl; use crate::impl_::lambda::IsLambda1; use crate::impl_::lambda::IsLambda2; use crate::impl_::lambda::IsLambda3; use crate::impl_::lambda::{lambda1, lambda2}; use crate::Lazy; use crate::listener::Listener; use crate::sodiu...
use crate::cell::Cell; use crate::impl_::dep::Dep; use crate::impl_::stream::Stream as StreamImpl; use crate::impl_::lambda::IsLambda1; use crate::impl_::lambda::IsLambda2; use crate::impl_::lambda::IsLambda3; use crate::impl_::lambda::{lambda1, lambda2}; use crate::Lazy; use crate::listener::Listener; use crate::sodiu...
let cc = cc.clone(); self.snapshot(cb, lambda2(move |a: &A, b: &B| f.call(a, b, &cc.sample()), deps)) } pub fn map<B:Send+Clone+'static,FN:IsLambda1<A,B>+Send+Sync+'static>(&self, f: FN) -> Stream<B> { Stream { impl_: self.impl_.map(f) } } pub fn map_to<B:Send+Sync+Clone+'stat...
if let Some(deps2) = f.deps_op() { deps = deps2.clone(); } else { deps = Vec::new(); }
if_condition
[ { "content": "pub fn lambda2<A,B,C,FN:FnMut(&A,&B)->C>(f: FN, deps: Vec<Dep>) -> Lambda<FN> {\n\n Lambda { f, deps }\n\n}\n\n\n", "file_path": "src/impl_/lambda.rs", "rank": 0, "score": 216730.23465108185 }, { "content": "pub fn lambda2_deps<A,B,C,FN:IsLambda2<A,B,C>>(f: &FN) -> Vec<Dep> ...
Rust
network-libp2p/src/message/dispatch.rs
terorie/nimiq-core-rs-albatross
56a214cd91d2230bc48693d0777cb5e88dd8a303
use std::{collections::HashMap, io::Cursor, sync::Arc}; use futures::{ channel::{mpsc, oneshot}, io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, WriteHalf}, lock::Mutex as AsyncMutex, task::{Context, Poll}, FutureExt, SinkExt, Stream, StreamExt, }; use parking_lot::Mutex; use beserial::Se...
use std::{collections::HashMap, io::Cursor, sync::Arc}; use futures::{ channel::{mpsc, oneshot}, io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, WriteHalf}, lock::Mutex as AsyncMutex, task::{Context, Poll}, FutureExt, SinkExt, Stream, StreamExt, }; use parking_lot::Mutex; use beserial::Se...
pub async fn send<M: Message>(&self, message: &M) -> Result<(), SerializingError> { let mut serialized = Vec::with_capacity(message.serialized_message_size()); message.serialize_message(&mut serialized)?; log::debug!("Sending message: {:?}", serialized); let mut outbound = self....
pub async fn close(&self) { log::debug!("Waiting for outbound lock..."); let mut outbound = self.outbound.lock().await; if let Some(mut outbound) = outbound.take() { log::debug!("Closing outbound..."); outbound.close().await.unwrap() } else { log::err...
function_block-full_function
[ { "content": "fn write_from_buf<'w, W>(inner: &mut W, buffer: &mut BytesMut, cx: &mut Context) -> Poll<Result<(), SerializingError>>\n\nwhere\n\n W: AsyncWrite + Unpin,\n\n{\n\n if buffer.remaining() > 0 {\n\n match Pin::new(inner).poll_write(cx, buffer.bytes()) {\n\n Poll::Ready(Ok(0)) ...
Rust
crates/rome_rowan/src/cursor/element.rs
RustPhilly/tools
a5c89104e6623b2eb51e2fc1881ddc551fde34d2
use crate::cursor::{SyntaxNode, SyntaxToken}; use crate::green::GreenElementRef; use crate::{NodeOrToken, RawSyntaxKind, TokenAtOffset}; use std::iter; use text_size::{TextRange, TextSize}; pub(crate) type SyntaxElement = NodeOrToken<SyntaxNode, SyntaxToken>; impl SyntaxElement { pub(super) fn new( elemen...
use crate::cursor::{SyntaxNode, SyntaxToken}; use crate::green::GreenElementRef; use crate::{NodeOrToken, RawSyntaxKind, TokenAtOffset}; use std::iter; use text_size::{TextRange, TextSize}; pub(crate) type SyntaxElement = NodeOrToken<SyntaxNode, SyntaxToken>; impl SyntaxElement { pub(super) fn new( elemen...
iter::successors(first, SyntaxNode::parent) } pub fn first_token(&self) -> Option<SyntaxToken> { match self { NodeOrToken::Node(it) => it.first_token(), NodeOrToken::Token(it) => Some(it.clone()), } } pub fn last_token(&self) -> Option<SyntaxToken> { ...
let first = match self { NodeOrToken::Node(it) => Some(it.clone()), NodeOrToken::Token(it) => it.parent(), };
assignment_statement
[ { "content": "#[inline]\n\npub fn comment(element: impl Into<FormatElement>) -> FormatElement {\n\n FormatElement::Comment(Box::new(element.into()))\n\n}\n\n\n\n/// Inserts a single space. Allows to separate different tokens.\n\n///\n\n/// ## Examples\n\n///\n\n/// ```\n\n/// use rome_formatter::{FormatOptio...
Rust
roller/src/lighting_engine/mod.rs
jacobh/roller
4640ac9e2feec6aa211ba0b47b77f287a439f67b
use chrono::Utc; use derive_more::Constructor; use rustc_hash::FxHashMap; use std::time::Instant; use roller_protocol::{ clock::{Clock, ClockEvent, Rate}, control::{InputEvent, NoteState}, fixture::FixtureGroupId, lighting_engine::FixtureGroupState, }; use crate::control::{ button::{ButtonGroup, B...
use chrono::Utc; use derive_more::Constructor; use rustc_hash::FxHashMap; use std::time::Instant; use roller_protocol::{ clock::{Clock, ClockEvent, Rate}, control::{InputEvent, NoteState}, fixture::FixtureGroupId, lighting_engine::FixtureGroupState, }; use crate::control::{ button::{ButtonGroup, B...
fn apply_event(&mut self, event: ControlEvent) { match (&self.control_mode, event) { (_, ControlEvent::UpdateControlMode(mode)) => { self.control_mode = mode; } (_, ControlEvent::UpdateMasterDimmer(dimmer)) => { self.master_dimmer...
f .control_mapping .faders .get(&fader_id) .map(|fader| fader.control_event(value)), InputEvent::ButtonPressed(location, coordinate) => self .control_mapping .find_button(location, coordinate) .an...
function_block-function_prefixed
[]
Rust
interp/src/main.rs
crystalhu26/calyx
a8bb4ed79c85fa37e696f558e59f31f84247e159
use calyx::{frontend, ir, pass_manager::PassManager, utils::OutputFile}; use interp::{ configuration, debugger::{source::SourceMap, Debugger}, environment::InterpreterState, errors::{InterpreterError, InterpreterResult}, interpreter::ComponentInterpreter, interpreter_ir as iir, }; use argh::Fro...
use calyx::{frontend, ir, pass_manager::PassManager, utils::OutputFile}; use interp::{ configuration, debugger::{source::SourceMap, Debugger}, environment::InterpreterState, errors::{InterpreterError, InterpreterResult}, interpreter::ComponentInterpreter, interpreter_ir as iir, }; use argh::Fro...
let ws = frontend::Workspace::construct(&opts.file, &opts.lib_path)?; let mut ctx = ir::from_ast::ast_to_ir(ws)?; let pm = PassManager::default_passes()?; if !opts.skip_verification { pm.execute_plan(&mut ctx, &["validate".to_string()], &[])?; } let entry_point = ctx.entrypoint;...
if config.allow_par_conflicts { warn!(log, "You have enabled Par conflicts. This is not recommended and is usually a bad idea") }
if_condition
[ { "content": "pub fn parse_command(input_str: &str) -> InterpreterResult<Command> {\n\n let inputs = CommandParser::parse(Rule::command, input_str)?;\n\n let input = inputs.single()?;\n\n Ok(CommandParser::command(input)?)\n\n}\n", "file_path": "interp/src/debugger/parser/command_parser.rs", "r...
Rust
src/cpu_hasher.rs
silverscania/engraver
de0fbe304e0ffc917fc9a7de0483513767f39815
use crate::poc_hashing::noncegen_rust; use libc::{c_void, size_t, uint64_t}; use std::slice::from_raw_parts_mut; use std::sync::mpsc::Sender; const NUM_SCOOPS: usize = 4096; const SCOOP_SIZE: usize = 64; const NONCE_SIZE: usize = (NUM_SCOOPS * SCOOP_SIZE); extern "C" { pub fn noncegen_sse2( cache: *mut c_...
use crate::poc_hashing::noncegen_rust; use libc::{c_void, size_t, uint64_t}; use std::slice::from_raw_parts_mut; use std::sync::mpsc::Sender; const NUM_SCOOPS: usize = 4096; const SCOOP_SIZE: usize = 64; const NONCE_SIZE: usize = (NUM_SCOOPS * SCOOP_SIZE); extern "C" { pub fn noncegen_sse2( cache: *mut c_...
if is_x86_feature_detected!("sse2") { let mut buf = vec![0; 32 * plotter::NONCE_SIZE as usize]; unsafe { plotter::init_shabal_sse2(); noncegen_sse2( buf.as_mut_ptr() as *mut c_void, 32, 0, ...
if is_x86_feature_detected!("avx") { let mut buf = vec![0; 32 * plotter::NONCE_SIZE as usize]; unsafe { plotter::init_shabal_avx(); noncegen_avx( buf.as_mut_ptr() as *mut c_void, 32, 0, ...
if_condition
[ { "content": "pub fn create_scheduler_thread(\n\n task: Arc<PlotterTask>,\n\n thread_pool: rayon::ThreadPool,\n\n mut nonces_hashed: u64,\n\n mut pb: Option<pbr::ProgressBar<pbr::Pipe>>,\n\n rx_empty_buffers: Receiver<Buffer>,\n\n tx_buffers_to_writer: Sender<Buffer>,\n\n simd_ext: String,\...
Rust
src/cli.rs
merfishtools/merfishtools
3a9d5e749a9f5d8df7a15936beb8cf34ff135bda
#![allow(non_snake_case)] use std; use std::collections; use std::io::prelude::*; use bio::stats::{LogProb, Prob}; use csv; use cue; use failure::Error; use itertools::Itertools; use regex::Regex; use crate::codebook; use crate::error_rates; use crate::io; use crate::io::merfishdata::{self, MerfishRecord, Reader};...
#![allow(non_snake_case)] use std; use std::collections; use std::io::prelude::*; use bio::stats::{LogProb, Prob}; use csv; use cue; use failure::Error; use itertools::Itertools; use regex::Regex; use crate::codebook; use crate::error_rates; use crate::io; use crate::io::merfishdata::{self, MerfishRecord, Reader};...
pub fn gen_codebook( words: &[codebook::Word], not_expressed_pattern: Option<&str>, ) -> Result<(), Error> { let not_expressed_re = if not_expressed_pattern.is_some() { Some(Regex::new(not_expressed_pattern.unwrap())?) } else { None }; let stdin = std::io::stdin(); let mut...
iter() .map(|&(_, ref a)| a.differential_expression_pep), ).collect_vec(); for (i, ((feature, estimate), fd)) in estimates.into_iter().zip(expected_fds).enumerate() { let fdr = LogProb(*fd - (i as f64 + 1.0).ln()); est_writer.write( &feature, estimate.differen...
function_block-function_prefix_line
[ { "content": "/// Calculate CDF of expression.\n\n///\n\n/// Returns a tuple of CDF and the MAP estimate.\n\npub fn cdf(feature: FeatureID, model: &mut model::readout::JointModel) -> (CDF, u32) {\n\n let (xmin, xmax) = model.window(feature);\n\n let likelihoods = (xmin..xmax + 1)\n\n .map(|x| model...
Rust
src/lib.rs
andrebsguedes/wireguard-proxy
c8497a6188abdae4cfbcb8bdbf4eec0ffc4250c0
use std::net::{TcpStream, UdpSocket}; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; mod error; use error::Result; fn arg_to_env(arg: &str) -> Option<String> { if !arg.starts_with("--") { return None; } let env = "WGP_".to_owned(); let mut env = env + &arg.trim_matches('-'...
use std::net::{TcpStream, UdpSocket}; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; mod error; use error::Result; fn arg_to_env(arg: &str) -> Option<String> { if !arg.starts_with("--") { return None; } let env = "WGP_".to_owned(); let mut env = env + &arg.trim_matches('-'...
socket_timeout: match secs { 0 => None, x => Some(Duration::from_secs(x)), }, }); ProxyServer { tcp_host, client_handler, } } } impl ProxyServerClientHandler { fn udp_bind(&self) -> Result<UdpSocket> { ...
cs: u64) -> ProxyClient { ProxyClient { udp_host, tcp_target, socket_timeout: match secs { 0 => None, x => Some(Duration::from_secs(x)), }, } } fn tcp_connect(&self) -> Result<TcpStream> { let tcp_stream = T...
random
[ { "content": "fn err() -> Error {\n\n Error::new(\"Error: compiled without TLS support\")\n\n}\n\n\n\npub struct TlsStream;\n\n\n\nimpl TlsStream {\n\n pub fn client(_hostname: Option<&str>, _pinnedpubkey: Option<&str>, _tcp_stream: TcpStream) -> Result<TlsStream> {\n\n Err(err())\n\n }\n\n}\n\n...
Rust
vendor/symphonia-bundle-mp3-0.2.0/src/header.rs
ritikmishra/babycat
ce21a5d07f3e0ce4d30b7109617ef48f29d350a8
use symphonia_core::errors::{Result, decode_error, unsupported_error}; use symphonia_core::io::ByteStream; use crate::common::*; static BIT_RATES_MPEG1_L1: [u32; 15] = [ 0, 32_000, 64_000, 96_000, 128_000, 160_000, 192_000, 224_000, 256_000, 288_000, 320_000, 352_000, 384_000, 416_000, 448_000, ]; st...
use symphonia_core::errors::{Result, decode_error, unsupported_error}; use symphonia_core::io::ByteStream; use crate::common::*; static BIT_RATES_MPEG1_L1: [u32; 15] = [ 0, 32_000, 64_000, 96_000, 128_000, 160_000, 192_000, 224_000, 256_000, 288_000, 320_000, 352_000, 384_000, 416_000, 448_000, ]; st...
ameHeader> { let version = match (header & 0x18_0000) >> 19 { 0b00 => MpegVersion::Mpeg2p5, 0b10 => MpegVersion::Mpeg2, 0b11 => MpegVersion::Mpeg1, _ => return decode_error("invalid MPEG version"), }; let layer = match (header & 0x6_000...
t<u32> { let mut sync = 0u32; while (sync & 0xffe0_0000) != 0xffe0_0000 { sync = (sync << 8) | u32::from(reader.read_u8()?); } Ok(sync) } pub fn parse_frame_header(header: u32) -> Result<Fr
random
[ { "content": "pub fn milliseconds_to_frames(frame_rate_hz: u32, duration_milliseconds: u64) -> u64 {\n\n (duration_milliseconds * frame_rate_hz as u64) / 1000\n\n}\n", "file_path": "src/backend/common.rs", "rank": 0, "score": 110395.55709234043 }, { "content": "pub fn resample(\n\n inp...