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
examples/handlers/async_handlers/src/main.rs
adoankim/gotham
a6539e95a36f2e8247959aa89bcfd0a9619d9d6f
#[macro_use] extern crate gotham_derive; #[macro_use] extern crate serde_derive; use futures::prelude::*; use std::pin::Pin; use gotham::hyper::StatusCode; #[cfg(not(test))] use gotham::hyper::{body, Client, Uri}; use gotham::handler::HandlerFuture; use gotham::helpers::http::response::create_response; use gotham::...
#[macro_use] extern crate gotham_derive; #[macro_use] extern crate serde_derive; use futures::prelude::*; use std::pin::Pin; use gotham::hyper::StatusCode; #[cfg(not(test))] use gotham::hyper::{body, Client, Uri}; use gotham::handler::HandlerFuture; use gotham::helpers::http::response::create_response; use gotham::...
) .boxed() } fn parallel_handler(mut state: State) -> Pin<Box<HandlerFuture>> { let length = QueryStringExtractor::take_from(&mut state).length; println!("parallel length: {} starting", length); let data_future: ResponseContentFuture = if length == 0 { future::ok(Vec::new()).boxed() ...
match result { Ok(data) => { let res = create_response(&state, StatusCode::OK, mime::TEXT_PLAIN, data); println!("loop length: {} finished", length); future::ok((state, res)) } Err(err) => future::err((state, err.into())), }
if_condition
[ { "content": "/// Extracts the elements of the POST request and prints them\n\nfn post_handler(mut state: State) -> Pin<Box<HandlerFuture>> {\n\n print_request_elements(&state);\n\n let f = body::to_bytes(Body::take_from(&mut state)).then(|full_body| match full_body {\n\n Ok(valid_body) => {\n\n ...
Rust
testcrate/tests/mem.rs
rust-lang-nursery/compiler-builtins
f10dbd9bb534b7fa945bff7ff2d7299c38dda389
extern crate compiler_builtins; use compiler_builtins::mem::{memcmp, memcpy, memmove, memset}; const WORD_SIZE: usize = core::mem::size_of::<usize>(); #[test] fn memcpy_3() { let mut arr: [u8; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; unsafe { let src = arr.as_ptr().offset(9); let dst = ar...
extern crate compiler_builtins; use compiler_builtins::mem::{memcmp, memcpy, memmove, memset}; const WORD_SIZE: usize = core::mem::size_of::<usize>(); #[test] fn memcpy_3() { let mut arr: [u8; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; unsafe { let src = arr.as_ptr().offset(9); let dst = ar...
es(reference.0.as_mut_ptr().add(3 + WORD_SIZE), 0xCC, 17); assert_eq!(arr.0, reference.0); } }
} } #[test] fn memset_zero() { let mut arr: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7]; unsafe { let ptr = arr.as_mut_ptr().offset(5); assert_eq!(memset(ptr, 0, 2), ptr); assert_eq!(arr, [0, 1, 2, 3, 4, 0, 0, 7]); assert_eq!(memset(arr.as_mut_ptr(), 0x2000, 8), arr.as_mut_...
random
[ { "content": "#[cfg_attr(not(target_has_atomic_load_store = \"8\"), allow(dead_code))]\n\nfn memmove_element_unordered_atomic<T: Copy>(dest: *mut T, src: *const T, bytes: usize) {\n\n unsafe {\n\n let n = exact_div(bytes, mem::size_of::<T>());\n\n if src < dest as *const T {\n\n // c...
Rust
src/backend/vulkan/src/window.rs
scoopr/gfx
c71fe15c1f93a3c0171414aa58ddb1f14b2eb376
use std::collections::VecDeque; use std::ptr; use std::sync::Arc; use std::os::raw::c_void; use ash::vk; use ash::extensions as ext; use hal; use hal::format::Format; #[cfg(feature = "winit")] use winit; use {conv, native}; use {VK_ENTRY, Backend, Instance, PhysicalDevice, QueueFamily, RawInstance}; pub struct Sur...
use std::collections::VecDeque; use std::ptr; use std::sync::Arc; use std::os::raw::c_void; use ash::vk; use ash::extensions as ext; use hal; use hal::format::Format; #[cfg(feature = "winit")] use winit; use {conv, native}; use {VK_ENTRY, Backend, Instance, PhysicalDevice, QueueFamily, RawInstance}; pub struct Sur...
} else { None }; let min_extent = hal::window::Extent2d { width: caps.min_image_extent.width, height: caps.min_image_extent.height, }; let max_extent = hal::window::Extent2d { width: caps.max_image_extent.width, ...
Some(hal::window::Extent2d { width: caps.current_extent.width, height: caps.current_extent.height, })
call_expression
[ { "content": "pub fn resize_swap_chain<Cf>(&mut self, factory: &mut Factory, width: Size, height: Size)\n\n -> Result<h::RenderTargetView<Resources, Cf>, winapi::HRESULT>\n\nwhere Cf: format::RenderFormat\n\n{\n\n let result = unsafe {\n\n (*self.swap_chain).ResizeBuffers(0,...
Rust
examples/kv/src/main.rs
blackredscarf/raftfwk
5d1f4ba0cfe5c43b8dafea1e506aa0cfa254dc10
#[macro_use] extern crate serde; extern crate raftfwk; use std::time::Duration; use std::collections::HashMap; use std::sync::{mpsc, Arc, Mutex}; use std::sync::mpsc::{Sender, Receiver, TryRecvError}; use std::thread; use raftfwk::msg::{Msg, RaftError, Normal}; use raftfwk::service::{ProposeCallback, RaftContext, Raf...
#[macro_use] extern crate serde; extern crate raftfwk; use std::time::Duration; use std::collections::HashMap; use std::sync::{mpsc, Arc, Mutex}; use std::sync::mpsc::{Sender, Receiver, TryRecvError}; use std::thread; use raftfwk::msg::{Msg, RaftError, Normal}; use raftfwk::service::{ProposeCallback, RaftContext, Raf...
Ok(v) => println!("Set: {}", v), Err(e) => println!("Error: {}", e) } } fn get(&self, vs: Vec<String>) { let (sender, receiver) = mpsc::channel(); let cb = Box::new(move |x: Option<Vec<u8>>| { sender.send(x); }); let v = Item { key: ...
sender.send(String::from_utf8(v).unwrap()); } else { sender.send(format!("Success")); } }); let v = Item { key: vs[1].clone(), value: vs[2].clone().into_bytes() }; let bytes = bincode::serialize(&v).unwrap(); matc...
function_block-random_span
[ { "content": "pub fn create_logger(id: u64, log_level: String) -> Logger {\n\n let decorator = slog_term::TermDecorator::new().build();\n\n let drain = slog_term::FullFormat::new(decorator).build().fuse();\n\n let drain = LevelFilter { drain: drain, level: log_level }.fuse();\n\n let drain = slog_as...
Rust
src/provider/provider.rs
russellwmy/near-api-rs
6f62d54cc6c0362779d7f5cb337397e6a2ef1041
use super::{ types::{ AccessKeyWithPublicKey, BlockChangeResult, BlockId, BlockReference, BlockResult, ChangeResult, ChunkId, ChunkResult, CryptoHash, EpochValidatorInfo, FinalExecutionOutcome, GasPrice, LightClientProof, LightClientProofRequest, NearProtocolConfig, NodeStatusResult, ...
use super::{ types::{ AccessKeyWithPublicKey, BlockChangeResult, BlockId, BlockReference, BlockResult, ChangeResult, ChunkId, ChunkResult, CryptoHash, EpochValidatorInfo, FinalExecutionOutcome, GasPrice, LightClientProof, LightClientProofRequest, NearProtocolConfig, NodeStatusResult, ...
e::BlockId(block_id) => match block_id { BlockId::Hash(block_id) => block_id.to_string(), _ => "Missing block id".to_string(), }, _ => "Missing block id".to_owned(), }; let finality = match block_query.clone() { BlockReference::Finality...
match response { Ok(response) => Ok(BlockResult::deserialize(response.result.unwrap()).unwrap()), Err(_) => Err(RpcError::parse_error(format!("Failed to get block info"))), } } pub async fn block_changes( &self, block_reference: BlockReference, ) -> Result<B...
random
[ { "content": "pub fn decoded_to_parsed(res: JsonResult<WireMessage>) -> Parsed {\n\n match res {\n\n Ok(WireMessage::Message(Message::UnmatchedSub(value))) => Err(Broken::Unmatched(value)),\n\n Ok(WireMessage::Message(m)) => Ok(m),\n\n Ok(WireMessage::Broken(b)) => Err(b),\n\n Err...
Rust
internal_types/src/freezable.rs
phial3/influxdb_iox
1b9212540b018ed7b41cd04c41660da91129ca7b
use std::ops::{Deref, DerefMut}; use std::sync::Arc; #[derive(Debug)] pub struct Freezable<T> { lock: Arc<tokio::sync::Mutex<()>>, payload: T, } impl<T> Freezable<T> { pub fn new(payload: T) -> Self { Self { lock: Default::default(), payload, } } ...
use std::ops::{Deref, DerefMut}; use std::sync::Arc; #[derive(Debug)] pub struct Freezable<T> { lock: Arc<tokio::sync::Mutex<()>>, payload: T, } impl<T> Freezable<T> { pub fn new(payload: T) -> Self { Self { lock: Default::default(), payload, } } ...
std::mem::drop(write_guard); let handle = freeze_fut.now_or_never().unwrap(); assert!(f.try_freeze().is_none()); assert!(f.get_mut().is_none()); let freeze_fut = f.freeze(); pin_mut!(freeze_fut); assert!(freeze_fut.poll_unpin(&m...
&mut self.freezable.payload } } #[derive(Debug)] pub struct FreezeHandle(tokio::sync::OwnedMutexGuard<()>); #[cfg(test)] mod tests { use super::*; use futures::{future::FutureExt, pin_mut}; use std::sync::RwLock; #[tokio::test] async fn test_freeze() { let waker = futures::task::noo...
random
[]
Rust
src/rustup.rs
mntns/cross
51fc390bcc44fbe0d4e845db89f3cf97f2c92e37
use std::path::Path; use std::process::Command; use rustc_version::{Channel, Version}; use crate::errors::*; use crate::extensions::CommandExt; use crate::Target; #[derive(Debug)] pub struct AvailableTargets { default: String, installed: Vec<String>, not_installed: Vec<String>, } impl AvailableTargets {...
use std::path::Path; use std::process::Command; use rustc_version::{Channel, Version}; use crate::errors::*; use crate::extensions::CommandExt; use crate::Target; #[derive(Debug)] pub struct AvailableTargets { default: String, installed: Vec<String>, not_installed: Vec<String>, } impl AvailableTargets {...
mponent: &str, toolchain: &str, verbose: bool) -> Result<()> { Command::new("rustup") .args(&["component", "add", component, "--toolchain", toolchain]) .run(verbose) .wrap_err_with(|| format!("couldn't install the `{component}` component")) } pub fn component_is_installed(component: &str, t...
sult<AvailableTargets> { let out = Command::new("rustup") .args(&["target", "list", "--toolchain", toolchain]) .run_and_get_stdout(verbose)?; let mut default = String::new(); let mut installed = vec![]; let mut not_installed = vec![]; for line in out.lines() { let target = ...
random
[ { "content": "/// Pretty format a file path. Also removes the path prefix from a command if wanted\n\npub fn pretty_path(path: impl AsRef<Path>, strip: impl for<'a> Fn(&'a str) -> bool) -> String {\n\n let path = path.as_ref();\n\n // TODO: Use Path::file_prefix\n\n let file_stem = path.file_stem();\n\...
Rust
src/main.rs
ruuda/btrfs-mirror-subvolumes
d0a697a2a7aff6ef36b2d46b5fc0b74b3083e19f
extern crate libc; extern crate walkdir; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::env; use std::fs; use std::ffi::OsString; use std::io; use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use std::process; use std::time::SystemTime; #[derive(Eq, Ord, Debug, Hash, P...
extern crate libc; extern crate walkdir; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::env; use std::fs; use std::ffi::OsString; use std::io; use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use std::process; use std::time::SystemTime; #[derive(Eq, Ord, Debug, Hash, P...
if let Some(fname) = path.file_name() { if let Some(paths) = self.entries_name.get(fname) { return Some(&paths[..]); } } None } } fn scan_dir<P: AsRef<Path>>(dir_path: P) -> io::Result<DirScan> { let mut entries_size_mtime: HashMap<FileInfo, Vec<...
f.entries_size_mtime.get(info) { return Some(&paths[..]); } if let Some(paths) = self.entries_size.get(&info.len) { for (i, matched_path) in paths.iter().enumerate() { if path.extension() == matched_path.extensio...
function_block-random_span
[ { "content": "def sync_one(src: str, dst: str, *, dry_run: bool) -> Optional[date]:\n\n \"\"\"\n\n From the snapshots that are present in src and missing in dst, pick the one\n\n that is closest to an existing snapshot in dst, and sync it. Returns the\n\n snapshot synced, or none if src and dst are ...
Rust
src/tag_validator.rs
belltoy/leetcode
11259de8cf06c240268022dfd4344cf0c05df508
pub struct Solution; impl Solution { pub fn is_valid(code: String) -> bool { code.chars().try_fold(Validator::new(), |mut validator, c| { validator.handle(c).map(|_| validator) }) .and_then(|validator| match validator.is_end() { true => Ok(()), _ => Err...
pub struct Solution; impl Solution { pub fn is_valid(code: String) -> bool { code.chars().try_fold(Validator::new(), |mut validator, c| { validator.handle(c).map(|_| validator) }) .and_then(|validator| match validator.is_end() { true => Ok(()), _ => Err...
Ok(()) } _ => Err("Wrong close tag"), } } ('/', 0, false) => { *is_close = true; Ok(()) ...
if self.stack.len() > 0 { self.state = State::TagContent; } else { self.state = State::End; }
if_condition
[ { "content": "type Result = std::result::Result<State, ()>;\n\n\n", "file_path": "src/valid_number.rs", "rank": 1, "score": 173607.68525792 }, { "content": "type Result<T> = std::result::Result<T, String>;\n\n\n\nimpl Solution {\n\n\n\n pub fn evaluate(expression: String) -> i32 {\n\n ...
Rust
src/dynprog.rs
sfb833-a3/seqalign
fb22556a1bfd6356330c35ddf40afc12097a012a
use std::collections::{HashSet, VecDeque}; use crate::op::{Backtrack, BestCost, IndexedOperation, Operation}; use crate::{Measure, SeqPair}; pub trait Align<'a, M, T> where M: Measure<T>, T: Eq, { fn align(&'a self, source: &'a [T], target: &'a [T]) -> Alignment<'a, M, T>; } impl<'a, M, T>...
use std::collections::{HashSet, VecDeque}; use crate::op::{Backtrack, BestCost, IndexedOperation, Operation}; use crate::{Measure, SeqPair}; pub trait Align<'a, M, T> where M: Measure<T>, T: Eq, { fn align(&'a self, source: &'a [T], target: &'a [T]) -> Alignment<'a, M, T>; } impl<'a, M, T>...
pub fn edit_scripts(&self) -> HashSet<Vec<IndexedOperation<M::Operation>>> { let mut q: VecDeque<BacktrackState<M, T>> = VecDeque::new(); q.push_back(BacktrackState { source_idx: self.pair.source.len(), target_idx: self.pair.target...
r, &self.cost_matrix, source_idx, target_idx) { let (new_source_idx, new_target_idx) = op .backtrack(&self.pair, source_idx, target_idx) .expect("Cannot backtrack"); source_idx = new_source_idx; target_idx = new_target_idx; script....
function_block-function_prefixed
[ { "content": "/// Trait for sequence edit operations.\n\npub trait Operation<T>: Clone + Debug + Eq + Hash {\n\n /// Return the cell after backtracking from the given cell with this operation.\n\n ///\n\n /// Must return `None` if backtracking is not possible (e.g. would lead\n\n /// to an invalid c...
Rust
ckb-bin/src/subcommand/list_hashes.rs
zhangsoledad/ckb
c419de3c93be101756afe2cccf40f4108d8f9e3f
use ckb_app_config::{cli, CKBAppConfig, ExitCode}; use ckb_chain_spec::ChainSpec; use ckb_resource::{Resource, AVAILABLE_SPECS}; use ckb_types::{packed::CellOutput, prelude::*, H256}; use clap::ArgMatches; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::convert::{TryFrom, TryInto}; use std...
use ckb_app_config::{cli, CKBAppConfig, ExitCode}; use ckb_chain_spec::ChainSpec; use ckb_resource::{Resource, AVAILABLE_SPECS}; use ckb_types::{packed::CellOutput, prelude::*, H256}; use clap::ArgMatches; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::convert::{TryFrom, TryInto}; use std...
c_hashes: SpecHashes = chain_spec.try_into()?; specs.push((spec_name, spec_hashes)); } println!(); let length = specs.len(); for (index, (name, spec_hashes)) in specs.into_iter().enumerate() { println!("# Spec: {}", name); let mut map = BTreeMap::default(); map.insert(na...
rror)?; let spec_name = spec.name.clone(); let spec_hashes: SpecHashes = spec.try_into()?; specs.push((spec_name, spec_hashes)); } } else { println!("# Generated by: ckb list-hashes"); let mut resource = Resource::ckb_config(&root_dir); if !resourc...
function_block-random_span
[ { "content": "fn log_failed_specs(error_spec_names: &[String]) -> Result<(), io::Error> {\n\n let path = if let Ok(path) = env::var(\"CKB_INTEGRATION_FAILURE_FILE\") {\n\n path\n\n } else {\n\n return Ok(());\n\n };\n\n\n\n let mut f = File::create(&path)?;\n\n for name in error_spe...
Rust
crates/libvmm/src/x86_64/svm/vmcb.rs
DeathWish5/RVM1.5
c340272c1e7efa5bb413533da5e2c9fa9b995eb6
use core::fmt::{Debug, Formatter, Result}; use core::mem::MaybeUninit; use super::flags::{VmcbCleanBits, VmcbIntInfo}; use super::{SvmExitCode, SvmIntercept}; #[repr(C, align(1024))] pub struct VmcbControlArea { pub intercept_cr: u32, pub intercept_dr: u32, pub intercept_exceptions: u32, pub intercept...
use core::fmt::{Debug, Formatter, Result}; use core::mem::MaybeUninit; use super::flags::{VmcbCleanBits, VmcbIntInfo}; use super::{SvmExitCode, SvmIntercept}; #[repr(C, align(1024))] pub struct VmcbControlArea { pub intercept_cr: u32, pub intercept_dr: u32, pub intercept_exceptions: u32, pub intercept...
} impl Debug for VmcbStateSaveArea { fn fmt(&self, f: &mut Formatter) -> Result { f.debug_struct("VmcbStateSaveArea") .field("es", &self.es) .field("cs", &self.cs) .field("ss", &self.ss) .field("ds", &self.ds) .field("fs", &self.fs) ....
l) .field("int_vector", &self.int_vector) .field("int_state", &self.int_state) .field("exit_code", &self.exit_code) .field("exit_info_1", &self.exit_info_1) .field("exit_info_2", &self.exit_info_2) .field("exit_int_info", &self.exit_int_info) ...
function_block-function_prefixed
[ { "content": "pub fn frequency() -> u16 {\n\n static CPU_FREQUENCY: spin::Once<u16> = spin::Once::new();\n\n *CPU_FREQUENCY.call_once(|| {\n\n const DEFAULT: u16 = 4000;\n\n super::cpuid::CpuId::new()\n\n .get_processor_frequency_info()\n\n .map(|info| info.processor_ba...
Rust
src/main.rs
cxfksword/douban-api-rs
3edba57ec27fb523c033687622f3a8ae38d3e756
use actix_web::{get, middleware, web, App, HttpResponse, HttpServer, Responder, Result}; mod api; mod bookapi; use api::Douban; use bookapi::DoubanBookApi; use clap::Parser; use serde::Deserialize; use std::env; #[get("/")] async fn index() -> impl Responder { HttpResponse::Ok() .content_type("text/html; c...
use actix_web::{get, middleware, web, App, HttpResponse, HttpServer, Responder, Result}; mod api; mod bookapi; use api::Douban; use bookapi::DoubanBookApi; use clap::Parser; use serde::Deserialize; use std::env; #[get("/")] async fn index() -> impl Responder { HttpResponse::Ok() .content_type("text/html; c...
tring> { let sid = path.into_inner(); let result = douban_api.get_wallpaper(&sid).await.unwrap(); Ok(serde_json::to_string(&result).unwrap()) } #[get("/v2/book/search")] async fn books(query: web::Query<Search>, book_api: web::Data<DoubanBookApi>) -> Result<String> { if query.q.is_empty() { ret...
into_inner(); let result = douban_api.get_celebrity(&id).await.unwrap(); Ok(serde_json::to_string(&result).unwrap()) } #[get("/photo/{sid}")] async fn photo(path: web::Path<String>, douban_api: web::Data<Douban>) -> Result<S
random
[ { "content": " .unwrap();\n\n let re_id = Regex::new(r\"sid: (\\d+?),\").unwrap();\n\n let re_remove_split_space = Regex::new(r\"\\s+?/\\s+\").unwrap();\n\n let re_info_pair = Regex::new(r\"([^\\s]+?):\\s*([^\\n]+)\").unwrap();\n\n Self {\n\n client,\n\n ...
Rust
libs/game/src/ecs/systems/mod.rs
henryksloan/grumpy_visitors
5443a3833d4f1d10abd1aefe590713818c0903de
pub mod missile; pub mod monster; pub mod player; mod action; mod damage_subsystem; mod level; mod net_connection_manager; mod pause; mod state_switcher; mod world_position_transform; mod world_state_subsystem; pub use self::{ action::ActionSystem, damage_subsystem::DamageSubsystem, level::LevelSystem, ...
pub mod missile; pub mod monster; pub mod player; mod action; mod damage_subsystem; mod level; mod net_connection_manager; mod pause; mod state_switcher; mod world_position_transform; mod world_state_subsystem; pub use self::{ action::ActionSystem, damage_subsystem::DamageSubsystem, level::LevelSystem, ...
#[cfg(not(feature = "client"))] fn play_animation( &mut self, _entity: Entity, _body_part_name: &str, _animation_id: AnimationId, ) { } #[cfg(feature = "client")] fn remove_animation( &mut self, entity: Entity, body_part_name: &str, ...
fn play_animation(&mut self, entity: Entity, body_part_name: &str, animation_id: AnimationId) { play_animation( &self.parent_hierarchy, &self.named, &self.animation_sets, &mut self.animation_control_sets, entity, body_part_name, ...
function_block-function_prefix_line
[ { "content": "pub fn create_color_material(world: &World, colour: LinSrgba) -> Handle<Material> {\n\n let mat_defaults = world.fetch::<MaterialDefaults>();\n\n let loader = world.fetch::<Loader>();\n\n\n\n let albedo = loader.load_from_data(load_from_linear_rgba(colour).into(), (), &world.fetch());\n\n...
Rust
src/sbe.rs
unterflow/unterflow-protocol
8d54e7cfa6f0810445d6a4ce1ef45cd316173520
use io::{Data, FromBytes, HasBlockLength, HasData, HasMessageLength, Message, ToBytes, ToData}; use message::{COMPLETE_STATE, NIL, TaskEvent}; use std; #[derive(Debug, PartialEq, FromBytes, ToBytes, HasBlockLength)] pub struct MessageHeader { pub block_length: u16, pub template_id: u16, pub schema_id: u16,...
use io::{Data, FromBytes, HasBlockLength, HasData, HasMessageLength, Message, ToBytes, ToData}; use message::{COMPLETE_STATE, NIL, TaskEvent}; use std; #[derive(Debug, PartialEq, FromBytes, ToBytes, HasBlockLength)] pub struct MessageHeader { pub block_length: u16, pub template_id: u16, pub schema_id: u16,...
} #[derive(Debug, PartialEq, FromBytes, ToBytes, HasBlockLength, HasMessageLength)] pub enum ErrorCode { MessageNotSupported, TopicNotFound, RequestWriteFailure, InvalidClientVersion, RequestTimeout, RequestProcessingFailure, InvalidMessage, } #[derive(Debug, PartialEq, FromBytes, ToBytes...
fn message_header() -> MessageHeader { MessageHeader { block_length: T::block_length(), template_id: T::template_id(), schema_id: T::schema_id(), version: T::version(), } }
function_block-full_function
[ { "content": "pub trait HasMessageLength {\n\n fn message_length(&self) -> u32;\n\n}\n\n\n\nmacro_rules! impl_has_message_length {\n\n ($t:ty) => (\n\n impl HasMessageLength for $t {\n\n fn message_length(&self) -> u32 {\n\n ::std::mem::size_of::<$t>() as u32\n\n ...
Rust
src/pipe_input.rs
sulanov/locomix
20d030c16f15a0ab6d6ee78f95ec6a5f3390966d
use crate::base::*; use crate::time::{Time, TimeDelta}; use libc; use nix; use nix::fcntl; use std; use std::fs::File; use std::io::Read; use std::os::linux::fs::MetadataExt; use std::os::unix::io::AsRawFd; use super::input::*; const FORMAT: SampleFormat = SampleFormat::F32LE; const FILE_REOPEN_FREQUENCY_SECS: i64 = ...
use crate::base::*; use crate::time::{Time, TimeDelta}; use libc; use nix; use nix::fcntl; use std; use std::fs::File; use std::io::Read; use std::os::linux::fs::MetadataExt; use std::os::unix::io::AsRawFd; use super::input::*; const FORMAT: SampleFormat = SampleFormat::F32LE; const FILE_REOPEN_FREQUENCY_SECS: i64 = ...
} impl Input for PipeInput { fn read(&mut self) -> Result<Option<Frame>> { self.try_reopen(); let bytes_per_frame = FORMAT.bytes_per_sample() * self.spec.channels.len(); let size = (self.period_duration.in_seconds_f() * self.sample_rate) as usize * bytes_per_frame / 2; ...
fn try_reopen(&mut self) { let now = Time::now(); if now - self.last_open_time < TimeDelta::seconds(FILE_REOPEN_FREQUENCY_SECS) { return; } self.last_open_time = now; match File::open(&self.spec.id) { Err(_) => { self.file = None; ...
function_block-full_function
[ { "content": "pub fn samples_to_timedelta(sample_rate: f64, samples: i64) -> TimeDelta {\n\n TimeDelta::seconds_f(samples as f64 / sample_rate)\n\n}\n\n\n", "file_path": "src/base.rs", "rank": 0, "score": 192948.81647919296 }, { "content": "pub fn get_sample_timestamp(start: Time, sample_...
Rust
src/main.rs
klamann/docuum
abe204e7953cfd1e74aaea154c647c77541d7e58
#![deny(clippy::all, clippy::pedantic, warnings)] mod format; mod run; mod state; use { crate::{format::CodeStr, run::run}, atty::Stream, byte_unit::Byte, chrono::Local, clap::{App, AppSettings, Arg}, env_logger::{fmt::Color, Builder}, log::{Level, LevelFilter}, regex::RegexSet, st...
#![deny(clippy::all, clippy::pedantic, warnings)] mod format; mod run; mod state; use { crate::{format::CodeStr, run::run}, atty::Stream, byte_unit::Byte, chrono::Local, clap::{App, AppSettings, Arg}, env_logger::{fmt::Color, Builder}, log::{Level, LevelFilter}, regex::RegexSet, st...
:ErrorKind::InvalidInput, e)), }, None => None, }; Ok(Settings { threshold, keep }) } fn main() { colored::control::set_override(atty::is(Stream::Stderr)); set_up_logging(); let settings = match settings() { Ok(settings) => settings, Err(error) => {...
let mut style = buf.style(); style.set_bold(true); match record.level() { Level::Error => { style.set_color(Color::Red); } Level::Warn => { style.set_color(Color::Yellow); } Le...
random
[]
Rust
lang/disassembler/src/code/exp/rf.rs
villesundell/move-tools
3af57b46f897ab8fb4430f00442fba7f47be440b
use crate::code::exp::{ExpLoc, Exp, SourceRange, find_range}; use crate::Encode; use anyhow::Error; use std::fmt::Write; use crate::code::translator::Context; use vm::file_format::*; use crate::code::locals::Local; use crate::unit::UnitAccess; #[derive(Debug)] pub struct FieldRef<'a> { is_mut: bool, field_name...
use crate::code::exp::{ExpLoc, Exp, SourceRange, find_range}; use crate::Encode; use anyhow::Error; use std::fmt::Write; use crate::code::translator::Context; use vm::file_format::*; use crate::code::locals::Local; use crate::unit::UnitAccess; #[derive(Debug)] pub struct FieldRef<'a> { is_mut: bool, field_name...
}
fn encode<W: Write>(&self, w: &mut W, _: usize) -> Result<(), Error> { w.write_str("*")?; self.val_ref.encode(w, 0)?; w.write_str(" = ")?; self.val.encode(w, 0) }
function_block-full_function
[ { "content": "/// Handles `BrFalse` instruction.\n\npub fn br_false<'a>(index: usize, _ctx: &mut impl Context<'a>) -> Exp<'a> {\n\n Exp::Error(Bytecode::BrFalse(index as u16))\n\n}\n\n\n", "file_path": "lang/disassembler/src/code/exp/branching/mod.rs", "rank": 0, "score": 375459.5283728658 }, ...
Rust
src/generator.rs
matmu/fq
4a770d2016090406a8962a59b33feee6214117bd
mod builder; pub use self::builder::Builder; use std::io::Write; use rand::{ distributions::{Distribution, Uniform}, rngs::SmallRng, Rng, SeedableRng, }; use super::{ distributions::{Character, QualityScores}, fastq::Record, }; static UPPER_ALPHA_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; ...
mod builder; pub use self::builder::Builder; use std::io::Write; use rand::{ distributions::{Distribution, Uniform}, rngs::SmallRng, Rng, SeedableRng, }; use super::{ distributions::{Character, QualityScores}, fastq::Record, }; static UPPER_ALPHA_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; ...
take(len).collect(); String::from_utf8(bytes).unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn test_next_record() { let mut generator = Generator::seed_from_u64(0); let mut record = Record::default(); generator.next_record(&mut record); assert_eq!( ...
cell_id<R>(rng: &mut R, len: usize) -> String where R: Rng, { let distribution = Character::new(UPPER_ALPHA_CHARSET); let bytes = rng.sample_iter(&distribution).
function_block-random_span
[ { "content": "fn build_filter<Rng>(mut rng: Rng, src_record_count: usize, dst_record_count: u64) -> BitVec\n\nwhere\n\n Rng: rand::Rng,\n\n{\n\n let mut bitmap = BitVec::new();\n\n bitmap.resize(src_record_count, false);\n\n\n\n let distribution = Uniform::from(0..src_record_count);\n\n let mut n...
Rust
third_party/rust_crates/vendor/semver/tests/test_version_req.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
mod node; mod util; use crate::util::*; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[cfg(test_node_semver)] use node::{req, VersionReq}; #[cfg(not(test_node_semver))] use semver::VersionReq; #[cfg_attr(not(no_track_caller), track_caller)] fn assert_match_all(req: &VersionReq, versi...
mod node; mod util; use crate::util::*; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[cfg(test_node_semver)] use node::{req, VersionReq}; #[cfg(not(test_node_semver))] use semver::VersionReq; #[cfg_attr(not(no_track_caller), track_caller)] fn assert_match_all(req: &VersionReq, versi...
l(r, &["0.1.6", "0.1.9"]); assert_match_none(r, &["0.1.0", "0.1.4", "0.2.0"]); let err = req_err("> 0.1.0,"); assert_to_string( err, "unexpected end of input while parsing major version number", ); let err = req_err("> 0.3.0, ,"); assert_to_string( err, "unexpec...
.0, >= 0.5.0"); assert_to_string(r, "<=0.2.0, >=0.5.0"); assert_match_none(r, &["0.0.8", "0.3.0", "0.5.1"]); let ref r = req("0.1.0, 0.1.4, 0.1.6"); assert_to_string(r, "^0.1.0, ^0.1.4, ^0.1.6"); assert_match_al
function_block-random_span
[]
Rust
hartex_plugins/src/information/userinfo.rs
mod-tc/HarTex-rust-discord-bot
1cbd3e8933ff71853eff0114fd2675f3e8b7b210
use hartex_cmdsys::{ command::{ Command, CommandType }, context::CommandContext }; use hartex_core::{ discord::{ cache_inmemory::InMemoryCache, embed_builder::{ EmbedAuthorBuilder, EmbedBuilder, EmbedFieldBuilder, ImageSo...
use hartex_cmdsys::{ command::{ Command, CommandType }, context::CommandContext }; use hartex_core::{ discord::{ cache_inmemory::InMemoryCache, embed_builder::{ EmbedAuthorBuilder, EmbedBuilder, EmbedFieldBuilder, ImageSo...
Interaction::ApplicationCommand(command) => command, _ => return Err( HarTexError::Custom { message: String::from("invalid interaction type: expected ApplicationCommand") } ) }; if interaction.guild_id.is_none() || interaction.user.is_some() { ctx...
function_block-function_prefix_line
[ { "content": "/// # Function `ansi_display`\n\n///\n\n/// Converts the provided parameters to a string that is `Display`able.\n\n///\n\n/// ## Parameters\n\n/// - `params`, type `Vec<i32>`: the parameters to convert\n\npub fn ansi_display(params: Vec<i32>) -> impl Display {\n\n let strings = params.iter().ma...
Rust
lib/src/view.rs
quark-zju/jj
0fb59a5155ad4ea083edbb9e078fd53a922d31e7
use std::cmp::min; use std::collections::{BTreeMap, HashSet}; use std::sync::Arc; use crate::commit::Commit; use crate::op_store; use crate::store::CommitId; use crate::store_wrapper::StoreWrapper; pub enum ViewRef<'a> { Readonly(&'a ReadonlyView), Mutable(&'a MutableView), } impl<'a> ViewRef<'a> { pub...
use std::cmp::min; use std::collections::{BTreeMap, HashSet}; use std::sync::Arc; use crate::commit::Commit; use crate::op_store; use crate::store::CommitId; use crate::store_wrapper::StoreWrapper; pub enum ViewRef<'a> { Readonly(&'a ReadonlyView), Mutable(&'a MutableView), } impl<'a> ViewRef<'a> { pub...
&self.store, &mut self.data); } pub fn add_public_head(&mut self, head: &Commit) { self.data.public_head_ids.insert(head.id().clone()); enforce_invariants(&self.store, &mut self.data); } pub fn remove_public_head(&mut self, head: &Commit) { self.data.public_head_ids.remove(head...
ore_view, } } pub fn start_modification(&self) -> MutableView { MutableView { store: self.store.clone(), data: self.data.clone(), } } pub fn as_view_ref(&self) -> ViewRef { ViewRef::Readonly(self) } pub fn checkout(&self) -> &Co...
random
[ { "content": "pub fn diff<'a>(left: &'a [u8], right: &'a [u8], callback: &mut impl FnMut(&DiffLine<'a>)) {\n\n // TODO: Should we attempt to interpret as utf-8 and otherwise break only at\n\n // newlines?\n\n let left_tokens = tokenize(left);\n\n let right_tokens = tokenize(right);\n\n let result...
Rust
control-plane/agents/core/src/core/reconciler/pool/mod.rs
Abhinandan-Purkait/mayastor-control-plane
73390a0e61dd93d1fb7c2735ebac579b7bb88434
use crate::core::{ specs::{OperationSequenceGuard, SpecOperations}, task_poller::{PollContext, PollPeriods, PollResult, PollTimer, PollerState, TaskPoller}, wrapper::ClientOps, }; use common_lib::types::v0::{ message_bus::{CreatePool, DestroyPool, NodeStatus}, store::{pool::PoolSpec, OperationMode, ...
use crate::core::{ specs::{OperationSequenceGuard, SpecOperations}, task_poller::{PollContext, PollPeriods, PollResult, PollTimer, PollerState, TaskPoller}, wrapper::ClientOps, }; use common_lib::types::v0::{ message_bus::{CreatePool, DestroyPool, NodeStatus}, store::{pool::PoolSpec, OperationMode, ...
pool = pool_spec.lock().clone(); match context .registry() .get_node_wrapper(&pool.node.clone()) .await { Ok(node) => { if !node.read().await.is_online() { return PollResult::Ok(PollerState::Idle); } } Err(_) => return Poll...
Err(error) } } } .instrument(tracing::info_span!("missing_pool_state_reconciler", pool.uuid = %pool.id, request.reconcile = true)) .await } else { PollResult::Ok(PollerState::Idle) } } #[tracing::instrument(skip(pool_spec, context), level = "trace", f...
random
[ { "content": "/// returns pool from pool option and returns an error on non existence\n\npub fn pool(pool_id: String, pool: Option<&Pool>) -> Result<Pool, ReplyError> {\n\n match pool {\n\n Some(pool) => Ok(pool.clone()),\n\n None => Err(ReplyError {\n\n kind: ReplyErrorKind::NotFoun...
Rust
src/main.rs
superdump/partyarty
bb2945bb6d35b99feb62ae2387592a2d7c192d15
#[macro_use] extern crate clap; extern crate failure; extern crate partyarty; extern crate rand; extern crate sdl2; use clap::{App, Arg}; use failure::Error; use partyarty::*; use rand::seq::SliceRandom; use rand::thread_rng; use sdl2::pixels::{Color, PixelFormatEnum}; use sdl2::event::Event; use sdl2::keyboard::Keyco...
#[macro_use] extern crate clap; extern crate failure; extern crate partyarty; extern crate rand; extern crate sdl2; use clap::{App, Arg}; use failure::Error; use partyarty::*; use rand::seq::SliceRandom; use rand::thread_rng; use sdl2::pixels::{Color, PixelFormatEnum}; use sdl2::event::Event; use sdl2::keyboard::Keyco...
e = 0.0; { world.exec(|(timers, samples_to_process,): (Read<PerfTimers>, Read<SamplesToProcessPerFrame>,)| { samples_per_sec_for_frame = samples_to_process.0 as f64 * 1000.0 / timers.0.frames_mean.q.back().unwrap(); }); } let mean = samples_per_sec.append(...
function_block-function_prefixed
[ { "content": "pub fn timer_transition(world: &mut World, a: &'static str, b: &'static str) {\n\n world.exec(|(mut timers, ): (Write<PerfTimers>, )| {\n\n timers.0.exit(a);\n\n timers.0.enter(b);\n\n });\n\n}\n\n\n", "file_path": "src/timers.rs", "rank": 0, "score": 183706.5154687...
Rust
src/main.rs
mschorsch/transfer-rs
546e0d5fd7866acd2cb92e33fdb4fbc783b6348b
#[macro_use] extern crate log; extern crate log4rs; extern crate clap; extern crate rand; extern crate regex; extern crate num_cpus; extern crate url; #[macro_use] extern crate lazy_static; #[macro_use] extern crate hyper; extern crate iron; extern crate router; extern crate multipart; #[macro_use] extern crate q...
#[macro_use] extern crate log; extern crate log4rs; extern crate clap; extern crate rand; extern crate regex; extern crate num_cpus; extern crate url; #[macro_use] extern crate lazy_static; #[macro_use] extern crate hyper; extern crate iron; extern crate router; extern crate multipart; #[macro_use] extern crate q...
fn get_port(port: Option<&str>, ssl: bool) -> Result<u16> { port.map(|port_str| port_str.parse::<u16>().map_err(|err| TransferError::from(err))) .unwrap_or_else(|| { if ssl { Ok(443u16) } else { Ok(80u16) } }) } fn get_directory<...
fn to_protocol(ssl: bool, ssl_cert: Option<&str>, ssl_key: Option<&str>, ssl_cert_chain: Option<&str>) -> Result<ExtIronProtocol> { if ssl { let cert = PathBuf::from(try!(get_directory(ssl_cert))); let key = PathBuf::from(try!(get_directory...
function_block-full_function
[ { "content": "// health handler\n\n//\n\npub fn health_handler(_: &mut IronRequest) -> IronResult<IronResponse> {\n\n Ok(IronResponse::with((status::Ok,\n\n \"Approaching Neutral Zone, all systems normal and functioning.\")))\n\n}\n\n\n\n// GET handler\n\n//\n\n#[derive(Debug, Clone...
Rust
fastanvil/src/tex/mod.rs
Badel2/fastnbt
c2799010a4f10ae349ac1984f4d9b9947bb73b97
use serde::Deserialize; use std::collections::HashMap; #[cfg(test)] mod test; #[derive(Deserialize, Debug, Clone)] pub struct Variant { pub model: String, pub x: Option<usize>, pub y: Option<usize>, pub uvlock: Option<bool>, } #[derive(Deserialize, Debug, Clone)] #[serde(untagged)] pub enum Variants ...
use serde::Deserialize; use std::collections::HashMap; #[cfg(test)] mod test; #[derive(Deserialize, Debug, Clone)] pub struct Variant { pub model: String, pub x: Option<usize>, pub y: Option<usize>, pub uvlock: Option<bool>, } #[derive(Deserialize, Debug, Clone)] #[serde(untagged)] pub enum Variants ...
fn model_get_top(&self, id: &str, encoded_props: &str, model_name: &str) -> Result<Texture> { let model = self.flatten_model(model_name)?; let els = &model.elements.ok_or(Error::MissingElements( id.to_owned(), encoded_props.to_owned(), model_name.to_ow...
pub fn new( blockstates: HashMap<String, Blockstate>, models: HashMap<String, Model>, textures: HashMap<String, Texture>, ) -> Self { Self { blockstates, models, textures, } }
function_block-full_function
[ { "content": "/// Palette can be used to take a block description to produce a colour that it\n\n/// should render to.\n\npub trait Palette {\n\n fn pick(&self, block: &Block, biome: Option<Biome>) -> Rgba;\n\n}\n\n\n\npub struct TopShadeRenderer<'a, P: Palette> {\n\n palette: &'a P,\n\n height_mode: H...
Rust
src/main.rs
ZigTag/spaceifier-app
079d195c1fd2f70251f5e7ffd8b76f60077c272d
use iced::{ button, text_input, Application, Button, Column, Command, Container, Element, Row, Settings, Text, TextInput, }; use iced::{executor, Background, Color, HorizontalAlignment, Length}; use copypasta::{ClipboardContext, ClipboardProvider}; fn main() { SpaceifierApp::run(Settings::default()); } s...
use iced::{ button, text_input, Application, Button, Column, Command, Container, Element, Row, Settings, Text, TextInput, }; use iced::{executor, Background, Color, HorizontalAlignment, Length}; use copypasta::{ClipboardContext, ClipboardProvider}; fn main() { SpaceifierApp::run(Settings::default()); } s...
}) .size(30), ) .push( Button::new( &mut self.copy_button_state, Text::new("Copy").size(20).color([1.0, 1.0, 1.0]), ) .on_press(Message::CopyButtonPress) ...
elf.text_input_state, "Enter text here...", self.text_input_value.as_str(), Message::TextInputChanged, ) .size(30) .padding(10), ...
random
[ { "content": "/// Takes a string and number of spaces and returns a string with that number of spaces in between\n\n/// every character\n\n/// ```\n\n/// let text = spaceifier::spaceify(\"Hello, world!\", 1);\n\n///\n\n/// assert_eq!(text, \"H e l l o , w o r l d !\");\n\n/// ```\n\npub fn spaceify(text: &str...
Rust
src/reexport.rs
Bobo1239/keystone-rs
876bc30cccce8939651a83df44dff48790c60fe7
#![allow( non_upper_case_globals, non_camel_case_types, non_snake_case )] use keystone_sys as kss; use crate::kss::{Arch::*, Error::*, Mode::*, OptionType::*, OptionValue::*}; use std::{convert, ops}; macro_rules! enum_association_wrapper { ([ $reexport_enum:ty ] $( -> $as...
#![allow( non_upper_case_globals, non_camel_case_types, non_snake_case )] use keystone_sys as kss; use crate::kss::{Arch::*, Error::*, Mode::*, OptionType::*, OptionValue::*}; use std::{convert, ops}; macro_rules! enum_association_wrapper { ([ $reexport_enum:ty ] $( -> $as...
_ERR_ASM_RPAREN; => AsmStatToken = KS_ERR_ASM_STAT_TOKEN; => AsmUnsupported = KS_ERR_ASM_UNSUPPORTED; => AsmMacroToken = KS_ERR_ASM_MACRO_TOKEN; => AsmMacroParen = KS_ERR_ASM_MACRO_PAREN; => AsmMacroEqu = KS_ERR_ASM_MACRO_EQU; => AsmMacroArgs = KS_ERR_ASM_MACRO_ARGS; => AsmMacroLevelsExceed ...
ectiveEqu = KS_ERR_ASM_DIRECTIVE_EQU; => AsmDirectiveInvalid = KS_ERR_ASM_DIRECTIVE_INVALID; => AsmVariantInvalid = KS_ERR_ASM_VARIANT_INVALID; => AsmExprBracket = KS_ERR_ASM_EXPR_BRACKET; => AsmSymbolModifier = KS_ERR_ASM_SYMBOL_MODIFIER; => AsmSymbolRedefined = KS_ERR_ASM_SYMBOL_REDEFINED; => ...
random
[ { "content": "/// Return whether an arch is supported\n\npub fn arch_supported(arch: kss::Arch) -> bool {\n\n unsafe { kss::ks_arch_supported(arch) }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_amd64() {\n\n let engine = Keystone::from(Arch::X86, Mode...
Rust
vendor/gl_generator/generators/debug_struct_gen.rs
vcapra1/alacritty
64026e22f889004c04297dfece71b2a65edb7f38
use registry::Registry; use std::io; #[allow(missing_copy_implementations)] pub struct DebugStructGenerator; impl super::Generator for DebugStructGenerator { fn write<W>(&self, registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write, { try!(write_header(dest)); tr...
use registry::Registry; use std::io; #[allow(missing_copy_implementations)] pub struct DebugStructGenerator; impl super::Generator for DebugStructGenerator { fn write<W>(&self, registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write, { try!(write_header(dest)); tr...
try!(writeln!(dest, "pub {name}: FnPtr,", name = cmd.proto.ident)); } try!(writeln!(dest, "_priv: ()")); writeln!(dest, "}}") } fn write_impl<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write, { try!(writeln!(dest, "impl {api} {{ /// ...
if let Some(v) = registry.aliases.get(&cmd.proto.ident) { try!(writeln!(dest, "/// Fallbacks: {}", v.join(", "))); }
if_condition
[]
Rust
src/math/plane/set.rs
brunoczim/thedes
d7fa3710f0f7c680bb8903945ad0c391598ccf31
use crate::math::plane::{Coord2, Direc, Nat}; use std::{ collections::{btree_set, BTreeSet}, ops::Bound, }; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Set { neighbours: Coord2<BTreeSet<Coord2<Nat>>>, } impl Default for Set { fn default() -> Self { Self::new() } } impl Set { ...
use crate::math::plane::{Coord2, Direc, Nat}; use std::{ collections::{btree_set, BTreeSet}, ops::Bound, }; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Set { neighbours: Coord2<BTreeSet<Coord2<Nat>>>, } impl Default for Set { fn default() -> Self { Self::new() } } impl Set { ...
.neighbours .y .range(!point ..= !Coord2 { y: Nat::max_value(), ..point }) .map(|&point| !point) .next_back(), Direc::Right => self .neighbours .x .range(point ..= Coord2 { x: Nat::max_value(),...
Direc::Down => self .neighbours .y .range(( Bound::Excluded(!point), Bound::Included(!Coord2 { y: Nat::max_value(), ..point }), )) .map(|&point| !point) .next(), Dire...
random
[ { "content": "fn unpack_chunk(point: Coord2<Nat>) -> Coord2<Nat> {\n\n point.zip_with(CHUNK_SIZE_EXP, |coord, exp| coord >> exp)\n\n}\n\n\n", "file_path": "src/map.rs", "rank": 0, "score": 150326.6942096273 }, { "content": "fn unpack_offset(point: Coord2<Nat>) -> Coord2<Nat> {\n\n poin...
Rust
meilisearch-lib/src/options.rs
Thearas/MeiliSearch
ae4e419db4da282c8301b807975c346e1953dbf4
use core::fmt; use std::{convert::TryFrom, num::ParseIntError, ops::Deref, str::FromStr}; use byte_unit::{Byte, ByteError}; use clap::Parser; use milli::update::IndexerConfig; use serde::Serialize; use sysinfo::{RefreshKind, System, SystemExt}; #[derive(Debug, Clone, Parser, Serialize)] pub struct IndexerOpts { ...
use core::fmt; use std::{convert::TryFrom, num::ParseIntError, ops::Deref, str::FromStr}; use byte_unit::{Byte, ByteError}; use clap::Parser; use milli::update::IndexerConfig; use serde::Serialize; use sysinfo::{RefreshKind, System, SystemExt}; #[derive(Debug, Clone, Parser, Serialize)] pub struct IndexerOpts { ...
Ok(Self { log_every_n: Some(other.log_every_n), max_nb_chunks: other.max_nb_chunks, max_memory: other.max_indexing_memory.map(|b| b.get_bytes() as usize), thread_pool: Some(thread_pool), max_positions_per_attributes: None, ..Default::defa...
let thread_pool = rayon::ThreadPoolBuilder::new() .num_threads(*other.max_indexing_threads) .build()?;
assignment_statement
[ { "content": "/// Check if a db is empty. It does not provide any information on the\n\n/// validity of the data in it.\n\n/// We consider a database as non empty when it's a non empty directory.\n\npub fn is_empty_db(db_path: impl AsRef<Path>) -> bool {\n\n let db_path = db_path.as_ref();\n\n\n\n if !db_...
Rust
src/unicorn/memory.rs
cksystemsgroup/unicorn
475f1ab888375ee891709cd3ae5c881847148220
use crate::unicorn::{HashableNodeRef, Model, Node, NodeRef, NodeType}; use log::{debug, trace}; use std::cell::RefCell; use std::collections::HashMap; use std::collections::HashSet; use std::mem::size_of; use std::rc::Rc; pub fn replace_memory(model: &mut Model) { debug!("Performing scalar replacement of all memor...
use crate::unicorn::{HashableNodeRef, Model, Node, NodeRef, NodeType}; use log::{debug, trace}; use std::cell::RefCell; use std::collections::HashMap; use std::collections::HashSet; use std::mem::size_of; use std::rc::Rc; pub fn replace_memory(model: &mut Model) { debug!("Performing scalar replacement of all memor...
impl MemoryReplacer { fn new(virtual_addresses: Vec<u64>) -> Self { Self { marks: HashSet::new(), mapping: HashMap::new(), memory_states: HashMap::new(), new_sequentials: Vec::new(), virtual_addresses, } } fn record_mapping(&mut ...
eRef { Rc::new(RefCell::new(Node::Next { nid: 0, sort: NodeType::Word, state: state.clone(), next: next.clone(), })) }
function_block-function_prefixed
[ { "content": "fn new_const_with_type(imm: u64, sort: NodeType) -> NodeRef {\n\n Rc::new(RefCell::new(Node::Const { nid: 0, sort, imm }))\n\n}\n\n\n", "file_path": "src/unicorn/optimize.rs", "rank": 2, "score": 264518.5473097238 }, { "content": "pub fn get_nid(node: &NodeRef) -> Nid {\n\n ...
Rust
server/src/main.rs
AlterionX/benxu.dev
994e2d11e9948350287f750075c920ffccd9a148
#![feature(proc_macro_hygiene, type_ascription, decl_macro)] #[macro_use] extern crate rocket; use crypto; use rocket_contrib::serve::StaticFiles; use std::{sync::Arc}; use tap::*; mod cfg; mod urls; mod util; use crate::{ urls::{blog_api_routes, blog_spa_routes, fixed_routes}, util::blog::DB as BlogDB, };...
#![feature(proc_macro_hygiene, type_ascription, decl_macro)] #[macro_use] extern crate rocket; use crypto; use rocket_contrib::serve::StaticFiles; use std::{sync::Arc}; use tap::*; mod cfg; mod urls; mod util; use crate::{ urls::{blog_api_routes, blog_spa_routes, fixed_routes}, util::blog::DB as BlogDB, };...
let static_key_store = Arc::new(cfg::pw_secret(&opt)); log::info!("Password secret key initialized."); static_key_store }; let crypto_init = { log::info!("Initialize multithreaded crypto crate."); let res = crypto::multithread_init().tap_err(|_| { ...
:data::Logo { src: "/public/img/branding.svg", href: Some("/"), }) } } struct Server { _sodiumoxide_init: (), _paseto_key: crypto::KeyRotator<cfg::TokenAlgo>, _local_loaded_key: Arc<crypto::StableKeyStore<cfg::PWAlgo>>, rocket: Option<rocket::Rock...
random
[ { "content": "/// Initializes the key rotation system for the token's secret key.\n\npub fn token_key() -> crypto::KeyRotator<TokenAlgo> {\n\n crypto::KeyRotator::init(TokenAlgo {}, None)\n\n}\n\n\n", "file_path": "server/src/cfg.rs", "rank": 0, "score": 192594.77238601138 }, { "content":...
Rust
master_thesis/src/camera.rs
MatusT/master-thesis
6fe2bb95e2bde72cf87caa88e6039f38229832ac
use bytemuck::*; use nalgebra_glm as glm; use wgpu::util::DeviceExt; use wgpu::*; use winit; use crate::*; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct CameraUbo { pub projection: glm::Mat4, pub view: glm::Mat4, pub projection_view: glm::Mat4, pub position: glm::Vec4, } impl CameraUbo { pu...
use bytemuck::*; use nalgebra_glm as glm; use wgpu::util::DeviceExt; use wgpu::*; use winit; use crate::*; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct CameraUbo { pub projection: glm::Mat4, pub view: glm::Mat4, pub projection_view: glm::Mat4, pub position: glm::Vec4, } impl CameraUbo { pu...
fn device_event(&mut self, event: &winit::event::DeviceEvent) { match event { winit::event::DeviceEvent::MouseMotion { delta: (x, y) } => { if self.mouse_pressed { self.add_yaw(*x as f64 / 100.0f64); self.add_pitch(*y as f64 / 100.0f64); ...
fn window_event(&mut self, event: &winit::event::WindowEvent) { match event { winit::event::WindowEvent::MouseWheel { delta, .. } => { if let winit::event::MouseScrollDelta::LineDelta(_, change) = delta { self.distance -= change * self.speed; } ...
function_block-full_function
[ { "content": "pub trait Camera {\n\n fn resize(&mut self, aspect: f32, fov: f32, near: f32);\n\n fn update(&mut self, event: &ApplicationEvent);\n\n fn ubo(&mut self) -> CameraUbo;\n\n\n\n fn speed(&self) -> f32;\n\n fn set_speed(&mut self, speed: f32);\n\n\n\n fn distance(&self) -> f32;\n\n ...
Rust
src/client_pin.rs
shimunn/ctap-hid-fido2
3357a7777986ffc89dae0e979f6549f957a2f3d0
use anyhow::{anyhow, Error, Result}; use crate::client_pin_command; use crate::client_pin_command::Permission; use crate::client_pin_command::SubCommand as PinCmd; use crate::client_pin_response; use crate::cose; use crate::ctaphid; use crate::enc_aes256_cbc; use crate::enc_hmac_sha_256; use crate::pintoken::PinToken;...
use anyhow::{anyhow, Error, Result}; use crate::client_pin_command; use crate::client_pin_command::Permission; use crate::client_pin_command::SubCommand as PinCmd; use crate::client_pin_response; use crate::cose; use crate::ctaphid; use crate::enc_aes256_cbc; use crate::enc_hmac_sha_256; use crate::pintoken::PinToken;...
pub fn change_pin(device: &FidoKeyHid, cid: &[u8], current_pin: &str, new_pin: &str) -> Result<()> { if current_pin.is_empty() { return Err(anyhow!("current pin not set")); } if new_pin.is_empty() { return Err(anyhow!("new pin not set")); } let send_payload = client_pin_co...
fn create_new_pin_enc(shared_secret: &SharedSecret, new_pin: &str) -> Result<Vec<u8>> { let new_pin_64 = padding_pin_64(new_pin)?; let new_pin_enc = enc_aes256_cbc::encrypt_message(&shared_secret.secret, &new_pin_64); Ok(new_pin_enc) }
function_block-full_function
[ { "content": "pub fn ctaphid_msg(device: &FidoKeyHid, cid: &[u8], payload: &[u8]) -> Result<Vec<u8>, String> {\n\n ctaphid_cbormsg(device, cid, CTAPHID_MSG, payload)\n\n}\n\n\n", "file_path": "src/ctaphid.rs", "rank": 3, "score": 375972.9306380724 }, { "content": "pub fn ctaphid_cbor(devi...
Rust
core/src/backend/video.rs
cyrozap/ruffle
88f368ad0a4fe207ecbe92ebf54cda889bcd7651
use crate::backend::render::{BitmapInfo, RenderBackend}; use generational_arena::{Arena, Index}; use swf::{VideoCodec, VideoDeblocking}; mod software; pub use crate::backend::video::software::SoftwareVideoBackend; pub type VideoStreamHandle = Index; pub type Error = Box<dyn std::error::Error>; pub struct Encoded...
use crate::backend::render::{BitmapInfo, RenderBackend}; use generational_arena::{Arena, Index}; use swf::{VideoCodec, VideoDeblocking}; mod software; pub use crate::backend::video::software::SoftwareVideoBackend; pub type VideoStreamHandle = Index; pub type Error = Box<dyn std::error::Error>; pub struct Encoded...
ency::None) } fn decode_video_stream_frame( &mut self, _stream: VideoStreamHandle, _encoded_frame: EncodedFrame<'_>, _renderer: &mut dyn RenderBackend, ) -> Result<BitmapInfo, Error> { Err("Video decoding not implemented".into()) } }
f, stream: VideoStreamHandle, encoded_frame: EncodedFrame<'_>, ) -> Result<FrameDependency, Error>; fn decode_video_stream_frame( &mut self, stream: VideoStreamHandle, encoded_frame: EncodedFrame<'_>, ...
random
[ { "content": "fn is_size_valid(swf_version: u8, width: u32, height: u32) -> bool {\n\n // From https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html:\n\n // \"In AIR 1.5 and Flash Player 10, the maximum size for a BitmapData object is 8,191 pixels in\n\n // w...
Rust
src/simulator/simulation.rs
dseevr/rust_backtesting_simulator
b1de900448714844d29f34079157936967e44fa5
use std::io::File; use chart::Chart; use config; use tick::Tick; use trade::Trade; static mut SIMULATION_ID: i32 = 1; pub struct Simulation { id: i32, in_sample: bool, jpy_base: bool, charts: Vec<Chart>, deposit: f32, last_equity_high: f32, last_equity_low: f32, highest_drawdown: f...
use std::io::File; use chart::Chart; use config; use tick::Tick; use trade::Trade; static mut SIMULATION_ID: i32 = 1; pub struct Simulation { id: i32, in_sample: bool, jpy_base: bool, charts: Vec<Chart>, deposit: f32, last_equity_high: f32, last_equity_low: f32, highest_drawdown: f...
pub fn get_highest_drawdown(&self) -> f32 { self.highest_drawdown } pub fn has_exceeded_max_drawdown(&self) -> bool { self.highest_drawdown < self.drawdown_limit } pub fn has_open_trades(&self) -> bool { self.open_trades.len() > 0 } pub fn log_trades(&self, logfi...
jpy_base { true => self.balance() + (equity / 100.0), false => self.balance() + equity, } }
function_block-function_prefixed
[ { "content": "pub fn get<'a>() -> &'a mut ConfigurationFile {\n\n unsafe {\n\n mem::transmute(CONFIG)\n\n }\n\n}\n\n\n\nimpl ConfigurationFile {\n\n pub fn load_from_file(path: &str) {\n\n lua::setup(path);\n\n\n\n let csv_path = lua::get_string_var(\"CSV_PATH\");\n\n\n\n le...
Rust
src/widget/sheet_editor/board.rs
ryanavella/harmoxen
0fa46fe247111d2329daebacbb5fc08f4c92c14f
use crate::commands; use crate::data::{ icp, sheet::{Interval, Note, Pitch, Sheet}, }; use crate::state::editors::sheet_editor::State; use crate::theme; use crate::util::coord::Coord; use crate::widget::common::{ParseLazy, TextBox}; use druid::kurbo::Line; use druid::{ BoxConstraints, Color, ContextMenu, Data, Env, ...
use crate::commands; use crate::data::{ icp, sheet::{Interval, Note, Pitch, Sheet}, }; use crate::state::editors::sheet_editor::State; use crate::theme; use crate::util::coord::Coord; use crate::widget::common::{ParseLazy, TextBox}; use druid::kurbo::Line; use druid::{ BoxConstraints, Color, ContextMenu, Data, Env, ...
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &State, env: &Env) { if let Some(widget) = &mut self.interval_input { widget.1.lifecycle(ctx, event, data, env); } } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &State, data: &State, env: &Env) { if old_data.frame != data.fr...
self.action = Action::Scale(idx, [(idx, note.length)].iter().cloned().collect()); } } } } } else if mouse.button.is_right() { self.interval_input = None; if let Some(id) = sheet.get_note_at(pos, coord.to_board_h(env.get(theme::NOTE_HEIGHT))) { sheet.remove_note(id); s...
function_block-function_prefix_line
[ { "content": "pub fn get_hover(x: f64, coord: Coord, layout: RefMut<Layout>) -> Option<usize> {\n\n\tlet extent = coord.to_board_w(8.0);\n\n\tlet offset = coord.to_board_w(4.0);\n\n\tfor (i, (marker_x, _)) in layout.markers.iter().enumerate() {\n\n\t\tif x > marker_x - offset && x < marker_x + extent + offset {...
Rust
src/des/ctrl.rs
tirust/msp432e4
479d52cb87a757f77406e1f314ea8acfba70f675
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::CTRL { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w...
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::CTRL { #[doc = r"Modifies the contents of the register"] #[inline(always)]
#[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { ...
pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); }
function_block-full_function
[ { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::BIT {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify...
Rust
crates/test-programs/wasi-tests/src/bin/truncation_rights.rs
iximeow/wasmtime
95c2addf15153c720da1402eec5e570e8f8ad646
use std::{env, mem, process}; use wasi_old::wasi_unstable; use wasi_tests::open_scratch_directory; use wasi_tests::utils::{cleanup_file, close_fd, create_file}; use wasi_tests::wasi_wrappers::{wasi_fd_fdstat_get, wasi_path_open}; unsafe fn test_truncation_rights(dir_fd: wasi_unstable::Fd) { create_file(dir_fd...
use std::{env, mem, process}; use wasi_old::wasi_unstable; use wasi_tests::open_scratch_directory; use wasi_tests::utils::{cleanup_file, close_fd, create_file}; use wasi_tests::wasi_wrappers::{wasi_fd_fdstat_get, wasi_path_open}; unsafe fn test_truncation_rights(dir_fd: wasi_unstable::Fd) { create_file(dir_fd...
status = wasi_path_open( dir_fd, 0, "file", wasi_unstable::O_TRUNC, 0, 0, 0, &mut file_fd, ); assert_eq!( status, wasi_unstable::raw::__WASI_ENOTCAPABLE, "truncating ...
); assert_eq!( status, wasi_unstable::raw::__WASI_ESUCCESS, "truncating a file" ); close_fd(file_fd); let mut rights_base: wasi_unstable::Rights = dir_fdstat.fs_rights_base; let mut rights_inheriting: wasi_unstable::Rights = dir_fdsta...
random
[ { "content": "/// Indicates how large a buffer to pre-allocate before reading the entire file.\n\n///\n\n/// Derived from the function of the same name in libstd.\n\nfn initial_buffer_size(file: &File) -> usize {\n\n // Allocate one extra byte so the buffer doesn't need to grow before the\n\n // final `re...
Rust
src/retro_types.rs
j-selby/oxretro
e036ccc38bde36404e2df2d6d0f5f372e3cebae6
use std::ffi::CString; use std::str::Utf8Error; use std::os::raw::*; use ffi::char_pointer_to_owned; pub type RetroInitFn = unsafe extern "C" fn() -> (); pub type RetroDeinitFn = unsafe extern "C" fn() -> (); pub type RetroApiVersionFn = unsafe extern "C" fn() -> c_uint; pub type RetroRunFn = unsafe extern "C"...
use std::ffi::CString; use std::str::Utf8Error; use std::os::raw::*; use ffi::char_pointer_to_owned; pub type RetroInitFn = unsafe extern "C" fn() -> (); pub type RetroDeinitFn = unsafe extern "C" fn() -> (); pub type RetroApiVersionFn = unsafe extern "C" fn() -> c_uint; pub type RetroRunFn = unsafe extern "C"...
pub fn from(format: u32) -> Option<RetroPixelFormat> { Some(match format { 0 => RetroPixelFormat::Format0RGB1555, 1 => RetroPixelFormat::FormatXRGB8888, 2 => RetroPixelFormat::FormatRGB565, _ => return None, }) } } #[derive(Debug)] pub enum...
h(original_data[pos + 1]); result.push(original_data[pos]); result.push(255); } }, &RetroPixelFormat::FormatRGB565 => for y in 0..height { for x in 0..width { let pos = (y * width + x) * pixel_size; ...
function_block-function_prefixed
[]
Rust
derive/src/json.rs
oasislabs/owasm-abi
edfbc937145fa9a873ecae03035cbf3bcd12fd5b
use {items, utils}; use serde_json; use std::{io}; use std; pub type JsonResult<T> = std::result::Result<T, JsonError>; #[derive(Debug)] pub enum JsonError { FailedToCreateDirectory(io::Error), FailedToCreateJsonFile(io::Error), FailedToWriteJsonAbiFile(serde_json::Error), } impl JsonError { pub fn failed...
use {items, utils}; use serde_json; use std::{io}; use std; pub type JsonResult<T> = std::result::Result<T, JsonError>; #[derive(Debug)] pub enum JsonError { FailedToCreateDirectory(io::Error), FailedToCreateJsonFile(io::Error), FailedToWriteJsonAbiFile(serde_json::Error), } impl JsonError { pub fn failed...
} impl From<FunctionEntry> for ConstructorEntry { fn from(func: FunctionEntry) -> Self { ConstructorEntry { arguments: func.arguments } } }
fn from(item: &items::Signature) -> Self { FunctionEntry { name: item.name.to_string(), arguments: item.arguments .iter() .map(|&(ref pat, ref ty)| Argument { name: quote! { #pat }.to_string(), ...
function_block-full_function
[ { "content": "fn push_canonicalized_type(target: &mut String, ty: &syn::Type) {\n\n\tmatch ty {\n\n\t\tsyn::Type::Path(type_path) if type_path.qself.is_none() => {\n\n\t\t\tpush_canonicalized_path(target, &type_path)\n\n\t\t},\n\n\t\tsyn::Type::Array(type_array) => {\n\n\t\t\t// Special cases for `bytesN`\n\n\t...
Rust
core/implement/math/piecewise.rs
clearlycloudy/e2
25b63e0f3426112a6ac6546168aea38a061dc33f
use std::cmp; use std::marker; use interface::i_interpolate::*; use interface::i_load; use implement::util::loadqueue; #[derive(Clone)] pub struct Piecewise< T, V > where T: IInterpolate< V >, V : Clone { pub _pieces: Vec< T >, _current_piece: u64, pub _total_steps: u64, pub _phantom: marker::Phantom...
use std::cmp; use std::marker; use interface::i_interpolate::*; use interface::i_load; use implement::util::loadqueue; #[derive(Clone)] pub struct
eturn Some(s), None => { self._current_piece = cmp::min( self._current_piece + 1, self._pieces.len() as _ ); if self._current_piece as usize >= self._pieces.len() { return None } else { match self...
Piecewise< T, V > where T: IInterpolate< V >, V : Clone { pub _pieces: Vec< T >, _current_piece: u64, pub _total_steps: u64, pub _phantom: marker::PhantomData< V >, pub _load: loadqueue::LoadQueue< V >, } impl < T, V > Piecewise< T, V > where T: IInterpolate< V >, V : Clone { pub fn init() -> ...
random
[]
Rust
picky/src/signature.rs
Devolutions/picky-rs
fc72d9c35db35cba01dcc9ed2d03384b9096dc7b
use crate::hash::HashAlgorithm; use crate::key::{KeyError, PrivateKey, PublicKey}; use core::convert::TryFrom; use picky_asn1_x509::{oids, AlgorithmIdentifier}; use rsa::{PublicKey as _, RsaPrivateKey, RsaPublicKey}; use serde::{Deserialize, Serialize}; use thiserror::Error; #[derive(Debug, Error)] #[non_exhaustive]...
use crate::hash::HashAlgorithm; use crate::key::{KeyError, PrivateKey, PublicKey}; use core::convert::TryFrom; use picky_asn1_x509::{oids, AlgorithmIdentifier}; use rsa::{PublicKey as _, RsaPrivateKey, RsaPublicKey}; use serde::{Deserialize, Serialize}; use thiserror::Error; #[derive(Debug, Error)] #[non_exhaustive]...
pub fn hash_algorithm(&self) -> HashAlgorithm { match &self { SignatureAlgorithm::RsaPkcs1v15(hash_algo) => *hash_algo, } } }
pub fn verify(self, public_key: &PublicKey, msg: &[u8], signature: &[u8]) -> Result<(), SignatureError> { match self { SignatureAlgorithm::RsaPkcs1v15(picky_hash_algo) => { let rsa_public_key = RsaPublicKey::try_from(public_key)?; let digest = picky_hash_algo.digest(m...
function_block-full_function
[ { "content": "fn is_algo_compatible_with_key(algo: SignatureAlgorithm, key: &PublicKey) -> bool {\n\n use picky_asn1_x509::oids::*;\n\n\n\n let key_algo = Into::<String>::into(key.as_inner().algorithm.oid());\n\n match algo {\n\n // Currently, SignatureHashType only contains RSA methods, so this...
Rust
src/windows/processor.rs
expenses/sysinfo
4970f57e22de632c812ee68291b41612f8800088
use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread::{self /*, sleep*/, JoinHandle}; use windows::tools::KeyHandler; use ProcessorExt; use winapi::shared::minwindef::{FALSE, ULONG}; use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::handleapi::CloseHandle; use winapi::um::pdh::{ ...
use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread::{self /*, sleep*/, JoinHandle}; use windows::tools::KeyHandler; use ProcessorExt; use winapi::shared::minwindef::{FALSE, ULONG}; use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::handleapi::CloseHandle; use winapi::um::pdh::{ ...
pub fn get_u64(&self, name: &String) -> Option<u64> { if let Ok(data) = self.internal.data.lock() { if let Some(ref counter) = data.get(name) { return Some(counter.value.get_u64()); } } None } pub fn add_counter(&mut self, name: &String, get...
pub fn get(&self, name: &String) -> Option<f32> { if let Ok(data) = self.internal.data.lock() { if let Some(ref counter) = data.get(name) { return Some(counter.value.get_f32()); } } None }
function_block-full_function
[ { "content": "pub fn compute_cpu_usage(p: &mut Process, nb_processors: u64, total_time: f32) {\n\n p.cpu_usage =\n\n ((p.utime - p.old_utime + p.stime - p.old_stime) * nb_processors * 100) as f32 / total_time;\n\n p.updated = false;\n\n}\n\n\n", "file_path": "src/linux/process.rs", "rank": ...
Rust
src/cli/config.rs
mariogmarq/syncro
33abe0a8bbc34e5614ef2fdc5e2b0cfc6d9dae23
use std::fs::OpenOptions; use std::io; use std::io::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{fs, io::BufRead}; const CONFIG_FILE_NAME: &str = ".syncro"; pub struct Config { files: Vec<String>, path: Option<std::path::PathBuf>, } impl Config { pub fn new() -> Config { ...
use std::fs::OpenOptions; use std::io; use std::io::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{fs, io::BufRead}; const CONFIG_FILE_NAME: &str = ".syncro"; pub struct Config { files: Vec<String>, path: Option<std::path::PathBuf>, } impl Config { pub fn new() -> Config { ...
} } } Ok(()) } pub fn create_in_path(path: &Path) -> std::result::Result<std::fs::File, std::io::Error> { let mut true_path; if !path.is_dir() { true_path = path.parent().unwrap().to_path_buf(); } e...
Err(io::Error::new( io::ErrorKind::Other, "Couldn't read from file", ))
call_expression
[ { "content": "pub fn add(files: &[PathBuf], cfg: &mut Config) {\n\n cfg.load();\n\n for file in files {\n\n cfg.add(file);\n\n }\n\n cfg.write(None);\n\n}\n", "file_path": "src/commands/add.rs", "rank": 0, "score": 107089.98689666277 }, { "content": "pub fn delete(files: &...
Rust
influxdb_iox/tests/end_to_end_cases/run_cli.rs
phial3/influxdb_iox
1b9212540b018ed7b41cd04c41660da91129ca7b
use std::{ io::Read, process::{Command, Stdio}, time::{Duration, Instant}, }; use assert_cmd::prelude::CommandCargoExt; use tempfile::NamedTempFile; use crate::common::server_fixture::BindAddresses; #[test] fn test_unreadable_store_early_exit() { let addrs = BindAddresses::default(); ...
use std::{ io::Read, process::{Command, Stdio}, time::{Duration, Instant}, }; use assert_cmd::prelude::CommandCargoExt; use tempfile::NamedTempFile; use crate::common::server_fixture::BindAddresses; #[test] fn test_unreadable_store_early_exit() { let addrs = BindAddresses::default(); ...
fn assert_early_exit_return_code(test_action: &str) { let addrs = BindAddresses::default(); let mut process = Command::cargo_bin("influxdb_iox") .unwrap() .arg("run") .arg("test") .arg("--test-action") .arg(test_action) .env("INFLUXDB_IOX_BIND_ADDR", addrs.http_bi...
function_block-full_function
[]
Rust
overkill_nvim/src/option/short_mess_item.rs
turboladen/overkill-nvim
836b229379c90be0602304f2c19d422a790b0b02
use super::{CharFlags, NvimOptionError}; use nvim_api::sys::api::nvim::{NvimString, Object}; use std::convert::TryFrom; #[derive(Debug, Clone, Copy, PartialEq)] pub enum ShortMessItem { AbbreviateFile, AbbreviateIncompleteLastLine, AbbreviateLinesAndChars, AbbreviateModified, ...
use super::{CharFlags, NvimOptionError}; use nvim_api::sys::api::nvim::{NvimString, Object}; use std::convert::TryFrom; #[derive(Debug, Clone, Copy, PartialEq)] pub enum ShortMessItem { AbbreviateFile, AbbreviateIncompleteLastLine, AbbreviateLinesAndChars, AbbreviateModified, ...
impl From<ShortMessItem> for char { fn from(item: ShortMessItem) -> Self { match item { ShortMessItem::AbbreviateFile => 'f', ShortMessItem::AbbreviateIncompleteLastLine => 'i', ShortMessItem::AbbreviateLinesAndChars => 'l', ShortMessItem::AbbreviateModified =...
r> for ShortMessItem { type Error = NvimOptionError; fn try_from(value: char) -> Result<Self, Self::Error> { let item = match value { 'f' => Self::AbbreviateFile, 'i' => Self::AbbreviateIncompleteLastLine, 'l' => Self::AbbreviateLinesAndChars, 'm' => Self...
random
[ { "content": "/// Simliar to `nvim_get_option` and `:set {option}?`.\n\n///\n\n/// # Errors\n\n///\n\n/// This errors if:\n\n///\n\n/// * If `name` contains a nul byte\n\n/// * If vim returns an error\n\n///\n\npub fn nvim_get_option(name: &str) -> Result<Object, Error> {\n\n let api_name = NvimString::new(n...
Rust
graph/src/components/ethereum/types.rs
tokenx-finance/graph-node
ac76222150c97b3b855e7bf4c9f321b36939d5b7
use serde::{Deserialize, Serialize}; use std::{convert::TryFrom, sync::Arc}; use web3::types::{ Action, Address, Block, Bytes, Log, Res, Trace, Transaction, TransactionReceipt, H256, U256, }; use crate::{ blockchain::BlockPtr, cheap_clone::CheapClone, prelude::{BlockNumber, DeploymentHash, EntityKey, T...
use serde::{Deserialize, Serialize}; use std::{convert::TryFrom, sync::Arc}; use web3::types::{ Action, Address, Block, Bytes, Log, Res, Trace, Transaction, TransactionReceipt, H256, U256, }; use crate::{ blockchain::BlockPtr, cheap_clone::CheapClone, prelude::{BlockNumber, DeploymentHash, EntityKey, T...
pub fn parent_ptr(&self) -> Option<BlockPtr> { match self { BlockFinality::Final(block) => block.parent_ptr(), BlockFinality::NonFinal(block) => block.ethereum_block.block.parent_ptr(), } } } #[derive(Clone, Debug)] pub struct EthereumBlockWithCalls { pub ethereum_...
r { match self { BlockFinality::Final(block) => block.block_ptr(), BlockFinality::NonFinal(block) => block.ethereum_block.block.block_ptr(), } }
function_block-function_prefixed
[ { "content": "pub fn as_hash(hash: String) -> Result<DeploymentHash, Error> {\n\n DeploymentHash::new(hash).map_err(|s| anyhow!(\"illegal deployment hash `{}`\", s))\n\n}\n", "file_path": "node/src/manager/deployment.rs", "rank": 0, "score": 343166.4630850067 }, { "content": "/// Returns ...
Rust
src/main.rs
rushmorem/git-author-rs
01db2e36057d271df4b719b938d0305cefb2c53e
use clap::{crate_description, crate_version, App, Arg, ArgMatches, SubCommand}; use git_author::{ error::*, git::{self, Author, ConfigFileLocation, ReplaceFilter, ReplaceTarget}, }; use std::error::Error as _; const NAME_KEY: &str = "name"; const EMAIL_KEY: &str = "email"; fn main() -> Result<(), Error> { ...
use clap::{crate_description, crate_version, App, Arg, ArgMatches, SubCommand}; use git_author::{ error::*, git::{self, Author, ConfigFileLocation, ReplaceFilter, ReplaceTarget}, }; use std::error::Error as _; const NAME_KEY: &str = "name"; const EMAIL_KEY: &str = "email"; fn main() -> Result<(), Error> { ...
dError::EmailIsNone.into()), (None, None) => Err(AuthorFieldError::NameAndEmailAreNone.into()), } } fn unset_author(matches: &ArgMatches) -> Result<(), Error> { let config_file_location = get_config_file_location(&matches); git::unset_author(config_file_location)?; Ok(()) } mod replace { p...
e) .help(&help) .required(false) .group("config") .long(&name) .display_order(0) }) .collect(); let get_subcommand = SubCommand::with_name("get") .about("get user.name and user.email") .usage("git author...
random
[ { "content": "/// Set git author\n\npub fn set_author(location: ConfigFileLocation, author: &Author) -> Result<(), SetError> {\n\n match (author.name(), author.email()) {\n\n (Some(name), Some(email)) => {\n\n set_git_user_param(location, UserParameter::Name, name)?;\n\n set_git_...
Rust
src/metadata/metadata.rs
whichxjy/bikeshed-rs-demo
7f3a4566732cb08facca0c3d7068bef8a983f62d
use regex::Regex; use titlecase::titlecase; use super::parse; use crate::config::SHORT_TO_LONG_STATUS; use crate::line::Line; use crate::spec::Spec; use crate::util::date::Date; #[derive(Debug, Clone, Default)] pub struct Metadata { pub has_keys: bool, pub abs: Vec<String>, pub canonical_url: Option<Strin...
use regex::Regex; use titlecase::titlecase; use super::parse; use crate::config::SHORT_TO_LONG_STATUS; use crate::line::Line; use crate::spec::Spec; use crate::util::date::Date; #[derive(Debug, Clone, Default)] pub struct Metadata { pub has_keys: bool, pub abs: Vec<String>, pub canonical_url: Option<Strin...
macros.insert("title", title.clone()); macros.insert("spectitle", title.clone()); } } pub fn compute_implicit_metadata(&mut self) { if self.canonical_url.as_ref().map_or(true, |url| url == "ED") { self.canonical_url = self.ed.clone(); } } pub ...
Y", self.date.day())) .to_string(), ); macros.insert("isodate", self.date.to_string()); if let Some(ref level) = self.level { macros.insert("level", level.clone()); } if let Some(ref shortname) = self.shortname { macros.insert("shortname",...
function_block-random_span
[ { "content": "pub fn add_canonical_url(doc: &mut Spec) {\n\n if let Some(canonical_url) = &doc.md.canonical_url {\n\n doc.head.as_ref().unwrap().append(html::node::new_element(\n\n \"link\",\n\n btreemap! {\n\n \"rel\" => \"canonical\".to_string(),\n\n ...
Rust
build.rs
alekitto/opencv-rust
0012bd7b30e67471331fa4439dbc86ca0bc6fad6
use std::{ collections::HashSet, env, ffi::OsStr, fs::File, io::{BufRead, BufReader}, path::{Path, PathBuf}, process::Command, }; use glob::glob; use once_cell::sync::{Lazy, OnceCell}; use semver::{Version, VersionReq}; use library::Library; #[path = "build/cmake_probe.rs"] mod cmake_probe; #[path = "build/ge...
use std::{ collections::HashSet, env, ffi::OsStr, fs::File, io::{BufRead, BufReader}, path::{Path, PathBuf}, process::Command, }; use glob::glob; use once_cell::sync::{Lazy, OnceCell}; use semver::{Version, VersionReq}; use library::Library; #[path = "build/cmake_probe.rs"] mod cmake_probe; #[path = "build/ge...
fn main() -> Result<()> { if cfg!(feature = "docs-only") { println!(r#"cargo:rustc-cfg=ocvrs_opencv_branch_4"#); for entry in SRC_DIR.join("opencv/hub").read_dir().expect("Can't read hub dir") { let entry = entry.expect("Can't read directory entry"); let path = entry.path(); if entry.file_type().map(|f...
fn build_wrapper(opencv: &Library) { let mut cc = build_compiler(opencv); let modules = MODULES.get().expect("MODULES not initialized"); for module in &["sys", "types"] { println!("cargo:rustc-cfg=ocvrs_has_module_{}", module); } for module in modules.iter() { println!("cargo:rustc-cfg=ocvrs_has_module_{}", m...
function_block-full_function
[ { "content": "pub fn read_str(node: &core::FileNode, value: &mut String, default_value: &str) -> Result<()> {\n\n\tstring_arg_output_send!(via value_via);\n\n\textern_container_arg!(default_value);\n\n\tlet out = unsafe { sys::cv_read_const_FileNodeR_stringR_const_stringR(node.as_raw_FileNode(), &mut value_via,...
Rust
src/main.rs
hockeybuggy/pivotal-tracker-epic-diagram
c4da6aa61d5818dece3651298ddf10c14c6d6758
mod epic_info { use serde::{Deserialize, Serialize}; const BASE_URL: &str = "https://www.pivotaltracker.com/services/v5"; #[derive(Serialize, Deserialize, Debug)] pub struct Epic { pub id: u64, pub project_id: u64, pub name: String, } #[derive(Serialize, Deserialize, D...
mod epic_info { use serde::{Deserialize, Serialize}; const BASE_URL: &str = "https://www.pivotaltracker.com/services/v5"; #[derive(Serialize, Deserialize, Debug)] pub struct Epic { pub id: u64, pub project_id: u64, pub name: String, } #[derive(Serialize, Deserialize, D...
} mod diagram_text_emitter { use lazy_static::lazy_static; use regex::Regex; use super::epic_info; const GREY: &str = "GREY"; const BLUE: &str = "BLUE"; const YELLOW: &str = "YELLOW"; const GREEN: &str = "GREEN"; const RED: &str = "RED"; fn prelude() -> String { ...
nse = request_project(format!("stories/{story_id}/blockers", story_id = story_id)).await?; let blockers: Vec<Blocker> = response.json().await?; return Ok(blockers); }
function_block-function_prefixed
[ { "content": "# Pivotal tracker epic diagrams\n\n\n\nThis repo creates a diagram of tickets and their blockers for a particular epic.\n\n\n\n\n\n## How does this work\n\n\n\nThis project makes calls to Pivotal tracker's API to fetch all the stories and\n\ntheir blockers. Once these have been retrieved we find t...
Rust
netlink-packet-sock-diag/src/unix/tests.rs
cathay4t/netlink
ee9bad4bfd4f63a69f433ecb1330c05f312c1282
use crate::{ constants::*, traits::{Emitable, Parseable}, unix::{ nlas::Nla, ShowFlags, StateFlags, UnixRequest, UnixResponse, UnixResponseBuffer, UnixResponseHeader, }, }; lazy_static! { static ref SOCKET_INFO: UnixRequest = UnixRequest { ...
use crate::{ constants::*, traits::{Emitable, Parseable}, unix::{ nlas::Nla, ShowFlags, StateFlags, UnixRequest, UnixResponse, UnixResponseBuffer, UnixResponseHeader, }, }; lazy_static! { static ref SOCKET_INFO: UnixRequest = UnixRequest { ...
assert_eq!(parsed, *LISTENING); } #[test] fn emit_listening() { assert_eq!(LISTENING.buffer_len(), 60); let mut buf = vec![0xff; LISTENING.buffer_len()]; LISTENING.emit(&mut buf); assert_eq!(&buf[..], &LISTENING_BUF[..]); } lazy_static! { static ref ESTABLISHED: UnixResponse = UnixR...
let parsed = UnixResponse::parse(&UnixResponseBuffer::new_checked(&&LISTENING_BUF[..]).unwrap()) .unwrap();
assignment_statement
[ { "content": "fn get_nlas() -> impl Iterator<Item = Result<NlaBuffer<&'static [u8]>, DecodeError>> {\n\n NlasIterator::new(&*BUFFER.value())\n\n}\n\n\n", "file_path": "netlink-packet-route/src/rtnl/link/nlas/tests.rs", "rank": 0, "score": 197579.3009426284 }, { "content": "fn get_byte_buf...
Rust
ncollide_utils/optimization.rs
johnpmayer/ncollide
e7f1ae4111c85aeef4b4383660bc4a24dfbda386
use std::ops::{Add, Sub, Mul}; use std::num::Float; use rand::{self, Rand}; use na::{Inv, POrd, SquareMat, Outer, Dot, RMul}; use na; use math::{Scalar, Vect}; pub fn maximize_with_newton<N, V, M, F: Fn(&V) -> N, D: Fn(&V) -> (V, M)>( niter: usize, num_gues...
use std::ops::{Add, Sub, Mul}; use std::num::Float; use rand::{self, Rand}; use na::{Inv, POrd, SquareMat, Outer, Dot, RMul}; use na; use math::{Scalar, Vect}; pub fn maximize_with_newton<N, V, M, F: Fn(&V) -> N, D: Fn(&V) -> (V, M)>( niter: usize, num_gues...
n(&V) -> N>(&self, f: &mut F, df: &V, x: &V, dir: &V) -> N { let t = -self.c * na::dot(df, dir); let fx = (*f)(x); let mut step = self.alpha.clone(); for _ in 0 .. self.niter { if fx - (*f)(&(*x + *dir * step)) >= step * t { break; } ...
num_guesses: usize, domain_min: &V, domain_max: &V, f: &mut F, df: &mut D) -> (V, N) where N: Scalar, V: Vect<N> + Outer<M>, M: SquareMat<N, V> + Add<M, Output = ...
random
[ { "content": "/// Centers and reduces a set of data.\n\n///\n\n/// Returns the covariance matrix, the center of the data, and a boolean that is `true` if the\n\n/// operation succeeded (otherwise, the returned value as valid, by the input points are left\n\n/// unchanged).\n\npub fn center_reduce<N, P, V, M>(pt...
Rust
sources/api/thar-be-updates/src/status.rs
spoonofpower/bottlerocket
c6a5a50bbc468b90d26b49a2c4c8172f0eee533b
use crate::error; use crate::error::Result; use bottlerocket_release::BottlerocketRelease; use chrono::{DateTime, Utc}; use model::modeled_types::FriendlyVersion; use serde::{Deserialize, Serialize}; use signpost::State; use snafu::{ensure, OptionExt, ResultExt}; use std::convert::TryInto; use std::fs::File; use std::o...
use crate::error; use crate::error::Result; use bottlerocket_release::BottlerocketRelease; use chrono::{DateTime, Utc}; use model::modeled_types::FriendlyVersion; use serde::{Deserialize, Serialize}; use signpost::State; use snafu::{ensure, OptionExt, ResultExt}; use std::convert::TryInto; use std::fs::File; use std::o...
es { if os_info.version_id < update.version || os_info.version_id > update.max_version { return Ok(Some(update)); } } Ok(None) } pub fn update_available_updates( &mut self, sock...
DATE_STATUS_FILE, })?; Ok( serde_json::from_reader(status_file).context(error::StatusParse { path: UPDATE_STATUS_FILE, })?, ) } impl UpdateStatus { pub fn new() -> Self { Self { update_state: UpdateState::Idle, available_updates: vec![], ...
random
[ { "content": "/// Spawns updog process to get list of updates and check if any of them can be updated to.\n\n/// Returns true if there is an available update, returns false otherwise.\n\nfn refresh(status: &mut UpdateStatus, socket_path: &str) -> Result<bool> {\n\n fork_and_return!({\n\n debug!(\"Spaw...
Rust
src/lib.rs
zesterer/lagoon
85e47af0f84addc50a23a86e20bc3bf46d42b92f
#![cfg_attr(docsrs, feature(doc_cfg))] #![deny(missing_docs)] #[cfg(feature = "scope")] mod scope; #[cfg(feature = "recv")] mod recv; #[cfg(feature = "scope")] #[cfg_attr(docsrs, doc(cfg(feature = "scope")))] pub use scope::Scope; #[cfg(feature = "recv")] #[cfg_attr(docsrs, doc(cfg(feature = "recv")))] pub use recv...
#![cfg_attr(docsrs, feature(doc_cfg))] #![deny(missing_docs)] #[cfg(feature = "scope")] mod scope; #[cfg(feature = "recv")] mod recv; #[cfg(feature = "scope")] #[cfg_attr(docsrs, doc(cfg(feature = "scope")))] pub use scope::Scope; #[cfg(feature = "recv")] #[cfg_attr(docsrs, doc(cfg(feature = "recv")))] pub use recv...
} impl error::Error for Error {} struct Job { f: Box<dyn FnOnce() + Send>, } static GLOBAL: spin::once::Once<ThreadPool, spin::Yield> = spin::once::Once::new(); pub struct ThreadPool { tx: Sender<Job>, handles: Vec<JoinHandle<()>>, } impl Default for ThreadPool { fn default() -> Self { Self::build...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Io(err) => write!(f, "{}", err), Self::NoThreads => write!(f, "thread pool has no threads"), Self::Timeout => write!(f, "a timeout occurred"), } }
function_block-full_function
[ { "content": "#[cfg(not(feature = \"recv\"))]\n\nfn main() { panic!(\"This example requires the `recv` feature\") }\n\n\n", "file_path": "examples/basic.rs", "rank": 1, "score": 37371.15469081495 }, { "content": "#[cfg(not(feature = \"scope\"))]\n\nfn main() { panic!(\"This example requires ...
Rust
conch-runtime/src/env/func.rs
PatrickShaw/conch-runtime
5deb6af53b1e08e07345946a177311b64c475c22
use crate::env::SubEnvironment; use std::collections::HashMap; use std::fmt; use std::hash::Hash; use std::sync::Arc; pub trait FunctionEnvironment { type FnName; type Fn; fn function(&self, name: &Self::FnName) -> Option<&Self::Fn>; fn set_function(&mut self, name: Self::FnName, f...
use crate::env::SubEnvironment; use std::collections::HashMap; use std::fmt; use std::hash::Hash; use std::sync::Arc; pub trait FunctionEnvironment { type FnName; type Fn; fn function(&self, name: &Self::FnName) -> Option<&Self::Fn>; fn set_function(&mut self, name: Self::FnName, f...
nc)); } } #[test] fn test_set_and_unset_function_in_child_should_not_affect_parent() { let fn_name_parent = "parent fn"; let fn_name_child = "child fn"; let fn_parent = 42; let fn_child = 5; let mut parent = FnEnv::new(); parent.set_function(fn_name...
derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct FnFrameEnv { num_frames: usize, } impl FnFrameEnv { pub fn new() -> Self { Self { num_frames: 0 } } } impl FunctionFrameEnvironment for FnFrameEnv { fn push_fn_frame(&mut self) { self.num_frame...
random
[]
Rust
mbus-api/src/mbus_nats.rs
tiagolobocastro/Mayastor
c9cf777e7776f529a2433d29b8513d1c601684a6
use super::*; use nats::asynk::Connection; use once_cell::sync::OnceCell; use tracing::{info, warn}; static NATS_MSG_BUS: OnceCell<NatsMessageBus> = OnceCell::new(); pub fn message_bus_init_tokio(server: String) { NATS_MSG_BUS.get_or_init(|| { tokio::runtime::Handle::current().block_on(async { ...
use super::*; use nats::asynk::Connection; use once_cell::sync::OnceCell; use tracing::{info, warn}; static NATS_MSG_BUS: OnceCell<NatsMessageBus> = OnceCell::new(); pub fn message_bus_init_tokio(server: String) { NATS_MSG_BUS.get_or_init(|| { tokio::runtime::Handle::current().block_on(async { ...
pub fn bus() -> DynBus { Box::new( NATS_MSG_BUS .get() .expect("Shared message bus should be initialised before use.") .clone(), ) } #[derive(Clone)] struct NatsMessageBus { timeout_options: TimeoutOptions, connection: Connection, } impl NatsMessageBus { ...
s_init_options( server: String, timeouts: TimeoutOptions, ) { let nc = NatsMessageBus::new(&server, BusOptions::new(), timeouts).await; NATS_MSG_BUS .set(nc) .ok() .expect("Expect to be initialised only once"); }
function_block-function_prefixed
[ { "content": "pub fn device_path_from_uri(device_uri: String) -> String {\n\n assert_ne!(\n\n Url::parse(device_uri.as_str()),\n\n Err(ParseError::RelativeUrlWithoutBase)\n\n );\n\n let url = Url::parse(device_uri.as_str()).unwrap();\n\n String::from(url.path())\n\n}\n\n\n", "file_...
Rust
src/core/resources/sound.rs
Antonio-Bennett/scion
aeb6c6a70cb257bf8462e299af3bf9bf381c8888
use std::{collections::HashMap, path::Path}; use crate::{ sound::{context::AudioContext, parse_ogg}, utils::file::read_file, }; #[derive(Debug)] pub enum Error { SoundNotRegistered, SoundAlreadyExists, ImpossibleToLoadSound, } #[derive(Clone, Debug)] pub enum SoundLoadingType { AlwaysInM...
use std::{collections::HashMap, path::Path}; use crate::{ sound::{context::AudioContext, parse_ogg}, utils::file::read_file, }; #[derive(Debug)] pub enum Error { SoundNotRegistered, SoundAlreadyExists, ImpossibleToLoadSound, } #[derive(Clone, Debug)] pub enum SoundLoadingType { AlwaysInM...
fn load_sound_in_memory(&mut self, name: &str) -> Result<usize, Error> { let sound = self .sounds_data .get(name) .expect("Sound loading failed, load_sound_in_memory tried to get unknown sound data"); match read_file(Path::new(sound.file_path.as_str())) { ...
pub(crate) fn system_ready(&mut self) { if !self.system_ready { self.context.system_ready(); self.system_ready = true; } }
function_block-full_function
[ { "content": "pub fn read_level(name: &str) -> Level {\n\n if let Ok(res) = scion::utils::file::read_file(Path::new(name)) {\n\n return serde_json::from_slice(res.as_slice()).expect(\"level error\");\n\n }\n\n panic!(\"level error\");\n\n}\n", "file_path": "examples/bomberman/level_reader.rs...
Rust
crates/wasi-crypto/src/wiggle_interfaces/common.rs
dheaton-arm/wasmtime
86611d3bbc92b781ed136dcda7cdba9ec2c1cbee
use super::{guest_types, WasiCryptoCtx}; use std::convert::TryInto; use wasi_crypto::{AlgorithmType, Version}; impl super::wasi_ephemeral_crypto_common::WasiEphemeralCryptoCommon for WasiCryptoCtx { fn options_open( &mut self, options_type: guest_types::AlgorithmType, ) -> Result<guest_t...
use super::{guest_types, WasiCryptoCtx}; use std::convert::TryInto; use wasi_crypto::{AlgorithmType, Version}; impl super::wasi_ephemeral_crypto_common::WasiEphemeralCryptoCommon for WasiCryptoCtx { fn options_open( &mut self, options_type: guest_types::AlgorithmType, ) -> Result<guest_t...
} }
match options_type { guest_types::AlgorithmType::Signatures => AlgorithmType::Signatures, guest_types::AlgorithmType::Symmetric => AlgorithmType::Symmetric, guest_types::AlgorithmType::KeyExchange => AlgorithmType::KeyExchange, }
if_condition
[ { "content": "/// Parse a float using the same format as `format_float` above.\n\n///\n\n/// The encoding parameters are:\n\n///\n\n/// w - exponent field width in bits\n\n/// t - trailing significand field width in bits\n\n///\n\nfn parse_float(s: &str, w: u8, t: u8) -> Result<u64, &'static str> {\n\n debug...
Rust
src/commands/yubihsm/keys/import.rs
rfunduk/kms
9d4d2824ced4b87360150862e01c9ccae4e2714b
use super::*; use abscissa::Callable; use signatory::ed25519; use std::{fs, path::PathBuf, process}; use subtle_encoding::base64; use tendermint::public_keys::ConsensusKey; use yubihsm::object; #[derive(Debug, Default, Options)] pub struct ImportCommand { #[options(short = "c", long = "config")] pub confi...
use super::*; use abscissa::Callable; use signatory::ed25519; use std::{fs, path::PathBuf, process}; use subtle_encoding::base64; use tendermint::public_keys::ConsensusKey; use yubihsm::object; #[derive(Debug, Default, Options)] pub struct ImportCommand { #[options(short = "c", long = "config")] pub confi...
} impl_command!(ImportCommand);
fn import_priv_validator_json(&self, json_data: &str) { if let Some(id) = self.wrap_key_id { status_warn!( "ignoring wrapkey ID: {} (not applicable to priv_validator.json files)", id ); } let key_id = self.key_id.unwrap_or_else(|| { ...
function_block-full_function
[ { "content": "/// Derive a wrap key from the given BIP39 `Mnemonic`\n\nfn derive_wrap_key_from_mnemonic(mnemonic: &Mnemonic, key_id: object::Id) -> wrap::Key {\n\n // Capabilities given to the initial wrap key:\n\n // wrap/unwrap both data and objects\n\n let wrap_key_capabilities = Capability::EXPORT_...
Rust
check-broken-packages/src/main.rs
bugabinga/pacman-hooks
d99221cb36b87840b4549d04ed4a40030373311d
use std::cmp; use std::collections::VecDeque; use std::fs; use std::io::BufRead; use std::iter::FromIterator; use std::os::unix::fs::PermissionsExt; use std::process::Command; use std::sync::Arc; use crossbeam::thread; use log::debug; type CrossbeamChannel<T> = ( crossbeam::channel::Sender<T>, crossbeam::chan...
use std::cmp; use std::collections::VecDeque; use std::fs; use std::io::BufRead; use std::iter::FromIterator; use std::os::unix::fs::PermissionsExt; use std::process::Command; use std::sync::Arc; use crossbeam::thread; use log::debug; type CrossbeamChannel<T> = ( crossbeam::channel::Sender<T>, crossbeam::chan...
ssing_dependencies("dummy"), [ "libavdevice.so.57", "libavfilter.so.6", "libavformat.so.57", "libavcodec.so.57", "libavresample.so.3", "libpostproc.so.54", "libswresample.so.2", "l...
if missing_deps_tx.send(to_send).is_err() { break; } } } }); } drop(missing_deps_tx); thread::scope(|scope| { let aur_packages = get_aur_packages(); ...
random
[ { "content": "# Pacman Hooks\n\n\n\nSet of hooks into pacman for my Arch Linux machines.\n\n\n\n## check-broken-packages\n\n\n\nCheck that existing packages still have needed dynamic libraries after an\n\nupgrade. Packages tend to break when installing/uninstalling packages from AUR a\n\nlot.\n\n\n\nThis hook i...
Rust
algorithms/linfa-elasticnet/src/hyperparams.rs
Christoff-Zulzi/linfa
47aae58d32f0ac68c2c157a5c4c52d8b749bfdc0
#[cfg(feature = "serde")] use serde_crate::{Deserialize, Serialize}; use linfa::{Float, ParamGuard}; use crate::error::ElasticNetError; use super::Result; #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] pub struct ElasticNetValidParams<F> { penalty: F,...
#[cfg(feature = "serde")] use serde_crate::{Deserialize, Serialize}; use linfa::{Float, ParamGuard}; use crate::error::ElasticNetError; use super::Result; #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] pub struct ElasticNetValidParams<F> { penalty: F,...
) -> Self { self.0.tolerance = tolerance; self } pub fn max_iterations(mut self, max_iterations: u32) -> Self { self.0.max_iterations = max_iterations; self } } impl<F: Float> ParamGuard for ElasticNetParams<F> { type Checked = ElasticNetValidParams<F>; ...
ms { penalty: F::one(), l1_ratio: F::cast(0.5), with_intercept: true, max_iterations: 1000, tolerance: F::cast(1e-4), }) } pub fn penalty(mut self, penalty: F) -> Self { self.0.penalty = penalty; self } ...
random
[ { "content": "pub fn outer<F: Float>(\n\n a: &ArrayBase<impl Data<Elem = F>, Ix1>,\n\n b: &ArrayBase<impl Data<Elem = F>, Ix1>,\n\n) -> Array2<F> {\n\n let mut outer = Array2::zeros((a.len(), b.len()));\n\n Zip::from(outer.rows_mut()).and(a).for_each(|mut out, ai| {\n\n out.assign(&b.mapv(|v|...
Rust
src/saf.rs
malthesr/angsd-io
62a4695bb0114e58ac299a20d972d2cdc7aa3389
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/saf_read.rs"))] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/saf_write.rs"))] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/saf_intersect.rs"))] use std::io; pub mod index; pub use index::Index; pu...
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/saf_read.rs"))] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/saf_write.rs"))] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/saf_intersect.rs"))] use std::io; pub mod index; pub use index::Index; pu...
#[test] fn test_seek() -> io::Result<()> { let records = records!["chr1":1, "chr1":2, "chr2":1, "chr2":2, "chr2":3, "chr3":1]; let mut reader = reader!(records); let mut record = reader.create_record_buf(); for name in vec!["chr2", "chr1", "chr3"] { reader.seek_by...
fn test_write_read_records() -> io::Result<()> { let records = records![ "chr1":1 => [0., -1., -2., -3., -4.], "chr1":2 => [1., -2., -3., -4., -5.], "chr2":1 => [2., -3., -4., -5., -6.], "chr2":2 => [3., -4., -5., -6., -7.], "chr2":3 => [4., -5., -6., ...
function_block-full_function
[ { "content": "fn read_record_unchecked<R>(reader: &mut R, record: &mut Record) -> io::Result<()>\n\nwhere\n\n R: io::BufRead,\n\n{\n\n reader.read_f64_into::<Endian>(record.as_mut_slice())\n\n}\n\n\n", "file_path": "src/glf/reader.rs", "rank": 0, "score": 179059.32897684962 }, { "conte...
Rust
gio/src/auto/subprocess_launcher.rs
elmarco/gtk-rs-core
89eaa1586abe6cf22284464dcae01b860e8398f6
use crate::Subprocess; use crate::SubprocessFlags; use glib::translate::*; #[cfg(any(unix, feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(unix)))] use std::boxed::Box as Box_; use std::fmt; use std::ptr; glib::wrapper! { pub struct SubprocessLauncher(Object<ffi::GSubprocessLauncher>); match fn { ...
use crate::Subprocess; use crate::SubprocessFlags; use glib::translate::*; #[cfg(any(unix, feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(unix)))] use std::boxed::Box as Box_; use std::fmt; use std::ptr; glib::wrapper! { pub struct SubprocessLauncher(Object<ffi::GSubprocessLauncher>); match fn { ...
} } #[cfg(any(unix, feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(unix)))] #[doc(alias = "g_subprocess_launcher_set_child_setup")] pub fn set_child_setup<P: Fn() + 'static>(&self, child_setup: P) { let child_setup_data: Box_<P> = Box_::new(child_setup); unsafe exte...
from_glib_none(ffi::g_subprocess_launcher_getenv( self.to_glib_none().0, variable.as_ref().to_glib_none().0, ))
call_expression
[ { "content": "#[doc(alias = \"g_set_printerr_handler\")]\n\npub fn set_printerr_handler<P: Fn(&str) + Send + Sync + 'static>(func: P) {\n\n unsafe extern \"C\" fn func_func(string: *const libc::c_char) {\n\n if let Some(callback) = PRINTERR_HANDLER\n\n .lock()\n\n .expect(\"Faile...
Rust
baokeshed_bin/src/main.rs
oconnor663/baokeshed
aadfee0a5cf11ec6d0ee61037aaa873854cbf2a6
use anyhow::{bail, Result}; use serde::Deserialize; use std::cmp; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; const VERSION: &str = env!("CARGO_PKG_VERSION"); const USAGE: &str = " Usage: baokeshed [<inputs>...] [--length=<bytes>] [--key=<hex> | --derive-key=<hex>] ...
use anyhow::{bail, Result}; use serde::Deserialize; use std::cmp; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; const VERSION: &str = env!("CARGO_PKG_VERSION"); const USAGE: &str = " Usage: baokeshed [<inputs>...] [--length=<bytes>] [--key=<hex> | --derive-key=<hex>] ...
fn hash(args: &Args) -> Result<()> { let byte_length = args.flag_length.unwrap_or(baokeshed::OUT_LEN as u64); let derive_key = args.flag_derive_key.is_some(); let key = if let Some(key_str) = args.flag_key.as_ref().or(args.flag_derive_key.as_ref()) { let key_bytes = hex::decode(key_str)?; ...
hex1.len() as u64); print!("{}", &hex1[..take as usize]); hex_bytes_remaining -= take; let hex2 = baokeshed::Hash::from(*hash2).to_hex(); let take = cmp::min(hex_bytes_remaining, hex2.len() as u64); print!("{}", &hex2[..take as usize]); hex_bytes_remaining -= take; } ...
function_block-function_prefixed
[ { "content": "/// The hash function with a key, returning an extensible output.\n\n///\n\n/// This is domain separated from `hash`.\n\npub fn keyed_hash_xof(key: &[u8; KEY_LEN], input: &[u8]) -> Output {\n\n let key_words = words_from_key_bytes(key);\n\n hash_internal(input, &key_words, Flags::KEYED_HASH)...
Rust
sdk/src/purchase_order/store/diesel/mod.rs
ardeshir/grid
9d87c9c6c3946540f4b7c7866a669a6b17ed20dc
pub mod models; mod operations; pub(in crate) mod schema; use diesel::connection::AnsiTransactionManager; use diesel::r2d2::{ConnectionManager, Pool}; use super::{ PurchaseOrder, PurchaseOrderAlternateId, PurchaseOrderAlternateIdList, PurchaseOrderList, PurchaseOrderStore, PurchaseOrderStoreError, PurchaseO...
pub mod models; mod operations; pub(in crate) mod schema; use diesel::connection::AnsiTransactionManager; use diesel::r2d2::{ConnectionManager, Pool}; use super::{ PurchaseOrder, PurchaseOrderAlternateId, PurchaseOrderAlternateIdList, PurchaseOrderList, PurchaseOrderStore, PurchaseOrderStoreError, PurchaseO...
ase_order(&self, order: PurchaseOrder) -> Result<(), PurchaseOrderStoreError> { PurchaseOrderStoreOperations::new(self.connection).add_purchase_order( order.clone().into(), make_purchase_order_versions(&order), make_purchase_order_version_revisions(&order), ) } ...
s_for_purchase_order( &self, purchase_order_uid: &str, org_id: &str, service_id: Option<&str>, offset: i64, limit: i64, ) -> Result<PurchaseOrderAlternateIdList, PurchaseOrderStoreError> { PurchaseOrderStoreOperations::new(self.connection).list_alternate_ids_f...
random
[ { "content": "#[cfg(all(feature = \"sqlite\", feature = \"diesel\"))]\n\npub fn run_migrations(conn: &SqliteConnection) -> Result<(), MigrationsError> {\n\n embedded_migrations::run(conn).map_err(|err| {\n\n MigrationsError::ResourceTemporarilyUnavailableError(\n\n ResourceTemporarilyUnavai...
Rust
t-rex-service/src/datasources.rs
arbakker/t-rex
be16422eb9fb73eb755f236d463672442c6d3dd6
use clap::ArgMatches; use std::collections::HashMap; use t_rex_core::core::config::{ApplicationCfg, DatasourceCfg}; use t_rex_core::core::feature::Feature; use t_rex_core::core::layer::Layer; use t_rex_core::core::Config; #[cfg(not(feature = "with-gdal"))] use t_rex_core::datasource::DummyDatasource as GdalDatasource...
use clap::ArgMatches; use std::collections::HashMap; use t_rex_core::core::config::{ApplicationCfg, DatasourceCfg}; use t_rex_core::core::feature::Feature; use t_rex_core::core::layer::Layer; use t_rex_core::core::Config; #[cfg(not(feature = "with-gdal"))] use t_rex_core::datasource::DummyDatasource as GdalDatasource...
fn detect_data_columns(&self, layer: &Layer, sql: Option<&String>) -> Vec<(String, String)> { match self { &Datasource::Postgis(ref ds) => ds.detect_data_columns(layer, sql), &Datasource::Gdal(ref ds) => ds.detect_data_columns(layer, sql), } } fn extent_from_wgs84(&s...
Datasource::Postgis(ref ds) => ds.detect_layers(detect_geometry_types), &Datasource::Gdal(ref ds) => ds.detect_layers(detect_geometry_types), } }
function_block-function_prefix_line
[ { "content": "/// Projected extent\n\npub fn extent_to_merc(extent: &Extent) -> Extent {\n\n let (minx, miny) = lonlat_to_merc(extent.minx, extent.miny);\n\n let (maxx, maxy) = lonlat_to_merc(extent.maxx, extent.maxy);\n\n Extent {\n\n minx,\n\n miny,\n\n maxx,\n\n maxy,\n\n...
Rust
roa/src/forward.rs
Hexilee/roa
aef916885a6076b28f9412d939cb356ac030f5df
use std::net::IpAddr; use crate::http::header::HOST; use crate::{Context, State}; pub trait Forward { fn host(&self) -> Option<&str>; fn client_ip(&self...
use std::net::IpAddr; use crate::http::header::HOST; use crate::{Context, State}; pub trait Forward { fn host(&self) -> Option<&str>; fn client_ip(&self...
#[inline] fn forwarded_ips(&self) -> Vec<IpAddr> { let mut addrs = Vec::new(); if let Some(value) = self.get("x-forwarded-for") { for addr_str in value.split(',') { if let Ok(addr) = addr_str.trim().parse() { addrs.push(addr) } ...
fn client_ip(&self) -> IpAddr { let addrs = self.forwarded_ips(); if addrs.is_empty() { self.remote_addr.ip() } else { addrs[0] } }
function_block-function_prefix_line
[ { "content": "pub fn post_router() -> Router<State> {\n\n Router::new()\n\n .on(\"/\", post(create_post))\n\n .on(\"/:id\", get(get_post).put(update_post).delete(delete_post))\n\n}\n\n\n\nasync fn create_post(ctx: &mut Context<State>) -> Result {\n\n let data: NewPost = ctx.read_json().await...
Rust
contracts/mirror_mint/src/testing/mock_querier.rs
stader-labs/mirror-contracts
d2bffaf0c62ce119375311ed659aa5a0d27cc350
use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_binary, from_slice, to_binary, Coin, ContractResult, Decimal, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, WasmQuery, }; use schemars::JsonSchema; use serde::{Dese...
use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_binary, from_slice, to_binary, Coin, ContractResult, Decimal, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, WasmQuery, }; use schemars::JsonSchema; use serde::{Dese...
)), None => SystemResult::Err(SystemError::InvalidRequest { error: "Collateral info does not exist".to_string(), request: msg.as_slice().into(), }), } } MockQueryMs...
to_binary( &CollateralPriceResponse { asset, rate: collateral_info.0, last_updated: 1000u64, multiplier: collateral_info.1, is_revok...
call_expression
[ { "content": "/// @dev Queries an asstet token price from hub. Hub contract will redirect the query to the corresponding price source.\n\n/// @param oracle_hub_addr : Oracle hub contract address\n\n/// @param asset_token : Asset token address. Native assets are not supported\n\n/// @param timeframe : (optional)...
Rust
src/disasm.rs
CoderPuppy/hp-prime-emu
7085165001ed398256e7a4035e981eb11c0f976c
use instr::*; use binutil::mask32; pub fn disasm_cond(asm: u32) -> Condition { match asm { 0b0000 => Condition::Equal, 0b0001 => Condition::NotEqual, 0b0010 => Condition::UnsignedGTE, 0b0011 => Condition::UnsignedLT, 0b0100 => Condition::Negative, 0b0101 => Condition::NonNegative, 0b0110 => Condition::O...
use instr::*; use binutil::mask32; pub fn disasm_cond(asm: u32) -> Condition { match asm { 0b0000 => Condition::Equal, 0b0001 => Condition::NotEqual, 0b0010 => Condition::UnsignedGTE, 0b0011 => Condition::UnsignedLT, 0b0100 => Condition::Negative, 0b0101 => Condition::NonNegative, 0b0110 => Condition::O...
1111), creg2: disasm_reg(asm >> 0 & 0b1111), } } else if asm & 0b0000_111_0000_0_0000_0000_0000_0000_0000 == 0b0000_110_0000_0_0000_0000_0000_0000_0000 { let data = (asm >> 0 & mask32(8)) as u8; let walk = asm >> 21 & 0b1 == 0b1; Instr::CoprocessorMem { cond: cond, op: match asm >> 20 & 0b1 { 0b0...
rTransfer::From, _ => unreachable!(), }), _ => unreachable!(), }, coproc: (asm >> 8 & 0b1111) as u8, opcode1: match asm >> 4 & 0b1 { 0b0 => asm >> 20 & 0b1111, 0b1 => asm >> 21 & 0b111, _ => unreachable!(), } as u8, opcode2: (asm >> 5 & 0b111) as u8, reg: disasm_reg(asm >> 12 ...
random
[ { "content": "pub fn disasm_cond(asm: u16) -> Condition {\n\n\tmatch asm {\n\n\t\t0b0000 => Condition::Equal,\n\n\t\t0b0001 => Condition::NotEqual,\n\n\t\t0b0010 => Condition::UnsignedGTE,\n\n\t\t0b0011 => Condition::UnsignedLT,\n\n\t\t0b0100 => Condition::Negative,\n\n\t\t0b0101 => Condition::NonNegative,\n\n\...
Rust
client-core/src/wallet/syncer_logic.rs
SchoolOfFreelancing/chain
c5f806393fbcffbdaa27d9f4843b6933ebac56b1
use non_empty_vec::NonEmpty; use std::collections::HashMap; use thiserror::Error; use chain_core::init::coin::{sum_coins, Coin, CoinError}; use chain_core::tx::{ data::{ input::{TxoPointer, TxoSize}, output::TxOut, TxId, }, fee::Fee, TransactionId, }; use client_common::tendermi...
use non_empty_vec::NonEmpty; use std::collections::HashMap; use thiserror::Error; use chain_core::init::coin::{sum_coins, Coin, CoinError}; use chain_core::tx::{ data::{ input::{TxoPointer, TxoSize}, output::TxOut, TxId, }, fee::Fee, TransactionId, }; use client_common::tendermi...
pub fn create_transaction_change( wallet: &Wallet, wallet_state: &WalletState, transaction: &Transaction, fee_paid: Fee, block_height: u64, block_time: Time, ) -> Result<TransactionChange, SyncerLogicError> { let transaction_id = transaction.id(); let outputs = transaction.outputs().to...
pub(crate) fn handle_blocks( wallet: &Wallet, wallet_state: &mut WalletState, blocks: &[FilteredBlock], enclave_transactions: &[Transaction], ) -> Result<WalletStateMemento, SyncerLogicError> { let enclave_transactions = enclave_transactions .iter() .map(|tx| (tx.id(), tx)) ....
function_block-full_function
[ { "content": "/// helper for summing coins in some iterable structure\n\npub fn sum_coins(mut coins: impl Iterator<Item = Coin>) -> Result<Coin, CoinError> {\n\n coins.try_fold(Coin::zero(), |acc, coin| acc + coin)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use quickcheck::quickcheck;...
Rust
src/node.rs
rust-playground/lars
5e7bb280fbd8197eda39a9ee473e5a77fbdb9ee7
extern crate hyper; use futures::Future; use hyper::Error; use hyper::{Request, Response}; use std::collections::HashMap; use std::fmt; pub trait Handler: 'static + Send + Sync { fn handle( &self, req: Request, params: RequestData, ) -> Box<Future<Item = Response, Error = Error>>; } ...
extern crate hyper; use futures::Future; use hyper::Error; use hyper::{Request, Response}; use std::collections::HashMap; use std::fmt; pub trait Handler: 'static + Send + Sync { fn handle( &self, req: Request, params: RequestData, ) -> Box<Future<Item = Response, Error = Error>>; } ...
Map::new()); } let p = results.params.params.as_mut().unwrap(); p.insert(enode.id.as_ref(), parts[0].to_owned()); } return results; } if self.wild.is_some() && path.len() > 0 { let enode = self.wild.as_ref().unwrap(); ...
("*") || parts[1].contains(":")) { panic!("no wildcard '*' nor param ':' is permitted after the first wildcard param, remaining path '{}'", path); } if self.wild.is_none() { self.wild = Some(NodeExtra { node: Box::new(Node::new()), ...
random
[ { "content": "fn test(req: Request, _params: RequestData) -> Box<Future<Item = Response, Error = Error>> {\n\n let body = format!(\"{}\", req.uri());\n\n Box::new(futures::future::ok(\n\n Response::new()\n\n .with_status(StatusCode::Ok)\n\n .with_header(ContentLength(body.len(...
Rust
src/registers/runtime.rs
noi/xhci
6cde670165daf830bf808de0dd99380bfc20a7a8
use super::capability::RuntimeRegisterSpaceOffset; use accessor::Mapper; use core::convert::TryFrom; use core::convert::TryInto; #[derive(Debug)] pub struct Runtime<M> where M: Mapper, { pub mfindex: accessor::Single<MicroframeIndexRegister, M>, } impl<M> Runtime<M> where M: Mapper, { ...
use super::capability::RuntimeRegisterSpaceOffset; use accessor::Mapper; use core::convert::TryFrom; use core::convert::TryInto; #[derive(Debug)] pub struct Runtime<M> where M: Mapper, { pub mfindex: accessor::Single<MicroframeIndexRegister, M>, } impl<M> Runtime<M> where M: Mapper, { ...
} #[repr(transparent)] #[derive(Copy, Clone)] pub struct InterrupterManagementRegister(u32); impl InterrupterManagementRegister { rw1c_bit!(0, interrupt_pending, "Interrupt Pending"); rw_bit!(1, interrupt_enable, "Interrupt Enable"); } impl_debug_from_methods! { InterrupterManagementRegister { int...
pub unsafe fn new<M>( mmio_base: usize, rtoff: RuntimeRegisterSpaceOffset, mapper: M, ) -> accessor::Array<Self, M> where M: Mapper, { const NUM_INTERRUPT_REGISTER_SET: usize = 1024; let base = mmio_base + usize::try_from(rtoff.get()).unwrap() + 0x20; ...
function_block-full_function
[]
Rust
src/radv/config.rs
isomer/erbium
7634509d2b69e217cc3bb94eda205f17ed8445a5
/* Copyright 2021 Perry Lorier * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
/* Copyright 2021 Perry Lorier * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
) } else { Ok(None) } } else { Err(Error::InvalidConfig(format!( "{} should be a hash, not {}", name, type_to_name(fragment) ))) } } fn parse_interface(name: &str, fragment: &yaml::Yaml) -> Result<Option<Interface>, Error> { if...
Some(Pref64 { prefix: prefix.addr, lifetime: lifetime.unwrap_or_else(|| std::time::Duration::from_secs(600)), prefixlen: prefix.prefixlen, })
call_expression
[ { "content": "pub fn parse_string_hwaddr(name: &str, fragment: &yaml::Yaml) -> Result<Option<Vec<u8>>, Error> {\n\n parse_string(name, fragment).and_then(str_hwaddr)\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 0, "score": 404148.5526436821 }, { "content": "pub fn parse_string_prefi...
Rust
piet-common/src/web_back.rs
siebelmann/piet
d05ec5f990a8edc9d5bf14e1c7cee36e6eeae8e1
use std::fmt; use std::marker::PhantomData; use std::path::Path; #[cfg(feature = "png")] use std::fs::File; #[cfg(feature = "png")] use std::io::BufWriter; #[cfg(feature = "png")] use png::{ColorType, Encoder}; use wasm_bindgen::JsCast; use piet::ImageFormat; #[doc(hidden)] pub use piet_web::*; pub type Piet<'a> ...
use std::fmt; use std::marker::PhantomData; use std::path::Path; #[cfg(feature = "png")] use std::fs::File; #[cfg(feature = "png")] use std::io::BufWriter; #[cfg(feature = "png")] use png::{ColorType, Encoder}; use wasm_bindgen::JsCast; use piet::ImageFormat; #[doc(hidden)] pub use piet_web::*; pub type Piet<'a> ...
} impl<'a> BitmapTarget<'a> { pub fn render_context(&mut self) -> WebRenderContext { WebRenderContext::new(self.context.clone(), web_sys::window().unwrap()) } fn raw_pixels(&mut self, fmt: ImageFormat) -> Result<Vec<u8>, piet::Error> { if fmt != ImageFormat::R...
pub fn bitmap_target( &mut self, width: usize, height: usize, pix_scale: f64, ) -> Result<BitmapTarget, piet::Error> { let document = web_sys::window().unwrap().document().unwrap(); let canvas = document .create_element("canvas") .unwrap() ...
function_block-full_function
[ { "content": "pub fn draw(rc: &mut impl RenderContext) -> Result<(), Error> {\n\n // Black background\n\n rc.clear(Color::BLACK);\n\n\n\n // do something texty\n\n let font = rc.text().new_font_by_name(\"Segoe UI\", 12.0).build()?;\n\n\n\n let layout = rc\n\n .text()\n\n .new_text_l...
Rust
src/parser.rs
getsentry/apple-crash-report-parser
e89269f20667bc0f8e5838890c17685727a870a1
use std::borrow::Cow; use std::collections::BTreeMap; use std::fmt; use std::io::{self, BufRead, BufReader, Read}; use chrono::{DateTime, FixedOffset, Utc}; use lazy_static::lazy_static; use regex::Regex; #[cfg(feature = "with_serde")] use serde::{Serialize, Serializer}; use uuid::Uuid; lazy_static! { static ref ...
use std::borrow::Cow; use std::collections::BTreeMap; use std::fmt; use std::io::{self, BufRead, BufReader, Read}; use chrono::{DateTime, FixedOffset, Utc}; use lazy_static::lazy_static; use regex::Regex; #[cfg(feature = "with_serde")] use serde::{Serialize, Serializer}; use uuid::Uuid; lazy_static! { static ref ...
} impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ParseError::Io(..) => write!(f, "io error during parsing"), ParseError::InvalidIncidentIdentifier(..) => write!(f, "invalid incident identifier"), ParseError::Inval...
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match *self { ParseError::Io(ref err) => Some(err), ParseError::InvalidIncidentIdentifier(ref err) => Some(err), ParseError::InvalidImageIdentifier(ref err) => Some(err), ParseError::InvalidReportVer...
function_block-full_function
[ { "content": "fn load_fixture(name: &str) -> String {\n\n fs::read_to_string(format!(\"tests/fixtures/{}.txt\", name)).unwrap()\n\n}\n\n\n\nmacro_rules! test_snapshots {\n\n ( $( $test:ident => $fixture:literal ),+ $(,)? ) => {\n\n $(\n\n #[test]\n\n fn $test() {\n\n ...
Rust
dust-lpc8xx/src/syscon/syscon_lpc84x.rs
starblue/dust
8930b40a999239806c33d458af1bcf922378372b
use volatile_register::{RO, RW}; #[repr(C)] pub struct Syscon { pub sysmemremap: RW<u32>, reserved_0x004: u32, pub syspllctrl: RW<u32>, pub syspllstat: RO<u32>, reserved_0x010: u32, reserved_0x014: u32, reserved_0x018: u32, reserved_0x01c: u32, pub sysoscctrl: RW<u32>, pub wdt...
use volatile_register::{RO, RW}; #[repr(C)] pub struct Syscon { pub sysmemremap: RW<u32>, reserved_0x004: u32, pub syspllctrl: RW<u32>, pub syspllstat: RO<u32>, reserved_0x010: u32, reserved_0x014: u32, reserved_0x018: u32, reserved_0x01c: u32, pub sysoscctrl: RW<u32>, pub wdt...
iv1), 0x4004_8148); assert_eq!(address(&syscon.ioconclkdiv0), 0x4004_814c); assert_eq!(address(&syscon.bodctrl), 0x4004_8150); assert_eq!(address(&syscon.systckcal), 0x4004_8154); assert_eq!(address(&syscon.irqlatency), 0x4004_8170); assert_eq!(address(&syscon.nmisrc), 0x4004_817...
0x4004_8050); assert_eq!(address(&syscon.mainclkuen), 0x4004_8054); assert_eq!(address(&syscon.sysahbclkdiv), 0x4004_8058); assert_eq!(address(&syscon.captclksel), 0x4004_8060); assert_eq!(address(&syscon.adcclksel), 0x4004_8064); assert_eq!(address(&syscon.adcclkdiv), 0x4004_806...
random
[ { "content": "/// Reverse the bit order of a 32-bit value\n\npub fn rbit(a: u32) -> u32 {\n\n let result: u32;\n\n unsafe {\n\n asm!(\"rbit $0, $1\"\n\n : \"=r\"(result)\n\n : \"r\"(a)\n\n :\n\n : );\n\n }\n\n result\n\n}\n\n\n\n// # A4.6.3 Unpr...
Rust
src/day3.rs
dkimbel/Advent-of-Code-2020
d63d1177538fcdcc6e9d5cacdda29d58a3ec93d4
use std::fs::File; use std::io::{BufRead, BufReader}; use anyhow::{anyhow, Context, Result}; use crate::problem::{Part, Solved}; const INPUT_FILE_PATH: &str = "src/day3/puzzle_inputs"; pub struct Day3; impl Day3 { fn solve(problem_part: Part, input_file_path: &str) -> Result<usize> { match problem_part...
use std::fs::File; use std::io::{BufRead, BufReader}; use anyhow::{anyhow, Context, Result}; use crate::problem::{Part, Solved}; const INPU
let analyzer = PathAnalyzer::new(input_file_path)?; analyzer.calculate_num_trees(Slope { tiles_right: 3, tiles_down: 1 }) }, Part::Two => { let analyzer = PathAnalyzer::new(input_file_path)?; let slopes = [ Slope { til...
T_FILE_PATH: &str = "src/day3/puzzle_inputs"; pub struct Day3; impl Day3 { fn solve(problem_part: Part, input_file_path: &str) -> Result<usize> { match problem_part { Part::One => {
random
[ { "content": "pub trait Solved {\n\n fn print_solution(part: Part);\n\n}\n", "file_path": "src/problem.rs", "rank": 0, "score": 21091.651522006192 }, { "content": "# Advent of Code 2020\n\n\n\nThis repository has my solutions for the 2020 Advent of Code. I didn't do these exercises in 202...
Rust
src/entries/withdrawal.rs
nervina-labs/compact-nft-aggregator
f5d4afebd732fdcd55c7590ddfc5af0eb30b2eda
use crate::entries::helper::{ generate_empty_value, generate_hold_key, generate_hold_value, generate_withdrawal_key_v1, generate_withdrawal_value_v1, with_lock, }; use crate::entries::smt::{generate_history_smt, init_smt}; use crate::indexer::index::get_cota_smt_root; use crate::models::hold::get_hold_cota_by_l...
use crate::entries::helper::{ generate_empty_value, generate_hold_key, generate_hold_value, generate_withdrawal_key_v1, generate_withdrawal_value_v1, with_lock, }; use crate::entries::smt::{generate_history_smt, init_smt}; use crate::indexer::index::get_cota_smt_root; use crate::models::hold::get_hold_cota_by_l...
?; let withdrawal_merkle_proof = smt .merkle_proof(update_leaves.iter().map(|leave| leave.0).collect()) .map_err(|e| { error!("Withdraw SMT proof error: {:?}", e.to_string()); Error::SMTProofError("Withdraw".to_string()) })?; let withdrawal_merkle_proof_compiled ...
with_lock(lock_hash, || { generate_history_smt(&mut smt, lock_hash, smt_root)?; smt.update_all(update_leaves.clone()) .map_err(|e| Error::SMTError(e.to_string()))?; smt.save_root_and_leaves(previous_leaves.clone())?; smt.commit() })
call_expression
[ { "content": "pub fn leaf_key_to_vec(lock_hash: [u8; 32], key: &H256) -> Vec<u8> {\n\n let mut ret = Vec::with_capacity(64);\n\n ret.extend_from_slice(&lock_hash);\n\n ret.extend_from_slice(key.as_slice());\n\n ret\n\n}\n\n\n", "file_path": "src/smt/store/serde.rs", "rank": 0, "score": 2...
Rust
signatory-sgx/src/seal_data.rs
linfeng-crypto/signatory
e942713f3dd4a3a667afdacfaa431af8efe47cd3
use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use sgx_isa::{Attributes, Miscselect}; #[cfg(feature = "sgx")] use crate::error::Error; #[cfg(feature = "sgx")] use rand::random; #[cfg(feature = "sgx")] use sgx_isa::Report; #[cfg(feature = "sgx")] use sgx_isa::{Keyname, Keypolicy, Keyrequest}; #[cfg(...
use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use sgx_isa::{Attributes, Miscselect}; #[cfg(feature = "sgx")] use crate::error::Error; #[cfg(feature = "sgx")] use rand::random; #[cfg(feature = "sgx")] use sgx_isa::Report; #[cfg(feature = "sgx")] use sgx_isa::{Keyname, Keypolicy, Keyrequest}; #[cfg(...
} } } pub type EgetKey = [u8; 16]; pub type Label = [u8; 16]; pub type Nonce = [u8; 12]; pub type CpuSvn = [u8; 16]; pub type IsvSvn = u16; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct SealData { rand: [u8; 16], pub nonce: Nonce, isvsvn: IsvSvn, cpusvn: CpuSvn, ...
Err(de::Error::custom(format!( "deserilize Miscselect from {} failed", bits )))
call_expression
[ { "content": "fn main() -> Result<(), Error> {\n\n let _ = logger::init();\n\n let addr = \"127.0.0.1:8888\";\n\n let listener = TcpListener::bind(addr).unwrap();\n\n info!(\"listening {:?}\", addr);\n\n\n\n for stream in listener.incoming() {\n\n let mut stream = match stream {\n\n ...
Rust
diesel_tests/tests/limit_offset.rs
NarrativeApp/diesel
daf1d331f941f759f8bf50ed807cce0b512c39a5
use super::schema::*; use diesel::*; #[test] fn limit() { use crate::schema::users::dsl::*; let connection = connection(); connection .execute("INSERT INTO users (name) VALUES ('Sean'), ('Tess')") .unwrap(); let expected_data = vec![("Sean".to_string(), None::<String>)]; let actua...
use super::schema::*; use diesel::*; #[test] fn limit() { use crate::schema::users::dsl::*; let connection = connection(); connection .execute("INSERT INTO users (name) VALUES ('Sean'), ('Tess')") .unwrap(); let expected_data = vec![("Sean".to_string(), None::<String>)]; let actua...
#[test] fn limit_offset() { use crate::schema::users::dsl::*; let connection = connection(); connection .execute("INSERT INTO users (name) VALUES ('Sean'), ('Tess'), ('Ruby')") .unwrap(); let expected_data = vec![("Ruby".to_string(), None::<String>)]; let q = users.select((name, ...
n'), ('Tess')") .unwrap(); let expected_data = vec![("Tess".to_string(), None::<String>)]; let q = users.select((name, hair_color)).offset(1); let actual_data: Vec<_> = q.load(&connection).unwrap(); assert_eq!(expected_data, actual_data); }
function_block-function_prefixed
[ { "content": "pub fn find_user_by_name(name: &str, connection: &TestConnection) -> User {\n\n users::table\n\n .filter(users::name.eq(name))\n\n .first(connection)\n\n .unwrap()\n\n}\n", "file_path": "diesel_tests/tests/schema/mod.rs", "rank": 0, "score": 382441.3642600095 ...
Rust
src/uint/from.rs
RustCrypto/crypto-bigint
e87253b36f09adc6388d7952952cd76fcf9325a5
use crate::{Limb, LimbUInt, Split, UInt, U128, U64}; impl<const LIMBS: usize> UInt<LIMBS> { pub const fn from_u8(n: u8) -> Self { assert!(LIMBS >= 1, "number of limbs must be greater than zero"); let mut limbs = [Limb::ZERO; LIMBS]; limbs[0].0 = n as LimbUInt; Self { lim...
use crate::{Limb, LimbUInt, Split, UInt, U128, U64}; impl<const LIMBS: usize> UInt<LIMBS> { pub const fn from_u8(n: u8) -> Self { assert!(LIMBS >= 1, "number of limbs must be greater than zero"); let mut limbs = [Limb::ZERO; LIMBS]; limbs[0].0 = n as LimbUInt; Self { lim...
} #[test] fn from_u64() { let n = UIntEx::from(42u64); assert_eq!(n.limbs(), &[Limb(42), Limb(0)]); } #[test] fn from_u128() { let n = U128::from(42u128); assert_eq!(&n.limbs()[..2], &[Limb(42), Limb(0)]); assert_eq!(u128::from(n), 42u128); } #...
hi = U64::from_u64((n >> 64) as u64); let mut limbs = [Limb::ZERO; LIMBS]; let mut i = 0; while i < lo.limbs.len() { limbs[i] = lo.limbs[i]; i += 1; } let mut j = 0; while j < hi.limbs.len() { limbs[i + j] = hi.limbs[j]; ...
random
[ { "content": "/// Split a number in half, returning the most significant half followed by\n\n/// the least significant.\n\npub trait Split<Rhs = Self> {\n\n /// Split output: high/low components of the value.\n\n type Output;\n\n\n\n /// Split this number in half, returning its high and low components\...
Rust
protocols/autonat/src/protocol.rs
Frederik-Baetens/rust-libp2p
16c29d18eb890d1a40120be80b7e87811c6d24dd
use crate::structs_proto; use async_trait::async_trait; use futures::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use libp2p_core::{upgrade, Multiaddr, PeerId}; use libp2p_request_response::{ProtocolName, RequestResponseCodec}; use prost::Message; use std::{convert::TryFrom, io}; #[derive(Clone, Debug)] pub struct Au...
use crate::structs_proto; use async_trait::async_trait; use futures::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use libp2p_core::{upgrade, Multiaddr, PeerId}; use libp2p_request_response::{ProtocolName, RequestResponseCodec}; use prost::Message; use std::{convert::TryFrom, io}; #[derive(Clone, Debug)] pub struct Au...
async fn read_response<T>( &mut self, _: &AutoNatProtocol, io: &mut T, ) -> io::Result<Self::Response> where T: AsyncRead + Send + Unpin, { let bytes = upgrade::read_length_prefixed(io, 1024).await?; let response = DialResponse::from_bytes(&bytes)?; ...
mut self, _: &AutoNatProtocol, io: &mut T, ) -> io::Result<Self::Request> where T: AsyncRead + Send + Unpin, { let bytes = upgrade::read_length_prefixed(io, 1024).await?; let request = DialRequest::from_bytes(&bytes)?; Ok(request) }
function_block-function_prefix_line
[ { "content": "/// Turns a protobuf message into an `IdentifyInfo`.\n\nfn parse_proto_msg(msg: impl AsRef<[u8]>) -> Result<IdentifyInfo, io::Error> {\n\n match structs_proto::Identify::decode(msg.as_ref()) {\n\n Ok(msg) => {\n\n fn parse_multiaddr(bytes: Vec<u8>) -> Result<Multiaddr, io::Err...
Rust
lib/tests/store.rs
jeremiahpslewis/oxigraph
aad84e43053764a34ab818151b28a753fd938c9b
use oxigraph::io::{DatasetFormat, GraphFormat}; use oxigraph::model::vocab::{rdf, xsd}; use oxigraph::model::*; use oxigraph::store::Store; use std::io::{Cursor, Result}; use std::process::Command; const DATA: &str = r#" @prefix schema: <http://schema.org/> . @prefix wd: <http://www.wikidata.org/entity/> . @prefix xsd...
use oxigraph::io::{DatasetFormat, GraphFormat}; use oxigraph::model::vocab::{rdf, xsd}; use oxigraph::model::*; use oxigraph::store::Store; use std::io::{Cursor, Result}; use std::process::Command; const DATA: &str = r#" @prefix schema: <http://schema.org/> . @prefix wd: <http://www.wikidata.org/entity/> . @prefix xsd...
#[test] fn test_bulk_load_dataset() -> Result<()> { let store = Store::new().unwrap(); store.bulk_load_dataset(Cursor::new(DATA), DatasetFormat::TriG, None)?; for q in quads(GraphNameRef::DefaultGraph) { assert!(store.contains(q)?); } Ok(()) } #[test] fn test_load_graph_generates_new_blan...
fn test_load_dataset() -> Result<()> { let store = Store::new()?; store.load_dataset(Cursor::new(DATA), DatasetFormat::TriG, None)?; for q in quads(GraphNameRef::DefaultGraph) { assert!(store.contains(q)?); } Ok(()) }
function_block-full_function
[ { "content": "fn run_testsuite(manifest_url: &str, ignored_tests: Vec<&str>) -> Result<()> {\n\n let mut evaluator = TestEvaluator::default();\n\n register_sparql_tests(&mut evaluator);\n\n let manifest = TestManifest::new(vec![manifest_url]);\n\n let results = evaluator.evaluate(manifest)?;\n\n\n\n...
Rust
src/parser/mod.rs
pwbrown/rust-monkey
0d5d7481d05bc4d59b3c43fb32c14260479b2067
#[cfg(test)] mod tests; use crate::ast::*; use crate::lexer::Lexer; use crate::token::Token; pub struct Parser<'a> { lexer: Lexer<'a>, curr_token: Token, peek_token: Token, errors: Vec<String>, } impl<'a> Parser<'a> { pub fn new(mut lexer: Lexer) -> Parser { Parser { curr...
#[cfg(test)] mod tests; use crate::ast::*; use crate::lexer::Lexer; use crate::token::Token; pub struct Parser<'a> { lexer: Lexer<'a>, curr_token: Token, peek_token: Token, errors: Vec<String>, } impl<'a> Parser<'a> { pub fn new(mut lexer: Lexer) -> Parser { Parser { curr...
params.push(ident.clone()), _ => { self.errors.push(format!( "expected an identifier, got a '{:?}'", self.curr_token )); return None; } } if self.peek_token...
recedence::Lowest) { Some(expr) => { if !self.expect_peek(Token::Rparen) { return None; } Some(expr) } None => None, } } fn parse_if_expr(&mut self) -> Option<Expr> { if !self.expect_peek(Tok...
random
[ { "content": "// Generates an infix expression\n\nfn infix(left: Expr, op: Infix, right: Expr) -> Expr {\n\n Expr::Infix(Box::new(left), op, Box::new(right))\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 0, "score": 185486.7398678784 }, { "content": "// Generates a return state...
Rust
src/main.rs
bittrance/mqtt-verify
5e686b6c5094c012a372f884e191a9daf86a38d9
use async_std::task; use evalexpr::Value; use futures::stream::StreamExt; use mqtt_verify::{analyzers, context, errors, scenario, source}; use std::rc::Rc; use std::str::FromStr; use std::time::Duration; use structopt::StructOpt; fn split_on_equal(input: &str) -> Result<(String, String), errors::MqttVerifyError> { ...
use async_std::task; use evalexpr::Value; use futures::stream::StreamExt; use mqtt_verify::{analyzers, context, errors, scenario, source}; use std::rc::Rc; use std::str::FromStr; use std::time::Duration; use structopt::StructOpt; fn split_on_equal(input: &str) -> Result<(String, String), errors::MqttVerifyError> { ...
#[cfg(test)] mod tests { use super::Opt; use mqtt_verify::errors; use structopt::StructOpt; fn basic_options(extra: Vec<&str>) -> Opt { let mut args = vec![ "./mqtt-verify", "--publish-uri", "tcp://localhost:1883", "--subscribe-uri", ...
match result { Ok(_) => (), Err(err) => return Err(err), } } Ok(()) }) }
function_block-function_prefix_line
[ { "content": "pub fn precompile(value: &str) -> Result<Node, MqttVerifyError> {\n\n let mut stop = 0;\n\n let mut parts: Vec<String> = Vec::new();\n\n for (start, _) in value.match_indices(\"{{\") {\n\n maybe_push_str(&mut parts, &value[stop..start]);\n\n stop = start\n\n + val...
Rust
influxdb2_client/src/data_point.rs
next-generation-search-engine/influxdb_iox
b8942dce0d8bc2bd692c1726f2993b8cebbfa0d4
use snafu::{ensure, Snafu}; use std::{collections::BTreeMap, io}; #[derive(Debug, Snafu)] pub enum DataPointError { #[snafu(display( "All `DataPoints` must have at least one field. Builder contains: {:?}", data_point_builder ))] AtLeastOneFieldRequired { data_po...
use snafu::{ensure, Snafu}; use std::{collections::BTreeMap, io}; #[derive(Debug, Snafu)] pub enum DataPointError { #[snafu(display( "All `DataPoints` must have at least one field. Builder contains: {:?}", data_point_builder ))] AtLeastOneFieldRequired { data_po...
est] fn special_characters_are_escaped_in_measurements() -> Result { assert_utf8_strings_eq( &ALL_THE_DELIMITERS.measurement_to_vec()?, br#"alpha\,beta=delta\ gamma"epsilon"#.as_ref(), )?; Ok(()) } #[test] fn special_characters_are_escaped_in_tag_keys() -...
ub trait WriteDataPoint { fn write_data_point_to<W>(&self, w: W) -> io::Result<()> where W: io::Write; } trait WriteMeasurement { fn write_measurement_to<W>(&self, w: W) -> io::Result<()> where W: io::Write; } impl WriteMeasurement for str { fn write_measurement_to<W...
random
[ { "content": "/// Create a predicate representing tag_name=tag_value in the horrible gRPC\n\n/// structs\n\nfn make_tag_predicate(tag_name: impl Into<String>, tag_value: impl Into<String>) -> Predicate {\n\n Predicate {\n\n root: Some(Node {\n\n node_type: NodeType::ComparisonExpression as ...
Rust
src/utc_offset.rs
hroi/time
5444119d8e57b8046e9f4635ae379e4690d37d86
#[cfg(feature = "alloc")] use crate::alloc_prelude::*; use crate::{ format::{parse, ParseError, ParseResult, ParsedItems}, DeferredFormat, Duration, }; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( feature = "serde", serde(from = "crate::serde::UtcOffset", int...
#[cfg(feature = "alloc")] use crate::alloc_prelude::*; use crate::{ format::{parse, ParseError, ParseResult, ParsedItems}, DeferredFormat, Duration, }; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( feature = "serde", serde(from = "crate::serde::UtcOffset", int...
#[test] fn directional_hours() { assert_eq!(UtcOffset::east_hours(1), offset!(+1)); assert_eq!(UtcOffset::west_hours(1), offset!(-1)); } #[test] fn minutes() { assert_eq!(UtcOffset::minutes(1).as_seconds(), 60); assert_eq!(UtcOffset::minutes(-1).as_seconds(), -60);...
fn hours() { assert_eq!(UtcOffset::hours(1).as_seconds(), 3_600); assert_eq!(UtcOffset::hours(-1).as_seconds(), -3_600); assert_eq!(UtcOffset::hours(23).as_seconds(), 82_800); assert_eq!(UtcOffset::hours(-23).as_seconds(), -82_800); }
function_block-full_function
[ { "content": "#[inline(always)]\n\npub fn validate_format_string(s: &str) -> Result<(), String> {\n\n try_parse_fmt_string(s).map(|_| ())\n\n}\n\n\n\n/// The type of padding to use when formatting.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub(crate) enum Padding {\n\n /// No padding. Minim...
Rust
chain/src/chain/link.rs
rustgd/rendy
ff05ccb646704ff7de82a0ec1442c3e215ab36e9
use crate::{ node::State, resource::{AccessFlags, Resource}, schedule::{QueueId, SubmissionId}, }; #[derive(Clone, Copy, Debug)] pub struct LinkQueueState<R: Resource> { pub first: usize, pub last: usize, pub access: R::Access, pub stages: gfx_hal::pso::PipelineStage, } impl<R> LinkQueueS...
use crate::{ node::State, resource::{AccessFlags, Resource}, schedule::{QueueId, SubmissionId}, }; #[derive(Clone, Copy, Debug)] pub struct LinkQueueState<R: Resource> { pub first: usize, pub last: usize, pub access: R::Access, pub stages: gfx_hal::pso::PipelineStage, } impl<R> LinkQueueS...
fn ensure_queue(&mut self, index: usize) { if index >= self.queues.len() { let reserve = index - self.queues.len() + 1; self.queues.reserve(reserve); while index >= self.queues.len() { self.queues.push(None); } } } ...
pub fn new(node: LinkNode<R>) -> Self { let mut link = Link { access: node.state.access, usage: node.state.usage, layout: node.state.layout, stages: node.state.stages, queue_count: 1, queues: Vec::new(), family: node.sid.family(...
function_block-full_function
[ { "content": "/// Trait to abstract of specific access flags.\n\npub trait AccessFlags: Copy + Debug + BitOr<Output = Self> + BitOrAssign + 'static {\n\n /// Get flags value with no flags set.\n\n fn empty() -> Self;\n\n\n\n /// Check if this access must be exclusive.\n\n /// \n\n /// Basically t...
Rust
dtag/src/types.rs
Oli-art/wasp
02f9d0bf417765e7bfcfe4bcc11ddeeb94b2e8df
#![allow(dead_code)] use wasmlib::*; use wasmlib::host::*; pub struct Bet { pub amount: i64, pub image_id: i32, pub player: ScAgentID, } impl Bet { pub fn from_bytes(bytes: &[u8]) -> Bet { let mut decode = BytesDecoder::new(bytes); Bet { amount: decode.int64(), ...
#![allow(dead_code)] use wasmlib::*; use wasmlib::host::*; pub struct Bet { pub amount: i64, pub image_id: i32, pub player: ScAgentID, } impl Bet { pub fn from_bytes(bytes: &[u8]) -> Bet { let mut decode = BytesDecoder::new(bytes); Bet { amount: decode.int64(), ...
} pub struct ImmutableBet { pub(crate) obj_id: i32, pub(crate) key_id: Key32, } impl ImmutableBet { pub fn exists(&self) -> bool { exists(self.obj_id, self.key_id, TYPE_BYTES) } pub fn value(&self) -> Bet { Bet::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) } }...
pub fn to_bytes(&self) -> Vec<u8> { let mut encode = BytesEncoder::new(); encode.int64(self.amount); encode.int32(self.image_id); encode.agent_id(&self.player); return encode.data(); }
function_block-full_function
[ { "content": "pub fn call_func(obj_id: i32, key_id: Key32, params: &[u8]) -> Vec<u8> {\n\n unsafe {\n\n let mut args = std::ptr::null();\n\n let mut size = params.len() as i32;\n\n if size != 0 {\n\n args = params.as_ptr();\n\n }\n\n\n\n // variable-sized type, f...
Rust
website/src/page.rs
kaylynn234/website
e43bfe2f9fe89071a27c7d9c08c991d9231f3cbd
use super::SYNTAX_SET; use chrono::{DateTime, Local, TimeZone}; use comrak::{ arena_tree::NodeEdge, nodes::{AstNode, NodeHtmlBlock, NodeValue}, Arena, ComrakExtensionOptions, ComrakOptions, ComrakRenderOptions, }; use indexmap::IndexMap; use lazy_static::lazy_static; use rocket::{ response::Responder, ...
use super::SYNTAX_SET; use chrono::{DateTime, Local, TimeZone}; use comrak::{ arena_tree::NodeEdge, nodes::{AstNode, NodeHtmlBlock, NodeValue}, Arena, ComrakExtensionOptions, ComrakOptions, ComrakRenderOptions, }; use indexmap::IndexMap; use lazy_static::lazy_static; use rocket::{ response::Responder, ...
Some(buffer[..end].to_owned()) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(crate = "rocket::serde")] pub struct PostInfo { pub title: String, #[serde(deserialize_with = "deserialize_config_date")] pub published: DateTime<Local>, #[serde(skip_deserializing)] pub rendered: String,...
if len > DESCRIPTION_LENGTH { let offset = buffer[..end] .chars() .rev() .take(3) .map(char::len_utf8) .sum::<usize>(); return Some(format!("{} [...]", &buffer[..end - offset].trim())); }
if_condition
[ { "content": "pub fn humanise(value: &Value, _: &HashMap<String, Value>) -> Result<Value> {\n\n let input = match value {\n\n Value::String(string) => Ok(string),\n\n _ => Err(Error::msg(\"Value is not a string\")),\n\n }?;\n\n\n\n let post_date = input\n\n .parse::<DateTime<Local>...
Rust
garnet/bin/battery_manager/src/power.rs
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
extern crate libc; use failure::{Error, ResultExt}; use fdio::{self, clone_channel}; use fidl_fuchsia_hardware_power as hpower; use fuchsia_async as fasync; use fuchsia_syslog::{fx_log_err, fx_log_info, fx_vlog}; use fuchsia_vfs_watcher as vfs_watcher; use fuchsia_zircon::{self as zx, Signals}; use futures::prelude:...
extern crate libc; use failure::{Error, ResultExt}; use fdio::{self, clone_channel}; use fidl_fuchsia_hardware_power as hpower; use fuchsia_async as fasync; use fuchsia_syslog::{fx_log_err, fx_log_info, fx_vlog}; use fuchsia_vfs_watcher as vfs_watcher; use fuchsia_zircon::{self as zx, Signals}; use futures::prelude:...
async fn add_listener<F>(file: &File, callback: F) -> ioResult<()> where F: 'static + Send + Fn(hpower::SourceInfo, Option<hpower::BatteryInfo>) + Sync, { let power_source = get_power_source_proxy(&file)?; let file_copy = file .try_clone() .map_err(|e| io::Error::new(e.kind(), format!("err...
tteryInfo> { let power_source = get_power_source_proxy(&file)?; match power_source.get_battery_info().map_err(|_| zx::Status::IO).await? { result => { let (status, info) = result; fx_vlog!(1, "battery_info: {:?}, status: {:?}", info, status); Ok(info) } } ...
function_block-function_prefixed
[]
Rust
router2/src/sharder/table_namespace_sharder.rs
Marwes/influxdb_iox
b3b2d9b6232a3341ff15506df1f02bef4dc81d6b
use std::{ fmt::Debug, hash::{Hash, Hasher}, }; use data_types::DatabaseName; use siphasher::sip::SipHasher13; use super::Sharder; #[derive(Debug)] pub struct TableNamespaceSharder<T> { hasher: SipHasher13, shards: Vec<T>, } impl<T> TableNamespaceSharder<T> { ...
use std::{ fmt::Debug, hash::{Hash, Hasher}, }; use data_types::DatabaseName; use siphasher::sip::SipHasher13; use super::Sharder; #[derive(Debug)] pub struct TableNamespaceSharder<T> { hasher: SipHasher13, shards: Vec<T>, } impl<T> TableNamespaceSharder<T> { ...
#[test] fn test_sharder_prefix_collision() { let hasher = TableNamespaceSharder::new(0..10_000); let a = hasher.shard("a", &DatabaseName::try_from("bc").unwrap(), &0); let b = hasher.shard("ab", &DatabaseName::try_from("c").unwrap(), &0); assert_ne!(a, b); } ...
fn test_sharder_impl() { let hasher = TableNamespaceSharder::new(0..10_000); let a = hasher.shard("table", &DatabaseName::try_from("namespace").unwrap(), &0); let b = hasher.shard("table", &DatabaseName::try_from("namespace2").unwrap(), &0); assert_ne!(a, b); let a = hasher.sha...
function_block-full_function
[ { "content": "/// A [`Sharder`] implementation is responsible for mapping an opaque payload\n\n/// for a given table name & namespace to an output type.\n\n///\n\n/// [`Sharder`] instances can be generic over any payload type (in which case,\n\n/// the implementation operates exclusively on the table name and/o...
Rust
src/gsm_encoding/mod.rs
yuthstyle88/huawei-modem
916943745fe3ae1d4f188d2001be63ab12036982
use crate::pdu::MessageEncoding; use std::convert::TryFrom; use crate::errors::*; mod lookup_tables; pub mod udh; use self::udh::{UserDataHeader, UdhComponent}; use self::lookup_tables::*; pub fn gsm_decode_string(input: &[u8]) -> String { let mut ret = String::new(); let mut skip = false; for (i, b) i...
use crate::pdu::MessageEncoding; use std::convert::TryFrom; use crate::errors::*; mod lookup_tables; pub mod udh; use self::udh::{UserDataHeader, UdhComponent}; use self::lookup_tables::*; pub fn gsm_decode_string(input: &[u8]) -> String { let mut ret = String::new(); let mut skip = false; for (i, b) i...
lf.bytes.get(start).is_none() { return Ok(DecodedMessage { text: String::new(), udh }); } match self.encoding { MessageEncoding::Gsm7Bit => { let buf = decode_sms_7bit(&self.bytes[start..], padding, self.user_data_len as...
rr(HuaweiError::InvalidPdu("UDHI specified, but no data"))? } let udhl = self.bytes[0] as usize; padding = 7 - (((udhl + 1) * 8) % 7); start = udhl + 1; if self.bytes.len() < start { Err(HuaweiError::InvalidPdu("UDHL goes past end of data"))? ...
random
[ { "content": "/// Set whether the modem will use text mode or not (`AT+CMGF`).\n\npub fn set_sms_textmode(modem: &mut HuaweiModem, text: bool) -> impl Future<Item = (), Error = HuaweiError> {\n\n modem.send_raw(AtCommand::Equals {\n\n param: \"+CMGF\".into(),\n\n value: AtValue::Integer(if text...
Rust
vendor/lambda_calculus/tests/pair_list.rs
mcheshkov/icfpc2020
337a94d648e517a0358ffdb86fe0d468a7462939
#![cfg(feature = "encoding")] #![allow(warnings)] extern crate lambda_calculus as lambda; use lambda::*; use lambda::data::list::pair::*; use lambda::data::num::church::is_zero; macro_rules! vec_church { ( $( $e:expr ),* ) => { { let mut vec = Vec::new(); $( vec.push($e.into_chur...
#![cfg(feature = "encoding")] #![allow(warnings)] extern crate lambda_calculus as lambda; use lambda::*; use lambda::data::list::pair::*; use lambda::data::num::church::is_zero; macro_rules! vec_church { ( $( $e:expr ),* ) => { { let mut vec = Vec::new(); $( vec.push($e.into_chur...
, 2, 3] => 3 ); test_list!(list_init, init, vec![1] => empty(), vec![1, 2] => vec![1], vec![1, 2, 3] => vec![1, 2] ); test_list!(list_zip, zip, empty(), vec![1] => empty(), vec![1], empty() => empty(), vec![1], vec![1] => vec![(1, 1)], vec![1, 2], vec![1] => vec![(1, 1)], vec![1], vec!...
vec_church![].into_pair_list() => vec_church![].into_pair_list(), 0.into_church(), vec_church![1].into_pair_list() => vec_church![1].into_pair_list(), 1.into_church(), vec_church![1].into_pair_list() => vec_church![].into_pair_list(), 1.into_church(), vec_church![1, 2].into_pair_lis...
random
[ { "content": "#[test]\n\nfn test_reduce_lists() {\n\n let test1 = \"ap ap cons 7 ap ap cons 123229502148636 nil\";\n\n let token = Action::parse(test1).pop().unwrap();\n\n let multi_token = token.reduce_args();\n\n let exp1 = Action::List(vec![Action::Value(\"7\"), Action::Value(\"123229502148636\")...
Rust
src/preview.rs
Elvyria/wcolor
5678d0e73fafc8c6cb6f23e6b07ef3c893e4fd0b
use crate::color::Color; use crate::win::hr; use std::ffi::OsStr; use std::io::Error; use std::ptr::{null, null_mut}; use wio::com::ComPtr; use wio::wide::ToWide; use winapi::Interface; use winapi::um::dcommon::{D2D1_PIXEL_FORMAT, D2D1_ALPHA_MODE_PREMULTIPLIED}; use winapi::um::dcomp::{DCompositionCreateDevice, IDCo...
use crate::color::Color; use crate::win::hr; use std::ffi::OsStr; use std::io::Error; use std::ptr::{null, null_mut}; use wio::com::ComPtr; use wio::wide::ToWide; use winapi::Interface; use winapi::um::dcommon::{D2D1_PIXEL_FORMAT, D2D1_ALPHA_MODE_PREMULTIPLIED}; use winapi::um::dcomp::{DCompositionCreateDevice, IDCo...
AlphaMode: DXGI_ALPHA_MODE_PREMULTIPLIED, Flags: 0, }; let mut swap_chain: *mut IDXGISwapChain1 = null_mut(); hr((*dxgi_factory).CreateSwapChainForComposition(device.as_raw() as _, &swap_chain_desc, null_mut(), &mut swap_chain))?; (*dxgi_factory).Release(); ...
pse_geometry as _, D2D1_DEFAULT_FLATTENING_TOLERANCE, 1.3, null_mut(), &mut stroke_realization); (*ellipse_geometry).Release(); Ok(Preview { hwnd, context, swap_chain, _target, brush: ComPtr::from_raw(brush), ellipse: ComPtr::from...
random
[ { "content": "// TODO: Try trait should be able to replace this macro in future\n\n// https://doc.rust-lang.org/std/ops/trait.Try.html\n\npub fn hr(code: HRESULT) -> Result<(), HRESULT> {\n\n match code {\n\n S_OK => Ok(()),\n\n _ => Err(code),\n\n }\n\n}\n\n\n\nmacro_rules! void {\n\n ($...
Rust
src/quickcheck.rs
soenkehahn/time
1860b1482e96e3973fbad634739eb21c5bc0190d
use alloc::boxed::Box; use quickcheck_dep::{empty_shrinker, single_shrinker, Arbitrary, Gen}; use crate::date::{MAX_YEAR, MIN_YEAR}; use crate::util::days_in_year; use crate::{Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday}; macro_rules! arbitrary_between { ($type:ty; $gen:expr, $m...
use alloc::boxed::Box; use quickcheck_dep::{empty_shrinker, single_shrinker, Arbitrary, Gen}; use crate::date::{MAX_YEAR, MIN_YEAR}; use crate::util::days_in_year; use crate::{Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday}; macro_rules! arbitrary_between { ($type:ty; $gen:expr, $m...
} impl Arbitrary for UtcOffset { fn arbitrary(g: &mut Gen) -> Self { let hours = arbitrary_between!(i8; g, -23, 23); let mut minutes = arbitrary_between!(i8; g, 0, 59); let mut seconds = arbitrary_between!(i8; g, 0, 59); if hours < 0 || (hours == 0 &&...
Box::new( (self.date, self.time) .shrink() .map(|(date, time)| Self { date, time }), ) }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn nanosecond() {\n\n assert_eq!(datetime!(\"2019-01-01 0:00\").nanosecond(), 0);\n\n assert_eq!(\n\n datetime!(\"2019-01-01 23:59:59.999_999_999\").nanosecond(),\n\n 999_999_999\n\n );\n\n}\n\n\n", "file_path": "tests/integration/primitive_date_time.rs", ...
Rust
src/os/unix/mod.rs
ZOTTCE/rust_libloading
1ab4c410034fb8896854c3b037a201913522ec16
use util::{ensure_compatible_types, cstr_cow_from_bytes}; use std::ffi::{CStr, OsStr}; use std::{fmt, io, marker, mem, ptr}; use std::os::raw; use std::os::unix::ffi::OsStrExt; extern "C" { fn rust_libloading_dlerror_mutex_lock(); fn rust_libloading_dlerror_mutex_unlock(); } struct DlerrorMutexGuard(()); im...
use util::{ensure_compatible_types, cstr_cow_from_bytes}; use std::ffi::{CStr, OsStr}; use std::{fmt, io, marker, mem, ptr}; use std::os::raw; use std::os::unix::ffi::OsStrExt; extern "C" { fn rust_libloading_dlerror_mutex_lock(); fn rust_libloading_dlerror_mutex_unlock(); } struct DlerrorMutexGuard(()); im...
.as_ptr()); if symbol.is_null() { None } else { Some(Symbol { pointer: symbol, pd: marker::PhantomData }) } }) { Err(None) => Ok(Symbol { pointer: ptr::null_mut...
::Error>> where F: FnOnce() -> Option<T> { let _lock = DlerrorMutexGuard::new(); closure().ok_or_else(|| unsafe { let error = dlerror(); if error.is_null() { None } else { ...
random
[ { "content": "fn with_get_last_error<T, F>(closure: F) -> Result<T, Option<io::Error>>\n\nwhere F: FnOnce() -> Option<T> {\n\n closure().ok_or_else(|| {\n\n let error = unsafe { errhandlingapi::GetLastError() };\n\n if error == 0 {\n\n None\n\n } else {\n\n Some(io:...