lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/geo_types.rs
x4d3/proj
d1ad05bb2c108090d10458252af1f4ceb4d08383
use crate::{Proj, ProjError}; use geo_types; impl<T: crate::proj::CoordinateType> crate::Coord<T> for geo_types::Coordinate<T> { fn x(&self) -> T { self.x } fn y(&self) -> T { self.y } fn from_xy(x: T, y: T) -> Self { Self { x, y } } } impl<T: crate::proj::CoordinateTyp...
use crate::{Proj, ProjError}; use geo_types; impl<T: crate::proj::CoordinateType> crate::Coord<T> for geo_types::Coordinate<T> { fn x(&self) -> T { self.x } fn y(&self) -> T { self.y } fn from_xy(x: T, y: T) -> Self { Self { x, y } } } impl<T: crate::proj::CoordinateTyp...
::GeometryCollection<T>, ProjError> where T: crate::proj::CoordinateType, { Ok(geo_types::GeometryCollection( geometry_collection .into_iter() .map(|g| self.convert_geometry(g)) .collect::<Result<Vec<_>, _>>()?, )) } } #[cf...
, ProjError> where T: crate::proj::CoordinateType, { Ok(geo_types::Triangle( self.convert(triangle.0)?, self.convert(triangle.1)?, self.convert(triangle.2)?, )) } pub fn convert_polygon<T>( &self, polygon: geo_ty...
random
[ { "content": "/// called by Proj::new and ProjBuilder::transform_new_crs\n\nfn transform_string(ctx: *mut PJ_CONTEXT, definition: &str) -> Option<Proj> {\n\n let c_definition = CString::new(definition).ok()?;\n\n let new_c_proj = unsafe { proj_create(ctx, c_definition.as_ptr()) };\n\n if new_c_proj.is_...
Rust
src/storage.rs
equalitie/btdht
a3bed7756b4e3ad47aa02ef960ef1d9f96267b04
use std::collections::hash_map::Entry; use std::collections::HashMap; use std::net::SocketAddr; use std::time::{Duration, Instant}; use crate::id::InfoHash; const MAX_ITEMS_STORED: usize = 500; pub struct AnnounceStorage { storage: HashMap<InfoHash, Vec<AnnounceItem>>, expires: Vec<ItemExpiration>, } impl A...
use std::collections::hash_map::Entry; use std::collections::HashMap; use std::net::SocketAddr; use std::time::{Duration, Instant}; use crate::id::InfoHash; const MAX_ITEMS_STORED: usize = 500; pub struct AnnounceStorage { storage: HashMap<InfoHash, Vec<AnnounceItem>>, expires: Vec<ItemExpiration>, } impl A...
fn find<'a>( &'a mut self, info_hash: &'_ InfoHash, curr_time: Instant, ) -> impl Iterator<Item = SocketAddr> + 'a { self.remove_expired_items(curr_time); self.storage .get(info_hash) .into_iter() .flatten() .map...
a mut self, info_hash: &'_ InfoHash, ) -> impl Iterator<Item = SocketAddr> + 'a { self.find(info_hash, Instant::now()) }
function_block-function_prefix_line
[ { "content": "/// Returns true if the overflow checked index is in bounds of the given length.\n\nfn index_is_in_bounds(length: usize, checked_index: Option<usize>) -> bool {\n\n match checked_index {\n\n Some(index) => index < length,\n\n None => false,\n\n }\n\n}\n\n\n\n// ----------------...
Rust
src/world/scheduler/builder.rs
SOF3/dynec
69bb5fbe65729f2eedb0387d382ad0e89f2fad16
use std::collections::{hash_map, HashMap}; use std::fmt; use indexmap::IndexSet; use parking_lot::Mutex; use super::{ Executor, Node, Order, PartitionIndex, ResourceAccess, ResourceType, Scheduler, SendSystemIndex, SyncState, Topology, UnsendSystemIndex, UnsyncState, }; use crate::system::{self, spec}; pub(c...
use std::collections::{hash_map, HashMap}; use std::fmt; use indexmap::IndexSet; use parking_lot::Mutex; use super::{ Executor, Node, Order, PartitionIndex, ResourceAccess, ResourceType, Scheduler, SendSystemIndex, SyncState, Topology, UnsendSystemIndex, UnsyncState, }; use crate::system::{self, spec}; pub(c...
} Ret(self, node) } pub(crate) fn add_dependency(&mut self, before: Node, after: Node) { self.orders.push(Order { before, after }); } pub(crate) fn build(self) -> Scheduler { let topology = Topology::init( self.send_systems.len(), self.unsend_s...
t::Formatter) -> fmt::Result { match self.1 { Node::SendSystem(index) => { let (debug_name, _) = self.0.send_systems.get(index.0).expect("invalid node index"); writeln!(f, "thread-safe system #{} ({})", index...
function_block-function_prefixed
[ { "content": "#[derive(Debug, Clone, Copy)]\n\nstruct Order {\n\n before: Node,\n\n after: Node,\n\n}\n\n\n", "file_path": "src/world/scheduler.rs", "rank": 0, "score": 154981.33134726709 }, { "content": "/// `push_send_system` and `push_unsend_system` only check the `debug_name` fiel...
Rust
src/developer/ffx/plugins/config/src/args.rs
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
use {argh::FromArgs, ffx_config::ConfigLevel, ffx_core::ffx_command}; #[ffx_command] #[derive(FromArgs, Debug, PartialEq)] #[argh( subcommand, name = "config", description = "View and switch default and user configurations" )] pub struct ConfigCommand { #[argh(subcommand)] pub sub: SubCommand, } ...
use {argh::FromArgs, ffx_config::ConfigLevel, ffx_core::ffx_command}; #[ffx_command] #[derive(FromArgs, Debug, PartialEq)] #[argh( subcommand, name = "config", description = "View and switch default and user configurations" )] pub struct ConfigCommand { #[argh(subcommand)] pub sub: SubCommand, } ...
#[test] fn test_get() { fn check(args: &[&str], expected_key: &str, expected_build_dir: Option<String>) { assert_eq!( ConfigCommand::from_args(CMD_NAME, args), Ok(ConfigCommand { sub: SubCommand::Get(GetCommand { s...
nd { sub: SubCommand::Env(EnvCommand { access: Some(EnvAccessCommand::Set(EnvSetCommand { level: expected_level, file: "/test/config.json".to_string(), build_dir: Some("/test/".to_string()), ...
function_block-function_prefixed
[]
Rust
src/lib.rs
tetris-bot-protocol/tbp-rs
85d0bbc59295cf4b016a430df8712e701e014bea
macro_rules! gen_type { ($(#[$($m:tt)*])* pub struct $Name:ident { $($c:tt)* } $($rest:tt)*) => { gen_type!(@struct [$(#[$($m)*])*] default $Name {} $($c)*); impl $Name { gen_type!(@new {} {} $($c)*); pub fn custom<T>(&self, name: &str) -> Option<serde_json::Result<T>> ...
macro_rules! gen_type { ($(#[$($m:tt)*])* pub struct $Name:ident { $($c:tt)* } $($rest:tt)*) => { gen_type!(@
nown<K> { Known(K), Unknown(serde_json::Value), } impl<K: Default> Default for MaybeUnknown<K> { fn default() -> Self { MaybeUnknown::Known(K::default()) } } impl<K> From<K> for MaybeUnknown<K> { fn from(v: K) -> MaybeUnknown<K> { MaybeUnknown::Known(v) } } impl<K> MaybeUnknow...
struct [$(#[$($m)*])*] default $Name {} $($c)*); impl $Name { gen_type!(@new {} {} $($c)*); pub fn custom<T>(&self, name: &str) -> Option<serde_json::Result<T>> where T: serde::de::DeserializeOwned { self.rest.get(name).map(|v| se...
random
[ { "content": "gen_type! {\n\n pub struct Stop {}\n\n\n\n pub struct Quit {}\n\n\n\n pub struct Start {\n\n required hold: Option<MaybeUnknown<Piece>>,\n\n required queue: Vec<MaybeUnknown<Piece>>,\n\n required combo: u32,\n\n required back_to_back: bool,\n\n required ...
Rust
src/filters/common.rs
philwhineray/tera
1c7e6cae7659a73ce72e712695367a52bcdabc59
use std::collections::HashMap; use std::iter::FromIterator; use serde_json::value::{Value, to_value}; use errors::Result; use chrono::{NaiveDateTime, DateTime, FixedOffset}; pub fn length(value: Value, _: HashMap<String, Value>) -> Result<Value> { match value { Value::Array(arr) => Ok(to_value(&arr.len(...
use std::collections::HashMap; use std::iter::FromIterator; use serde_json::value::{Value, to_value}; use errors::Result; use chrono::{NaiveDateTime, DateTime, FixedOffset}; pub fn length(value: Value, _: HashMap<String, Value>) -> Result<Value> { match value { Value::Array(arr) => Ok(to_value(&arr.len(...
lt.unwrap(), to_value(dt.format("%Y-%m-%d").to_string())); } }
`value`: got `{:?}` but expected i64|u64|String", value ); } }; let format = match args.get("format") { Some(val) => try_get_value!("date", "format", String, val.clone()), None => "%Y-%m-%d".to_string(), }; Ok(to_value(&dt.format(&format).to_string(...
random
[ { "content": "/// Convert a value to lowercase.\n\npub fn lower(value: Value, _: HashMap<String, Value>) -> Result<Value> {\n\n let s = try_get_value!(\"lower\", \"value\", String, value);\n\n\n\n Ok(to_value(&s.to_lowercase()))\n\n}\n\n\n", "file_path": "src/filters/string.rs", "rank": 1, "sc...
Rust
build.rs
LeonardKoenig/libhttp_parser-sys-rs
55b08ea48f57f6f14e1414f6de4527f023792011
extern crate bindgen; use std::env; use std::io::{self, Read}; use std::fs::{self, File}; use std::os::unix::fs::symlink; use std::process::Command; use std::path::{Path, PathBuf}; macro_rules! t { ($e: expr) => { match $e { Ok(n) => n, Err(e) => panic!("\n{} failed with {}\n", str...
extern crate bindgen; use std::env; use std::io::{self, Read}; use std::fs::{self, File}; use std::os::unix::fs::symlink; use std::process::Command; use std::path::{Path, PathBuf}; macro_rules! t { ($e: expr) => { match $e { Ok(n) => n, Err(e) => panic!("\n{} failed with {}\n", str...
.collect::<Vec<&str>>() .last().unwrap() .parse::<u8>().unwrap(); t!(fs::create_dir_all(dst.join("include"))); t!(fs::create_dir_all(dst.join("lib"))); t!(fs::copy( build.join("libhttp_parser.a"), dst.join("lib/libhttp_parser.a") )); let libname = f...
.parse::<u8>().unwrap(); let sominor = sover_lines[1] .split(" ") .collect::<Vec<&str>>() .last().unwrap() .parse::<u8>().unwrap(); let sorev = sover_lines[2] .split(" ")
random
[ { "content": "#![allow(non_upper_case_globals)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(non_snake_case)]\n\n\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/bindings.rs\"));\n", "file_path": "src/lib.rs", "rank": 5, "score": 11691.70538558552 } ]
Rust
src/test/instruction_tests/instr_vpunpckhdq.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpunpckhdq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPUNPCKHDQ, ...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpunpckhdq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPUNPCKHDQ, ...
) } #[test] fn vpunpckhdq_11() { run_test( &Instruction { mnemonic: Mnemonic::VPUNPCKHDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM5)), operand3: Some(IndirectScaledDisplaced( EDI, Two, 7689928...
operand3: Some(IndirectScaledIndexed( EAX, EBX, Two, Some(OperandSize::Xmmword), None, )), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: ...
random
[ { "content": "fn encode16_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
src/cli.rs
dbr/vidl-rs
6b0d348b4119f765231432517b1d3142f2dd1740
use anyhow::Result; use clap::{App, Arg, SubCommand}; use log::{debug, info, warn}; use crate::common::{ChannelID, Service}; use crate::db; use crate::source::base::ChannelData; use crate::worker::{WorkItem, WorkerPool}; fn update(force: bool) -> Result<()> { debug!("Loading config"); let cfg = crate::co...
use anyhow::Result; use clap::{App, Arg, SubCommand}; use log::{debug, info, warn}; use crate::common::{ChannelID, Service}; use crate::db; use crate::source::base::ChannelData; use crate::worker::{WorkItem, WorkerPool}; fn update(force: bool) -> Result<()> { debug!("Loading config"); let cfg = crate::co...
let sc_remove = SubCommand::with_name("remove") .about("remove given channel and all videos in it") .arg(Arg::with_name("id").required(true)); let sc_update = SubCommand::with_name("update") .about("Updates all added channel info") .arg( Arg::with_name("force"...
let sc_add = SubCommand::with_name("add") .about("Add channel") .arg(Arg::with_name("chanid").required(true)) .arg( Arg::with_name("service") .required(true) .default_value("youtube") .possible_values(&["youtube", "vimeo"]) ...
assignment_statement
[ { "content": "/// Called regularly to check if a channel needs updated.\n\n/// Then either updates the channel or does nothing.\n\nfn worker_update(chan: &Channel, force: bool) -> Result<()> {\n\n let cfg = crate::config::Config::load();\n\n let db = crate::db::Database::open(&cfg)?;\n\n let last_updat...
Rust
lang/rs/bindings/cne/src/lib.rs
CloudNativeDataPlane/cndp
cc83410b525bd3aacaf72ad12f8d4f4af5b28727
/* SPDX-License-Identifier: BSD-3-Clause * Copyright (c) 2020-2022 Intel Corporation. */ pub(crate) mod config; pub mod error; pub mod instance; pub mod packet; pub mod port; mod util; #[cfg(test)] mod tests { use super::config; use super::instance::*; use super::packet::*; use etherparse::Ethernet2...
/* SPDX-License-Identifier: BSD-3-Clause * Copyright (c) 2020-2022 Intel Corporation. */ pub(crate) mod config; pub mod error; pub mod instance; pub mod packet; pub mod port; mod util; #[cfg(test)] mod tests { use super::config; use super::instance::*; use super::packet::*; use etherparse::Ethernet2...
#[test] fn test_tx_burst() { init(); let jsonc_file = get_jsonc_file(); let cne = CneInstance::get_instance(); let ret = cne.configure(&jsonc_file); assert!(ret.is_ok()); let port = cne.get_port(0); assert!(port.is...
len.is_some()); log::debug!("packet data length = {}", data_len.unwrap()); Packet::free_packet_buffer(&mut rx_pkts[..pkts_read as usize]); break; } else { thread::sleep(Duration::from_micros(2...
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn get_string_from_c_array(c_arr: &[c_char]) -> Result<String, Utf8Error> {\n\n let c_str: &CStr = unsafe { CStr::from_ptr(c_arr.as_ptr()) };\n\n let ret = c_str.to_str().map(String::from);\n\n ret\n\n}\n", "file_path": "lang/rs/bindings/cne/src/util.rs", ...
Rust
src/client.rs
tanyav2/doh-dns
c49f957ee7957cbb69772a4d4bf8cb8aa8915e9e
use async_trait::async_trait; use futures_util::future::{err, ok, Ready}; use hyper::{ client::{connect::dns::Name, HttpConnector}, error::Result as HyperResult, Body, Client, Request, Response, Uri, }; use hyper_tls::HttpsConnector; use std::{ io, net::{IpAddr, Ipv4Addr}, sync::{ atomi...
use async_trait::async_trait; use futures_util::future::{err, ok, Ready}; use hyper::{ client::{connect::dns::Name, HttpConnector}, error::Result as HyperResult, Body, Client, Request, Response, Uri, }; use hyper_tls::HttpsConnector; use std::{ io, net::{IpAddr, Ipv4Addr}, sync::{ atomi...
}
async fn test_static_resolve() { let mut resolver = UrlStaticResolver::new(); let n = Name::from_str("dns.google").unwrap(); let mut g1 = resolver.call(n.clone()).await.unwrap(); assert_eq!(g1.next(), Some(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)))); assert_eq!(g1.next(), None); ...
function_block-full_function
[ { "content": "struct Rtype(pub u32, pub &'static str);\n\n\n\nmacro_rules! rtypes {\n\n (\n\n $(\n\n $(#[$docs:meta])*\n\n ($konst:ident, $num:expr);\n\n )+\n\n ) => {\n\n paste::item! {\n\n impl<C: DnsClient> Dns<C> {\n\n $(\n\n ...
Rust
src/main.rs
Aksheet10/rustywitness
bf07bd5b9ada59d9f2ba871b423c9c8fb4b1cbcf
use clap::{clap_app, crate_authors, crate_description, crate_name, crate_version}; use fantoccini::ClientBuilder; use std::env; use tokio::fs; use std::process::{Command, Stdio}; use once_cell::sync::Lazy; struct TemporaryProcess(std::process::Child); impl Drop for TemporaryProcess { fn drop(&mut self) { ...
use clap::{clap_app, crate_authors, crate_description, crate_name, crate_version}; use fantoccini::ClientBuilder; use std::env; use tokio::fs; use std::process::{Command, Stdio}; use once_cell::sync::Lazy; struct TemporaryProcess(std::process::Child); impl Drop for TemporaryProcess { fn drop(&mut self) { ...
async fn run_driver(port: u32, driver_path: Option<&str>) -> TemporaryProcess { let key = "PATH"; let chromedriver = "chromedriver"; let geckodriver = "geckodriver"; let mut found_driver: Option<&str> = None; if driver_path.is_none() { match env::var_os(key) { Some(paths) => { ...
let filename = "screenshots/".to_owned() + &url.replace("://", "-") .replace("/", "_") + ".png"; fs::write( filename, &png_data, ).await?; println!("[+] Captured screenshot of URL: {}", url); Ok(()) }
function_block-function_prefix_line
[ { "content": "# Introducing Rustywitness\n\n\n\nThis is Rust implementation of [Eyewitness](https://github.com/FortyNorthSecurity/EyeWitness)/[gowitness](https://github.com/sensepost/gowitness)\n\n\n\n---\n\n# Why Use?\n\n\n\nGrab screenshots of websites from terminal!\n\n\n\nAnd is 2x times faster than [Eyewit...
Rust
tls/src/key_schedule.rs
newAM/w5500-rs
a43f6746f55fd9989a660e9f118bbc8b417a1e3e
use core::mem::size_of; use hkdf::Hkdf; use hmac::Mac; use p256::{ ecdh::{EphemeralSecret, SharedSecret}, EncodedPoint, PublicKey, }; use rand_core::{CryptoRng, RngCore}; use sha2::{ digest::{ crypto_common::generic_array::{ArrayLength, GenericArray}, typenum::{Unsigned, U12, U32}, ...
use core::mem::size_of; use hkdf::Hkdf; use hmac::Mac; use p256::{ ecdh::{EphemeralSecret, SharedSecret}, EncodedPoint, PublicKey, }; use rand_core::{CryptoRng, RngCore}; use sha2::{ digest::{ crypto_common::generic_array::{ArrayLength, GenericArray}, typenum::{Unsigned, U12, U32}, ...
.iter() .enumerate() .for_each(|(idx, byte)| iv[idx + 4] ^= byte); Some((key, iv.into())) } pub fn server_key_and_nonce(&self) -> Option<([u8; 16], [u8; 12])> { let traffic_secret = self.server_traffic_secret.as_r...
self.read_record_sequence_number = 0; self.write_record_sequence_number = 0; #[cfg(feature = "std")] { print_nss_key_log( &format!("CLIENT_TRAFFIC_SECRET_{}", self.traffic_secret_count), self.client_random.as_ref().unwrap(), &cli...
random
[ { "content": "pub fn encode_variable_byte_integer(mut integer: u32) -> ([u8; 4], usize) {\n\n let mut buf: [u8; 4] = [0; 4];\n\n let mut len: usize = 0;\n\n\n\n loop {\n\n buf[len] = (integer % 128) as u8;\n\n integer /= 128;\n\n if integer > 0 {\n\n buf[len] |= 0x80;\n\...
Rust
src/keyword.rs
linasdev/ross-dsl
3ab7a201ebb761be3a0fa6cbcad45499dad5ad2d
use nom::{Err as NomErr, IResult}; use crate::error::{ErrorKind, Expectation, ParserError}; use crate::parser::name_parser; macro_rules! implement_keyword_parser { ($parser_name:ident, $keyword:expr) => { pub fn $parser_name(text: &str) -> IResult<&str, &str, ParserError<&str>> { match name_pa...
use nom::{Err as NomErr, IResult}; use crate::error::{ErrorKind, Expectation, ParserError}; use crate::parser::name_parser; macro_rules! implement_keyword_parser { ($parser_name:ident, $keyword:expr) => { pub fn $parser_name(text: &str) -> IResult<&str, &str, ParserError<&str>> {
rd, "double_exclusive");
match name_parser(text) { Ok((input, $keyword)) => Ok((input, $keyword)), Ok((_, value)) => Err(NomErr::Error(ParserError::Base { location: value, kind: ErrorKind::Expected(Expectation::Keyword($keyword)), child: None, ...
random
[]
Rust
src/stmt.rs
hrishimk/deslite
e82113a2b4a8d001c62420f2986f0d7f01ffc18e
use super::{ffi, Connection, Error, Lesult, SqliteTypes, Value}; use std; use std::ffi::CStr; use std::os::raw::c_int; use Row; use Rows; #[derive(Debug)] pub struct Stmt<'con> { con: &'con Connection, pub stmt: *mut ffi::sqlite3_stmt, } impl<'con> Drop for Stmt<'con> { fn drop(&mut self) { let ...
use super::{ffi, Connection, Error, Lesult, SqliteTypes, Value}; use std; use std::ffi::CStr; use std::os::raw::c_int; use Row; use Rows; #[derive(Debug)] pub struct Stmt<'con> { con: &'con Connection, pub stmt: *mut ffi::sqlite3_stmt, } impl<'con> Drop for Stmt<'con> { fn drop(&mut self) { let ...
{ ffi::sqlite3_clear_bindings(self.stmt); } } pub fn colum_count(&self) -> usize { unsafe { ffi::sqlite3_column_count(self.stmt) as usize } } pub fn colum_name(&self, index: usize) -> &str { unsafe { CStr::from_ptr(ffi::sqlite3_column_name(self.stmt, index as c_int)...
) }; if rc != ffi::SQLITE_OK { return Err(Error::PrepareErr(self.con.get_last_error(rc))); } Ok(self) } fn bind_buff<T>(&mut self, v: Vec<T>, i: std::os::raw::c_int) -> c_int where std::vec::Vec<u8>: std::convert::From<std::vec::Vec<T>>, { ...
random
[ { "content": "type Lesult<T> = Result<T, Error>;\n\n\n\nimpl SqliteTypes {\n\n pub fn new(code: c_int) -> Lesult<Self> {\n\n match code {\n\n ffi::SQLITE_INTEGER => Ok(SqliteTypes::Int),\n\n ffi::SQLITE_FLOAT => Ok(SqliteTypes::FLoat),\n\n ffi::SQLITE_BLOB => Ok(Sqlite...
Rust
tirocks/src/option/flush.rs
BusyJay/tirocks
f8300ee481d1ae31f355057350b7c443146a2738
use std::mem::MaybeUninit; use tirocks_sys::{ rocksdb_BottommostLevelCompaction, rocksdb_CompactRangeOptions, rocksdb_CompactionOptions, rocksdb_FlushOptions, rocksdb_IngestExternalFileOptions, }; use super::CompressionType; #[derive(Debug)] #[repr(transparent)] pub struct FlushOptions { raw: rocksdb_F...
use std::mem::MaybeUninit; use tirocks_sys::{ rocksdb_BottommostLevelCompaction, rocksdb_CompactRangeOptions, rocksdb_CompactionOptions, rocksdb_FlushOptions, rocksdb_IngestExternalFileOptions, }; use super::CompressionType; #[derive(Debug)] #[repr(transparent)] pub struct FlushOptions { raw: rocksdb_F...
} impl IngestExternalFileOptions { #[inline] pub fn set_move_files(&mut self, m: bool) -> &mut Self { self.raw.move_files = m; self } #[inline] pub fn set_failed_move_fall_back_to_copy(&mut self, fallback: bool) -> &mut Self { self.raw.failed_move_fall_back_to_co...
e { tirocks_sys::crocksdb_ingestexternalfileoptions_init(opt.as_mut_ptr()); Self { raw: opt.assume_init(), } } }
function_block-function_prefixed
[ { "content": "/// Get all supported comressions.\n\npub fn supported_compressions() -> Vec<CompressionType> {\n\n unsafe {\n\n let n = tirocks_sys::crocksdb_get_supported_compression_number();\n\n let mut v = Vec::with_capacity(n);\n\n tirocks_sys::crocksdb_get_supported_compression(v.as...
Rust
examples/server_tcp.rs
vodovozovge/coap-lite
fb8fc964664f38e3911775027b2a1c830e270bef
use coap_lite::{ CoapMessageExt, CoapOption, CoapRequest, CoapSignal, MessageClass, Packet, PacketTcp, RequestType, SignalType, }; use std::io::{BufReader, Read, Write}; use std::net::TcpListener; use std::{collections::LinkedList, sync::Mutex, thread, time::Duration}; use rustls; use rustls::{NoClientAuth, Se...
use coap_lite::{ CoapMessageExt, CoapOption, CoapRequest, CoapSignal, MessageClass, Packet, PacketTcp, RequestType, SignalType, }; use std::io::{BufReader, Read, Write}; use std::net::TcpListener; use std::{collections::LinkedList, sync::Mutex, thread, time::Duration}; use rustls; use rustls::{NoClientAuth, Se...
:?}", buf.len(), buf); if let Ok(parsed_packet) = PacketTcp::from_bytes(&buf[..]) { println!("Parsed packet type {}", parsed_packet.get_code()); let payload = parsed_packet.get_payload(); if payload.len() > 0 { println!( "Payload: {}", String::fro...
ts(); if processed.is_err() { println!("cannot process packet: {:?}", processed); break; } } if tls_session.wants_write() { handle_incoming_data(&mut *tls_session); ...
random
[ { "content": "fn main() {\n\n let mut request = PacketUdp::new();\n\n request.set_message_id(23839);\n\n request\n\n .set_code_from_message_class(MessageClass::Request(RequestType::Get));\n\n request.set_token(vec![0, 0, 57, 116]);\n\n request.add_option(CoapOption::UriHost, b\"localhost\"...
Rust
src/feed.rs
travispaul/nvd_cve
fa7f0cf9403d46b085621c7536cbb4ce144f257f
use crate::client::{BlockingHttpClient, HttpError}; use chrono::{DateTime, NaiveDateTime, ParseError}; use log::warn; use std::fs; use std::io::Error; use std::num::ParseIntError; use std::path::Path; use std::str::FromStr; #[derive(Debug)] pub struct Feed { pub name: String, pub metafile: Option<Metafile>, ...
use crate::client::{BlockingHttpClient, HttpError}; use chrono::{DateTime, NaiveDateTime, ParseError}; use log::warn; use std::fs; use std::io::Error; use std::num::ParseIntError; use std::path::Path; use std::str::FromStr; #[derive(Debug)] pub struct Feed { pub name: String, pub metafile: Option<Metafile>, ...
pub fn format_last_modified_date(&self) -> String { self.last_modified_date .format("%Y-%m-%dT%H:%M:%S") .to_string() } }
DateTime::parse_from_rfc3339(datetime) { Ok(parsed_dt) => parsed_dt.naive_utc(), Err(_) => match NaiveDateTime::parse_from_str(datetime, "%Y-%m-%dT%H:%M:%S") { Ok(parsed_ndt) => parsed_ndt, Err(_) => { warn!("Failed parsing datetime: {:?}", dat...
function_block-function_prefixed
[ { "content": "/// Syncs the remote feeds to the local cache using the provided ``BlockingHttpClient``\n\n///\n\n/// ## Example:\n\n/// ```no_run\n\n/// use nvd_cve::cache::{CacheConfig, sync_blocking};\n\n/// use nvd_cve::client::{ReqwestBlockingClient, BlockingHttpClient};\n\n///\n\n/// let mut config = CacheC...
Rust
dokan-sys/build.rs
dokan-dev/dokan-rust
1e2676d2ad7d74a9747107ba0ed2f1530259da5b
extern crate cc; use std::env; use std::fs; use std::process::{Command, Stdio}; use cc::{Build, Tool}; fn print_env(compiler: &Tool) { eprintln!("Environment variables:"); for (k, v) in env::vars() { eprintln!("{}={}", k, v); } eprintln!("\nCompiler:\n{}", compiler.path().to_string_lossy()); eprintln!("\nComp...
extern crate cc; use std::env; use std::fs; use std::process::{Command, Stdio}; use cc::{Build, Tool}; fn print_env(compiler: &Tool) { eprintln!("Environment variables:"); for (k, v) in env::vars() { eprintln!("{}={}", k, v); } eprintln!("\nCompiler:\n{}", compiler.path().to_string_lossy()); eprintln!("\nComp...
fn main() { let compiler = Build::new().get_compiler(); print_env(&compiler); let version = run_generator(&compiler); assert_eq!( format!("dokan{}", version), env::var("CARGO_PKG_VERSION").unwrap().split('+').last().unwrap(), "Mismatch detected between crate version and bundled Dokan source version.", ); ...
r); let dll_path = format!("{}/{}", out_dir, dll_name); let mut compiler_cmd = compiler.to_command(); compiler_cmd .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .arg("-D_WINDLL") .arg("-D_EXPORTING") .arg("-DUNICODE") .arg("-D_UNICODE") .arg("-DWINVER=0x0A00") .arg("-D_WIN32_WINNT=0x0A00") .a...
function_block-function_prefixed
[ { "content": "fn convert_str(s: impl AsRef<str>) -> U16CString {\n\n\tunsafe { U16CString::from_str_unchecked(s) }\n\n}\n\n\n", "file_path": "dokan/src/tests.rs", "rank": 3, "score": 142892.6155254807 }, { "content": "#[must_use]\n\npub fn notify_delete(path: impl AsRef<U16CStr>, is_dir: boo...
Rust
cargo_test_parser/src/parse_context.rs
PhilipDaniels/rtest
6a666646cdcde08a600913595c1f4bc5f2348a0e
pub struct ParseContext<'a> { data: &'a str, lines: Vec<&'a str>, current_line_number: LineNumber, } enum LineNumber { NotStarted, InProgress(usize), Finished, } impl<'a> ParseContext<'a> { pub fn new(data: &'a str) -> Self { Self { data, lines: data.lines...
pub struct ParseContext<'a> { data: &'a str, lines: Vec<&'a str>, current_line_number: LineNumber, } enum LineNumber { NotStarted, InProgress(usize), Finished, } impl<'a> ParseContext<'a> { pub fn new(data: &'a str) -> Self { Self { data, lines: data.lines...
} #[cfg(test)] mod parse_context_tests { use super::*; #[test] fn new_for_empty_data() { let mut pc = ParseContext::new(""); assert_eq!(pc.current_line_number(), None); assert_eq!(pc.current_line(), None); let peeked_line = pc.peek(); assert_eq!(peeked_line, None,...
LineNumber::InProgress(idx) => { self.current_line_number = LineNumber::InProgress(idx + 1); Some(&self.lines[idx]) } LineNumber::Finished => None, } }
function_block-function_prefix_line
[ { "content": "/// Splits the input into the part before and including\n\n/// the character at `idx`, and the part after that.\n\npub fn inclusive_split_at_index(data: &str, idx: usize) -> (&str, &str) {\n\n (&data[..idx + 1], &data[idx + 1..])\n\n}\n\n\n", "file_path": "cargo_test_parser/src/utils.rs", ...
Rust
examples/static_server.rs
dushaobindoudou/rust-static-server
14b92b734159d7098f782b6ba7c83894c4216ebd
#![deny(warnings)] use std::path::PathBuf; use std::{env}; use mime_guess; use hyper::header; use tokio::fs::File; use tokio_util::codec::{BytesCodec, FramedRead}; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server, StatusCode}; static NOTFOUND: &[u8] = b"404 File Not Fou...
#![deny(warnings)] use std::path::PathBuf; use std::{env}; use mime_guess; use hyper::header; use tokio::fs::File; use tokio_util::codec::{BytesCodec, FramedRead}; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server, StatusCode}; static NOTFOUND: &[u8] = b"404 File Not Fou...
async fn echo(req: Request<Body>) -> Result<Response<Body>, hyper::Error> { let mut current_woker = env::current_dir().unwrap(); let origin_url_path = PathBuf::from(req.uri().path()); let request_path = PathBuf::from(req.uri().path()); let request_path_str = request_path.strip_prefix("/").unwrap().disp...
fn not_found() -> Response<Body> { Response::builder() .status(StatusCode::NOT_FOUND) .body(NOTFOUND.into()) .unwrap() }
function_block-full_function
[ { "content": "fn body(b: &'static [u8]) -> hyper::Body {\n\n b.into()\n\n}\n\n\n", "file_path": "benches/server.rs", "rank": 0, "score": 169218.47463623402 }, { "content": "type StaticBuf = &'static [u8];\n\n\n\n/// Encoders to handle different Transfer-Encodings.\n\n#[derive(Debug, Clone...
Rust
src/macros.rs
ark0f/dockerfile.rs
a8eab65133fcf38a99f70a092b34ffa43dae01ef
#![allow(non_snake_case)] #[macro_export] macro_rules! FROM { ($image:ident) => {{ use $crate::From; From { image: stringify!($image).to_string(), tag_or_digest: None, name: None, } }}; ($image:ident AS $name:ident) => {{ use $crate::From;...
#![allow(non_snake_case)] #[macro_export] macro_rules! FROM { ($image:ident) => {{ use $crate::From; From { image: stringify!($image).to_string(), tag_or_digest: None, name: None, } }}; ($image:ident AS $name:ident) => {{ use $crate::From;...
#[test] fn run() { let _ = RUN!["/bin/bash", "-c", "echo"]; } #[test] fn cmd() { let _ = CMD!["echo", "Hello, world!"]; } #[test] fn label() { let _ = LABEL!["key" => "value"]; let _ = LABEL!["key" => "value", "hello" => "world"]; } #[test] ...
b); let _ = FROM!(rust: latest); let _ = FROM!(rust:latest AS crab); let _ = FROM!(rust@digest); let _ = FROM!(rust@digest AS crab); }
function_block-function_prefixed
[ { "content": "EXPOSE 80\n\nENV RUST=\"1.0.0\"\n\nADD \"/var/run\" \"/home\"\n\nCOPY \"/var/run\" \"/home\"\n\nVOLUME [\"/var/run\", \"/var/www\"]\n\nUSER rustacean\n\nWORKDIR \"/home/rustacean\"\n\nARG build=\"yes\"\n\nSTOPSIGNAL SIGKILL\n\nHEALTHCHECK NONE\n\nSHELL [\"/bin/bash\", \"-c\"]\n\n\n\nONBUILD CMD [\...
Rust
src/collision/polygon_polygon_collider.rs
mattnenterprise/rust-box2d
22a69d1c454261e62e2620373774dad6477cd39f
use super::super::shape::shape::Shape::PolygonShape; use super::super::body::Body; use super::super::common::Vec2; use super::super::manifold::Manifold; use super::collider::Collider; use super::collider_result::ColliderResult; pub struct PolygonPolygonCollider { pair: (Body, Body) } impl Collider for PolygonPoly...
use super::super::shape::shape::Shape::PolygonShape; use super::super::body::Body; use super::super::common::Vec2; use super::super::manifold::Manifold; use super::collider::Collider; use super::collider_re
sult::new_empty_false(); } } for axis in axes_two { let min1: f32 = get_min(&points_a, axis, self.pair().0.position); let max1: f32 = get_max(&points_a, axis, self.pair().0.position); let min2: f32 = get_min(&points_b, axis, self.pair().1.position);...
sult::ColliderResult; pub struct PolygonPolygonCollider { pair: (Body, Body) } impl Collider for PolygonPolygonCollider { fn new(pair: (Body, Body)) -> PolygonPolygonCollider { return PolygonPolygonCollider{ pair: pair } } fn pair(&self) -> (Body, Body) { return self.pair.clone(); ...
random
[ { "content": "use super::Vec2;\n\nuse super::Rot;\n\nuse super::Transform;\n\n\n\n// This function is used to ensure that a floating point number of non a NaN or infinity.\n", "file_path": "src/common/math.rs", "rank": 0, "score": 3.857285625512782 }, { "content": "use super::super::super::c...
Rust
src/lib.rs
RedShadeSoftware/copyvec
680a09bb6b534f731704ec03a4a2564120306fcd
#![no_std] use core::{mem::MaybeUninit}; #[macro_export] macro_rules! copy_vec { ($array_type:ty, $n:literal => $($elem:expr),* $(,)?) => { { let mut cv: $crate::CopyVec<$array_type, $n> = Default::default(); $( cv.push($elem); )* cv } }; ($n:literal => ...
#![no_std] use core::{mem::MaybeUninit}; #[macro_export] macro_rules! copy_vec { ($array_type:ty, $n:literal => $($elem:expr),* $(,)?) => { { let mut cv: $crate::CopyVec<$array_type, $n> = Default::default(); $( cv.push($elem); )* cv } }; ($n:literal => ...
&mut Self::Target { self.unsafe_mut_slice() } } impl<T: Copy, const N: usize> Default for CopyVec<T, N> { fn default() -> Self { Self::new() } } impl<T: Copy, const N: usize> AsMut<[T]> for CopyVec<T, N> { fn as_mut(&mut self) -> &mut [T] { self.unsafe_mut_slice() } } imp...
> panic!("trying to remove index {} of copyvec with length {}", index, self.len), } } pub fn clear(&mut self) { self.len = 0; } pub fn push(&mut self, value: T) { if let Err(_) = self.try_push(value) { panic!("copyvec out of capacity") } } pub fn tr...
random
[ { "content": "#[test]\n\nfn test_macro() {\n\n let mut expected: CopyVec<i32, 4> = CopyVec::new();\n\n expected.push(1);\n\n expected.push(2);\n\n expected.push(3);\n\n\n\n assert_eq!(copy_vec!(4 => 1, 2, 3), expected);\n\n}\n\n\n", "file_path": "tests/copyvec.rs", "rank": 1, "score":...
Rust
src/dirutils/mod.rs
synasius/fuzzle
ff8f92712f3d485e95ee5b16c880bd4103efd1d5
use ini::Ini; use std::fs; use std::path::{Path, PathBuf}; use std::sync::Arc; use walkdir::WalkDir; use xdg::BaseDirectories; use crate::SearchResult; fn search_dirs() -> Vec<PathBuf> { let base_dirs = BaseDirectories::new() .expect("Can't find xdg directories! Good luck and thanks for all the fish"); ...
use ini::Ini; use std::fs; use std::path::{Path, PathBuf}; use std::sync::Arc; use walkdir::WalkDir; use xdg::BaseDirectories; use crate::SearchResult; fn search_dirs() -> Vec<PathBuf> { let base_dirs = BaseDirectories::new() .expect("Can't find xdg directories! Good luck and thanks for all the fish"); ...
} fn searchresult_from_bin(command_path: &Path) -> Option<SearchResult> { let name = match command_path.file_stem() { Some(os_str) => { if let Some(str_ref) = os_str.to_str() { str_ref.to_string() } else { return None; } } ...
Some(SearchResult { icon_path: search_icon(icon), desktop_entry_path, name, description, command, score: 0, selected: false, indices: Arc::new(vec![]), })
call_expression
[ { "content": "fn main() -> Result<(), PlatformError> {\n\n let main_window = WindowDesc::new(make_ui)\n\n .window_size((550., 320.00))\n\n .title(LocalizedString::new(\"fuzzle\").with_placeholder(String::from(\"fuzzle\")));\n\n let data = AppState {\n\n input_text: \"\".into(),\n\n ...
Rust
lesson-25-x-image-gen/ui/src/lib.rs
MerHS/rust-and-opengl-lessons
a7d78b852b62f2aab559b533c03293399298c468
#![forbid(unsafe_code)] extern crate nalgebra as na; #[macro_use] extern crate log; #[macro_use] extern crate slotmap; extern crate slab; extern crate metrohash; extern crate sha1; extern crate byteorder; extern crate font_kit; extern crate harfbuzz_rs; extern crate lyon_path; extern crate lyon_geom; exte...
#![forbid(unsafe_code)] extern crate nalgebra as na; #[macro_use] extern crate log; #[macro_use] extern crate slotmap; extern crate slab; extern crate metrohash; extern crate sha1; extern crate byteorder; extern crate font_kit; extern crate harfbuzz_rs; extern crate lyon_path; extern crate lyon_geom; exte...
pub fn to_flow(&self, flow: FlowDirection) -> (i32, i32) { match flow { FlowDirection::Horizontal => (self.h, self.w), FlowDirection::Vertical => (self.w, self.h), } } pub fn par(&self, flow: FlowDirection) -> i32 { match flow { FlowDirection::Ver...
pub fn from_flow(flow: FlowDirection, width: i32, forward_val: i32) -> ResolvedSize { match flow { FlowDirection::Horizontal => ResolvedSize { w: forward_val, h: width }, FlowDirection::Vertical => ResolvedSize { w: width, h: forward_val }, } }
function_block-full_function
[]
Rust
tests/internet/ip.rs
diogo464/etherparse
dc9efc94c13310b4fb3d63f8566ad2fee39cb10d
use super::super::*; #[test] fn readwrite_ip_header() { use std::io::Cursor; let inputs = [ IpHeader::Version4({ let mut header: Ipv4Header = Default::default(); header.differentiated_services_code_point = 42; header.explicit_congestion_notification = 3; ...
use super::super::*; #[test] fn readwrite_ip_header() { use std::io::Cursor; let inputs = [ IpHeader::Version4({ let mut header: Ipv4Header = Default::default(); header.differentiated_services_code_point = 42; header.explicit_congestion_notification = 3; ...
}
fn is_ipv6_ext_header_value() { use crate::IpTrafficClass; use crate::IpTrafficClass::*; let ext_ids = [ IPv6HeaderHopByHop as u8, IPv6RouteHeader as u8, IPv6FragmentationHeader as u8, IPv6EncapSecurityPayload as u8, IPv6AuthenticationH...
function_block-full_function
[ { "content": "#[test]\n\nfn write_error_source() {\n\n use super::WriteError::{IoError, SliceTooSmall};\n\n use std::error::Error;\n\n\n\n assert_matches!(\n\n IoError(std::io::Error::new(std::io::ErrorKind::Other, \"some error\")).source(),\n\n Some(_)\n\n );\n\n\n\n assert_matches...
Rust
src/main.rs
JamesFator/FerrisChat
9cd4899ba805b4dd5f7d4ed41e9c6292637f3e9c
extern crate serde; #[macro_use] extern crate stdweb; use specs::prelude::*; use std::cell::RefCell; use std::rc::Rc; use stdweb::traits::*; use stdweb::web::{event::ClickEvent, event::KeyDownEvent, Date, IEventTarget}; mod canvas; use canvas::{Canvas, DrawSystem}; use ferris_chat::components::*; use ferris_chat::ent...
extern crate serde; #[macro_use] extern crate stdweb; use specs::prelude::*; use std::cell::RefCell; use std::rc::Rc; use stdweb::traits::*; use stdweb::web::{event::ClickEvent, event::KeyDownEvent, Date, IEventTarget}; mod canvas; use canvas::{Canvas, DrawSystem}; use ferris_chat::components::*; use ferris_chat::ent...
fn read_from_local_storage(mut ecs: &mut World) { let chat_input = stdweb::web::window().local_storage().get("chat_input"); if let Some(chat_msg) = chat_input { if chat_msg.len() == 0 { return; } let player_id = ecs.fetch::<String>().to_string(); let player_in...
fn update_fps_tracker(mut ecs: &mut World, fps_tracker: &mut FPSTracker) { { let now = Date::new().get_seconds() as u64; if fps_tracker.for_time != now { fps_tracker.for_time = now; fps_tracker.prev_fps = fps_tracker.seen_frames; fps_tracker.seen_frames = 0; ...
function_block-full_function
[ { "content": "pub fn handle_input(ecs: &mut World, input: &str, player_id: &String) {\n\n let maybe_entity;\n\n {\n\n maybe_entity = get_player_with_id(&ecs, &player_id);\n\n if maybe_entity.is_none() {\n\n println!(\"Entity ID {} doesn't exist!\", &player_id);\n\n retu...
Rust
src/forest.rs
CraigMacomber/sequence
ada56998a853ea19b5a6536e7b79771400044bc0
use std::cell::{Ref, RefCell}; use crate::{util::ImHashMap, Label, NodeId, NodeNav}; use im_rc::ordmap::DiffItem; #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Copy, Hash)] pub struct ChunkId(pub NodeId); pub trait Chunk { type View; fn get(&self, first_id: NodeId, id: NodeId) -> Op...
use std::cell::{Ref, RefCell}; use crate::{util::ImHashMap, Label, NodeId, NodeNav}; use im_rc::ordmap::DiffItem; #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Copy, Hash)] pub struct ChunkId(pub NodeId); pub trait Chunk { type View; fn get(&self, first_id: NodeId, id: NodeId) -> Op...
} } impl<TNodes> Forest<TNodes> where TNodes: PartialEq<TNodes>, for<'a> &'a TNodes: NodeNav<ChunkId> + Nodes, { pub fn get_parent_data(&self) -> Ref<ImHashMap<ChunkId, ParentInfo<ChunkId>>> { { let mut parent_data = self.parent_data.borrow_mut(); for d in self.old_map....
match self.map.get_prev(&ChunkId(id)) { Some((chunk, v)) => v.get(chunk.0, id), None => None, }
if_condition
[ { "content": "pub fn walk_direct_all(forest: &Forest, id: ChunkId) -> usize {\n\n let mut count = 1;\n\n let n = forest.find_nodes(id).unwrap();\n\n for t in n.get_traits() {\n\n for c in n.get_trait(t) {\n\n count += walk_direct_all(forest, c);\n\n }\n\n }\n\n count\n\n}...
Rust
tokio/src/runtime/context.rs
appaquet/tokio
32e15b3a24ac177c92a78eb04e233534583eae17
use crate::runtime::Spawner; use std::cell::RefCell; thread_local! { static CONTEXT: RefCell<Option<ThreadContext>> = RefCell::new(None) } #[derive(Debug, Clone)] pub(crate) struct ThreadContext { spawner: Spawner, io_handle: crate::runtime::io::Handle, time_handle: crate::runtime::t...
use crate::runtime::Spawner; use std::cell::RefCell; thread_local! { static CONTEXT: RefCell<Option<ThreadContext>> = RefCell::new(None) } #[derive(Debug, Clone)] pub(crate) struct ThreadContext { spawner: Spawner, io_handle: crate::runtime::io::Handle, time_handle: crate::runtime::t...
); } }
match self.previous.clone() { Some(prev) => ctx.borrow_mut().replace(prev), None => ctx.borrow_mut().take(), }
if_condition
[ { "content": "fn gated() -> impl Future<Output = &'static str> {\n\n gated2(false)\n\n}\n\n\n", "file_path": "tokio/src/runtime/thread_pool/tests/loom_pool.rs", "rank": 0, "score": 300886.82143992756 }, { "content": "/// Spawn a thread to wait on the join handle. Uses a single task.\n\nfn...
Rust
src/client.rs
GrayJack/janetrs
12ae9f4f3ffe06de63444d16548c750e98815045
use core::{ fmt::{self, Display}, sync::atomic::{AtomicBool, Ordering}, }; #[cfg(feature = "std")] use std::{error::Error as StdError, thread_local}; use crate::{ env::{CFunOptions, DefOptions, JanetEnvironment, VarOptions}, Janet, JanetTable, }; #[cfg(feature = "std")] thread_local! { static IN...
use core::{ fmt::{self, Display}, sync::atomic::{AtomicBool, Ordering}, }; #[cfg(feature = "std")] use std::{error::Error as StdError, thread_local}; use crate::{ env::{CFunOptions, DefOptions, JanetEnvironment, VarOptions}, Janet, JanetTable, }; #[cfg(feature = "std")] thread_local! { static IN...
#[inline] pub fn run_bytes(&self, code: impl AsRef<[u8]>) -> Result<Janet, Error> { let code = code.as_ref(); let env = match self.env_table.as_ref() { Some(e) => e.ta...
pub fn add_c_fn(&mut self, cfun_opt: CFunOptions) { if self.env().is_none() { self.env_table = Some(JanetEnvironment::default()); } if let Some(ref mut env) = self.env_table { env.add_c_fn(cfun_opt); } }
function_block-full_function
[ { "content": "#[doc(hidden)]\n\n#[inline]\n\npub fn _panic(msg: Janet) -> ! {\n\n unsafe { evil_janet::janet_panicv(msg.inner) }\n\n #[allow(clippy::empty_loop)]\n\n loop {}\n\n}\n", "file_path": "src/util.rs", "rank": 0, "score": 138400.8722056672 }, { "content": "#[proc_macro_attr...
Rust
examples/upgradeable-contracts/delegate-calls/upgradeable-flipper/upgradeable.rs
kaiweicai/ink-example
ad64f980f50939b844598fd0635d6af529351087
use core::marker::PhantomData; use ink_primitives::{ Key, KeyPtr, }; use ink_storage::traits::{ PackedAllocate, PackedLayout, SpreadAllocate, SpreadLayout, }; use scale::{ Decode, Encode, }; #[derive(Debug)] pub struct Initialized; #[derive(Debug)] pub struct NotInitialized; #[derive(...
use core::marker::PhantomData; use ink_primitives::{ Key, KeyPtr, }; use ink_storage::traits::{ PackedAllocate, PackedLayout, SpreadAllocate, SpreadLayout, }; use scale::{ Decode, Encode, }; #[derive(Debug)] pub struct Initialized; #[derive(Debug)] pub struct NotInitialized; #[derive(...
} impl<T: PackedLayout> SpreadLayout for Upgradeable<T, Initialized> { const FOOTPRINT: u64 = T::FOOTPRINT; const REQUIRES_DEEP_CLEAN_UP: bool = T::REQUIRES_DEEP_CLEAN_UP; fn pull_spread(ptr: &mut KeyPtr) -> Self { Upgradeable::new(T::pull_spread(ptr)) } fn push_spread(&self, ptr: &mut K...
pub fn new(inner: T) -> Self { Upgradeable { inner, status: Default::default(), } }
function_block-full_function
[ { "content": "/// Types that can be stored to and loaded from a single contract storage cell.\n\npub trait PackedLayout: SpreadLayout + scale::Encode + scale::Decode {\n\n /// Indicates to `self` that is has just been pulled from the storage.\n\n ///\n\n /// # Note\n\n ///\n\n /// Most types will...
Rust
wpilib/src/relay.rs
auscompgeek/first-rust-competition
47084451c4c01109a47611b21c2cfed77b72a5b2
use std::marker::PhantomData; use wpilib_sys::*; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Value { Off, On, Forward, Reverse, } /* /// Convenience for treating bidirectional and unidirectional relays the same. impl From<bool> for Value { fn from(v: bool) -> ...
use std::marker::PhantomData; use wpilib_sys::*; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Value { Off, On, Forward, Reverse, } /* /// Convenience for treating bidirectional and unidirectional relays the same. impl From<bool> for Value { fn from(v: bool) -> ...
pub fn get(&self) -> HalResult<Value> { match ( hal_call!(HAL_GetRelay(self.forward_handle))? != 0, hal_call!(HAL_GetRelay(self.reverse_handle))? != 0, ) { (true, true) => Ok(Value::On), (true, false) => Ok(Value::Forward), (false, t...
pub fn set(&mut self, value: Value) -> HalResult<()> { self.set_forward(match value { Value::On | Value::Forward => true, _ => false, })?; self.set_reverse(match value { Value::On | Value::Reverse => true, _ => false, }) }
function_block-full_function
[ { "content": "/// Check if a PWM channel is valid.\n\nfn check_pwm_channel(channel: i32) -> bool {\n\n unsafe { HAL_CheckPWMChannel(channel) != 0 }\n\n}\n\n\n\n/// Represents the amount to multiply the minimum servo-pulse pwm period by.\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]\n...
Rust
src/interactive.rs
arloherrine/fith
c18a7dcccd2e86e4847483ff22c9ef4ff94f8cc8
use interpreter::Interpreter; use termion; use termion::event::Key; use termion::input::TermRead; use termion::raw::IntoRawMode; use std::io::{Write, stdout, stdin}; pub fn run(mut interpreter: Interpreter) { let mut stdout = stdout().into_raw_mode().unwrap(); write!(stdout, "Welcome to fith. ^D t...
use interpreter::Interpreter; use termion; use termion::event::Key; use termion::input::TermRead; use termion::raw::IntoRawMode; use std::io::{Write, stdout, stdin}; pub fn run(mut interpreter: Interpreter) { let mut stdout = stdout().into_raw_mode().unwrap(); write!(stdout, "Welcome to fith. ^D t...
cursor_pos += 1; let line_str: String = current_line.iter().cloned().collect(); let mut tmp_interpreter = interpreter.duplicate(); let result = tmp_interpreter.execute_line(&line_str); write_stack_line(&mut stdout, &tmp_interpreter.stack_d...
if current_line.len() > cursor_pos { current_line.insert(cursor_pos, c); } else { current_line.push(c); }
if_condition
[ { "content": "fn main() {\n\n let interp = interpreter::Interpreter::new();\n\n /* TODO if non- interactive\n\n\n\n let stdin = io::stdin();\n\n for line in stdin.lock().lines() {\n\n println!(\"{}\", interp.execute_line(&line.unwrap()));\n\n }\n\n */\n\n interactive::run(interp);\n...
Rust
src/apu.rs
goooosick/les
4b02a031c6d2469e57f6376a7c5553063b0a6867
use bit_field::BitField; use std::collections::VecDeque; mod dmc; mod noise; mod pulse; mod triangle; mod units; use dmc::Dmc; use noise::Noise; use pulse::Pulse; use triangle::Triangle; use units::*; trait Channel { fn sample(&mut self) -> u8; fn tick(&mut self); fn tick_len(&mut self); fn tick_eve...
use bit_field::BitField; use std::collections::VecDeque; mod dmc; mod noise; mod pulse; mod triangle; mod units; use dmc::Dmc; use noise::Noise; use pulse::Pulse; use triangle::Triangle; use units::*; trait Channel { fn sample(&mut self) -> u8; fn tick(&mut self); fn tick_len(&mut self); fn tick_eve...
lf.channel_ctrl[1]; let tnd_index = self.triangle.sample() * 3 * self.channel_ctrl[2] + self.noise.sample() * 2 * self.channel_ctrl[3] + self.dmc.sample() * self.channel_ctrl[4]; self.samples .push_back(PULSE_TABLE[pulse_index as usize] + TND_TABLE[tnd_index as usize]...
tick(); self.frame_tick(step); self.cycles += 1; if self.cycles % 2 == 0 { self.pulse1.tick(); self.pulse2.tick(); self.noise.tick(); self.dmc.tick(); } self.triangle.tick(); let pulse_index = self.pulse1.sample() * self.c...
function_block-random_span
[ { "content": "trait Channel {\n\n fn sample(&mut self) -> u8;\n\n\n\n fn tick(&mut self);\n\n fn tick_len(&mut self);\n\n fn tick_eve(&mut self);\n\n\n\n fn write_reg0(&mut self, data: u8);\n\n fn write_reg1(&mut self, data: u8);\n\n fn write_reg2(&mut self, data: u8);\n\n fn write_reg3(...
Rust
src/lib.rs
quininer/mem-aead-mrs
d8e365f207a1ed7e5848239a888708651c6fb915
#![no_std] mod common; use core::marker::PhantomData; use core::mem; use arrayref::{ array_ref, array_mut_ref }; use subtle::ConstantTimeEq; use common::{ Tag, tags, with }; pub(crate) type U = u64; pub(crate) const W: usize = 64; pub(crate) const L: usize = 4; pub(crate) const T: usize = W * 4; pub(crate) const LEN...
#![no_std] mod common; use core::marker::PhantomData; use core::mem; use arrayref::{ array_ref, array_mut_ref }; use subtle::ConstantTimeEq; use common::{ Tag, tags, with }; pub(crate) type U = u64; pub(crate) const W: usize = 64; pub(crate) const L: usize = 4; pub(crate) const T: usize = W * 4; pub(crate) const LEN...
pub(crate) fn encrypt_data(&mut self, m: &mut [u8]) { #[inline] fn encrypt_block<P: Permutation>(state: &mut [U; LENGTH], chunk: &mut [u8; BLOCK_LENGTH]) { P::permutation(state); with(state, |state| { for i in 0..BLOCK_LENGTH { state[i] ...
pub(crate) fn finalise(&mut self, hlen: usize, mlen: usize, tag: &mut [u8; TAG_LENGTH]) { P::permutation(&mut self.state); self.state[0] ^= hlen as U; self.state[1] ^= mlen as U; P::permutation(&mut self.state); with(&mut self.state, |state| { tag.copy_from_slice(&...
function_block-full_function
[ { "content": "pub fn aead_decrypt<P: Permutation>(key: &[u8; KEY_LENGTH], nonce: &[u8; NONCE_LENGTH], aad: &[u8], c: &[u8], m: &mut [u8]) -> bool {\n\n assert!(c.len() >= TAG_LENGTH);\n\n assert_eq!(m.len() + TAG_LENGTH, c.len());\n\n\n\n let (c, tag) = c.split_at(m.len());\n\n m.copy_from_slice(c);...
Rust
src/js_utils/adapters/proxies.rs
SreeniIO/utils
ed9ed1e6597a8c3e1707d3395dafdeb06ffe940b
use crate::js_utils::adapters::JsRealmAdapter; use crate::js_utils::JsError; use std::collections::HashMap; pub type JsProxyConstructor<R> = dyn Fn( &<R as JsRealmAdapter>::JsRuntimeAdapterType, &R, JsProxyInstanceId, &[<R as JsRealmAdapter>::JsValueAdapterType], ) -> Result<(), JsError>; pub type JsMe...
use crate::js_utils::adapters::JsRealmAdapter; use crate::js_utils::JsError; use std::collections::HashMap; pub type JsProxyConstructor<R> = dyn Fn( &<R as JsRealmAdapter>::JsRuntimeAdapterType, &R, JsProxyInstanceId, &[<R as JsRealmAdapter>::JsValueAdapterType], ) -> Result<(), JsError>; pub type JsMe...
pub fn set_constructor<C>(mut self, constructor: C) -> Self where C: Fn( &R::JsRuntimeAdapterType, &R, JsProxyInstanceId, &[R::JsValueAdapterType], ) -> Result<(), JsError> + 'static, { assert!(self.cons...
pub fn new(namespace: &'static [&'static str], name: &'static str) -> Self { Self { name, namespace, constructor: None, members: Default::default(), static_members: Default::default(), finalizer: None, event_target: false, ...
function_block-full_function
[ { "content": "/// add an async task the the \"helper\" thread pool\n\npub fn add_helper_task_async<R: Send + 'static, T: Future<Output = R> + Send + 'static>(\n\n task: T,\n\n) -> impl Future<Output = Result<R, JoinError>> {\n\n log::trace!(\"adding an async helper task\");\n\n HELPER_TASKS.add_task_as...
Rust
lp-import/src/readers/artist.rs
zaeleus/lp-tools
4102c51c54341e2c7311c01c9751cdc2c84f5119
use lp::models::{Artist, ArtistKind}; use lp::repositories::{ArtistNameRepository, ArtistRepository, ArtistUrlRepository}; use toml::Value; use crate::readers::{self, Error}; use crate::Context; pub fn create(ctx: &Context, root: &Value) -> Result<Artist, Error> { let artist = new(ctx, root)?; names(ctx, roo...
use lp::models::{Artist, ArtistKind}; use lp::repositories::{ArtistNameRepository, ArtistRepository, ArtistUrlRepository}; use toml::Value; use crate::readers::{self, Error}; use crate::Context; pub fn create(ctx: &Context, root: &Value) -> Result<Artist, Error> { let artist = new(ctx, root)?; names(ctx, roo...
fn urls(ctx: &Context, array: &Value, artist: &Artist) -> Result<(), Error> { let repo = ArtistUrlRepository::new(ctx.connection()); let values = array .as_array() .ok_or_else(|| Error::Parse(String::from("expected artist.urls to be an array")))?; for (i, value) in values.iter().enumerat...
fn members(ctx: &Context, array: &Value, artist: &Artist) -> Result<(), Error> { let values = array .as_array() .ok_or_else(|| Error::Parse(String::from("expected artist.members to be an array")))?; for value in values { readers::membership::create(ctx, value, artist)?; } Ok(()...
function_block-function_prefix_line
[]
Rust
src/hikapi/triggers_parser.rs
CornerBit/HikSink
07f5e5757ce58d2484c6657020772a4d874a38e7
use minidom::Element; use serde::{Deserialize, Serialize}; use super::EventIdentifier; #[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Clone)] pub struct TriggerItem { pub identifier: EventIdentifier, pub hik_id: String, pub description: String, } impl TriggerItem { pub fn parse(s: &str) -> Re...
use minidom::Element; use serde::{Deserialize, Serialize}; use super::EventIdentifier; #[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Clone)] pub struct TriggerItem { pub identifier: EventIdentifier, pub hik_id: String, pub description: String, } impl TriggerItem {
} impl From<EventIdentifier> for TriggerItem { fn from(e: EventIdentifier) -> Self { TriggerItem { description: String::new(), hik_id: format!( "{}{}", e.event_type.to_string(), e.channel .as_ref() ...
pub fn parse(s: &str) -> Result<Vec<TriggerItem>, TriggerParseError> { let root: Element = s.parse()?; let event_triggers = root .get_child("EventNotification", minidom::NSChoice::Any) .unwrap_or(&root) .get_child("EventTriggerList", minidom::NSChoice::Any) ...
function_block-full_function
[ { "content": "pub fn load_config(data: impl figment::Provider) -> Result<Config, String> {\n\n let mut cfg: Config = Figment::new()\n\n .merge(figment::providers::Env::prefixed(\"HIKSINK_\"))\n\n .merge(data)\n\n .extract()\n\n .map_err(|e| e.to_string())?;\n\n\n\n // Generate ...
Rust
interactive_engine/executor/Pegasus/src/channel/counted.rs
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
use std::marker::PhantomData; use super::*; use crate::channel::eventio::EventsBuffer; use crate::event::Event; use std::collections::{HashMap, HashSet}; use std::collections::vec_deque::VecDeque; #[allow(dead_code)] pub struct CountedPush<D, P> { ch_id: ChannelId, worker: WorkerId, target: WorkerId, ...
use std::marker::PhantomData; use super::*; use crate::channel::eventio::EventsBuffer; use crate::event::Event; use std::collections::{HashMap, HashSet}; use std::collections::vec_deque::VecDeque; #[allow(dead_code)] pub struct CountedPush<D, P> { ch_id: ChannelId, worker: WorkerId, target: WorkerId, ...
k(None) } } }
rkerId, target: WorkerId, push: P, events_buf: &EventsBuffer) -> Self{ CountedPush { ch_id, worker, target, inner: push, events_buf: events_buf.clone(), _ph: Default::default(), } } } impl<D: Data, P: Push<DataSe...
random
[ { "content": "fn internal_inner_join<L: Data + HasKey, R: Data + HasKey<Target = L::Target>>(\n\n this: Stream<L>, other: Stream<R>,\n\n) -> Result<Stream<(L, R)>, BuildJobError>\n\nwhere\n\n L::Target: Clone + Send,\n\n{\n\n this.binary(\"inner_join\", other, |info| {\n\n let mut helper = Helpe...
Rust
src/lib.rs
yodaldevoid/triangulation
9e72113206249e36dad6107b19e17b76094912a4
use core::marker::PhantomData; #[cfg(feature = "rayon")] use rayon::prelude::*; pub mod dcel; pub mod geom; pub use dcel::{EdgeIndex, PointIndex, TrianglesDCEL}; pub use geom::{Point, Triangle}; const STACK_CAPACITY: usize = 512; #[derive(Clone, Copy, Eq, Hash, Ord)] pub struct OptionIndex<T: Into<usize> + From<us...
use core::marker::PhantomData; #[cfg(feature = "rayon")] use rayon::prelude::*; pub mod dcel; pub mod geom; pub use dcel::{EdgeIndex, PointIndex, TrianglesDCEL}; pub use geom::{Point, Triangle}; const STACK_CAPACITY: usize = 512; #[derive(Clone, Copy, Eq, Hash, Ord)] pub struct OptionIndex<T: Into<usize> + From<us...
}
oop { if self.hull.triangles[edge] == OptionIndex::some(bl) { self.hull.triangles[edge] = OptionIndex::some(a); break; } edge = self.hull.next[edge].as_usize().into(); if edge.as_usize() == ...
function_block-function_prefixed
[ { "content": "/// Monotonically increases with the real angle, returns vales in range [0; 1]\n\n///\n\n/// # Examples\n\n/// ```\n\n/// # use triangulation::geom::pseudo_angle;\n\n/// let a = pseudo_angle(1.0, 1.0); // 45 degrees\n\n/// let b = pseudo_angle(2.0, 1.0); // 26 degrees\n\n/// assert!(a > b);\n\n/...
Rust
gameoflife/src/main.rs
ewized/rust
4adb152f73da3b979ee9a5be57fb681ff64d8872
use std::fmt::{Display, Formatter, Result}; use std::io::{stdin, stdout, Write}; use std::process; const WIDTH: usize = 80; const HEIGHT: usize = 15; const BLOCK: char = '*'; const SPACE: char = ' '; type PlayingArea<const X: usize, const Y: usize> = [[char; X]; Y]; fn generate_world<F, const X: usize, const Y: usiz...
use std::fmt::{Display, Formatter, Result}; use std::io::{stdin, stdout, Write}; use std::process; const WIDTH: usize = 80; const HEIGHT: usize = 15; const BLOCK: char = '*'; const SPACE: char = ' '; type PlayingArea<const X: usize, const Y: usize> = [[char; X]; Y]; fn generate_world<F, const X: usize, const Y: usiz...
let filled_world = [ [BLOCK, BLOCK, BLOCK, BLOCK, BLOCK], [BLOCK, BLOCK, BLOCK, BLOCK, BLOCK], [BLOCK, BLOCK, BLOCK, BLOCK, BLOCK], [BLOCK, BLOCK, BLOCK, BLOCK, BLOCK], [BLOCK, BLOCK, BLOCK, BLOCK, BLOCK], ]; assert_eq!(generate_world::<_, 5, 5>(|_| false), empty_world); a...
let empty_world = [ [SPACE, SPACE, SPACE, SPACE, SPACE], [SPACE, SPACE, SPACE, SPACE, SPACE], [SPACE, SPACE, SPACE, SPACE, SPACE], [SPACE, SPACE, SPACE, SPACE, SPACE], [SPACE, SPACE, SPACE, SPACE, SPACE], ];
assignment_statement
[ { "content": "fn sort(x: &str) -> String {\n\n let mut chars: Vec<char> = x.chars().collect();\n\n chars.sort_by(|a, b| a.cmp(b));\n\n\n\n String::from_iter(chars)\n\n}\n\n\n", "file_path": "anagram/src/lib.rs", "rank": 4, "score": 58452.43563598253 }, { "content": "fn main() {\n\n print...
Rust
src/lib.rs
rust-lang-nursery/seme-regions
3e9cc883048546d8705ffdaf00838e56b67347f2
#![feature(crate_in_paths)] #![feature(extern_absolute_paths)] #![feature(extern_prelude)] #![feature(in_band_lifetimes)] use std::fmt::Debug; mod test; #[derive(Clone, Debug)] pub struct SemeRegion<P: Point> { head: P, tails: Vec<P>, } pub trait Point: Copy + Ord + Debug { fn entry() -> Self; } pub tr...
#![feature(crate_in_paths)] #![feature(extern_absolute_paths)] #![feature(extern_prelude)] #![feature(in_band_lifetimes)] use std::fmt::Debug; mod test; #[derive(Clone, Debug)] pub struct SemeRegion<P: Point> { head: P, tails: Vec<P>, } pub trait Point: Copy + Ord + Debug { fn entry() -> Self; } pub tr...
pub fn is_empty(&self) -> bool { self.tails.is_empty() } pub fn contains(&self, graph: impl GraphRef<P>, point: P) -> bool { graph.dominates(self.head, point) && self.dominates_any_tail(graph, point) } fn dominates_any_tail(&self, graph: impl GraphRef<P>, point...
pub fn empty() -> SemeRegion<P> { SemeRegion { head: P::entry(), tails: vec![], } }
function_block-full_function
[ { "content": "struct GraphPair {\n\n graph: Graph<(), ()>,\n\n dominators: Dominators<NodeIndex>,\n\n}\n\n\n\nimpl GraphPair {\n\n fn new(edges: &[(usize, usize)]) -> GraphPair {\n\n let num_nodes = edges\n\n .iter()\n\n .map(|(a, b)| ::std::cmp::max(a + 1, b + 1))\n\n ...
Rust
sgx/ias-types/src/quote.rs
MixinNetwork/mobilecoin
5ffd861904185edbc0d17ab6b37bcd8983d7b15b
use core::convert::{TryFrom, TryInto}; use mc_sgx_core_types::{ReportBody, SecurityVersion, REPORT_BODY_SIZE, SECURITY_VERSION_SIZE}; use mc_sgx_epid_types::{ Basename, EpidGroupId, Quote as SgxQuote, QuoteSign, BASENAME_SIZE, EPID_GROUP_ID_SIZE, }; use mc_util_encodings::{Error as EncodingError, FromBase64, INTE...
use core::convert::{TryFrom, TryInto}; use mc_sgx_core_types::{ReportBody, SecurityVersion, REPORT_BODY_SIZE, SECURITY_VERSION_SIZE}; use mc_sgx_epid_types
u32 == self.qe_svn && other.pce_security_version() as u32 == self.pce_svn && other.xeid() == self.xeid && other.basename() == self.basename && other.report_body() == self.report_body } } impl ReprBytes for Quote { type Size = U432; type Error = EncodingError;...
::{ Basename, EpidGroupId, Quote as SgxQuote, QuoteSign, BASENAME_SIZE, EPID_GROUP_ID_SIZE, }; use mc_util_encodings::{Error as EncodingError, FromBase64, INTEL_U16_SIZE, INTEL_U32_SIZE}; use mc_util_repr_bytes::{typenum::U432, GenericArray, ReprBytes}; #[cfg(feature = "use_prost")] use prost::Message; const VERSI...
random
[ { "content": "## Prohibited Uses and Transfers of MobileCoins and Uses of MobileCoin Wallets\n\n\n\nYou may not:\n\n- use or transfer MobileCoins or access or use a MobileCoin Wallet in order to disguise the origin or nature of illicit proceeds of, or to further, any breach of applicable laws, or to transact or...
Rust
src/conventional/changelog.rs
cpoissonnier/cocogitto
551dc326ee5baf586bd26e49d5f1be35135b7f02
use crate::conventional::commit::Commit; use crate::{OidOf, COMMITS_METADATA}; use anyhow::Result; use itertools::Itertools; use std::fmt::Write; use std::fs; use std::path::PathBuf; pub(crate) struct Changelog { pub from: OidOf, pub to: OidOf, pub date: String, pub commits: Vec<Commit>, pub tag_na...
use crate::conventional::commit::Commit; use crate::{OidOf, COMMITS_METADATA}; use anyhow::Result; use itertools::Itertools; use std::fmt::Write; use std::fs; use std::path::PathBuf; pub(crate) struct Changelog { pub from: OidOf, pub to: OidOf, pub date: String, pub commits: Vec<Commit>, pub tag_na...
}
let content = ch.markdown(false); println!("{}", content); assert!(content.contains("## 5375e1..35085f")); assert!(!content.contains("### Features")); Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn verify(author: Option<String>, message: &str) -> Result<(), ParseError> {\n\n let commit = conventional_commit_parser::parse(message);\n\n\n\n match commit {\n\n Ok(message) => {\n\n println!(\n\n \"{}\",\n\n Commit {\n\n ...
Rust
src/signature.rs
stormasm/engine-q1
038de047e01bac48ecb266673b53775c470db943
use crate::{parser::SyntaxShape, Declaration, VarId}; #[derive(Debug, Clone)] pub struct Flag { pub long: String, pub short: Option<char>, pub arg: Option<SyntaxShape>, pub required: bool, pub desc: String, pub var_id: Option<VarId>, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Pos...
use crate::{parser::SyntaxShape, Declaration, VarId}; #[derive(Debug, Clone)] pub struct Flag { pub long: String, pub short: Option<char>, pub arg: Option<SyntaxShape>, pub required: bool, pub desc: String, pub var_id: Option<VarId>, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Pos...
pub fn switch( mut self, name: impl Into<String>, desc: impl Into<String>, short: Option<char>, ) -> Signature { let s = short.map(|c| { debug_assert!( !self.get_shorts().contains(&c), "There may be duplicate short flags,...
impl Into<SyntaxShape>, desc: impl Into<String>, short: Option<char>, ) -> Signature { let s = short.map(|c| { debug_assert!(!self.get_shorts().contains(&c)); c }); self.named.push(Flag { long: name.into(), short: s, ...
function_block-function_prefixed
[]
Rust
src/vm.rs
UCSBarchlab/Sprocket
c782e01b38629400360f1138be3445991db20d4c
use alloc::boxed::Box; use core; use process; use x86::shared::segmentation::SegmentDescriptor; use x86::shared::segmentation as seg; use x86::shared::dtables::{DescriptorTablePointer, lgdt}; use x86::shared::PrivilegeLevel; use x86::shared::control_regs; use spinlock::Mutex; use mmu; use mem::{PhysAddr, VirtAddr, Addr...
use alloc::boxed::Box; use core; use process; use x86::shared::segmentation::SegmentDescriptor; use x86::shared::segmentation as seg; use x86::shared::dtables::{DescriptorTablePointer, lgdt}; use x86::shared::PrivilegeLevel; use x86::shared::control_regs; use spinlock::Mutex; use mmu; use mem::{PhysAddr, VirtAddr, Addr...
= PRESENT { panic!("remap failed"); } let mut new_entry = permissions | PRESENT; new_entry.bits |= pa.addr(); *pte = PageTableEntry(new_entry); if a == last { break; } a = a.offset::<u8>(PGSIZE as isize); pa = pa.offset::<u8>(PGSIZ...
d: EXTMEM, perm: WRITABLE, }, Kmap { virt: KERNLINK, p_start: KERNLINK.to_phys(), p_end: DATA_BEGIN.to_phys(), perm: Entry::empty(), }, Kmap { virt: DATA_BEGIN, ...
random
[ { "content": "/// A utility trait that implements common methods for `PhysAddr` and `VirtAddr`\n\npub trait Address {\n\n fn new(usize) -> Self where Self: core::marker::Sized;\n\n\n\n fn addr(&self) -> usize;\n\n\n\n fn is_page_aligned(&self) -> bool {\n\n self.addr() % PGSIZE == 0\n\n }\n\n...
Rust
src/lib.rs
lxsymington/WASM_Game_Of_Life
8a1cfef15539ff05c5ae6257853f940b65f5c936
extern crate fixedbitset; extern crate js_sys; mod cell_buffer; mod graph; mod timer; mod utils; use cell_buffer::CellBuffer; use fixedbitset::FixedBitSet; use graph::Graph; use std::fmt; use wasm_bindgen::prelude::*; /* When the `wee_alloc` feature is enabled, use `wee_alloc` as the global allocator. */ #[cfg(featu...
extern crate fixedbitset; extern crate js_sys; mod cell_buffer; mod graph; mod timer; mod utils; use cell_buffer::CellBuffer; use fixedbitset::FixedBitSet; use graph::Graph; use std::fmt; use wasm_bindgen::prelude::*; /* When the `wee_alloc` feature is enabled, use `wee_alloc` as the global allocator. */ #[cfg(featu...
pub fn cell_coords(&mut self) -> *const f32 { let (active, _) = self.cell_buffer.buffers(); self.graph.cell_coords(active, self.width, self.height) } pub fn cell_coords_count(&self) -> u32 { self.graph.cell_coords_count() } pub fn grid_line_coords(&mut self) -> *const f3...
pub fn insert_pulsar(&mut self, row: u32, col: u32) { let pulsar = vec![ (-6, -4), (-6, -3), (-6, -2), (-6, 2), (-6, 3), (-6, 4), (-4, -6), (-4, -1), (-4, 1), (-4, 6), (-3, -6), ...
function_block-full_function
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
oauth2-client/src/client_credentials_grant/provider_ext.rs
bk-rs/oauth2-rs
c4ea79eff2d8063870fb447561b7ca2d0d26a884
use std::{error, fmt}; use dyn_clone::{clone_trait_object, DynClone}; pub use oauth2_core::access_token_request::BodyWithClientCredentialsGrant; use crate::{ re_exports::{Body, ClientId, ClientSecret, Map, Request, Scope, Url, Value}, Provider, }; pub trait ProviderExtClientCredentialsGrant: Provider + DynCl...
use std::{error, fmt}; use dyn_clone::{clone_trait_object, DynClone}; pub use oauth2_core::access_token_request::BodyWithClientCredentialsGrant; use crate::{ re_exports::{Body, ClientId, ClientSecret, Map, Request, Scope, Url, Value}, Provider, }; pub trait ProviderExtClientCredentialsGrant: Provider + DynCl...
self.inner.access_token_request_body_extra(&body) } fn access_token_request_url_modifying(&self, url: &mut Url) { self.inner.access_token_request_url_modifying(url) } fn access_token_request_modifying(&self, request: &mut Request<Body>) { self.inner.access_token_request_modif...
let body = match BodyWithClientCredentialsGrant::<<P as Provider>::Scope>::try_from_t_with_string( body, ) { Ok(x) => x, Err(err) => return Some(Err(Box::new(err))), };
assignment_statement
[ { "content": "//\n\npub trait Scope: str::FromStr + ToString + fmt::Debug + Clone + cmp::PartialEq {}\n\n\n\nimpl Scope for String {}\n\n\n\n//\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub struct ScopeParameter<T>(pub Vec<T>);\n\n\n\nimpl<T> From<Vec<T>> for ScopeParameter<T> {\n\n fn from(v: Vec<T>) -> ...
Rust
docstore-adapter-2ry-pg/src/storage.rs
crocme10/j3-graphql
1e11d426a1d01fe48582c0ce78e9f5dd08511b3e
use async_trait::async_trait; use chrono::{DateTime, Utc}; use sqlx::postgres::PgRow; use sqlx::{FromRow, Row}; use uuid::Uuid; use super::Error as PostgresError; use super::PostgresqlStorage; use docstore_domain::model::document::{ AddDocumentRequest, Document, Genre, GetDocumentRequest, ListDocumentsRequest, }; ...
use async_trait::async_trait; use chrono::{DateTime, Utc}; use sqlx::postgres::PgRow; use sqlx::{FromRow, Row}; use uuid::Uuid; use super::Error as PostgresError; use super::PostgresqlStorage; use docstore_domain::model::document::{ AddDocumentRequest, Document, Genre, GetDocumentRequest, ListDocumentsRequest, }; ...
let documents = entities.into_iter().map(Document::from).collect::<Vec<_>>(); Ok(documents) } async fn add_document(&self, request: &AddDocumentRequest) -> Result<Document, Error> { let entity: DocumentEntity = sqlx::query_as(r#"SELECT * FROM api.add_document($1::UUID, $2...
let entities: Vec<DocumentEntity> = sqlx::query_as(r#"SELECT * FROM api.list_documents($1::INTEGER, $2::INTEGER)"#) .bind(&request.limit) .bind(&request.offset) .fetch_all(&*self.pool) .await .map_err(PostgresError::from)?;
assignment_statement
[ { "content": "pub fn default_genre() -> Genre {\n\n Genre::Tbd\n\n}\n\n\n\nimpl Genre {\n\n pub fn as_str(&self) -> &'static str {\n\n match self {\n\n Genre::Tutorial => \"tutorial\",\n\n Genre::Howto => \"howto\",\n\n Genre::Background => \"background\",\n\n ...
Rust
src/wrappers/unreal/goal.rs
edmiester777/bakkesmod-rust
d7ef3861cfa9f80c8eaa2bbf443028361b14287e
use crate::wrappers::{*, structs::*, unreal::*}; use super::*; pub struct GoalWrapper(pub usize); impl_object!(GoalWrapper); impl Goal for GoalWrapper {} pub trait Goal : Object { fn get_goal_orientation(&self) -> Option<ActorWrapper> { unsafe { ActorWrapper::try_new(Goal_TA_Get_GoalOrientati...
use crate::wrappers::{*, structs::*, unreal::*}; use super::*; pub struct GoalWrapper(pub usize); impl_object!(GoalWrapper); impl Goal for GoalWrapper {} pub trait Goal : Object { fn get_goal_orientation(&self) -> Option<ActorWrapper> { unsafe { ActorWrapper::try_new(Goal_TA_Get_GoalOrientati...
fn get_local_extent(&self) -> Vector { unsafe { let mut result = Vector::new(); let result_ptr: *mut Vector = &mut result as *mut Vector; Goal_TA_Get_LocalExtent(self.addr(), result_ptr); result } } fn get_world_center(&self) -> Vector { ...
fn get_rotation(&self) -> Rotator { unsafe { let mut result = Rotator::new(); let result_ptr: *mut Rotator = &mut result as *mut Rotator; Goal_TA_Get_Rotation(self.addr(), result_ptr); result } }
function_block-full_function
[ { "content": "pub fn is_ranked(playlist_id: i32) -> bool {\n\n unsafe { IsRanked(playlist_id) }\n\n}\n\n\n", "file_path": "src/wrappers/mmr.rs", "rank": 1, "score": 251528.19301122363 }, { "content": "pub fn calculate_mmr(skill_rating: SkillRating, disregard_placements: bool) -> f32 {\n\n...
Rust
src/ps/agent/messages.rs
Pennsieve/agent
28340a66abfe8916aea6566261678ae9eddd9d7f
use std::net::SocketAddr; use std::path::Path; use std::string::ToString; use actix::prelude::*; use actix_net::server as s; use serde_derive::{Deserialize, Serialize}; use crate::ps::agent::server; #[derive(Clone, Debug, Message)] pub struct SystemShutdown; #[derive(Clone, Debug)] pub struct StartStatusServer { ...
use std::net::SocketAddr; use std::path::Path; use std::string::ToString; use actix::prelude::*; use actix_net::server as s; use serde_derive::{Deserialize, Serialize}; use crate::ps::agent::server; #[derive(Clone, Debug, Message)] pub struct SystemShutdown; #[derive(Clone, Debug)] pub struct StartStatusServer { ...
} #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(tag = "message")] pub enum Response { Error { context: String }, UploadError { context: String, import_id: String }, IncomingProxyRequest { url: String }, FileQueuedForUpload { path: Strin...
pub fn queue_upload( dataset: String, package: Option<String>, files: Vec<String>, recursive: Option<bool>, append: Option<bool>, ) -> Self { Request::QueueUpload { body: QueueUpload { dataset, package, files...
function_block-full_function
[ { "content": "/// Generate a 50x HTTP response with the specified message\n\npub fn fail_with_message(reason: String) -> Response<Body> {\n\n Response::builder()\n\n .status(StatusCode::INTERNAL_SERVER_ERROR)\n\n .body(reason.into())\n\n .expect(\"couldn't create response\")\n\n}\n\n\n\n...
Rust
src/tree.rs
yoshuawuyts/eyros
7782fd6294d77a9654df5e9db38f7355d8cf3c21
use random_access_storage::RandomAccess; use failure::{Error,format_err,bail}; use std::cell::RefCell; use std::rc::Rc; use std::mem::size_of; use crate::{Point,Value,Location}; use crate::branch::{Branch,Node}; use crate::data::{DataStore,DataMerge,DataBatch}; use crate::read_block::read_block; pub struct TreeIterat...
use random_access_storage::RandomAccess; use failure::{Error,format_err,bail}; use std::cell::RefCell; use std::rc::Rc; use std::mem::size_of; use crate::{Point,Value,Location}; use crate::branch::{Branch,Node}; use crate::data::{DataStore,DataMerge,DataBatch}; use crate::read_block::read_block; pub struct TreeIterat...
max_data_size: usize, } impl<S,P,V> Tree<S,P,V> where S: RandomAccess<Error=Error>, P: Point, V: Value { pub fn open (opts: TreeOpts<S,P,V>) -> Result<Self,Error> { let bytes = opts.store.len()? as u64; let data_merge = Rc::new(RefCell::new( DataMerge::new(Rc::clone(&opts.data_store)))); Ok(Self...
eOpts<S,P,V> where S: RandomAccess<Error=Error>, P: Point, V: Value { pub store: S, pub data_store: Rc<RefCell<DataStore<S,P,V>>>, pub branch_factor: usize, pub max_data_size: usize, pub index: usize, } pub struct Tree<S,P,V> where S: RandomAccess<Error=Error>, P: Point, V: Value { pub store: S, data_sto...
random
[ { "content": "pub fn pad<P> (xs: &Vec<P>, n: usize) -> Vec<P> where P: Point {\n\n let mut len = xs.len();\n\n if len == 0 {\n\n panic![\"attempted to pad pivots from an empty source\"];\n\n }\n\n let mut res = xs.clone();\n\n if len == 1 {\n\n let r = res[0];\n\n for _ in 1..n {\n\n res.push...
Rust
src/lib.rs
Wafflespeanut/Memoir
09bf9a882c24061da1560416c57f64b22a13b683
#![allow(dead_code, unused_imports)] extern crate libc; extern crate rand as random; extern crate rustc_serialize as serialize; mod cipher; use cipher::{Mode, zombify}; use std::ffi::{CStr, CString}; use std::fs::File; use std::io::Read; use std::sync::{Arc, mpsc}; use std::{str, slice, thread}; use libc::{size_t, c_...
#![allow(dead_code, unused_imports)] extern crate libc; extern crate rand as random; extern crate rustc_serialize as serialize; mod cipher; use cipher::{Mode, zombify}; use std::ffi::{CStr, CString}; use std::fs::File; use std::io::Read; use std::sync::{Arc, mpsc}; use std::{str, slice, thread}; use libc::{size_t, c_...
let end_idx = start_idx + slice_size; let sender = tx.clone(); let handle = thread::spawn(move || { let thread_stuff = stuff[start_idx..end_idx] .iter() .map(|&file_name| (start_idx, count_words(file_name, &key, word)))...
let slice_size = match thread_idx < extra { true => stuff_per_chunk + 1, false => stuff_per_chunk, };
assignment_statement
[ { "content": "// Invokes the helper functions and does its shifting thing\n\npub fn zombify(mode: Mode, data: &[u8], key: &str) -> Vec<u8> {\n\n let hexed_key = key.as_bytes().to_hex();\n\n let amount = hexed_key.as_bytes()\n\n .iter()\n\n .fold(0u8, |amt,...
Rust
src/rust/bluetooth_device.rs
jdm/blurdroid
5b22d7322acbf302905bf110799f909ac7f7b2d7
use ffi; use std::cell::Cell; use std::collections::HashMap; use std::error::Error; use std::os::raw::{c_char, c_int}; use std::ptr::{self}; use std::sync::Arc; use utils; use bluetooth_adapter::Adapter; #[derive(Clone, Debug)] struct IDevice { device: Cell<*mut ffi::BluetoothDevice>, } #[derive(Debug)] pub stru...
use ffi; use std::cell::Cell; use std::collections::HashMap; use std::error::Error; use std::os::raw::{c_char, c_int}; use std::ptr::{self}; use std::sync::Arc; use utils; use bluetooth_adapter::Adapter; #[derive(Clone, Debug)] struct IDevice { device: Cell<*mut ffi::BluetoothDevice>, } #[derive(Debug)] pub stru...
pub fn get_appearance(&self) -> Result<u16, Box<Error>> { Err(Box::from(utils::NOT_SUPPORTED_ERROR)) } pub fn get_icon(&self) -> Result<String, Box<Error>> { Err(Box::from(utils::NOT_SUPPORTED_ERROR)) } pub fn get_class(&self) -> Result<u32, Box<Error>> { Err(Box::from(ut...
0 { ffi::jni_free_int_array(values); } m.insert(key, v); } } Ok(m) }
function_block-function_prefixed
[ { "content": "pub fn convert_cstr(c: & *const c_char, err: &str) -> Result<String, Box<Error>> {\n\n let res = match from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }) {\n\n Ok(a) => Ok(a.to_string()),\n\n Err(_) => Err(Box::from(err)),\n\n };\n\n res\n\n}\n", "file_path": "src/rust...
Rust
src/photovoltaic_simulator.rs
at-robins/pv_simulator
01e3b954ea35629de04050c2df0bb4e60feba87e
extern crate rand; use super::meter::{BrokerMessage, METER_ROUTING_KEY}; use super::pv_error::PvError; use amiquip::{Connection, ConsumerMessage, ConsumerOptions, QueueDeclareOptions}; use chrono::{DateTime, NaiveTime, Timelike, Utc}; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use std::fs::{cre...
extern crate rand; use super::meter::{BrokerMessage, METER_ROUTING_KEY}; use super::pv_error::PvError; use amiquip::{Connection, ConsumerMessage, ConsumerOptions, QueueDeclareOptions}; use chrono::{DateTime, NaiveTime, Timelike, Utc}; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use std::fs::{cre...
} ConsumerMessage::ClientCancelled => break, other => { return Err(PvError::InternalError(format!( "Consumer did not expect: {:?}", other ))) } ...
if message.is_simulation_end() { consumer.cancel()?; } else { let record = self.message_to_record(message)?; self.records.push(record); }
if_condition
[ { "content": "/// Simulates the `Meter` and photovoltaic component as specified by the exercise's description.\n\n/// The results are written to the specified file.\n\n///\n\n/// # Parameters\n\n/// * `stride` - the simulated time steps\n\n/// * `simulation_length` - the total simulation length\n\n/// * `broker...
Rust
crates/rune/src/hash.rs
cmarincia/rune
26a784353c6aaa1573daed15a9625bab615dd2ca
use crate::compile::{IntoComponent, Item}; use crate::runtime::Protocol; use crate::Any; use serde::{Deserialize, Serialize}; use std::any; use std::fmt; use std::hash::{self, BuildHasher, BuildHasherDefault, Hash as _, Hasher}; use std::mem; use twox_hash::XxHash64; const SEP: u64 = 0x4bc94d6bd06053ad; const PARAMS: ...
use crate::compile::{IntoComponent, Item}; use crate::runtime::Protocol; use crate::Any; use serde::{Deserialize, Serialize}; use std::any; use std::fmt; use std::hash::{self, BuildHasher, BuildHasherDefault, Hash as _, Hasher}; use std::mem; use twox_hash::XxHash64; const SEP: u64 = 0x4bc94d6bd06053ad; const PARAMS: ...
} #[derive(Clone, Copy)] pub struct Params<T, P>(pub T, pub P); impl<T, P> InstFnName for Params<T, P> where T: InstFnName, P: Copy + IntoIterator, P::Item: IntoTypeHash, { fn name_hash(self) -> Hash { self.0.name_hash() } fn info(self) -> InstFnInfo { let info = self.0.info(...
fn info(self) -> InstFnInfo { InstFnInfo { hash: self, kind: InstFnKind::Hash(self), parameters: Hash::EMPTY, } }
function_block-function_prefix_line
[]
Rust
src/combination.rs
ssccinng/pcf
12337b018d416e23d9d696ba9f9cb9187016b6fd
use crate::*; pub fn find_combinations( piece_set: PieceSet, board: BitBoard, height: usize, mut combo_consumer: impl FnMut(&[Placement]) -> SearchStatus ) { find_combos_st( &mut vec![], board, BitBoard::filled(height), piece_set, height, &mut combo_consumer ...
use crate::*; pub fn find_combinations( piece_set: PieceSet, board: BitBoard, height: usize, mut combo_consumer: impl F
pub fn find_combinations_mt( piece_set: PieceSet, board: BitBoard, height: usize, combo_consumer: impl FnMut(&[Placement]) -> SearchStatus + Clone + Send ) { rayon::scope(|scope| find_combos_mt( scope, vec![], board, BitBoard::filled(height), piece_set, height, 0, combo_consumer ...
nMut(&[Placement]) -> SearchStatus ) { find_combos_st( &mut vec![], board, BitBoard::filled(height), piece_set, height, &mut combo_consumer ); }
function_block-function_prefixed
[ { "content": "pub fn hard_drop_only(mut board: BitBoard, placement: Placement) -> bool {\n\n for y in 0..6 {\n\n if board.line_filled(y) {\n\n board.0 &= !((1<<10)-1 << 10*y);\n\n }\n\n }\n\n !board.overlaps(placement.harddrop_mask())\n\n}\n\n\n", "file_path": "src/placeabi...
Rust
diary_app_lib/src/s3_interface.rs
ddboline/diary_app_rust
235296f39529c53f5a5f4da9b75a6b0690eb306f
use anyhow::{format_err, Error}; use chrono::{DateTime, NaiveDate, Utc}; use futures::future::try_join_all; use lazy_static::lazy_static; use log::debug; use rusoto_s3::Object; use stack_string::StackString; use std::{ collections::HashMap, convert::{TryFrom, TryInto}, sync::Arc, }; use tokio::sync::RwLock;...
use anyhow::{format_err, Error}; use chrono::{DateTime, NaiveDate, Utc}; use futures::future::try_join_all; use lazy_static::lazy_static; use log::debug; use rusoto_s3::Object; use stack_string::StackString; use std::{ collections::HashMap, convert::{TryFrom, TryInto}, sync::Arc, }; use tokio::sync::RwLock;...
pub async fn upload_entry(&self, date: NaiveDate) -> Result<Option<DiaryEntries>, Error> { let entry = match DiaryEntries::get_by_date(date, &self.pool).await? { Some(e) => e, None => return Ok(None), }; if entry.diary_text.trim().is_empty() { return Ok(...
None => true, }; if should_update { return self.upload_entry(diary_date).await; } Ok(None) } }); let results: Result<Vec<_>, Error> = try_join_all(futures).await; Ok(result...
function_block-function_prefix_line
[ { "content": "fn extract_dates(path: &Path) -> Result<HashSet<NaiveDate>, Error> {\n\n path.read_dir()?\n\n .map(|entry| {\n\n if let Some(filename) = entry?.path().file_name() {\n\n let filename = filename.to_string_lossy().replace(\".txt\", \"\");\n\n let dat...
Rust
examples/amdgpu/gemm/main.rs
Flakebi/geobacter
b6fccb57c19c44a445416ac8c99849ec6ef28173
#![feature(geobacter)] #![feature(register_attr)] #![register_attr(geobacter_attr)] extern crate grt_amd as geobacter_runtime_amd; use grt_amd::prelude::*; use grt_amd::texture::{access::*, geometry::*}; use num_traits::AsPrimitive; use rand::distributions::Uniform; use rand::prelude::*; use packed_simd::*; use...
#![feature(geobacter)] #![feature(register_attr)] #![register_attr(geobacter_attr)] extern crate grt_amd as geobacter_runtime_amd; use grt_amd::prelude::*; use grt_amd::texture::{access::*, geometry::*}; use num_traits::AsPrimitive; use rand::distributions::Uniform; use rand::prelude::*; use packed_simd::*; use...
:<ETy>()) / 1024 / 1024); let mut la = LapVec::with_capacity_in(SIZE, alloc.clone()); let mut lb = LapVec::with_capacity_in(SIZE, alloc.clone()); let mut lc: LapVec<ETy> = LapVec::with_capacity_in(SIZE, alloc.clone()); let mut nd_lc = LapVec::with_capacity_in(SIZE, alloc.clone()); la.resize(SIZE, 0u32....
AXIS_SIZE; const GRID: usize = AXIS_SIZE; let shape = (AXIS_SIZE, AXIS_SIZE); let dim = NonZeroU16::new(AXIS_SIZE as u16).unwrap(); let hardness = (2 * AXIS_SIZE * AXIS_SIZE * AXIS_SIZE) as f64; let mut invoc = GemmArgs::module(&dev); invoc.define_param(dim_spec_param, &dim); invoc.define_param(mod_bloc...
function_block-random_span
[ { "content": "pub fn time<F, R>(what: &str, f: F) -> R\n\n where F: FnOnce() -> R,\n\n{\n\n let start = Instant::now();\n\n let r = f();\n\n let elapsed = start.elapsed();\n\n println!(\"{} took {}ms ({}μs)\", what,\n\n elapsed.as_millis(), elapsed.as_micros());\n\n\n\n r\n\n}\n\n\n", "file_...
Rust
src/r3_core/src/utils/alloc.rs
r3-os/r3
46f460a031ad518fd4c3582ab9c87e31e9cc8806
use core::{alloc::Layout, ptr, ptr::NonNull}; macro_rules! const_try_result { ($x:expr) => { match $x { Ok(x) => x, Err(x) => return Err(x), } }; } pub struct ConstAllocator { ref_count: *mut usize, } impl ConstAllocator { ...
use core::{alloc::Layout, ptr, ptr::NonNull}; macro_rules! const_try_result { ($x:expr) => { match $x { Ok(x) => x, Err(x) => return Err(x), } }; } pub struct ConstAllocator { ref_count: *mut usize, } impl ConstAllocator { ...
&A where A: ~const Allocator + ?Sized, { #[inline] fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { (**self).allocate(layout) } #[inline] fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { (**self).allocate_zeroed(layout) ...
let this = Self { ref_count }; f.call(&this) } } trait FnOnceConstAllocator { type Output; fn call(self, allocator: &ConstAllocator) -> Self::Output; } impl<T: ~const FnOnce(&ConstAllocator) -> Output, Output> const FnOnceConstAllocator for T { type Output = Output; fn call(self, allocato...
random
[ { "content": "/// Sort the slice with a comparator function.\n\npub fn insertion_sort_by<T>(a: &mut [T], mut f: impl FnMut(&T, &T) -> Ordering) {\n\n insertion_sort_inner(a, |x, y| f(x, y) == Ordering::Less);\n\n}\n\n\n", "file_path": "src/r3_test_suite/src/utils/sort.rs", "rank": 0, "score": 306...
Rust
compiler/codegen/src/string.rs
peakchen90/xlang
3e98e03d12f8b3e65c3bfdbbfb38887c8d6ed424
use crate::utils::{encode_utf16_str, get_string_utf16_chars}; use crate::Compiler; use inkwell::types::*; use inkwell::values::{ AggregateValue, ArrayValue, BasicValue, FloatValue, InstructionOpcode, InstructionValue, IntValue, PointerValue, StructValue, }; use inkwell::AddressSpace; impl<'ctx> Compiler<'ctx> ...
use crate::utils::{encode_utf16_str, get_string_utf16_chars}; use crate::Compiler; use inkwell::types::*; use inkwell::values::{ AggregateValue, ArrayValue, BasicValue, FloatValue, InstructionOpcode, InstructionValue, IntValue, PointerValue, StructValue, }; use inkwell:
self.builder.build_store(ptr2, ty2.const_float(6.8)); let a = self.builder.build_ptr_to_int(ptr2, ty, "aa"); self.builder.build_store(ptr, a); let address = self.builder.build_load(ptr, "").into_int_value(); let a_ptr = self.builder.build_int_to_ptr( address, ...
:AddressSpace; impl<'ctx> Compiler<'ctx> { pub fn build_string_value(&self, value: &str) -> IntValue<'ctx> { let chars = get_string_utf16_chars(value); let size = chars.len() as u32; let i16_type = self.context.i16_type(); let i32_type = self.context.i32_type(); l...
random
[ { "content": "use crate::helper::{never, Terminator};\n\nuse crate::scope::{BlockScope, FunctionScope, Label, Labels, ScopeType};\n\nuse inkwell::builder::Builder;\n\nuse inkwell::context::Context;\n\nuse inkwell::execution_engine::*;\n\nuse inkwell::module::Module;\n\nuse inkwell::targets::*;\n\nuse inkwell::t...
Rust
src/volume/mod.rs
pjohansson/create_system
3c69cd4853f0ee838b6d6c21c7935654b90da7a5
mod cuboid; mod cylinder; mod sphere; use crate::{ coord::{Coord, Direction, Periodic}, iterator::ResidueIterOut, system::Component, }; pub use self::{cuboid::Cuboid, cylinder::Cylinder, sphere::Spheroid}; use serde_derive::{Deserialize, Serialize}; pub trait Contains { fn contains(&self, coo...
mod cuboid; mod cylinder; mod sphere; use crate::{ coord::{Coord, Direction, Periodic}, iterator::ResidueIterOut, system::Component, }; pub use self::{cuboid::Cuboid, cylinder::Cylinder, sphere::Spheroid}; use serde_derive::{Deserialize, Serialize}; pub trait Contains { fn contains(&self, coo...
#[test] fn coordinates_within_cuboid_are_pruned() { let pruning_vol = Cuboid { size: Coord::new(1.0, 1.0, 1.0), ..Cuboid::default() }; let coords_within = vec![ Coord::new(0.1, 0.1, 0.1), Coord::new(0.5, 0.5, 0.5), Coord::new...
assert_eq!( FillType::Density(density).to_num_coords(&cuboid), expected_num_coords ); let num = 11; assert_eq!(FillType::NumCoords(num).to_num_coords(&cuboid), num); }
function_block-function_prefix_line
[ { "content": "/// Cut a set of coordinates into a circle with input radius in the x-y plane.\n\nfn cut_circle(coords: &[Coord], center: Coord, box_size: Coord, radius: f64) -> Vec<Coord> {\n\n coords\n\n .iter()\n\n .map(|&coord| coord.with_pbc(box_size) - center)\n\n .filter(|coord| {\n...
Rust
tests/health_check.rs
kod-kristoff/zero2prod-axum
f7e16613109795e98bd8acebfea578a154ce6ce8
use std::net::{SocketAddr, TcpListener}; use secrecy::ExposeSecret; use sqlx::{postgres::PgConnection, Connection, Executor}; use zero2prod::configuration::{get_configuration, DatabaseSettings}; use zero2prod::db::DbPool; #[tokio::test] async fn health_check_works() { let ctx = Context::try_new().await.expe...
use std::net::{SocketAddr, TcpListener}; use secrecy::ExposeSecret; use sqlx::{postgres::PgConnection, Connection, Executor}; use zero2prod::configuration::{get_configuration, DatabaseSettings}; use zero2prod::db::DbPool; #[tokio::test] async fn health_check_works() { let ctx = Context::try_new().await.expe...
} async fn serve(pool: DbPool) -> Result<SocketAddr, Box<dyn std::error::Error>> { let addr = SocketAddr::from(([127, 0, 0, 1], 0)); let listener = TcpListener::bind(&addr)?; let addr = listener.local_addr()?; tokio::spawn(async move { zero2prod::startup::run(listener, pool).await }); Ok(ad...
async fn try_new() -> Result<Self, Box<dyn std::error::Error>> { Lazy::force(&TRACING); let mut configuration = get_configuration().expect("Failed to read configuration."); configuration.database.database_name = uuid::Uuid::new_v4().to_string(); let pool = configure_database(&configurati...
function_block-full_function
[ { "content": "pub fn init_subscriber(subscriber: impl Subscriber + Send + Sync) {\n\n tracing_log::LogTracer::init().expect(\"Failed to set logger\");\n\n tracing::subscriber::set_global_default(subscriber).expect(\"Failed to set subscriber\");\n\n}\n\n\n", "file_path": "src/telemetry.rs", "rank":...
Rust
crates/wasmer/src/lib.rs
tsmartt/wasmer-ruby
c1b554b5b3d14f17405940dc6c0951b898113ef1
#![deny(warnings)] #[cfg(doc)] mod doc; mod error; mod exports; mod externals; mod import_object; mod instance; mod memory; mod module; mod prelude; mod store; mod types; mod values; mod wasi; mod wat; #[cfg(doc)] pub use doc::*; use crate::memory::views::{ Int16Array, Int32Array, Int8Array, Uint16Array, Uint32A...
#![deny(warnings)] #[cfg(doc)] mod doc; mod error; mod exports; mod externals; mod import_object; mod instance; mod memory; mod module; mod prelude; mod store; mod types; mod values; mod wasi; mod wat; #[cfg(doc)] pub use doc::*; use crate::memory::views::{ Int16Array, Int32Array, Int8Array, Uint16Array, Uint32A...
class (externals::global::ruby_global) Global { def_self (new) "new"; def (mutable) "mutable?"; def (get_value) "value"; def (set_value) "value="; def (r#type) "type"; }; class (externals::table::ruby_table) Table {...
function_block-function_prefix_line
[ { "content": "pub fn to_ruby_err<Type, Error>(error: Error) -> AnyException\n\nwhere\n\n Type: ErrorType,\n\n Error: ToString,\n\n{\n\n AnyException::new(Type::name(), Some(error.to_string().as_ref()))\n\n}\n", "file_path": "crates/wasmer/src/error.rs", "rank": 0, "score": 196762.7197243163...
Rust
src/winffi.rs
masthoon/appjaillauncher-rs
c45f1b22cf9fb384563343f354c8e858cc0b6053
#![allow(dead_code)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![cfg(windows)] extern crate winapi; extern crate kernel32; extern crate libc; extern crate widestring; #[allow(unused_imports)] use log::*; use self::widestring::WideString; use self::winapi::*; use std...
#![allow(dead_code)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![cfg(windows)] extern crate winapi; extern crate kernel32; extern crate libc; extern crate widestring; #[allow(unused_imports)] use log::*; use self::widestring::WideString; use self::winapi::*; use std...
pub fn sid_to_string(pSid: PSID) -> Result<String, DWORD> { let mut rawStringSid: LPWSTR = 0 as LPWSTR; if unsafe { ConvertSidToStringSidW(pSid, &mut rawStringSid) } == 0 || rawStringSid == (0 as LPWSTR) { return Err(unsafe { kernel32::GetLastError() }); } let rawStringSidLen = unsafe...
if unsafe { ConvertStringSidToSidW(wSid.as_ptr(), &mut pSid) } == 0 { return Err(unsafe { kernel32::GetLastError() }); } Ok(SidPtr::new(pSid)) }
function_block-function_prefix_line
[]
Rust
src/project/cargo.rs
jpastuszek/denim
ce38002ee5a57ec9272cc71f7b0dabcc154de5a1
use cotton::prelude::*; use super::Project; use serde_json::Value; #[derive(Debug, Clone, Copy)] pub enum CargoMode { Silent, Verbose, } #[derive(Debug, Clone, Copy)] pub enum CargoState { ScriptDiffers, NoBinary, BinaryOutdated, UpToDate, } impl CargoState { pub fn needs_update(&self) ->...
use cotton::prelude::*; use super::Project; use serde_json::Value; #[derive(Debug, Clone, Copy)] pub enum CargoMode { Silent, Verbose, } #[derive(Debug, Clone, Copy)] pub enum CargoState { ScriptDiffers, NoBinary, BinaryOutdated, UpToDate, } impl CargoState { pub fn needs_update(&self) ->...
pub fn build(&self, mode: CargoMode) -> PResult<()> { info!("Building release target"); match mode { CargoMode::Silent => cmd!("cargo", "build", "--release").dir(&self.project.home).silent(), CargoMode::Verbose => cmd!("cargo", "build", "--color", "always", "--release"...
pub fn update(&self) -> PResult<()> { info!("Updating project"); write(&self.main_path(), self.script_content()?).problem_while("writing new main.rs file")?; write(&self.manifest_path(), self.manifest_content()?).problem_while("writing new Cargo.toml file")?; Ok(()) }
function_block-full_function
[ { "content": "fn write_template<'i>(script: &Path, template: String) -> PResult<()> {\n\n write(script, &template).problem_while(\"writing template to new scipt file\")?;\n\n\n\n let file = File::open(script).unwrap();\n\n let meta = file.metadata().unwrap();\n\n let mut perm = meta.permissions();\n...
Rust
src-tauri/src/logging/file.rs
Cielquan/RUlaub
9b671eab09a9389fe76b5c918b7c819631fd78f0
use std::fs::File; use std::io::Write; use std::path::{self, Path, PathBuf}; use std::{env, fs}; use glob::{glob, GlobError}; use super::LOGGING_DIR_PATH; use crate::{NAME, PROJECT_DIRS}; pub fn get_logging_dir_path() -> Option<String> { trace!( target = "tracing", message = "Try building logging...
use std::fs::File; use std::io::Write; use std::path::{self, Path, PathBuf}; use std::{env, fs}; use glob::{glob, GlobError}; use super::LOGGING_DIR_PATH; use crate::{NAME, PROJECT_DIRS}; pub fn get_logging_dir_path() -> Option<String> { trace!( target = "tracing", message = "Try building logging...
et = "tracing-cleanup", message = "Failed to create/open README file", error = ?err ); return; } Ok(mut file) => { trace!(target = "tracing-cleanup", message = "Write to README file"); if let Err(err) = write!(file, "{}", *L...
ebug!( target = "tracing", message = "Could not build logging dir path; try using current dir" ); match env::current_dir() { Err(err) => { error!( target = "tracing", message = "Failed to get current dir", error = ?err ...
random
[ { "content": "/// Take a tracing level and transform it into an [`EnvFilter`]. The [`EnvFilter`] can be used to\n\n/// update the tracing level via the reload handle.\n\npub fn create_env_filter(level: &str) -> tracing_subscriber::EnvFilter {\n\n trace!(\n\n target = \"tracing\",\n\n message = ...
Rust
serde-sarif/src/converters/clippy.rs
GeekMasher/sarif-rs
7e77d969903c5e9db840ad42045444580565dd26
use std::{ collections::HashMap, convert::From, convert::TryFrom, io::{BufRead, BufWriter, Write}, }; use crate::sarif::{self, BuilderError}; use anyhow::Result; use cargo_metadata::{ self, diagnostic::{Diagnostic, DiagnosticLevel, DiagnosticSpan}, Message, }; use std::convert::TryInto; impl TryFrom<&Di...
use std::{ collections::HashMap, convert::From, convert::TryFrom, io::{BufRead, BufWriter, Write}, }; use crate::sarif::{self, BuilderError}; use anyhow::Result; use cargo_metadata::{ self, diagnostic::{Diagnostic, DiagnosticLevel, DiagnosticSpan}, Message, }; use std::convert::TryInto; impl TryFrom<&Di...
} } fn build_global_message<W: Write>( diagnostic: &Diagnostic, writer: &mut BufWriter<W>, ) -> Result<()> { if diagnostic.spans.is_empty() { writeln!(writer, "{}", diagnostic.message)?; } diagnostic .children .iter() .try_for_each(|diagnostic| build_global_message(diagnostic, writer))...
Ok( sarif::LocationBuilder::default() .physical_location( sarif::PhysicalLocationBuilder::default() .artifact_location(artifact_location) .region(region) .build()?, ) .build()?, )
call_expression
[ { "content": "// Run `rustfmt` in the input text\n\nfn reformat(text: impl std::fmt::Display) -> Result<String> {\n\n let mut rustfmt = Command::new(\"rustfmt\")\n\n .stdin(Stdio::piped())\n\n .stdout(Stdio::piped())\n\n .spawn()?;\n\n write!(rustfmt.stdin.take().unwrap(), \"{}\", text)?;\n\n let ou...
Rust
js/permissions.rs
dimfeld/ergo
e8610f0a826378e827d72e51d386839c28fa67d5
use std::convert::TryFrom; use ipnet::IpNet; use thiserror::Error; use url::Url; #[derive(Clone, Debug, Error)] pub enum PermissionsError { #[error("Network destination disallowed")] NetAddressDenied, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct NetHostAndPort { pub host: String, pub port: Opt...
use std::convert::TryFrom; use ipnet::IpNet; use thiserror::Error; use url::Url; #[derive(Clone, Debug, Error)] pub enum PermissionsError { #[error("Network destination disallowed")] NetAddressDenied, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct NetHostAndPort { pub host: String, pub port: Opt...
} impl TryFrom<&str> for NetHostAndPort { type Error = url::ParseError; fn try_from(value: &str) -> Result<Self, Self::Error> { let (url, port) = if value.contains('/') { let url = Url::parse(value)?; let port = url.port_or_known_default(); (url, port) } el...
f, host: T, port: Option<u16>) -> bool { if self.host != host.as_ref() { return false; } match (self.port, port) { (Some(a), Some(b)) => a == b, (None, _) => true, (Some(_), None) => false, } }
function_block-function_prefixed
[ { "content": "pub fn new_hash(password: &str) -> Result<String, Error> {\n\n let salt = uuid::Uuid::new_v4();\n\n hash_password(password, &salt)\n\n}\n\n\n", "file_path": "auth/password.rs", "rank": 0, "score": 213746.82502411288 }, { "content": "pub fn configure(name: impl Into<String...
Rust
src/pallas.rs
davidnevadoc/pasta_curves
de99732e20e46024e41db4db6c230e198ae915d6
use super::{Ep, EpAffine, Fp, Fq}; pub type Base = Fp; pub type Scalar = Fq; pub type Point = Ep; pub type Affine = EpAffine; #[cfg(feature = "alloc")] #[test] #[allow(clippy::many_single_char_names)] fn test_iso_map() { use crate::arithmetic::CurveExt; use group::Group; let r = super...
use super::{Ep, EpAffine, Fp, Fq}; pub type Base = Fp; pub type Scalar = Fq; pub type Point = Ep; pub type Affine = EpAffine; #[cfg(feature = "alloc")] #[test] #[allow(clippy::many_single_char_names)]
#[cfg(feature = "alloc")] #[test] fn test_iso_map_identity() { use crate::arithmetic::CurveExt; use group::Group; let r = super::IsoEp::new_jacobian( Base::from_raw([ 0xc37f111df5c4419e, 0x593c053e5e2337ad, 0x9c6cfc47bce1aba6, 0x0a881e4d556945aa, ...
fn test_iso_map() { use crate::arithmetic::CurveExt; use group::Group; let r = super::IsoEp::new_jacobian( Base::from_raw([ 0xc37f111df5c4419e, 0x593c053e5e2337ad, 0x9c6cfc47bce1aba6, 0x0a881e4d556945aa, ]), Base::from_r...
function_block-full_function
[ { "content": "#[cfg(feature = \"alloc\")]\n\n#[cfg_attr(docsrs, doc(cfg(feature = \"alloc\")))]\n\npub trait CurveAffine:\n\n PrimeCurveAffine<\n\n Scalar = <Self as CurveAffine>::ScalarExt,\n\n Curve = <Self as CurveAffine>::CurveExt,\n\n > + Default\n\n + Add<Output = <Self as PrimeCurv...
Rust
emf-core-base-rs/src/module/native_module.rs
GabeRealB/emf-rs
24a812c052602aeb7aa8747ab306e4c33a0a72d6
use crate::ffi::collections::NonNullConst; use crate::ffi::module::native_module::{ NativeModule as NativeModuleFFI, NativeModuleBinding, NativeModuleInterface as NativeModuleInterfaceFFI, }; use crate::ffi::CBaseBinding; use crate::module::{Interface, InterfaceDescriptor, Module, ModuleInfo}; use crate::owner...
use crate::ffi::collections::NonNullConst; use crate::ffi::module::native_module::{ NativeModule as NativeModuleFFI, NativeModuleBinding, NativeModuleInterface as NativeModuleInterfaceFFI, }; use crate::ffi::CBaseBinding; use crate::module::{Interface, InterfaceDescriptor, Module, ModuleInfo}; use crate::owner...
#[inline] pub unsafe fn terminate( &mut self, instance: &mut NativeModuleInstance<'_, Owned>, ) -> Result<(), Error<Owned>> { self._interface .into_mut() .as_mut() .termin...
pub unsafe fn initialize( &mut self, instance: &mut NativeModuleInstance<'_, Owned>, ) -> Result<(), Error<Owned>> { self._interface .into_mut() .as_mut() .initialize(instance.as_handle()) .into_rust() .map_or_else(|e| Err(Error::fr...
function_block-full_function
[]
Rust
src/model/mod.rs
dnsl48/yamlette
593f172622d393086450023433549bf23843933f
pub mod yaml; pub mod yamlette; pub mod schema; pub mod renderer; pub mod rope; pub mod style; pub mod tagged_value; extern crate skimmer; use std::any::Any; use std::borrow::Cow; use std::iter::Iterator; pub use self::renderer::{ EncodedString, Renderer, Node }; pub use self::rope::Rope; pub use self::schema::Sche...
pub mod yaml; pub mod yamlette; pub mod schema; pub mod renderer; pub mod rope; pub mod style; pub mod tagged_value; extern crate skimmer; use std::any::Any; use std::borrow::Cow; use std::iter::Iterator; pub use self::renderer::{ EncodedString, Renderer, Node }; pub use self::rope::Rope; pub use self::schema::Sche...
pub fn model_tag (model: &Model, tags: &mut Iterator<Item=&(Cow<'static, str>, Cow<'static, str>)>) -> Node { match model.get_tag () { Cow::Borrowed (tag) => _model_tag_static_str (tag, tags), Cow::Owned (ref tag) => _model_tag_string (tag, tags) } } fn _model_tag_static_str (tag: &'static st...
pub fn model_alias (_model: &Model, alias: Cow<'static, str>) -> Node { match alias { Cow::Borrowed (alias) => Node::AmpersandString (EncodedString::from (alias.as_bytes ())), Cow::Owned (alias) => Node::AmpersandString (EncodedString::from (alias.into_bytes ())) } }
function_block-full_function
[ { "content": "pub trait Schema: Send + Sync {\n\n fn get_common_styles (&self) -> CommonStyles;\n\n\n\n fn get_yaml_version (&self) -> (u8, u8);\n\n\n\n fn get_tag_handles (&self) -> &[(Cow<'static, str>, Cow<'static, str>)];\n\n\n\n fn look_up_model<'a, 'b> (&'a self, &'b str) -> Option<&'a Model>;...
Rust
gazebo/src/ext/iter.rs
ndmitchell/gazebo
06cd28d1ff28ef20b0ce38ff0b0cdcc865c2b6a5
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use s...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use s...
}
None => return Ok(Ordering::Greater), Some(val) => val, }; match cmp(x, y)? { Ordering::Equal => {} non_eq => return Ok(non_eq), } } }
function_block-function_prefix_line
[ { "content": "/// Compares a type `T` that is maybe comparable\n\n///\n\n/// ```\n\n/// use gazebo::cmp::{MaybeEq, MaybeEq_Never, maybe_eq, PartialEqAny};\n\n///\n\n/// #[derive(MaybeEq_Never)]\n\n/// struct NotComparable;\n\n///\n\n/// assert_eq!(maybe_eq(&NotComparable, &NotComparable), None);\n\n///\n\n/// #...
Rust
ramneryd/src/render/pipeline.rs
NiklasJonsson/ramneryd
d9d02a7f57667cf51ec36e17861c66f41ff69582
use std::path::Path; use std::path::PathBuf; use thiserror::Error; use std::sync::Arc; use std::sync::Mutex; #[derive(Debug, Clone, Default)] pub struct Defines { vals: Vec<(String, String)>, } impl Defines { pub fn push(&mut self, v: (String, String)) { self.vals.push(v); } pub fn iter(&sel...
use std::path::Path; use std::path::PathBuf; use thiserror::Error; use std::sync::Arc; use std::sync::Mutex; #[derive(Debug, Clone, Default)] pub struct Defines { vals: Vec<(String, String)>, } impl Defines { pub fn push(&mut self, v: (String, String)) { self.vals.push(v); } pub fn iter(&sel...
impl ShaderCompiler { pub fn new() -> Result<Self, CompilerError> { let compiler = Arc::new(Mutex::new( shaderc::Compiler::new().ok_or(CompilerError::Init)?, )); Ok(Self { compiler }) } pub fn compile<P: AsRef<Path>>( &self, defines: &Defines, r...
fn log_compilation(defines: &Defines, rel_path: &Path, ty: ShaderType) { log::trace!("Compiling {} as {:?}", rel_path.display(), ty); log::trace!("With defines:"); for d in defines.iter() { log::trace!("{} = {}", d.0, d.1); } }
function_block-function_prefix_line
[ { "content": "", "file_path": "ram-derive/src/visit.rs", "rank": 0, "score": 184634.2439348734 }, { "content": "", "file_path": "ram-derive/src/visit.rs", "rank": 1, "score": 179320.10187451495 }, { "content": "", "file_path": "ram/src/render/debug/mod.rs", "rank"...
Rust
benches/major_libs.rs
hagnerd/RESS
4d164f383258f1f891d06187fa322414245dbbef
#![cfg(test)] #![feature(test)] extern crate ress; extern crate test; #[macro_use] extern crate lazy_static; #[macro_use] extern crate criterion; use criterion::black_box; use criterion::Criterion; use ress::Scanner; use std::fs::read_to_string; use std::path::PathBuf; lazy_static! { static ref NG: String = get...
#![cfg(test)] #![feature(test)] extern crate ress; extern crate test; #[macro_use] extern crate lazy_static; #[macro_use] extern crate criterion; use criterion::black_box; use criterion::Criterion; use ress::Scanner; use std::fs::read_to_string; use std::path::PathBuf; lazy_static! { static ref NG: String = get...
impl Lib { pub fn path(&self) -> String { match self { Lib::Jquery => "node_modules/jquery/dist/jquery.js", Lib::Angular => "node_modules/angular/angular.js", Lib::React => "node_modules/react/umd/react.development.js", Lib::ReactDom => "node_modules/react-d...
fn get_min_js(l: Lib) -> Result<String, ::std::io::Error> { let path = PathBuf::from(l.min_path()); if !path.exists() { npm_install(); if !path.exists() { panic!("npm install failed to make {} available", path.display()); } } read_to_string(path) }
function_block-full_function
[ { "content": "fn strings(c: &mut Criterion) {\n\n c.bench_function(\"strings\", |b| {\n\n b.iter(|| {\n\n for s in STRINGS {\n\n black_box(Tokenizer::new(s).next().unwrap());\n\n }\n\n })\n\n });\n\n}\n\n\n", "file_path": "benches/ref_perf_vs.rs", ...
Rust
src/syntax/raw.rs
ratmice/pikelet
822664f74c2717a747cd35e6d536182988e0144f
use codespan::{ByteIndex, ByteSpan}; use moniker::{Binder, Embed, Nest, Scope, Var}; use std::fmt; use std::ops; use std::rc::Rc; use syntax::pretty::{self, ToDoc}; use syntax::{Label, Level}; pub struct Module { pub items: Vec<Item>, } #[derive(Debug, Clone, PartialEq)] pub enum Item { Declarati...
use codespan::{ByteIndex, ByteSpan}; use moniker::{Binder, Embed, Nest, Scope, Var}; use std::fmt; use std::ops; use std::rc::Rc; use syntax::pretty::{self, ToDoc}; use syntax::{Label, Level}; pub struct Module { pub items: Vec<Item>, } #[derive(Debug, Clone, PartialEq)] pub enum Item { Declarati...
} impl fmt::Display for Term { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_doc().group().render_fmt(pretty::FALLBACK_WIDTH, f) } } #[derive(Debug, Clone, PartialEq, BoundTerm)] pub struct RcTerm { pub inner: Rc<Term>, } impl From<Term> for RcTerm { fn from(src: Term) -> Rc...
Term::Pi(span, _) | Term::Lam(span, _) | Term::RecordType(span, _) | Term::Record(span, _) | Term::Proj(span, _, _, _) | Term::Case(span, _, _) | Term::Array(span, _) => span, Term::Literal(ref literal) => literal.span(), Te...
function_block-function_prefix_line
[ { "content": "fn pretty_lam(binder: &Binder<String>, ann: &impl ToDoc, body: &impl ToDoc) -> StaticDoc {\n\n sexpr(\n\n \"λ\",\n\n Doc::group(parens(\n\n pretty_binder(binder)\n\n .append(Doc::space())\n\n .append(ann.to_doc().group()),\n\n )).app...
Rust
feo3boy/src/gbz80core.rs
zstewar1/feo3boy
cce4428f2f6e2681f62cb72e772ed907367f4f8d
use std::borrow::BorrowMut; use bitflags::bitflags; use crate::interrupts::InterruptFlags; use crate::memdev::MemDevice; pub use opcode::{CBOpcode, CBOperation, Opcode}; pub use opcode_args::{AluOp, AluUnaryOp, ConditionCode, Operand16, Operand8}; mod opcode; mod opcode_args; mod oputils; bitflags! { #[der...
use std::borrow::BorrowMut; use bitflags::bitflags; use crate::interrupts::InterruptFlags; use crate::memdev::MemDevice; pub use opcode::{CBOpcode, CBOperation, Opcode}; pub use opcode_args::{AluOp, AluUnaryOp, ConditionCode, Operand16, Operand8}; mod opcode; mod opcode_args; mod oputils; bitflags! { #[der...
ustate.regs.acc, 0x81, "{:?}", cpustate.regs); tick((&mut cpustate, &mut testmem)); assert_eq!(cpustate.regs.c, 0x85, "{:?}", cpustate.regs); tick((&mut cpustate, &mut testmem)); assert_eq!(cpustate.regs.acc, 0x6, "{:?}", cpustate.regs); assert!( cpustate.regs.flags...
pub fn merge(&mut self, flags: Flags, mask: Flags) { *self = (*self & !mask) | (flags & mask); } pub fn check_zero(val: u8) -> Flags { if val == 0 { Flags::ZERO } else { Flags::empty() } } pub fn check_carry(carry: bool) -> Flags { ...
random
[ { "content": "/// Implements 8 bit load operations.\n\nfn load8(ctx: &mut impl CpuContext, dest: Operand8, source: Operand8) {\n\n let val = source.read(ctx);\n\n trace!(\"Evaluating LD {},{} (<- {})\", dest, source, val);\n\n dest.write(ctx, val);\n\n}\n\n\n", "file_path": "feo3boy/src/gbz80core/o...
Rust
lib/base/src/board.rs
GuillaumeEscande/gaming-tools
2803d32fcefec90d28e43f9efd32ab1338de78f6
pub mod base { use std::vec::Vec; pub trait BoardCase< T: Eq + PartialEq + Sized > { fn position(&self)->Vec<usize>; fn get_value(&self)->&T; } pub trait Board< T : Eq + PartialEq + Sized > { fn neighbors(&self, origin: &dyn BoardCase<T> )->Vec<&dyn BoardCase<T> >; ...
pub mod base { use std::vec::Vec; pub trait BoardCase< T: Eq + PartialEq + Sized > { fn position(&self)->Vec<usize>; fn get_value(&self)->&T; } pub trait Board< T : Eq + PartialEq + Sized > { fn neighbors(&self, origin: &dyn BoardCase<T> )->Vec<&dyn BoardCase<T> >; ...
} impl< T : Eq + PartialEq + Sized > base::Board< T > for Hexagon< T > { fn neighbors(&self, origin: &dyn base::BoardCase<T> )->Vec<&dyn base::BoardCase<T> >{ let pos1 : usize = origin.position()[0] as usize; let pos2 : usize = origin.position()[1] as usize;...
for c1 in 0..size{ board.push(Vec::with_capacity(size)); for c2 in 0..size{ board[c1].push(Vec::with_capacity(size)); for c3 in 0..size{ let case = HexagonCase::<T>{ line1 ...
function_block-function_prefix_line
[ { "content": " pub trait Gameable : Eq + PartialEq + Sized + Clone {\n\n fn actions(self) -> LinkedList< (Self, i64) >;\n\n }\n\n\n\n}", "file_path": "lib/base/src/model.rs", "rank": 1, "score": 144402.6041704753 }, { "content": " pub trait Solvable : Eq + PartialEq + Sized {...
Rust
examples/nonfungible-token/src/lib.rs
zhiwei-w-luo/near-sdk-rs
bdb6f93c9a3783a9fd4b2a32f03ce3a517be5024
use std::ops::Add; use std::collections::HashMap; use borsh::{BorshDeserialize, BorshSerialize}; use near_sdk::{AccountId, Balance, env, near_bindgen}; use near_sdk::json_types::U128; pub type TokenId = u128; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[near_bindgen] #[derive...
use std::ops::Add; use std::collections::HashMap; use borsh::{BorshDeserialize, BorshSerialize}; use near_sdk::{AccountId, Balance, env, near_bindgen}; use near_sdk::json_types::U128; pub type TokenId = u128; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[near_bindgen] #[derive...
for token_id in start_id..end_id { self.tokens.insert(token_id, caller_id.clone()); } let from_owner_count = *self.owner_to_tokens.get(&caller_id).unwrap_or(&0); let amout: Balance = from_owner_count + amount; self.owner_to_tokens.insert(caller_id.clone(), amout);...
pub fn new(owner_id: AccountId, total_supply: U128) -> Self { assert!(env::is_valid_account_id(owner_id.as_bytes()), "Owner's account ID is invalid"); let total_supply = total_supply.into(); assert!(!env::state_exists(), "Already initialized"); let mut nft = Self { owner: ...
random
[ { "content": "#[proc_macro_attribute]\n\npub fn init(_attr: TokenStream, item: TokenStream) -> TokenStream {\n\n item\n\n}\n\n\n\n/// `metadata` generates the metadata method and should be placed at the very end of the `lib.rs` file.\n\n/// TODO: Once Rust allows inner attributes and custom procedural macros...
Rust
day7/src/bags_graph.rs
theonejb/advent-of-code-20
d0cbefd5ef88cae566df1260750c1c7d7a98a9ec
use std::collections::HashMap; use std::fmt::{Display, Formatter}; use std::fmt; use regex::Regex; #[derive(Debug)] pub struct Bag { name: String } impl Display for Bag { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.name) } } impl Bag { pub fn new(name: &str) -> ...
use std::collections::HashMap; use std::fmt::{Display, Formatter}; use std::fmt; use regex::Regex; #[derive(Debug)] pub struct Bag { name: String } impl Display for Bag { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.name) } } impl Bag { pub fn new(name: &str) -> ...
}
fn has_bag_type_with_name(&self, bag_name: &str) -> bool { for bag_type in self.bags.iter() { if bag_type.name == bag_name { return true; } } false }
function_block-full_function
[ { "content": "fn get_input(rules_filename: &str, data_filename: &str) -> (Vec<String>, Vec<String>) {\n\n let f = File::open(Path::new(rules_filename)).unwrap();\n\n let mut rules = vec![];\n\n for line in BufReader::new(f).lines() {\n\n rules.push(line.unwrap());\n\n }\n\n\n\n let f = Fil...
Rust
dom/src/cached_node.rs
cakekindel/moxie
f209cb8e8b8d7cc4a23a5b79fda85b345e715b03
use augdom::{Dom, Node}; use moxie::cache_with; use std::{ cell::Cell, fmt::{Debug, Formatter, Result as FmtResult}, }; pub struct CachedNode { id: topo::CallId, last_child: Cell<Option<Node>>, node: Node, } impl CachedNode { #[topo::nested] pub(crate) fn new(node: Node) -> Self { ...
use augdom::{Dom, Node}; use moxie::cache_with; use std::{ cell::Cell, fmt::{Debug, Formatter, Result as FmtResult}, }; pub struct CachedNode { id: topo::CallId,
"<div id=\"aha\">\n</div>" ); } }
last_child: Cell<Option<Node>>, node: Node, } impl CachedNode { #[topo::nested] pub(crate) fn new(node: Node) -> Self { Self { node, last_child: Cell::new(None), id: topo::CallId::current() } } pub(crate) fn raw_node(&self) -> &Node { &self.node } #[topo::nested(slo...
random
[ { "content": "/// A built Element. See [`ElementBuilder`] docs for more details.\n\npub trait Element: crate::interfaces::node::NodeWrapper {}\n", "file_path": "dom/src/interfaces/element.rs", "rank": 0, "score": 117076.23799635985 }, { "content": "/// Element is the most general base class ...
Rust
src/gen/perlin.rs
lfdoherty/noise
015981c9fd16a4f8e167109afca0d1add926d39f
use std::rand::{ Rng, XorShiftRng, weak_rng }; use utils::{ fade, fastfloor, lerp }; use utils::grad::{ grad1, grad2, grad3 }; use gen::NoiseGen; #[derive(Clone, PartialEq, Eq)] pub struct Perlin { perm: Vec<u8> } impl Perlin { pub fn new() -> Perlin { l...
use std::rand::{ Rng, XorShiftRng, weak_rng }; use utils::{ fade, fastfloor, lerp }; use utils::grad::{ grad1, grad2, grad3 }; use gen::NoiseGen; #[derive(Clone, PartialEq, Eq)] pub struct Perlin { perm: Vec<u8> } impl Perlin { pub fn new() -> Perlin { l...
size]}).collect(); Perlin { perm: perm } } } impl NoiseGen for Perlin { fn noise1d(&self, xin: f64) -> f64 { let ix0: i64 = fastfloor(xin); let fx0: f64 = xin - ix0 as f64; let fx1: f64 = fx0 - 1.0; let ix1: i64 = ix0 ...
let p: Vec<u8> = (0..256).map(|_| rng.gen::<u8>()).collect(); let perm: Vec<u8> = (0..512).map(|idx:i32| {p[(idx & 255) as u
function_block-random_span
[ { "content": "#[inline]\n\npub fn fade(t: f64) -> f64 {\n\n t * t * t * ( t * ( t * 6.0 - 15.0 ) + 10.0 )\n\n}\n", "file_path": "src/utils/fade.rs", "rank": 0, "score": 125240.28523474294 }, { "content": "#[inline]\n\npub fn fastfloor(x: f64) -> i64 {\n\n if x > 0.0 {\n\n x as i...
Rust
examples/testbed/tests/slider_crank_1.rs
HumMan/box2d-rs
a9731ec7b3d6857c505498e1cccf154b1d688e2b
use super::super::draw::*; use super::super::settings::*; use super::super::test::*; use box2d_rs::b2_body::*; use box2d_rs::b2_joint::*; use box2d_rs::b2_math::*; use box2d_rs::b2_settings::*; use box2d_rs::b2_world::*; use box2d_rs::b2_world_callbacks::*; use box2d_rs::joints::b2_prismatic_joint::*; use box2d_rs::joi...
use super::super::draw::*; use super::super::settings::*; use super::super::test::*; use box2d_rs::b2_body::*; use box2d_rs::b2_joint::*; use box2d_rs::b2_math::*; use box2d_rs::b2_settings::*; use box2d_rs::b2_world::*; use box2d_rs::b2_world_callbacks::*; use box2d_rs::joints::b2_prismatic_joint::*; use box2d_rs::joi...
} impl<D: UserDataType, F: Facade> TestDyn<D, F> for SliderCrank1<D> { fn get_base(&self) -> TestBasePtr<D> { return self.base.clone(); } fn step( &mut self, ui: &imgui::Ui<'_>, display: &F, target: &mut glium::Frame, settings: &mut Settings, camera: &mut Camera, ) { Test::step(self.base.clone(), ...
fn init(&mut self) { let m_world = self.base.borrow().m_world.clone(); let ground; { let mut bd = B2bodyDef::default(); bd.position.set(0.0, 17.0); ground = B2world::create_body(m_world.clone(), &bd); } { let mut prev_body: BodyPtr<D> = ground.clone(); { let mut shape = B2polygonShape:...
function_block-full_function
[ { "content": "pub fn synchronize_fixtures_by_world<D: UserDataType>(self_: &mut B2body<D>, world: &B2world<D>) {\n\n\tsynchronize_fixtures_internal(self_, world);\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 0, "score": 262290.6873687553 }, { "content": "pub fn synchr...
Rust
src/main.rs
yo-kondo/add_send_date_to_file_name
4851964cde70cd6f9f93d0aaaabdf7e4a9129dee
use regex::Regex; use std::cmp::Ordering; use std::fs; use std::fs::File; use std::io::Read; use walkdir::WalkDir; fn main() { const TARGET_DIR: &str = r"D:\temp\data"; let target_files = get_target_files(TARGET_DIR); for file_name in target_files { let mut file = File::open(&file_name).unwrap(); ...
use regex::Regex; use std::cmp::Ordering; use std::fs; use std::fs::File; use std::io::Read; use walkdir::WalkDir; fn main() { const TARGET_DIR: &str = r"D:\temp\data"; let target_files = get_target_files(TARGET_DIR); for file_name in target_files { let mut file = File::open(&file_name).unwrap(); ...
; let mut rtn_date = year.to_string(); rtn_date.push_str(month); rtn_date.push_str(&day); rtn_date } fn change_date_jp(date: &str) -> String { let reg = Regex::new(r"(?P<year>\d+)年(?P<month>\d+)月(?P<day>\d+)日").unwrap(); let cap = reg.captures(date).unwrap(); let year = &cap["year"]; l...
match month { "January" => "01", "February" => "02", "March" => "03", "April" => "04", "May" => "05", "June" => "06", "July" => "07", "August" => "08", "September" => "09", "October" => "10", "November" => "11", "December" =...
if_condition
[]
Rust
tests/core/arith_one_reg.rs
mlafroce/avr-avogadro
2bbd07c4c699749354a5b2f4a1ecd9c6855ab183
extern crate avr_avogadro; use avr_avogadro::core::mcu_factory::McuFactory; #[test] fn test_com() { let mut mcu = McuFactory::create("attiny85"); let program_memory = vec![0x80, 0x95, 0x90, 0x95, 0xA0, 0x95]; mcu.load_program_memory(&program_memory); mcu.set_register(24, 0); mcu.set_register(25, ...
extern crate avr_avogadro; use avr_avogadro::core::mcu_factory::McuFactory; #[test] fn test_com() { let mut mcu = McuFactory::create("attiny85"); let program_memory = vec![0x80, 0x95, 0x90, 0x95, 0xA0, 0x95]; mcu.load_program_memory(&program_memory); mcu.set_register(24, 0); mcu.set_register(25, ...
0x14, flag_as_byte); mcu.step(); flag_as_byte = mcu.get_flags().into(); assert_eq!(mcu.get_register(16), 0); assert_eq!(0x02, flag_as_byte, "Flags assertion failed: {:08b} != {:08b}", 0x02, flag_as_byte); mcu.set_register(16, 0x7F); mcu.step(); flag_as_byte...
eq!(mcu.get_register(25), 0x00); assert_eq!(0x3, flag_as_byte, "Flags assertion failed: {:08b} != {:08b}", 0x3, flag_as_byte); mcu.step(); flag_as_byte = mcu.get_flags().into(); assert_eq!(mcu.get_register(26), 0x88); assert_eq!(0x15, flag_as_byte, "Flags ass...
random
[ { "content": "#[no_mangle]\n\npub fn mcu_set_register(p_mcu: &mut Mcu, reg_num: u8, value: u8) {\n\n p_mcu.set_register(reg_num, value);\n\n}\n\n\n\n/// Puts registers data into a buffer\n\n/// # Safety\n\n///\n\n/// `p_mcu` must be a pointer to a valid Mcu\n\n/// `buffer` must be a char array with at least ...
Rust
src/language/scanner.rs
JarnaChao09/Innovation_PL
f56ab93ea1030dca628938e2831718a50f7f4b59
use super::token::*; pub struct Scanner { source: String, start_index: usize, current_index: usize, line: i32, } impl Scanner { pub fn new(source: String) -> Scanner { Scanner { source, start_index: 0, current_index: 0, line: 1 } ...
use super::token::*; pub struct Scanner { source: String, start_index: usize, current_index: usize, line: i32, } impl Scanner { pub fn new(source: String) -> Scanner { Scanner { source, start_index: 0, current_index: 0, line: 1 } ...
pub fn identifier_type(&mut self) -> TokenType { unsafe { match self.source.chars().nth(self.start_index).unwrap() { 'c' => self.match_keyword(1, String::from("lass"), TokenType::Class), 'e' => self.match_keyword(1, String::from("lse"), TokenType::Else), ...
pub fn make_identifier(&mut self) -> Token { while self.peek().is_alphabetic() || self.peek().is_numeric() { self.advance(); } let id_type = self.identifier_type(); self.make_token(id_type) }
function_block-full_function
[ { "content": "type ParseFn = fn(&mut Parser, &mut Scanner, &mut Chunk) -> ();\n\n\n", "file_path": "src/language/parser.rs", "rank": 0, "score": 88231.34531308802 }, { "content": "fn run_file(vm: &mut language::vm::VM, path: &String) {\n\n let file = File::open(path);\n\n\n\n let mut s...
Rust
rlink/src/runtime/worker/runnable/watermark_assigner_runnable.rs
biuboombiuboom/rlink-rs
877e20b5404d866d63724b842edd86c8000dd4e6
use std::borrow::BorrowMut; use crate::core::checkpoint::{Checkpoint, CheckpointHandle, FunctionSnapshotContext}; use crate::core::element::Element; use crate::core::operator::DefaultStreamOperator; use crate::core::runtime::{OperatorId, TaskId}; use crate::core::watermark::{Watermark, WatermarkAssigner, MIN_WATERMARK...
use std::borrow::BorrowMut; use crate::core::checkpoint::{Checkpoint, CheckpointHandle, FunctionSnapshotContext}; use crate::core::element::Element; use crate::core::operator::DefaultStreamOperator; use crate::core::runtime::{OperatorId, TaskId}; use crate::core::watermark::{Watermark, WatermarkAssigner, MIN_WATERMARK...
mp { let n = self.expire_counter.fetch_add(1); if n & 8388605 == 1 { warn!( "lost delay data {} < {}", record.timestamp, self.watermark.timestamp ); ...
watermark_gauge: Gauge::default(), expire_counter: Counter::default(), } } } impl Runnable for WatermarkAssignerRunnable { fn open(&mut self, context: &RunnableContext) -> anyhow::Result<()> { self.next_runnable.as_mut().unwrap().open(context)?; self.context = Some(conte...
random
[ { "content": "pub fn create_context() -> anyhow::Result<Context> {\n\n let work_space = get_work_space();\n\n let conf_path = work_space.clone().join(\"config\");\n\n\n\n let standalone_file = conf_path.clone().join(\"standalone.yaml\");\n\n let config = load_config(standalone_file.clone())?;\n\n\n\...
Rust
src/eval.rs
n01e0/alone
5d7150ed98fd0d79f4bc05f4baf513d620d234ba
use super::ast; use super::env::make_global_env; use std::collections::HashMap; use std::fmt; #[derive(Debug, PartialEq, Clone)] pub struct Cons(Box<Value>, Box<Value>); impl Cons { pub fn new(car: Value, cdr: Value) -> Self { Cons(Box::new(car), Box::new(cdr)) } pub fn car(&self) -> Value { ...
use super::ast; use super::env::make_global_env; use std::collections::HashMap; use std::fmt; #[derive(Debug, PartialEq, Clone)] pub struct Cons(Box<Value>, Box<Value>); impl Cons { pub fn new(car: Value, cdr: Value) -> Self { Cons(Box::new(car), Box::new(cdr)) } pub fn car(&self) -> Value { ...
, _ => Err(EvalError(format!("eval: Invalid function {}", sym))), } } } } fn to_sym(token: ast::Token) -> Result<String, EvalError> { match token.kind { ast::TokenKind::Symbol(s) => Ok(s), other => Err(EvalError(format!("Token '{:?}' is not symbol", other))),...
c(args .into_iter() .map(|expr| eval_with_env(expr, env)) .collect::<Result<Vec<_>, _>>()?)
call_expression
[ { "content": "pub fn make_global_env() -> HashMap<String, Value> {\n\n let mut env = HashMap::new();\n\n\n\n env.insert(\n\n S(\"print\"),\n\n Value::Callable(|values| {\n\n for value in values.iter() {\n\n println!(\"{}\", value);\n\n }\n\n Ok...
Rust
src/fuel_fmt/bitmap.rs
widberg/dpc
64ee5d85b688eb777d4fb83fe08bc06360d3c040
use std::io::{Error, ErrorKind, Write}; use std::path::Path; use binwrite::BinWrite; use byteorder::ByteOrder; use byteorder::LittleEndian; use nom_derive::{NomLE, Parse}; use serde::{Deserialize, Serialize}; use crate::fuel_fmt::common::{write_option, FUELObjectFormatTrait}; use crate::File; use ddsfile::{D3DFormat,...
use std::io::{Error, ErrorKind, Write}; use std::path::Path; use binwrite::BinWrite; use byteorder::ByteOrder; use byteorder::LittleEndian; use nom_derive::{NomLE, Parse}; use serde::{Deserialize, Serialize}; use crate::fuel_fmt::common::{write_option, FUELObjectFormatTrait}; use crate::File; use ddsfile::{D3DFormat,...
} pub struct BitmapObjectFormatAlt; impl BitmapObjectFormatAlt { pub fn new<'a>() -> &'a Self { &Self {} } } impl FUELObjectFormatTrait for BitmapObjectFormatAlt { fn pack( self: &Self, input_path: &Path, header: &mut Vec<u8>, body: &mut Vec<u8>, ) -> Result<(...
fn unpack(self: &Self, header: &[u8], body: &[u8], output_path: &Path) -> Result<(), Error> { let json_path = output_path.join("object.json"); let mut output_file = File::create(json_path)?; let bitmap_header = match BitmapZHeader::parse(&header) { Ok((_, h)) => h, Err(_...
function_block-full_function
[ { "content": "pub fn get_formats<'a>(version: &String) -> HashMap<u32, &'a dyn FUELObjectFormatTrait> {\n\n let mut formats: HashMap<u32, &'a dyn FUELObjectFormatTrait> = HashMap::new();\n\n\n\n formats.insert(1175485833, AnimationObjectFormat::new());\n\n formats.insert(4240844041, CameraObjectFormat:...
Rust
maistra/vendor/proxy_wasm_cpp_host__wasmtime_c_api_macros__0_19_0/crates/wasi-crypto/spec/implementations/hostcalls/rust/src/key_exchange/kem/kyber.rs
Maistra/proxy
96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f
use super::*; pub use pqcrypto::kem::kyber768; pub use pqcrypto::prelude::*; #[derive(Clone, Derivative)] #[derivative(Debug)] pub struct Kyber768PublicKey { alg: KxAlgorithm, #[derivative(Debug = "ignore")] pq_pk: kyber768::PublicKey, } impl Kyber768PublicKey { fn new(alg: KxAlgorithm, raw: &[u8]) ->...
use super::*; pub use pqcrypto::kem::kyber768; pub use pqcrypto::prelude::*; #[derive(Clone, Derivative)] #[derivative(Debug)] pub struct Kyber768PublicKey { alg: KxAlgorithm, #[derivative(Debug = "ignore")] pq_pk: kyber768::PublicKey, } impl Kyber768PublicKey { fn new(alg: KxAlgorithm, raw: &[u8]) ->...
ew(self.kyber768_publickey()?))) } fn decapsulate(&self, encapsulated_secret: &[u8]) -> Result<Vec<u8>, CryptoError> { let pq_encapsulated_secret = kyber768::Ciphertext::from_bytes(encapsulated_secret) .map_err(|_| CryptoError::VerificationFailed)?; Ok(kyber768::decapsulate(&pq_enca...
let pq_sk = kyber768::SecretKey::from_bytes(&raw).map_err(|_| CryptoError::InvalidKey)?; Ok(Kyber768SecretKey { alg, pq_sk }) } } #[derive(Clone, Debug)] pub struct Kyber768KeyPair { alg: KxAlgorithm, pk: Kyber768PublicKey, sk: Kyber768SecretKey, } pub struct Kyber768KeyPairBuilder { ...
random
[ { "content": "// RequestInfo represents the information collected from filter stream\n\n// callbacks. This is used to fill metrics and logs.\n\nstruct RequestInfo {\n\n // Start timestamp in nanoseconds.\n\n int64_t start_time;\n\n\n\n // The total duration of the request in nanoseconds.\n\n int64_t duratio...
Rust
examples/demo/station_sleep.rs
azriel91/choochoo
61835c5c9e9e44d7ca99eba3a3a1c78957186cee
use std::path::Path; use choochoo::cfg_model::{ rt::{CheckStatus, Files, FilesRw, ProgressLimit}, srcerr::{ codespan::{FileId, Span}, codespan_reporting::diagnostic::Severity, }, SetupFn, StationFn, StationId, StationSpec, StationSpecFns, }; use futures::{stream, stream::StreamExt}; use...
use std::path::Path; use choochoo::cfg_model::{ rt::{CheckStatus, Files, FilesRw, ProgressLimit}, srcerr::{ codespan::{FileId, Span}, codespan_reporting::diagnostic::Severity, }, SetupFn, StationFn, StationId, StationSpec, StationSpecFns, }; use futures::{stream, stream::StreamExt}; use...
fn write_error( files: &mut Files, station_file_path: &'static Path, error: std::io::Error, error_fn: fn(FileId, Span, std::io::Error) -> DemoError, ) -> Result<DemoError, DemoError> { let station_file_name = station_file_path.file_name().ok_or_else(|| { let...
e, } })?; Result::<(), DemoError>::Ok(()) }) }) }
function_block-function_prefixed
[ { "content": "fn station_b() -> Result<StationSpec<ExampleError>, StationIdInvalidFmt<'static>> {\n\n new_station(\n\n \"b\",\n\n \"Station B\",\n\n \"Reads `simple.toml` and reports error.\",\n\n StationFn::new(move |_station, resources| {\n\n Box::pin(async move {\n\n...
Rust
feeder/src/updates/tg/source_provider.rs
aCLr/feeder
49d1ababf54d72790191669080972a72ecc96055
use super::handler::Handler; use crate::models; use crate::result::{Error, Result}; use crate::storage::Storage; use crate::updates::tg::TelegramSource; use crate::updates::{Source, SourceData, SourceProvider}; use async_trait::async_trait; use chrono::NaiveDateTime; use std::collections::HashMap; use std::convert::Try...
use super::handler::Handler; use crate::models; use crate::result::{Error, Result}; use crate::storage::Storage; use crate::updates::tg::TelegramSource; use crate::updates::{Source, SourceData, SourceProvider}; use async_trait::async_trait; use chrono::NaiveDateTime; use std::collections::HashMap; use std::convert::Try...
async fn synchronize(&self, secs_depth: i32) -> Result<()> { debug!("start syncing {:?}", self.get_source()); let channels = { let cr = self.collector.read().await; trace!("lock acquired"); cr.get_all_channels(1000).await? }; let until = SystemT...
await .search_public_chats(query) .await?; let mut sources = vec![]; for ch in channels { let source: models::NewSource = ch.into(); match self.storage.save_sources(vec![source]).await { Ok(s) => sources.extend(s), Err(e) =>...
function_block-function_prefix_line
[ { "content": "fn parse_rss_feed(link: &str, content: &str) -> Result<Feed> {\n\n let channel = Channel::from_str(content)?;\n\n let mut feed_items: Vec<FeedItem> = vec![];\n\n for item in channel.items() {\n\n let description = item\n\n .content()\n\n .unwrap_or_else(|| ite...
Rust
microservice_note/src/main.rs
zhongwei/rustnote
64a1924acc9776df446ec5460164e0db9d45e110
#![feature(proc_macro)] extern crate hyper; extern crate maud; extern crate futures; extern crate url; #[macro_use] extern crate log; extern crate env_logger; #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] extern crate diesel; use std::collections::HashMap; use std::io; ...
#![feature(proc_macro)] extern crate hyper; extern crate maud; extern crate futures; extern crate url; #[macro_use] extern crate log; extern crate env_logger; #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] extern crate diesel; use std::collections::HashMap; use std::io; ...
fn make_post_response( result: Result<i64, hyper::Error>, ) -> FutureResult<hyper::Response, hyper::Error> { match result { Ok(timestamp) => { let payload = json!({"timestamp": timestamp}).to_string(); let response = Response::new() .with_header(ContentLength(pa...
fn parse_form(form_chunk: Chunk) -> FutureResult<NewMessage, hyper::Error> { let mut form = url::form_urlencoded::parse(form_chunk.as_ref()) .into_owned() .collect::<HashMap<String, String>>(); if let Some(message) = form.remove("message") { let username = form.remove("username").unwrap...
function_block-full_function
[ { "content": "fn get_content(url: &str) -> reqwest::Result<String> {\n\n reqwest::get(url)?.text()\n\n}\n\n\n\nconst INDEX_HTML: &'static [u8] = include_bytes!(\"../public/index.html\");\n\nconst BULMA_CSS: &'static [u8] = include_bytes!(\"../public/vendor/bulma.min.css\");\n\n\n", "file_path": "blockcha...
Rust
src/cube/motor/acceleration.rs
kaz399/rs_toio_core_cube
f2347c975d8db328ff32c16888cba41ac492ce0d
use super::def::{CommandId, Period}; use crate::payload::ToPayload; use serde::Serialize; use serde::Serializer; #[derive(Serialize, Debug, Copy, Clone)] struct MotorControlAcceleration { command: CommandId, acceleration: Acceleration, angle_velocity: AngleVelocity, moving_direction: MovingDirection, ...
use super::def::{CommandId, Period}; use crate::payload::ToPayload; use serde::Serialize; use serde::Serializer; #[derive(Serialize, Debug, Copy, Clone)] struct MotorControlAcceleration { command: CommandId, acceleration: Acceleration, angle_velocity: AngleVelocity, moving_direction: MovingDirection, ...
} } impl Serialize for RotationDirection { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let byte_string: u8 = u8::from(*self); serializer.serialize_u8(byte_string) } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum MovingDi...
match rotation_direction { RotationDirection::Positive => 0u8, RotationDirection::Negative => 1u8, }
if_condition
[ { "content": "pub trait Simple {\n\n // --------------------------------------------------------------------------------\n\n // Motor Control\n\n\n\n /// Motor control with specified duration\n\n fn go(\n\n left: Velocity,\n\n right: Velocity,\n\n period: Period,\n\n ) -> Res...
Rust
src/lib.rs
kavirajk/xmodem
fca88ee67405a8745259a41bb6f5dbfae224a1d8
mod progress; #[cfg(test)] mod tests; use progress::*; use std::io::{self, Read, Result, Write}; pub const SOH: u8 = 0x01; pub const EOT: u8 = 0x04; pub const ACK: u8 = 0x06; pub const NAK: u8 = 0x15; pub const CAN: u8 = 0x18; struct Xmodem<T> { inner: T, packet: u8, started: bool, progress: Progres...
mod progress; #[cfg(test)] mod tests; use progress::*; use std::io::{self, Read, Result, Write}; pub const SOH: u8 = 0x01; pub const EOT: u8 = 0x04; pub const ACK: u8 = 0x06; pub const NAK: u8 = 0x15; pub const CAN: u8 = 0x18; struct Xmodem<T> { inner: T, packet: u8, started: bool, progress: Progres...
(self.progress)(Progress::Waiting); self.expect_byte(NAK, "expected NAK from receiver")?; (self.progress)(Progress::Started); self.started = true; } if buf.len() == 0 { self.write_byte(EOT)?; self.expect_byte(NAK, "expected NAK ...
r) -> Result<u8> { let b = self.read_byte()?; if b == byte { return Ok(byte); } self.inner.write(&mut [CAN])?; match b { CAN => Err(io::Error::new(io::ErrorKind::ConnectionAborted, msg)), _ => { println!("got: {}", b); ...
random
[ { "content": "pub fn noop(_: Progress) {}\n", "file_path": "src/progress.rs", "rank": 0, "score": 82578.17654460328 }, { "content": "struct Pipe(Sender<u8>, Receiver<u8>, Vec<u8>);\n\n\n", "file_path": "src/tests.rs", "rank": 1, "score": 77590.1776420642 }, { "content": "...
Rust
sfq/src/util/common.rs
lisp-rbi/sfq
93855f63e15561ea36644fa6bcf7d72266974f4d
use std::fs::{metadata,remove_file,remove_dir_all,create_dir}; use std::str; use std::mem; use regex::Regex; use rand::prelude::*; use fxhash::FxHashSet; pub fn make_dir(dirname: &str) -> bool{ if metadata(&dirname).is_ok() == true { if metadata(&dirname).unwrap().is_file() == true { remove_fil...
use std::fs::{metadata,remove_file,remove_dir_all,create_dir}; use std::str; use std::mem; use regex::Regex; use rand::prelude::*; use fxhash::FxHashSet; pub fn make_dir(dirname: &str) -> bool{ if metadata(&dirname).is_ok() == true { if metadata(&dirname).unwrap().is_file() == true { remove_fil...
pub fn remove_cpcnt(v: &mut Vec<u8>) -> Vec<usize> { let mut cpcnt: Vec<usize> = Vec::new(); let mut tmp_count: Vec<u8> = Vec::new(); let mut result: Vec<u8> = Vec::new(); let mut copy: bool = true; let mut i: usize = 1; for element in v.clone() { if element == 98u8 { copy = ...
function_block-full_function
[ { "content": "pub fn encode (num: usize, word: usize, alpha: &Vec<u8> ) -> Vec<u8> {\n\n\n\n let mut v = vec![0u8;word];\n\n let mut rmd = 0;\n\n let mut res = num;\n\n\n\n for i in 0..word {\n\n rmd = res%4;\n\n res = res/4;\n\n v[word-(i+1)] = alpha[rmd];\n\n }\n\n v\n\n...
Rust
src/alchemy/debug.rs
Trouv/alchemy
92440b0ea0991675bb93fcfee2a48caf87cabbb1
use crate::{alchemy::BrewingPlugin, AppState}; use bevy::prelude::*; pub struct BrewingPluginDebug; impl Plugin for BrewingPluginDebug { fn build(&self, app: &mut AppBuilder) { app.add_plugin(BrewingPlugin) .add_system_set( SystemSet::on_enter(AppState::Brewing) ...
use crate::{alchemy::BrewingPlugin, AppState}; use bevy::prelude::*; pub struct BrewingPluginDebug; impl Plugin for BrewingPluginDebug { fn build(&self, app: &mut AppBuilder) { app.add_plugin(BrewingPlugin) .add_system_set( SystemSet::on_enter(AppState::Brewing) ...
} mod transitions { use crate::alchemy::{components::*, compound::Compound}; use bevy::prelude::*; use std::str::FromStr; pub fn spawn_test_compounds(mut commands: Commands) { for _ in 0..20 { commands.spawn().insert(Compound::from_str("A3B").unwrap()); } for _ in ...
g) .with_system(systems::compound_rank_display.system()) .with_system(systems::reaction_test_input.system()), ); }
function_block-function_prefixed
[ { "content": "pub fn insert_reaction_rules(mut commands: Commands) {\n\n commands.insert_resource(load_reaction_rules().expect(\"Failed to load reaction rules\"))\n\n}\n", "file_path": "src/alchemy/resources.rs", "rank": 0, "score": 70887.20433897268 }, { "content": "pub fn element_parser...
Rust
day_04/src/main.rs
lvdr/aoc2018
8589f80f4e03a6e40ae90899dce5cfafbc964394
use std::cmp::Ordering; use std::cmp; use std::collections::BTreeSet; use std::collections::HashMap; use std::io::prelude::*; use std::fs::File; #[cfg(test)] mod tests { use super::*; #[test] fn test_ordered() { let input = String::from("[1518-11-01 00:00] Guard #10 begins shift\n\ ...
use std::cmp::Ordering; use std::cmp; use std::collections::BTreeSet; use std::collections::HashMap; use std::io::prelude::*; use std::fs::File; #[cfg(test)] mod tests { use super::*; #[test] fn test_ordered() { let input = String::from("[1518-11-01 00:00] Guard #10 begins shift\n\ ...
d.1) } fn main() { let mut input = String::new(); let mut f = File::open("input").expect("Failed to open input."); f.read_to_string(&mut input).expect("Failed to read input."); let log = parse_input(input); let guard_naps = parse_log(log); let guard_naps_by_minute = naps_by_minute(guard_naps)...
sleepiest_minute = cmp::max((minutes[i], i), sleepiest_minute); } let this_guard = (sleepiest_minute.0, sleepiest_minute.1 as u32, *guard); sleepiest_guard = cmp::max(sleepiest_guard, this_guard); } (sleepiest_guard.2, sleepiest_guar
function_block-random_span
[ { "content": "fn parse_line(line: &str, id: usize) -> Coord {\n\n let mut xy = line.split(\", \");\n\n let x = xy.next().unwrap()\n\n .parse::<usize>().unwrap();\n\n let y = xy.next().unwrap()\n\n .parse::<usize>().unwrap();\n\n Coord{ id: id, x: x, y: y }\n\n}\n\n\n", ...
Rust
src/engine/parser/lexer/error.rs
colin-kiegel/twig-rust
3a70dc5e8f1d410b3e31c5f3bcc78fd8ea2da152
use std::fmt::{self, Display}; use std::error::Error; use std::num::{ParseFloatError, ParseIntError}; use engine::parser::token; use engine::parser::lexer::job::cursor; use regex; #[derive(Debug)] pub enum SyntaxError { Unreachable { reason: String, cursor: cursor::CursorDump, }, Unexpect...
use std::fmt::{self, Display}; use std::error::Error; use std::num::{ParseFloatError, ParseIntError}; use engine::parser::token; use engine::parser::lexer::job::cursor; use regex; #[derive(Debug)] pub enum SyntaxError { Unreachable { reason: String, cursor: cursor::CursorDump, }, Unexpect...
} impl Display for SyntaxError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "{}", self.description())); match *self { SyntaxError::Unreachable { reason: ref r, cursor: ref c } => write!(f, " {reason} at {cursor}.",...
fn description(&self) -> &str { match *self { SyntaxError::Unreachable{..} => { "Unexptected syntax error (please report as bug with details)." } SyntaxError::UnexpectedCharacter{..} => "Unexpected character.", SyntaxError::UnexpectedBracket{..} =>...
function_block-full_function
[ { "content": "// supposed to be *compatible* with PHP implementation\n\n// - http://php.net/manual/en/function.stripcslashes.php\n\n// - https://github.com/php/php-src/blob/master/ext/standard/string.c\n\n//\n\n// see also https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences\n\n//\n\npu...