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
ironrdp/src/rdp/vc/dvc/gfx/graphics_messages.rs
msabansal/IronRDP
04711ff0bc4ac7891403dc591405cba623c14956
mod client; mod server; #[cfg(test)] pub mod test; pub use client::{CacheImportReplyPdu, CapabilitiesAdvertisePdu, FrameAcknowledgePdu, QueueDepth}; pub use server::{ CacheToSurfacePdu, CapabilitiesConfirmPdu, Codec1Type, Codec2Type, CreateSurfacePdu, DeleteEncodingContextPdu, DeleteSurfacePdu, EndFramePdu, Ev...
mod client; mod server; #[cfg(test)] pub mod test; pub use client::{CacheImportReplyPdu, CapabilitiesAdvertisePdu, FrameAcknowledgePdu, QueueDepth}; pub use server::{ CacheToSurfacePdu, CapabilitiesConfirmPdu, Codec1Type, Codec2Type, CreateSurfacePdu, DeleteEncodingContextPdu, DeleteSurfacePdu, EndFramePdu, Ev...
} } #[derive(Debug, Clone, PartialEq)] pub struct Color { b: u8, g: u8, r: u8, xa: u8, } impl PduParsing for Color { type Error = GraphicsMessagesError; fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> { let b = stream.read_u8()?; let g = stream.read...
match self { CapabilitySet::V8 { .. } | CapabilitySet::V8_1 { .. } | CapabilitySet::V10 { .. } | CapabilitySet::V10_2 { .. } | CapabilitySet::V10_3 { .. } | CapabilitySet::V10_4 { .. } | CapabilitySet::V10_5 ...
if_condition
[ { "content": "pub fn write_u32(mut stream: impl io::Write, value: u32) -> io::Result<usize> {\n\n if value <= 0xff {\n\n let size = write_length(&mut stream, 1)?;\n\n stream.write_u8(value as u8)?;\n\n\n\n Ok(size + 1)\n\n } else if value <= 0xffff {\n\n let size = write_length...
Rust
src/apple/deps/update.rs
Cactice/cargo-mobile
20f2d1aee8b9c94de32fff40d9b0b6c15147966b
use super::{ util::{self, CaptureGroupError}, GemCache, PACKAGES, }; use once_cell_regex::regex; use serde::Deserialize; use thiserror::Error; #[derive(Debug, Error)] pub enum RegexError { #[error("Failed to match regex in string {revision:?}")] SearchFailed { revision: String }, #[error(transparen...
use super::{ util::{self, CaptureGroupError}, GemCache, PACKAGES, }; use once_cell_regex::regex; use serde::Deserialize; use thiserror::Error; #[derive(Debug, Error)] pub enum RegexError { #[error("Failed to match regex in string {revision:?}")] SearchFailed { revision: String }, #[error(transparen...
} fn from_gem_outdated_str(revision: &str) -> Result<Self, RegexError> { let caps = regex!(r"(?P<name>.+) \((?P<installed_version>.+) < (?P<latest_version>.+)\)") .captures(revision) .ok_or_else(|| RegexError::SearchFailed { revision: revision.to_owned(), ...
if self.installed_versions.len() == 1 { println!( " - `{}` is at {}; latest version is {}", self.name, self.installed_versions[0], self.current_version ); } else { println!( " - `{}` is at [{}]; latest version is {}", ...
if_condition
[ { "content": "pub fn list_display(list: &[impl Display]) -> String {\n\n if list.len() == 1 {\n\n list[0].to_string()\n\n } else if list.len() == 2 {\n\n format!(\"{} and {}\", list[0], list[1])\n\n } else {\n\n let mut display = String::new();\n\n for (idx, item) in list.it...
Rust
rust/protocols/src/gc.rs
yexincheng/delphi
7230fc9977008eab20bc1918c479c8294c93667c
use crate::{AdditiveShare, InMessage, OutMessage}; use algebra::{ fields::PrimeField, fixed_point::{FixedPoint, FixedPointParameters}, fp_64::Fp64Parameters, BigInteger64, FpParameters, UniformRandom, }; use crypto_primitives::{ gc::{ fancy_garbling, fancy_garbling::{ cir...
use crate::{AdditiveShare, InMessage, OutMessage}; use algebra::{ fields::PrimeField, fixed_point::{FixedPoint, FixedPointParameters}, fp_64::Fp64Parameters, BigInteger64, FpParameters, UniformRandom, }; use crypto_primitives::{ gc::{ fancy_garbling, fancy_garbling::{ cir...
}
s: &[Wire], client_input_wires: &[Wire], evaluators: &[GarbledCircuit], next_layer_randomizers: &[P::Field], ) -> Result<Vec<AdditiveShare<P>>, bincode::Error> { let start_time = timer_start!(|| "ReLU online protocol"); let rcv_time = timer_start!(|| "Receiving inputs"); ...
function_block-function_prefixed
[ { "content": "pub fn gc<R: RngCore + CryptoRng>(server_addr: &str, number_of_relus: usize, rng: &mut R) {\n\n let (mut reader, mut writer) = server_connect(server_addr);\n\n\n\n let key_time = timer_start!(|| \"Keygen\");\n\n let keys: OfflineServerKeyRcv = protocols::bytes::deserialize(&mut reader).un...
Rust
src/lexer/token.rs
jsinger67/parol_runtime
496caa8dfb377647735c4ea9d213ff277cab65d5
use crate::lexer::{FormatToken, OwnedToken, TerminalIndex}; use miette::SourceSpan; use std::convert::From; use std::fmt::{Debug, Display, Error, Formatter}; pub const EOI: TerminalIndex = 0; pub const NEW_LINE: TerminalIndex = 1; pub const WHITESPACE: TerminalIndex = 2; pub const LINE_COMMENT: TerminalIndex = 3; ...
use crate::lexer::{FormatToken, OwnedToken, TerminalIndex}; use miette::SourceSpan; use std::convert::From; use std::fmt::{Debug, Display, Error, Formatter}; pub const EOI: TerminalIndex = 0; pub const NEW_LINE: TerminalIndex = 1; pub const WHITESPACE: TerminalIndex = 2; pub const LINE_COMMENT: TerminalIndex = 3; ...
} impl FormatToken for Token<'_> { fn format<T>( &self, file_name: &T, terminal_names: &'static [&'static str], ) -> std::string::String where T: AsRef<std::path::Path>, { let name = terminal_names[self.token_type]; format!( "'{}'({}) at {}:{...
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> { let (c1, c2) = if self.symbol.starts_with('\'') { ('<', '>') } else { ('\'', '\'') }; write!( f, "{}{}{}, Ty:{}, Loc:{},{}-{}", c1, self.symbol...
function_block-full_function
[ { "content": "#[test]\n\nfn tokenizer_test() {\n\n assert_eq!(\n\n 11, TOKENIZERS[0].1.error_token_type,\n\n \"Error token index is wrong\"\n\n );\n\n}\n\n\n", "file_path": "tests/lexer_test.rs", "rank": 0, "score": 32085.231815791984 }, { "content": "#[test]\n\n#[should_...
Rust
crates/compiler/examples/extensions.rs
hotg-ai/rune
b8303c36f16e8f0fe2ffa6cd7da262f5ef1a1f76
use codespan_reporting::diagnostic::{Diagnostic, Severity}; use hotg_rune_compiler::{ BuildContext, Diagnostics, FeatureFlags, hooks::{ AfterCodegenContext, AfterLoweringContext, AfterTypeCheckingContext, Continuation, Hooks, }, lowering::{Model, Name, Resource, ResourceData}, }; use l...
use codespan_reporting::diagnostic::{Diagnostic, Severity}; use hotg_rune_compiler::{ BuildContext, Diagnostics, FeatureFlags, hooks::{ AfterCodegenContext, AfterLoweringContext, AfterTypeCheckingContext, Continuation, Hooks, }, lowering::{Model, Name, Resource, ResourceData}, }; use l...
} fn warn_about_every_model_in_the_rune(ctx: &mut dyn AfterLoweringContext) { let mut diags = ctx.diagnostics_mut(); let mut model_names = <&Name>::query().filter(component::<Model>()); for name in model_names.iter(ctx.world()) { let msg = format!("The Rune contains a model called \"{}\"", name);...
match core::str::from_utf8(&file.data) { Ok(string) => { for line in string.lines() { writeln!(msg, "\t{}", line).unwrap(); } }, Err(_) => writeln!(msg, "\t(binary)").unwrap(), } log::...
function_block-function_prefix_line
[ { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let filename = std::env::args()\n\n .nth(1)\n\n .expect(\"Usage: validate-runefile-schema <runefile>\");\n\n\n\n let src = std::fs::read_to_string(&filename)?;\n\n let document: Value = serde_yaml::from_str(&src)?;\n\n\n\n let...
Rust
src/config/types.rs
fossabot/gh-trs
37a2f1c4292915104bc7b328bc02e368a03fe9e5
use crate::github_api; use crate::raw_url; use crate::remote; use anyhow::{anyhow, Context, Result}; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; use std::collections::HashMap; use std::fmt; use std::path::{Path, PathBuf}; use url::Url; use uuid::Uuid; #[skip_serializing_none] #[derive(...
use crate::github_api; use crate::raw_url; use crate::remote; use anyhow::{anyhow, Context, Result}; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; use std::collections::HashMap; use std::fmt; use std::path::{Path, PathBuf}; use url::Url; use uuid::Uuid; #[skip_serializing_none] #[derive(...
fault(); assert_eq!(testing.id, "test_1"); assert_eq!(testing.files.len(), 3); Ok(()) } #[test] fn test_test_file_new() -> Result<()> { let url = Url::parse("https://example.com/path/to/file.txt")?; let target = Some(PathBuf::from("path/to/file.txt")); let fi...
)) } } #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum TestFileType { WfParams, WfEngineParams, Other, } #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub struct Zenodo { pub url: Url, pub id: u64, pub doi: String, pu...
random
[ { "content": "pub fn wf_url(wf: &config::types::Workflow) -> Result<String> {\n\n let primary_wf = wf.primary_wf()?;\n\n match wf.language.r#type.clone().unwrap() {\n\n config::types::LanguageType::Nfl => {\n\n let file_name = match primary_wf.target.unwrap().to_str() {\n\n ...
Rust
cargo-fuzzcheck/src/ui/app.rs
binier/fuzzcheck-rs
68e5dcf7665c0e3fc27b443237140f11f3138369
use std::{path::PathBuf, rc::Rc, sync::mpsc::Sender}; use project::FullConfig; use termion::event::Key; use tui::{ backend::Backend, layout::{Constraint, Direction, Layout, Rect}, style::{Color, Style}, widgets::Paragraph, Frame, }; use crate::project::{self, Root}; use crate::ui::framework::View...
use std::{path::PathBuf, rc::Rc, sync::mpsc::Sender}; use project::FullConfig; use termion::event::Key; use tui::{ backend::Backend, layout::{Constraint, Direction, Layout, Rect}, style::{Color, Style}, widgets::Paragraph, Frame, }; use crate::project::{self, Root}; use crate::ui::framework::View...
idget(explain_text, chunks[2]); } } impl ParentView<preinit::PreInitView> for State { fn convert_child_update(update: <preinit::PreInitView as ViewState>::Update) -> Self::Update { Self::Update::PreInit(update) } fn convert_to_child_in_message( message: &Self::InMessage, ) -> Optio...
root_path: root_path.clone(), phase: Phase::PreInit(state), sender, }, Err(err) => { let state = error_view::ErrorView::new(Box::new(err)); State { root_path: root_path.clone(), ...
random
[ { "content": "fn fuzz_targets_from_root(root: &Root) -> Vec<String> {\n\n let mut targets = root\n\n .fuzz\n\n .non_instrumented\n\n .fuzz_targets\n\n .targets\n\n .keys()\n\n .map(|k| {\n\n let target = PathBuf::from(k);\n\n target.file_stem()....
Rust
src/main.rs
Pfeil/herosheet
09790f77fd5063d00a223ee4c6f7fac5d61185fe
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket::{ State, http::Status, response::Redirect, form::{Context, Contextual, Form, FromForm}, }; use rocket_dyn_templates::Template; use serde::{Deserialize, Serialize}; #[derive(Debug, FromForm, Serialize, Deseria...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket::{ State, http::Status, response::Redirect, form::{Context, Contextual, Form, FromForm}, }; use rocket_dyn_templates::Template; use serde::{Deserialize, Serialize}; #[derive(Debug, FromForm, Serialize, Deseria...
#[derive(Deserialize)] struct CharacterDirectory{ character_directory: String, } impl CharacterDirectory { fn as_str(&self) -> &str { self.character_directory.as_str() } } #[launch] fn rocket() -> _ { use rocket::fairing::AdHoc; use rocket::fs; rocket::build() .attach(AdHoc:...
er.as_str()) { error!("ERROR: Failed storing character. {:?}", e); } Template::render("index", &form.context) } None => Template::render("index", &form.context), }; (form.context.status(), template) }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn test_good_forms() {\n\n let client = Client::tracked(rocket()).unwrap();\n\n let mut input = FormInput {\n\n checkbox: true,\n\n number: 310,\n\n radio: FormOption::A,\n\n password: \"beep\".into(),\n\n text_area: \"bop\".to_string(),\n\n ...
Rust
src/messages/uri.rs
mikelodder7/aries-core-rs
c282eaf349fe9c1b1805093389c3f446a2edf165
/* * Copyright 2020 * * 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 agreed to in writing, ...
/* * Copyright 2020 * * 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 agreed to in writing, ...
}
fn message_uri_test() { println!(r#"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping"#); let res = MessageTypeUri::from_str(r#"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping"#); println!("{:?}", res); assert!(res.is_ok()); let msg = res.unwrap(); ...
function_block-full_function
[ { "content": "/// All enclaves structs should use this trait so the callers\n\n/// can simply use them without diving into the details\n\n/// for each unique configuration. This trait is meant\n\n/// to be used by the non-security minded and should be hard\n\n/// to mess up––misuse resistant.\n\npub trait Encla...
Rust
src/framework/src/model.rs
ktmlm/KKcloud
28432dd3187233cb8fab2c5d27e330cfc4a2f989
use crate::err::*; use ruc::*; use serde::{Deserialize, Serialize}; use std::{ collections::{HashMap, HashSet}, fmt::Debug, fs, mem, path::{Path, PathBuf}, sync::Arc, }; pub type Id = u64; pub const DEFAULT_ID: Id = 0; pub type EnvId = Id; pub type VmId = Id; pub type UserId = String; pub ty...
use crate::err::*; use ruc::*; use serde::{Deserialize, Serialize}; use std::{ collections::{HashMap, HashSet}, fmt::Debug, fs, mem, path::{Path, PathBuf}, sync::Arc, }; pub type Id = u64; pub const DEFAULT_ID: Id = 0; pub type EnvId = Id; pub type VmId = Id; pub type UserId = String; pub ty...
} pub trait Network { fn set_net(&self, vm: &mut Vm) -> Result<()>; fn unset_net(&self, vm: &mut Vm) -> Result<()>; fn deny_outgoing(&self, vm: &mut Vm) -> Result<()>; fn allow_outgoing(&self, vm: &mut Vm) -> Result<()>; fn set_blacklist(&self, vm: &mut Vm) -> Resul...
fn apply_snapshot(&mut self, vm: &mut Vm, name: &str) -> Result<()> { self.stop_vm(vm) .and_then(|_| { let snapshot = vm.snapshots.get(name).ok_or(eg!())?; let mut cached_vm = self .restore_from_meta(&snapshot.meta_path) .c(e!(E...
function_block-function_prefix_line
[]
Rust
src/transform/desugar_destructuring.rs
markshust/nickel
d7e5a4ad1ad10171afd3c7c9a814d624f142064f
use crate::destruct::{Destruct, Match}; use crate::identifier::Ident; use crate::match_sharedterm; use crate::term::make::{op1, op2}; use crate::term::{ BinaryOp::DynRemove, BindingType, MetaValue, RichTerm, Term, UnaryOp::StaticAccess, }; pub fn transform_one(rt: RichTerm) -> RichTerm { match *rt.term { ...
use crate::destruct::{Destruct, Match}; use crate::identifier::Ident; use crate::match_sharedterm; use crate::term::make::{op1, op2}; use crate::term::{ BinaryOp::DynRemove, BindingType, MetaValue, RichTerm, Term, UnaryOp::StaticAccess, }; pub fn transform_one(rt: RichTerm) -> RichTerm { match *rt.term { ...
let pos = body.pos; match pat { Destruct::Record { matches, .. } => matches.iter().fold(body, move |t, m| match m { Match::Simple(id, _) => RichTerm::new( Term::Let( id.clone(), op1(StaticAccess(id.clone()), Term::Var(x.clone())), ...
rest: Some(x), .. } => (matches, x.clone()), Destruct::Record { matches, open: true, rest: None, .. } => (matches, super::fresh_var()), Destruct::Record { open: false, rest: None, .....
random
[ { "content": "/// Apply the full free var transformation on a term.\n\npub fn transform(rt: &mut RichTerm) {\n\n collect_free_vars(rt, &mut HashSet::new())\n\n}\n\n\n", "file_path": "src/transform/free_vars.rs", "rank": 2, "score": 256422.11469726992 }, { "content": "/// Remove the variab...
Rust
pac/atsame54p/src/sercom0/i2cs/status.rs
theatrus/atsamd
8c4035668064609ff1561e32e17e92165cb70187
#[doc = "Reader of register STATUS"] pub type R = crate::R<u16, super::STATUS>; #[doc = "Writer for register STATUS"] pub type W = crate::W<u16, super::STATUS>; #[doc = "Register STATUS `reset()`'s with value 0"] impl crate::ResetValue for super::STATUS { type Type = u16; #[inline(always)] fn reset_value() ...
#[doc = "Reader of register STATUS"] pub type R = crate::R<u16, super::STATUS>; #[doc = "Writer for register STATUS"] pub type W = crate::W<u16, super::STATUS>; #[doc = "Register STATUS `reset()`'s with value 0"] impl crate::ResetValue for super::STATUS { type Type = u16; #[inline(always)] fn reset_value() ...
ets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn ...
lf.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u16) & 0x01) << 3); self.w } } #[doc = "Reader of field `SR`"] pub type SR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SR`"] pub struct SR_W<'a> { w: &'a mut W, } impl<'a> SR_W<'a> { #[doc = r"Sets the field bit"] #[inline(alwa...
random
[]
Rust
cardano/src/hash.rs
nahern/rust-cardano
03fc923641808361273f1645eef221fdf908f5cf
use std::{fmt, result, str::{FromStr}, ops::{Deref}}; use cryptoxide::digest::Digest; use cryptoxide::blake2b::Blake2b; use cryptoxide::sha3::Sha3; use util::{hex, try_from_slice::{TryFromSlice}}; use cbor_event::{self, de::RawCbor}; #[cfg(feature = "generic-serialization")] use serde; #[derive(Debug, PartialEq, ...
use std::{fmt, result, str::{FromStr}, ops::{Deref}}; use cryptoxide::digest::Digest; use cryptoxide::blake2b::Blake2b; use cryptoxide::sha3::Sha3; use util::{hex, try_from_slice::{TryFromSlice}}; use cbor_event::{self, de::RawCbor}; #[cfg(feature = "generic-serialization")] use serde; #[derive(Debug, PartialEq, ...
Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] pub struct Sha3_256([u8;HASH_SIZE_256]); define_hash_object!(Sha3_256, Sha3_256, HASH_SIZE_256); impl Sha3_256 { pub fn new(buf: &[u8]) -> Self { let mut sh3 = Sha3::sha3_256(); let mut out = [0;Self::HASH_SIZE]; sh3.input(buf.as_ref()); ...
type Target = [u8; Self::HASH_SIZE]; fn deref(&self) -> &Self::Target { &self.0 } } impl AsRef<[u8]> for $hash_ty { fn as_ref(&self) -> &[u8] { self.0.as_ref() } } impl From<$hash_ty> for [u8;$hash_size] { fn from(bytes: $hash_ty) -> Self { b...
random
[ { "content": "// write size to the mutable buffer in big endian\n\npub fn write_size(buf: &mut [u8], sz: Size) {\n\n buf[0] = (sz >> 24) as u8;\n\n buf[1] = (sz >> 16) as u8;\n\n buf[2] = (sz >> 8) as u8;\n\n buf[3] = sz as u8;\n\n}\n\n\n", "file_path": "storage/src/utils/serialize.rs", "ran...
Rust
src/wrapper/build.rs
rowhit/vagga
ab6ff2027edfee64843be6a734a47e5fb5903e79
use std::env; use std::fs::{File, read_link}; use std::io::Write; use std::ffi::OsString; use std::io::ErrorKind::NotFound; use std::ascii::AsciiExt; use std::fs::{rename}; use std::fs::{remove_file, remove_dir}; use std::io::{stdout, stderr}; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}; use std::os:...
use std::env; use std::fs::{File, read_link}; use std::io::Write; use std::ffi::OsString; use std::io::ErrorKind::NotFound; use std::ascii::AsciiExt; use std::fs::{rename}; use std::fs::{remove_file, remove_dir}; use std::io::{stdout, stderr}; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}; use std::os:...
pub fn commit_root(tmp_path: &Path, final_path: &Path) -> Result<(), String> { let mut path_to_remove = None; if final_path.exists() { let rempath = tmp_path.with_file_name( tmp_path.file_name().unwrap().to_str() .unwrap().to_string() + ".old"); if rempath....
oot_dir(path: &Path) -> Result<(), String> { if path.exists() { try!(clean_dir(path, true) .map_err(|x| format!("Error removing directory: {}", x))); } try_msg!(create_dir(path, true), "Error creating directory: {err}"); let rootdir = path.join("root"); try_msg!(create_...
function_block-function_prefixed
[ { "content": "pub fn namespace_dir() -> PathBuf {\n\n let uid = unsafe { geteuid() };\n\n env::var(\"XDG_RUNTIME_DIR\")\n\n .map(|v| Path::new(&v).join(\"vagga\"))\n\n .unwrap_or(PathBuf::from(format!(\"/tmp/vagga-{}\", uid)))\n\n}\n\n\n", "file_path": "src/launcher/network.rs", "ran...
Rust
src/explorer/parallel_list.rs
dan-zheng/telamon
de463284fdcea70ce29cf43a9c62f3aa2da14276
pub use crate::explorer::candidate::Candidate; use crate::device::Context; use crate::explorer::choice; use crate::explorer::store::Store; use interval_heap::IntervalHeap; use log::{info, warn}; use rpds::List; use std; use std::f64; use utils::unwrap; impl Store for ParallelCandidateList { type PayLoad = (); ...
pub use crate::explorer::candidate::Candidate; use crate::device::Context; use crate::explorer::choice; use crate::explorer::store::Store; use interval_heap::IntervalHeap; use log::{info, warn}; use rpds::List; use std; use std::f64; use utils::unwrap; impl Store for ParallelCandidateList { type PayLoad = (); ...
self.n_candidate, x.depth, x.bound.value(), self.cut, self.queue.len(), self.n_leaf); } candidate } fn drop_candidate(&mut self, candidate: &Candidate) { info!( "dropping candidate: {:.4e}ns >= {:.4e}ns.", candidate.bound.value(), ...
{ } fn explore(&self, context: &dyn Context) -> Option<(Candidate, Self::PayLoad)> { loop { if let Some(candidate) = self.pop() { let choice_opt = choice::default_list(&candidate.space).next(); if let Some(choice) = choice_opt { self.inse...
random
[ { "content": "/// Compare two f64, panic if one of them is nan\n\npub fn cmp_f64(a: f64, b: f64) -> std::cmp::Ordering {\n\n if a.is_nan() || b.is_nan() {\n\n panic!(\"Comparing a nan !\");\n\n }\n\n\n\n if a < b {\n\n std::cmp::Ordering::Less\n\n } else if (a - b).abs() < std::f64::EP...
Rust
src/queues/centralized_autoscaling_qnetwork.rs
marceleng/queueing-network-simulator
1671d1bb4aa191c636ce56bff7152e75a22a2483
use std::vec::Vec; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use queues::queueing_network::{QNet,Transition,TransitionError}; use queues::Queue; use queues::mg1ps::MG1PS; use queues::mginf::MGINF; use queues::file_logger::FileLogger; use queues::request::Request; use helpers::distribution::Mut...
use std::vec::Vec; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use queues::queueing_network::{QNet,Transition,TransitionError}; use queues::Queue; use queues::mg1ps::MG1PS; use queues::mginf::MGINF; use queues::file_logger::FileLogger; use queues::request::Request; use helpers::distribution::Mut...
} impl Queue for ScalingSchedule { fn arrival (&mut self, _: Request) { panic!("You should not arrive in this queue"); } fn update_time (&mut self, _time: f64) {} fn read_next_exit (&self) -> Option<(f64,&Request)> { match self.1 { None=>None, Some((t, ref r)) => Some((t,...
pub fn from_csv (filename: &'static str, delimiter: char) -> Self { let mut ret = ScalingSchedule { 0: FloatBinaryHeap::new(), 1: None }; let sched_csv = File::open(filename).unwrap(); let buf_read = BufReader::new(sched_csv); for line in buf_read.lines(...
function_block-full_function
[ { "content": "#[derive(PartialEq,Clone,Debug)]\n\nstruct _Request {\n\n id: usize,\n\n content: usize,\n\n log: Vec<(LogKey, LogEntry)>,\n\n}\n\n\n\nimpl Request {\n\n pub fn new (content: usize) -> Self {\n\n Request { 0: Box::new(_Request::new(content)) }\n\n }\n\n\n\n pub fn get_cont...
Rust
common/functions/src/aggregators/aggregator_test.rs
tlightsky/fuse-query
94626a4d50d9afda2b8b7ee2e32ba8a2c7831780
use common_exception::Result; #[test] fn test_aggregator_function() -> Result<()> { use std::sync::Arc; use common_datablocks::DataBlock; use common_datavalues::*; use pretty_assertions::assert_eq; use crate::aggregators::*; use crate::arithmetics::*; use crate::*; #[allow(dead_cod...
use common_exception::Result; #[test] fn test_aggregator_function() -> Result<()> { use std::sync::Arc; use common_datablocks::DataBlock; use common_datavalues::*; use pretty_assertions::assert_eq; use crate::aggregators::*; use crate::arithmetics::*; use crate::*; #[allow(dead_cod...
let schema = Arc::new(DataSchema::new(vec![ DataField::new("a", DataType::Int64, false), DataField::new("b", DataType::Int64, false), ])); let block = DataBlock::create(schema.clone(), vec![ Arc::new(Int64Array::from(vec![4, 3, 2, 1])), Arc::new(Int64Array::from(vec![1, 2, 3, 4])...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_data_block() -> anyhow::Result<()> {\n\n use std::sync::Arc;\n\n\n\n use common_datavalues::*;\n\n\n\n use crate::DataBlock;\n\n\n\n let schema = Arc::new(DataSchema::new(vec![DataField::new(\n\n \"a\",\n\n DataType::Int64,\n\n false\n\n )]));...
Rust
src/main.rs
tommythorn/bevmnist
d03d3cd7ad1e7ecdc3307d23c2a9c010b5d1a887
use bevy::{ asset::{AssetLoader, LoadContext, LoadedAsset}, prelude::*, type_registry::TypeUuid, utils::BoxedFuture, }; use tract_onnx::prelude::*; #[derive(Debug, TypeUuid)] #[uuid = "39cadc56-aa9c-4543-8640-a018b7fff052"] pub struct OnnxModel { pub model: SimplePlan< TypedFact, Bo...
use bevy::{ asset::{AssetLoader, LoadContext, LoadedAsset}, prelude::*, type_registry::TypeUuid, utils::BoxedFuture, }; use tract_onnx::prelude::*; #[derive(Debug, TypeUuid)] #[uuid = "39cadc56-aa9c-4543-8640-a018b7fff052"] pub struct OnnxModel { pub model: SimplePlan< TypedFact, Bo...
if val > pixel_size * pixel_size / 2 { 1. as f32 } else { 0. as f32 } }) .into(); if let Some(model) = models.get(state.model.as_ref().unwrap()) { let result = model.model.run(tvec!(image)).unwrap(); if let Some((v...
function_block-function_prefix_line
[ { "content": "# bevmnist\n\n\n\nRunning MNIST inference in [bevy](https://github.com/bevyengine/bevy) with [tract](https://github.com/sonos/tract). And in wasm!\n\n\n\n![demo](https://raw.githubusercontent.com/vleue/bevmnist/main/demo.gif)\n\n\n\n\n\n## Optional Setup\n\nTo install the required target, WASM uti...
Rust
src/vendor/mdbook/src/bin/mdbook.rs
ryoon/rustc-1.19.0
4ca47e69f710b93580101782576ebad2bef64749
extern crate mdbook; #[macro_use] extern crate clap; extern crate log; extern crate env_logger; extern crate open; #[cfg(feature = "watch")] extern crate notify; #[cfg(feature = "watch")] extern crate time; #[cfg(feature = "watch")] extern crate crossbeam; #[cfg(feature = "serve")] extern crate iron; #[cfg(feature = ...
extern crate mdbook; #[macro_use] extern crate clap; extern crate log; extern crate env_logger; extern crate open; #[cfg(feature = "watch")] extern crate notify; #[cfg(feature = "watch")] extern crate time; #[cfg(feature = "watch")] extern crate crossbeam; #[cfg(feature = "serve")] extern crate iron; #[cfg(feature = ...
; Ok(()) } fn test(args: &ArgMatches) -> Result<(), Box<Error>> { let book_dir = get_book_dir(args); let mut book = MDBook::new(&book_dir).read_config(); try!(book.test()); Ok(()) } fn get_book_dir(args: &ArgMatches) -> PathBuf { if let Some(dir) = args.value_of("dir") { le...
trigger_on_change(&mut book, move |path, book| { println!("File changed: {:?}\nBuilding book...\n", path); match book.build() { Err(e) => println!("Error while building: {:?}", e), _ => broadcaster.send(RELOAD_COMMAND).unwrap(), } println!(""); })
call_expression
[]
Rust
day07/src/lib.rs
jwarwick/aoc_2018
1b5b7578b3999ed85e787768588f0b30bff94b9d
extern crate util; #[macro_use] extern crate scan_fmt; use std::collections::HashSet; use std::collections::HashMap; type NodeType = HashMap<char, (bool, HashSet<char>)>; #[derive(Debug, Clone)] struct Graph { nodes: NodeType, } impl Graph { fn new() -> Graph { Graph {nodes: HashMap::new()} } ...
extern crate util; #[macro_use] extern crate scan_fmt; use std::collections::HashSet; use std::collections::HashMap; type NodeType = HashMap<char, (bool, HashSet<char>)>; #[derive(Debug, Clone)] struct Graph { nodes: NodeType, } impl Graph { fn new() -> Graph { Graph {nodes: HashMap::new()} } ...
fn remove_edges_from(c: char, nodes: &mut NodeType) { for (_claim, val) in nodes.values_mut() { val.remove(&c); } } fn claim(c: char, nodes: &mut NodeType) { if let Some((claim, _val)) = nodes.get_mut(&c) { *claim = true; } } fn next_node(n...
fn topo_sort(&self) -> String { let mut n = self.nodes.clone(); let mut output: String = String::new(); while !n.is_empty() { let s = Graph::next_node(&mut n).expect("Didn't find an edge node"); n.remove(&s); Graph::remove_edges_from(s, &mut n); o...
function_block-full_function
[ { "content": "fn is_close(a: &Vec<char>, b: &Vec<char>) -> bool {\n\n 1 == id_diff(&a, &b)\n\n}\n\n\n", "file_path": "day02/src/lib.rs", "rank": 1, "score": 196921.1999673818 }, { "content": "fn update_node(loc: &Location, nodes: &mut HashMap<Point, Node>) -> bool {\n\n let child_node ...
Rust
src/hooks/engine/mod.rs
YaLTeR/hls-autopause
407e47392aee8ef1ba070442e00e8b8c7ab51c3a
use features; use function::Function; use hookable::*; use libc; use libc::*; use moduleinfo::ModuleInfo; use std::{mem, ptr}; use std::sync::RwLock; use winapi; pub mod icvar; use self::icvar::*; lazy_static! { pub static ref MODULE: RwLock<EngineModule> = RwLock::new(EngineModule::default()); static ref DAT...
use features; use function::Function; use hookable::*; use libc; use libc::*; use moduleinfo::ModuleInfo; use std::{mem, ptr}; use std::sync::RwLock; use winapi; pub mod icvar; use self::icvar::*; lazy_static! { pub static ref MODULE: RwLock<EngineModule> = RwLock::new(EngineModule::default()); static ref DAT...
fn unhook(&mut self) { let mut pointers = POINTERS.write().unwrap(); unhook!("server", pointers, Host_Spawn_f, Host_UnPause_f ); *DATA.write().unwrap() = Data::default(); *pointers = Engine::default(); *self = Self::default(); } } impl...
fn hook(&mut self, module_info: &ModuleInfo) { self.module_info = Some(module_info.clone()); self.current_name_index = self.compute_current_name_index(module_info); debug!(target: "engine", "Base: {:p}; size = {}", module_info.base, module_info.size); let addr_Cbuf_AddText = module_in...
function_block-full_function
[ { "content": "type FnCommandCompletionCallback = extern \"C\" fn(partial: *const c_char,\n\n commands: *const *mut c_char)\n\n -> c_int;\n\n\n\n#[repr(C)]\n\npub struct ConCommand {\n\n pub base: ConCommandBase,\n...
Rust
src/timer.rs
nebelgrau77/pcf8563-rs
5edbea14ae4eb2dbf2771a30c8b034bf4991e886
use super::{PCF8563, DEVICE_ADDRESS, hal, Error, Register, BitFlags, Control}; use hal::blocking::i2c::{Write, WriteRead}; #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[repr(u8)] pub enum TimerFreq { Timer_4096Hz = 0b0000_0000, Timer_64Hz = 0b0000_0001, ...
use super::{PCF8563, DEVICE_ADDRESS, hal, Error, Register, BitFlags, Control}; use hal::blocking::i2c::{Write, WriteRead}; #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[repr(u8)] pub enum TimerFreq { Timer_4096Hz = 0b0000_0000, Timer_64Hz = 0b0000_0001, ...
/* USE THIS EXAMPLE FOR GET_TIMER_FREQUENCY() ? pub fn get_square_wave_output_rate(&mut self) -> Result<SQWOUTRateBits, Error<E>> { let data = self.read_register(Register::SQWOUT)?; Ok(SQWOUTRateBits { rs0: (data & BitFlags::OUTRATERS0) != 0, ...
pub fn get_timer(&mut self) -> Result<u8, Error<E>> { let mut data = [0]; self.i2c .write_read(DEVICE_ADDRESS, &[Register::TIMER], &mut data) .map_err(Error::I2C)?; Ok(data[0]) }
function_block-full_function
[ { "content": "/// Convert the decimal value to Binary Coded Decimal.\n\nfn encode_bcd(input: u8) -> u8 {\n\n let digits: u8 = input%10;\n\n let tens: u8 = input/10;\n\n let tens = tens << 4;\n\n tens + digits\n\n }\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use embedded_hal_mock as hal;\n\n \n\...
Rust
rubullet/examples/create_multi_body_batch.rs
neachdainn/rubullet
43c54498b3e6495aa3ecd77769dd0b0e4c141d43
use std::time::Duration; use anyhow::Result; use nalgebra::{Isometry3, Vector3}; use rubullet::DebugVisualizerFlag::{CovEnableGui, CovEnableRendering, CovEnableTinyRenderer}; use rubullet::*; fn main() -> Result<()> { let mut physics_client = PhysicsClient::connect(Mode::Gui)?; physics_client.set_additional...
use std::time::Duration; use anyhow::Result; use nalgebra::{Isometry3, Vector3}; use rubullet::DebugVisualizerFlag::{CovEnableGui, CovEnableRendering, CovEnableTinyRenderer}; use rubullet::*; fn main() -> Result<()> { let mut physics_client = PhysicsClient::connect(Mode::Gui)?; physics_client.set_additional...
_scaling, }, None, )?; let tex_uid = physics_client.load_texture("tex256.png")?; let mut batch_positions = Vec::with_capacity(32 * 32 * 10 * 3); for x in 0..32 { for y in 0..32 { for z in 0..10 { batch_positions.push(Vector3::new( ...
r(CovEnableRendering, false); physics_client.configure_debug_visualizer(CovEnableGui, false); physics_client.configure_debug_visualizer(CovEnableTinyRenderer, false); let shift = Isometry3::translation(0.0, -0.02, 0.0); let mesh_scaling = Vector3::from_element(0.1); let vertices = vec![ [-...
random
[ { "content": "fn main() -> Result<()> {\n\n let mut physics_client = PhysicsClient::connect(Mode::Gui)?;\n\n physics_client.set_additional_search_path(\"../rubullet-sys/bullet3/libbullet3/data\")?;\n\n physics_client.load_urdf(\"plane.urdf\", None)?;\n\n let cube_id = physics_client.load_urdf(\n\n ...
Rust
autd3-emulator-server/src/parser.rs
shinolab/autd-emulator
a93d040ba54ccda3cd2bf34ad8e7d315f416d157
/* * File: parser.rs * Project: src * Created Date: 29/04/2020 * Author: Shun Suzuki * ----- * Last Modified: 17/12/2021 * Modified By: Shun Suzuki (suzuki@hapis.k.u-tokyo.ac.jp) * ----- * Copyright (c) 2020 Hapis Lab. All rights reserved. * */ use std::{mem::size_of, vec}; use autd3_core::{ hardware_d...
/* * File: parser.rs * Project: src * Created Date: 29/04/2020 * Author: Shun Suzuki * ----- * Last Modified: 17/12/2021 * Modified By: Shun Suzuki (suzuki@hapis.k.u-tokyo.ac.jp) * ----- * Copyright (c) 2020 Hapis Lab. All rights reserved. * */ use std::{mem::size_of, vec}; use autd3_core::{ hardware_d...
} else { None } } } fn parse_as_gain_sequence(&mut self, buf: &[u8]) -> Option<GainSequence> { unsafe { let header = buf.as_ptr() as *const GlobalHeader; let seq_begin = (*header).cpu_flag.contains(CPUControlFlags::SEQ_BEGIN); ...
Some(PointSequence { seq_div: self.point_seq_div as u32 + 1, seq_data: self.point_seq_buf.take().unwrap(), wavelength: self.wavelength, })
call_expression
[ { "content": "pub fn quaternion_to(vec: Vector3, to: Vector3) -> Quaternion {\n\n let a = vecmath::vec3_normalized(vec);\n\n let b = vecmath::vec3_normalized(to);\n\n\n\n let c = vecmath::vec3_cross(b, a);\n\n let c = vecmath::vec3_normalized(c);\n\n if !vec3_is_valid(c) {\n\n return (1.0,...
Rust
src/input/parser.rs
Maxgy/kingslayer
0cfb0d5b4c894fd0b73e7099521f77c2499b76c6
use crate::{ cli::Cli, input::CmdTokens, player::Player, types::{Action, CmdResult}, world::World, }; #[derive(Debug)] pub struct Parser; impl Parser { fn parse_attack( verb: &str, words: &CmdTokens, world: &mut World, player: &mut Player, ) -> CmdResult { ...
use crate::{ cli::Cli, input::CmdTokens, player::Player, types::{Action, CmdResult}, world::World, }; #[derive(Debug)] pub struct Parser; impl Parser { fn parse_attack( verb: &str, words: &CmdTokens, world: &mut World, player: &mut Player, ) -> CmdResult { ...
r: &mut Player, ) -> CmdResult { if let Some(obj) = words.obj() { world.insert(obj, player.remove(obj)) } else { CmdResult::do_what(verb) } } fn parse_equip(verb: &str, words: &CmdTokens, player: &mut Player) -> CmdResult { if let Some(obj) = words.ob...
let res = world.harm_enemy(obj, player.attack_with(obj_prep)); if res.is_active() { player.engage_combat() } res } else { CmdResult::no_comprendo() } } else if player.ma...
random
[ { "content": "pub fn read_line(prompt: &str) -> String {\n\n print!(\"{}\", prompt);\n\n io::stdout().flush().expect(\"Error flushing stdout\");\n\n\n\n let mut input = String::new();\n\n io::stdin()\n\n .read_line(&mut input)\n\n .expect(\"Error reading stdin\");\n\n input.trim().t...
Rust
diff/src/lib.rs
jneem/jp
eb02257954efbf4b1222e1f5d46cd167346eca36
#[cfg(test)] #[macro_use] extern crate proptest; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::hash::{Hash, Hasher}; mod lis; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum LineDiff { New(usize), Delete(usize), Keep(usize, usize), }...
#[cfg(test)] #[macro_use] extern crate proptest; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::hash::{Hash, Hasher}; mod lis; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum LineDiff { New(usize), Delete(usize), Keep(usize, usize), }...
; prev_b_idx = next_b_idx; prev_a_idx = next_a_idx; } let a_chunk = &a_mid[prev_a_idx..]; let b_chunk = &b_mid[prev_b_idx..]; diff_ends( a_chunk, pref_len + prev_a_idx, b_chunk, pref_len + prev_b_idx, &mut ret, ); for i in 0..suff_len { ...
diff_ends( a_chunk, pref_len + prev_a_idx, b_chunk, pref_len + prev_b_idx, &mut ret, )
call_expression
[ { "content": "pub fn run(m: &ArgMatches<'_>) -> Result<(), Error> {\n\n let repo = super::open_repo()?;\n\n let branch = super::branch(&repo, m);\n\n let file_name = super::file_path(m);\n\n\n\n let diff = diff(&repo, &branch, &file_name)?;\n\n print!(\"{}\", DiffDisplay(diff));\n\n\n\n Ok(())...
Rust
src/storage/meta/backend/rocksdb.rs
mattzque/rupee
8186cabbf0923c25c132164b12078f87abe64aca
use uuid::Uuid; use crate::storage::meta::{MetaStorageError, MetaStorage}; use crate::domain::meta::BlobMeta; use crate::storage::blob::{BlobRef, BlobStorage, BlobStorageError}; use std::any::Any; use std::collections::HashMap; use std::fmt; use std::fs; use std::sync::Arc; use std::path::{Path, PathBuf}; use std::us...
use uuid::Uuid; use crate::storage::meta::{MetaStorageError, MetaStorage}; use crate::domain::meta::BlobMeta; use crate::storage::blob::{BlobRef, BlobStorage, BlobStorageError}; use std::any::Any; use std::collections::HashMap; use std::fmt; use std::fs; use std::sync::Arc; use std::path::{Path, PathBuf}; use std::us...
pub fn new(config: RocksDbMetaStorageConfig) -> Result<Self, MetaStorageError> { let metas = DB::open_default(config.path.join("metas"))?; let blob_refs = DB::open_default(config.path.join("blob_refs"))?; Ok(Self { metas, blob_refs }) } } impl MetaStorage for RocksDbMetaStorage { ...
ig.path.is_dir() { if let Err(_) = fs::create_dir_all(&config.path) { return Err(MetaStorageError::CreateStorageError( "Error creating the blob storage directory!", )); } } Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn create_meta_storage(config: MetaStorageConfig) -> Result<Box<dyn MetaStorage>, MetaStorageError> {\n\n match config.storage_meta_type.as_ref() {\n\n \"mem\" => {\n\n Ok(Box::new(MemoryMetaStorage::new(config.storage_meta_mem)?))\n\n }\n\n \"rocksdb\" => {\...
Rust
src/client/stub/mod.rs
palfrey/reqwest_mock
b5bce84d2f2b8de3ba3c933edcd7d1ba6f16dffd
use body::Body; use client::Client; use config::ClientConfig; use error::Error; use request::{Request, RequestHeader}; use reqwest::header::Headers; use reqwest::{Method, StatusCode, Url}; use response::Response; use std::collections::{BTreeMap, HashMap}; mod settings; pub use self::settings::{StubDefault, StubSetting...
use body::Body; use client::Client; use config::ClientConfig; use error::Error; use request::{Request, RequestHeader}; use reqwest::header::Headers; use reqwest::{Method, StatusCode, Url}; use response::Response; use std::collections::{BTreeMap, HashMap}; mod settings; pub use self::settings::{StubDefault, StubSetting...
self.stubs.insert(key, response); Ok(()) } } impl Client for StubClient { fn execute(&self, config: Option<&ClientConfig>, request: Request) -> Result<Response, Error> { let header = request.header; let body = match request.body { Some(b) => Some(b.try_to_v...
let response = Response { url: key.url.clone(), status: value.status_code, headers: value.headers, body: value .body .map(|b| b.try_to_vec()) .unwrap_or_else(|| Ok(Vec::new())) .map_err(|e| RegisterStubError:...
assignment_statement
[ { "content": "pub fn serialize_headers(headers: &Headers) -> BTreeMap<String, String> {\n\n let tuples_iter = headers\n\n .iter()\n\n .map(|hv| (hv.name().to_string(), hv.value_string()));\n\n\n\n BTreeMap::<String, String>::from_iter(tuples_iter)\n\n}\n\n\n", "file_path": "src/helper.rs...
Rust
src/node.rs
cowprotocol/hdnode
37b9594694b9af6cea8b416d184f0ebd843197a7
pub mod eth; pub mod transaction; pub mod typeddata; pub mod types; use self::{eth::Eth, transaction::TransactionRequest, typeddata::TypedData}; use crate::{ jsonrpc::{self, Id, JsonRpc, Params, Request, Response}, serialization::{Addresses, Bytes, NoParameters}, signer::{wallet::UnknownSignerError, BoxS...
pub mod eth; pub mod transaction; pub mod typeddata; pub mod types; use self::{eth::Eth, transaction::TransactionRequest, typeddata::TypedData}; use crate::{ jsonrpc::{self, Id, JsonRpc, Params, Request, Response}, serialization::{Addresses, Bytes, NoParameters}, signer::{wallet::UnknownSignerError, BoxS...
uest.jsonrpc, result: Ok(value), id: request.id, }), Ok(Handled::Remote(method, params)) => Outcome::Remote(Request { jsonrpc: request.jsonrpc, method, params, id: request.id, }), ...
t.params.clone()) .await { Ok(Handled::Internal(value)) => Outcome::Internal(Response { jsonrpc: req
function_block-random_span
[ { "content": "/// Prepares a request.\n\nfn prepare(method: &'static str, params: impl Serialize) -> Result<Request> {\n\n let params = match serde_json::to_value(params)? {\n\n Value::Array(array) => Params::Array(array),\n\n other => bail!(\"invalid Ethereum JSON RPC parameters {other}\"),\n\...
Rust
src/decode.rs
kphelps/avro-rs
dd707216707a16ee225d338675a5ca1c9948d1e9
use std::collections::HashMap; use std::io::Read; use std::mem::transmute; use failure::Error; use crate::schema::{FullSchema, Schema, SchemaTypes, UnionRef}; use crate::types::Value; use crate::util::{safe_len, zag_i32, zag_i64, DecodeError}; #[inline] fn decode_long<R: Read>(reader: &mut R) -> Result<Value, Error>...
use std::collections::HashMap; use std::io::Read; use std::mem::transmute; use failure::Error; use crate::schema::{FullSchema, Schema, SchemaTypes, UnionRef}; use crate::types::Value; use crate::util::{safe_len, zag_i32, zag_i64, DecodeError}; #[inline] fn decode_long<R: Read>(reader: &mut R) -> Result<Value, Error>...
}, Schema::Record(ref record) => { let mut items = Vec::new(); for field in &record.fields { let x = (field.name.clone(), decode_with_context(&field.schema, types, reader)?); items.push(x); } O...
match variants.get(index as usize) { Some(variant) => { let union_ref = UnionRef::from_schema(variant); decode_with_context(variant, types, reader) .map(|x| Value::Union(union_ref, Box::new(x))) } None => Err...
if_condition
[ { "content": "pub fn zag_i64<R: Read>(reader: &mut R) -> Result<i64, Error> {\n\n let z = decode_variable(reader)?;\n\n Ok(if z & 0x1 == 0 {\n\n (z >> 1) as i64\n\n } else {\n\n !(z >> 1) as i64\n\n })\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 5, "score": 254023.7917...
Rust
src/object.rs
bpandreotti/monkey-rust
970b808530495d94d1bb82a3787c198bcef3b7c7
use crate::builtins::BuiltinFn; use crate::compiler::code; use crate::interpreter::environment; use crate::parser::ast; use std::collections::HashMap; use std::convert::From; use std::fmt; #[derive(Debug, Clone)] #[cfg_attr(test, derive(PartialEq))] pub enum Object { Nil, Integer(i64), Boolean(bool), ...
use crate::builtins::BuiltinFn; use crate::compiler::code; use crate::interpreter::environment; use crate::parser::ast; use std::collections::HashMap; use std::convert::From; use std::fmt; #[derive(Debug, Clone)] #[cfg_attr(test, derive(PartialEq))] pub enum Object { Nil, Integer(i64), Boolean(bool), ...
il, Object::Nil) => Some(true), (Object::Integer(l), Object::Integer(r)) => Some(l == r), (Object::Boolean(l), Object::Boolean(r)) => Some(l == r), (Object::Str(l), Object::Str(r)) => Some(l == r), _ => None, } } } impl From<&str> for Object { fn from(s: ...
let mut keys_sorted = h.keys().collect::<Vec<_>>(); keys_sorted.sort(); write!(f, "{}: {}", keys_sorted[0], h[keys_sorted[0]])?; for key in &keys_sorted[1..] { write!(f, ", {}: {}", key, h[key])?; } write!(f, "}}"...
random
[ { "content": "pub fn eval_index_expression(object: &Object, index: &Object) -> Result<Object, RuntimeError> {\n\n // This function is pub because the \"get\" built-in needs to call it\n\n match (object, index) {\n\n (Object::Array(vector), Object::Integer(i)) => {\n\n if *i < 0 || *i >= ...
Rust
src/deflate_stream.rs
mayamaclean/deflate_stream
8ac55caa51bf397bdb0144963b160e9e9e458ae0
use crossbeam_channel::RecvTimeoutError; use crossbeam_channel::RecvError; use crossbeam_channel::{Sender, unbounded}; use flamer::flame; use intmap::IntMap; use ordered_stream::OrderedStream; use rayon::{ThreadPool, ThreadPoolBuilder}; use std::io::{self, ErrorKind, Read, Write}; use std::os::raw::*; use std::sync::{A...
use crossbeam_channel::RecvTimeoutError; use crossbeam_channel::RecvError; use crossbeam_channel::{Sender, unbounded}; use flamer::flame; use intmap::IntMap; use ordered_stream::OrderedStream; use rayon::{ThreadPool, ThreadPoolBuilder}; use std::io::{self, ErrorKind, Read, Write}; use std::os::raw::*; use std::sync::{A...
; let mut dictionary = dicts.lock().expect("error locking dictionary map for write"); dictionary.insert(idx + 1, dict_to_add); drop(dictionary); let mut dict = None; if idx > 0 { loop { let mut dictionary = dicts.lock().ex...
if msg.len() < WINDOW_SIZE { msg.to_vec() } else { msg[msg.len() - WINDOW_SIZE..].to_vec() }
if_condition
[ { "content": "pub fn crc_stream<C: Crc32Calculator>(threads: usize) -> (CrcStreamW<C>, CrcStreamR<C>) {\n\n let (data_tx, data_rx) = unbounded::<(u64, Vec<u8>)>();\n\n let (tag_tx, tag_rx) = unbounded::<(u64, Vec<CrcRs>)>();\n\n\n\n let data_stream = OrderedStream::with_recvr(data_rx);\n\n let tag_s...
Rust
src/main.rs
franc90/worm
f72ced6ed8c10f8503d2bfe37e0761aeb6959c80
use std::cell::RefCell; use std::error::Error; use std::fs::File; use std::io::{self, BufReader, Read}; use std::path::Path; use std::rc::Rc; use clap::{App, Arg, ArgMatches}; use cursive::event::Event; use log::info; use rand::seq::SliceRandom; use rand::thread_rng; use simplelog::{Config, LevelFilter, WriteLogger}; ...
use std::cell::RefCell; use std::error::Error; use std::fs::File; use std::io::{self, BufReader, Read}; use std::path::Path; use std::rc::Rc; use clap::{App, Arg, ArgMatches}; use cursive::event::Event; use log::info; use rand::seq::SliceRandom; use rand::thread_rng; use simplelog::{Config, LevelFilter, WriteLogger}; ...
fn set_up_logger(debug_file: &str) { WriteLogger::init( LevelFilter::Info, Config::default(), File::create(debug_file).unwrap(), ) .unwrap(); } fn read_card_set( input_file: Option<&str>, shuffle_cards: bool, ) -> Result<Rc<RefCell<CardSet>>, Box<dyn Error>> { Ok(Rc::n...
fn parse_comman_line_args<'a>() -> ArgMatches<'a> { let matches = App::new("worm") .version(env!("CARGO_PKG_VERSION")) .about("WORd Memorizer") .arg( Arg::with_name("input") .value_name("INPUT") .help("JSON file with content; if not provided stdin ...
function_block-full_function
[ { "content": "pub fn display(siv: &mut Cursive, card_set: &CardSet) {\n\n update_optional_view(siv, TITLE_BAR, &card_set.get_title(), |view, text| {\n\n let title = format!(\n\n \"{}: {}/{}\",\n\n text,\n\n card_set.current_card + 1,\n\n card_set.cards_len()...
Rust
src/server.rs
tonlabs/ton-labs-adnl
b26695a94ddc88dc484ec6708df00692dd4f1360
use crate::{ dump, from_slice, common::{ AdnlHandshake, AdnlPeers, AdnlPingSubscriber, AdnlStream, AdnlStreamCrypto, deserialize, KeyId, KeyOption, KeyOptionJson, Query, serialize_inplace, Subscriber, TARGET, Timeouts } }; use std::{net::SocketAddr, sync::Arc, time::Duration}; use stream_ca...
use crate::{ dump, from_slice, common::{ AdnlHandshake, AdnlPeers, AdnlPingSubscriber, AdnlStream, AdnlStreamCrypto, deserialize, KeyId, KeyOption, KeyOptionJson, Query, serialize_inplace, Subscriber, TARGET, Timeouts } }; use std::{net::SocketAddr, sync::Arc, time::Duration}; use stream_ca...
async fn run( mut stream: AdnlStream, key: Arc<lockfree::map::Map<Arc<KeyId>, Arc<KeyOption>>>, clients: Arc<Option<lockfree::map::Map<[u8; 32], u8>>>, subscribers: Arc<Vec<Arc<dyn Subscriber>>> ) -> Result<()> { let mut buf = Vec::with_capacity(256); stream.rea...
async move { if let Err(e) = AdnlServerThread::run(stream, key, clients, subscribers).await { log::warn!(target: TARGET, "ERROR --> {}", e); return; } unreachable!(); } ); }
function_block-function_prefix_line
[ { "content": "/// Deserialize TL object from bytes\n\npub fn deserialize(bytes: &[u8]) -> Result<TLObject> {\n\n let mut reader = bytes;\n\n Deserializer::new(&mut reader).read_boxed::<TLObject>()\n\n}\n\n\n", "file_path": "src/common.rs", "rank": 0, "score": 137213.69228343095 }, { "c...
Rust
dmbc/src/currency/wallet/wallet.rs
rude69/blockchain
1f861b13531d4b3931d1cf3d4791366839896950
use exonum::encoding::Field; use currency::assets::AssetBundle; use currency::error::Error; encoding_struct! { #[derive(Eq, PartialOrd, Ord)] struct Wallet { balance: u64, assets: Vec<AssetBundle>, } } impl Wallet { pub fn new_empty() -> Self { Wallet::new(0, Vec::n...
use exonum::encoding::Field; use currency::assets::AssetBundle; use currency::error::Error; encoding_struct! { #[derive(Eq, PartialOrd, Ord)] struct Wallet { balance: u64, assets: Vec<AssetBundle>, } } impl Wallet { pub fn new_empty() -> Self { Wallet::new(0, Vec::n...
pub fn remove_assets<I>(&mut self, assets_to_remove: I) -> Result<(), Error> where I: IntoIterator<Item = AssetBundle>, { let mut assets = self.assets(); for to_remove in assets_to_remove { if let Some(index) = assets.iter_mut().position(|a| a.id() == to_remove.id(...
t() + new.amount(); *asset = AssetBundle::new(asset.id(), new_amount); } else { assets.push(new); } } *self = Wallet::new(self.balance(), assets); }
function_block-function_prefixed
[ { "content": "pub fn create_add_asset_tx(wallet: Wallet, assets: Vec<MetaAsset>) -> String {\n\n let tx = transaction::Builder::new()\n\n .keypair(wallet.public, wallet.secret.clone())\n\n .tx_add_assets()\n\n .add_asset_value(assets[0].clone())\n\n .build();\n\n\n\n serialize(...
Rust
src/main.rs
dpetersen/kv
9134598cd2c6fac6329a0e87cc16347a756b488b
use serde_json::Value; use std::collections::HashMap; use std::io::Read; use std::io::Write; use std::str::FromStr; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "basic")] struct Opt { #[structopt()] subcommand: Subcommand, #[structopt(short, long)] key: String, #[struct...
use serde_json::Value; use std::collections::HashMap; use std::io::Read; use std::io::Write; use std::str::FromStr; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "basic")] struct Opt { #[structopt()] subcommand: Subcommand, #[structopt(short, long)] key: String, #[struct...
9, kind: Other, message: "Bad file descriptor" }', src/libcore/result.rs:1165:5 stack backtrace: 0: backtrace::backtrace::libunwind::trace at /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.37/src/backtrace/libunwind.rs:88 1: backtrace::backtrace::trace_unsynchronized ...
::to_string(&map)?; std::fs::write("kv.db", jstr.as_bytes())?; Ok(()) } fn load_keys() -> std::io::Result<HashMap<String, String>> { let mut file = match std::fs::File::open("kv.db") { Ok(file) => file, Err(err) if err.kind() == std::io::ErrorKind::NotFound => std::fs::File::create("kv.db"...
random
[ { "content": "<h1 align=\"center\">Welcome to kv 👋</h1>\n\n<p>\n\n <a href=\"#\" target=\"_blank\">\n\n <img alt=\"License: MIT\" src=\"https://img.shields.io/badge/License-MIT-yellow.svg\" />\n\n </a>\n\n <a href=\"https://twitter.com/bketelsen\" target=\"_blank\">\n\n <img alt=\"Twitter: bketelsen\"...
Rust
src/main.rs
f-koehler/impromptu
7e5a4deb1b1f78178c195309f26e9fe429e50296
extern crate chrono; extern crate clap; extern crate git2; #[macro_use] extern crate lazy_static; extern crate nix; #[macro_use] extern crate cached; pub mod git; pub mod hostname; pub mod python; pub mod shell; pub mod style; pub mod terminal; pub mod user; pub mod widget; use style::Color::*; use style::Style::*; u...
extern crate chrono; extern crate clap; extern crate git2; #[macro_use] extern crate lazy_static; extern crate nix; #[macro_use] extern crate cached; pub mod git; pub mod hostname; pub mod python; pub mod shell; pub mod style; pub mod terminal; pub mod user; pub mod widget; use style::Color::*; use style::Style::*; u...
u") .version("0.1") .author("Fabian Köhler <fkoehler1024@googlemail.com>") .about("A portable and fast shell for your prompt") .arg( Arg::with_name("RETVAL") .help("Return code of last shell command") .required(true), ) .arg( ...
function_block-function_prefixed
[ { "content": "pub fn parse_retval(matches: &clap::ArgMatches) -> i64 {\n\n match matches.value_of(\"RETVAL\") {\n\n None => 0i64,\n\n Some(m) => match m.parse::<i64>() {\n\n Err(_) => 0i64,\n\n Ok(retval) => retval,\n\n },\n\n }\n\n}\n\n\n\ncached! {\n\n SHELL...
Rust
src/core/registry.rs
louaykamel/overclock
6a663c577cab5ef2fef1384bf320f623b6a39eaf
use super::{Route, Shutdown}; use rand::distributions::Uniform; use std::{any::TypeId, collections::HashMap}; use tokio::sync::RwLock; pub type Depth = usize; pub type ScopeId = usize; pub type PartitionedScopes = RwLock<HashMap<ScopeId, Scope>>; lazy_static::lazy_static! { pub static ref PROMETHEUS_REGI...
use super::{Route, Shutdown}; use rand::distributions::Uniform; use std::{any::TypeId, collections::HashMap}; use tokio::sync::RwLock; pub type Depth = usize; pub type ScopeId = usize; pub type PartitionedScopes = RwLock<HashMap<ScopeId, Scope>>; lazy_static::lazy_static! { pub static ref PROMETHEUS_REGI...
} pub enum Subscriber<T: Resource> { OneCopy(tokio::sync::oneshot::Sender<anyhow::Result<T>>), LinkedCopy( Option<tokio::sync::oneshot::Sender<anyhow::Result<T>>>, Box<dyn Shutdown>, bool, ), DynCopy(super::ResourceRef, Box<dyn Route<super::Event<T...
subscribers.insert(scope_id, subscriber); Self { resource: None, subscribers, } }
function_block-function_prefix_line
[ { "content": "#[async_trait::async_trait]\n\npub trait Shutdown: Send + 'static + Sync + dyn_clone::DynClone {\n\n /// Send shutdown signal to the corresponding actor\n\n async fn shutdown(&self);\n\n /// Return the corresponding actor's scope_id\n\n fn scope_id(&self) -> super::ScopeId;\n\n}\n\n\n\...
Rust
examples/scanner_states/scanner_states_grammar.rs
Techcable/parol
85363f7ea2340d028dd311e7d3507a14c8bf74ce
use crate::scanner_states_grammar_trait::ScannerStatesGrammarTrait; use id_tree::Tree; use log::trace; use miette::{bail, miette, Result}; use parol_runtime::parser::{ParseTreeStackEntry, ParseTreeType}; use std::fmt::{Debug, Display, Error, Formatter}; #[derive(Debug, Clone)] pub enum ScannerStatesGrammarItem { I...
use crate::scanner_states_grammar_trait::ScannerStatesGrammarTrait; use id_tree::Tree; use log::trace; use miette::{bail, miette, Result}; use parol_runtime::parser::{ParseTreeStackEntry, ParseTreeType}; use std::fmt::{Debug, Display, Error, Formatter}; #[derive(Debug, Clone)] pub enum ScannerStatesGrammarItem { I...
fn string_delimiter_14( &mut self, _string_delimiter_0: &ParseTreeStackEntry, _parse_tree: &Tree<ParseTreeType>, ) -> Result<()> { let context = "string_delimiter_14"; if self.in_string { self.in_string = false; } else { ...
fn none_quote_13( &mut self, none_quote_0: &ParseTreeStackEntry, parse_tree: &Tree<ParseTreeType>, ) -> Result<()> { let context = "none_quote_13"; if let Some(ScannerStatesGrammarItem::String(mut s)) = self.pop(context) { let element = none_quote_0.symbol(parse_t...
function_block-full_function
[ { "content": "pub fn short_cut_disjunction_combine<A, F, G>(f: F, g: G) -> impl Fn(&A) -> bool\n\nwhere\n\n F: Fn(&A) -> bool,\n\n G: Fn(&A) -> bool,\n\n{\n\n move |x| {\n\n let r = f(x);\n\n if r {\n\n r\n\n } else {\n\n g(x)\n\n }\n\n }\n\n}\n\n\n"...
Rust
tests/client.rs
bkchr/schluesselwert
05e7de37916e5d51bc4047076c8e9d4d7cd0ba51
extern crate futures; extern crate rand; extern crate schluesselwert; extern crate tempdir; extern crate tokio; mod common; use common::*; use schluesselwert::{Client, Error}; use std::collections::HashMap; use tokio::executor::current_thread; use futures::{future, Future}; use tempdir::TempDir; fn check_data_w...
extern crate futures; extern crate rand; extern crate schluesselwert; extern crate tempdir; extern crate tokio; mod common; use common::*; use schluesselwert::{Client, Error}; use std::collections::HashMap; use tokio::executor::current_thread; use futures::{future, Future}; use tempdir::TempDir; fn check_data_w...
_node_snapshots(&nodes_map); } #[test] fn remove_leader_and_re_add_node() { let (nodes, listen_ports) = create_nodes(5, 20070); let mut nodes_map = setup_nodes(nodes, listen_ports.clone()); let nodes = listen_ports_to_socket_addrs(listen_ports); let mut client = Client::new(nodes); let test_data ...
clone(), v.clone())), )).unwrap(); let (nodes, _) = create_nodes(5, 20060); let (new_node, listen_port) = create_node(5, 20060); let new_nodes_map = setup_nodes_with_cluster_nodes(vec![new_node.clone()], vec![listen_port], None, nodes); nodes_map.merge(new_nodes_map); current...
function_block-random_span
[ { "content": "fn start_node(\n\n node: Peer,\n\n listen_port: u16,\n\n peers: Vec<Peer>,\n\n path: Option<TempDir>,\n\n) -> Receiver<(NodeHandle, UnboundedSender<TestMessages>, TempDir)> {\n\n let (sender, receiver) = channel();\n\n thread::spawn(move || {\n\n let dir = path.unwrap_or_e...
Rust
definition_language/src/lib.rs
alec-deason/virtual_modular
77857488c4b573522807430855c83bfc3d588647
#![feature(hash_drain_filter)] #[cfg(feature = "code_generation")] pub mod code_generation; use std::convert::{TryFrom, TryInto}; pub fn parse(data: &str) -> Result<Vec<Line>, String> { use pom::parser::Parser; use pom::parser::*; use std::str::{self, FromStr}; fn node_name<'a>() -> Parser<'a, u8, S...
#![feature(hash_drain_filter)] #[cfg(feature = "code_generation")] pub mod code_generation; use std::convert::{TryFrom, TryInto}; pub fn parse(data: &str) -> Result<Vec<Line>, String> { use pom::parser::Parser; use pom::parser::*; use std::str::{self, FromStr}; fn node_name<'a>() -> Parser<'a, u8, S...
fn comment<'a>() -> Parser<'a, u8, Vec<Line>> { let comment = (sym(b'#') * none_of(b"\n").repeat(0..)) - sym(b'\n'); let empty_line = (sym(b'\n')).repeat(1); (comment | empty_line).map(|_| vec![Line::Comment]) } fn bridge<'a>() -> Parser<'a, u8, Vec<Line>> { let n_in = seq...
fn external_parameter<'a>() -> Parser<'a, u8, Vec<Line>> { (none_of(b"\n=(),").repeat(1..).convert(String::from_utf8) - sym(b'=') - seq(b"e{") + none_of(b"}").repeat(1..).convert(String::from_utf8) - sym(b'}')) .map(|(n, k)| vec![Line::ExternalParam(n, k)]) }
function_block-full_function
[ { "content": "pub fn make_coprime(numbers: &mut [u32]) {\n\n for n in numbers.iter_mut() {\n\n if *n <= 1 {\n\n *n = 2;\n\n }\n\n }\n\n for i in 1..numbers.len() {\n\n let mut done = false;\n\n while !done {\n\n done = true;\n\n for j in 0..i...
Rust
src/lib.rs
Byter09/rcc
6b83fd519f2db1a7d186e868166cd875a0ce7cc9
#![allow(clippy::cognitive_complexity)] #![allow(clippy::mem_replace_with_default)] #![warn(absolute_paths_not_starting_with_crate)] #![warn(explicit_outlives_requirements)] #![warn(unreachable_pub)] #![warn(deprecated_in_future)] #![deny(unsafe_code)] #![deny(unused_extern_crates)] use std::collections::VecDeque; us...
#![allow(clippy::cognitive_complexity)] #![allow(clippy::mem_replace_with_default)] #![warn(absolute_paths_not_starting_with_crate)] #![warn(explicit_outlives_requirements)] #![warn(unreachable_pub)] #![warn(deprecated_in_future)] #![deny(unsafe_code)] #![deny(unused_extern_crates)] use std::collections::VecDeque; us...
} fn compile_err(src: &str) -> VecDeque<CompileError> { match compile(src).err().unwrap() { Error::Source(errs) => errs, _ => unreachable!(), } } #[test] fn empty() { let mut lex_errs = compile_err("`\n"); assert!(lex_errs.pop_front().unwrap()...
match res { Ok(decls) => Ok(decls.into_iter().map(|l| l.data).collect()), Err(errs) => Err(Error::Source(errs)), }
if_condition
[ { "content": "pub fn compile_and_run(program: &str, path: PathBuf, args: &[&str]) -> Result<Output, Error> {\n\n let output = compile(program, path, false)\n\n .unwrap_or_else(|err| panic!(\"failed to compile program '{}': {}\", program, err));\n\n info!(\"running file {:?}\", output);\n\n run(&...
Rust
automerge-backend-wasm/src/lib.rs
inkandswitch/automerge-rs
7ff72656378eef1bf63aa97035ac8832d03e9fd9
use automerge_backend::{ActorID, AutomergeError, Backend, Change, ChangeRequest, Clock}; use serde::de::DeserializeOwned; use serde::Serialize; use wasm_bindgen::prelude::*; extern crate web_sys; #[allow(unused_macros)] macro_rules! log { ( $( $t:tt )* ) => { }; } #[cfg(feature = "wee_alloc")] #[glob...
use automerge_backend::{ActorID, AutomergeError, Backend, Change, ChangeRequest, Clock}; use serde::de::DeserializeOwned; use serde::Serialize; use wasm_bindgen::prelude::*; extern crate web_sys; #[allow(unused_macros)] macro_rules! log { ( $( $t:tt )* ) => { }; } #[cfg(feature = "wee_alloc")] #[glob...
#[wasm_bindgen(js_name = getPatch)] pub fn get_patch(&self) -> Result<JsValue, JsValue> { log!("get_patch"); let patch = self.backend.get_patch(); rust_to_js(&patch) } #[wasm_bindgen(js_name = getChanges)] pub fn get_changes(&self, state: &State) -> Result<JsValue, JsValue...
pub fn apply_local_change(&mut self, change: JsValue) -> Result<JsValue, JsValue> { log!("apply_local_changes {:?}", change); let c: ChangeRequest = js_to_rust(change)?; let patch = self .backend .apply_local_change(c) .map_err(automerge_error_to_js)?; ...
function_block-full_function
[ { "content": "pub fn list_ops_in_order<'a, S: BuildHasher>(\n\n operations_by_elemid: &'a HashMap<ElementID, ConcurrentOperations, S>,\n\n following: &HashMap<ElementID, Vec<ElementID>, S>,\n\n) -> Result<Vec<(ElementID, &'a ConcurrentOperations)>, AutomergeError> {\n\n // First we construct a vector o...
Rust
examples/ocr/src/main.rs
willi-kappler/darwin-rs
e687ca8d3443302e7596dae1dbe5d4c511b61567
extern crate rand; #[macro_use] extern crate log; extern crate image; extern crate imageproc; extern crate rusttype; extern crate simplelog; extern crate darwin_rs; use std::sync::Arc; use rand::Rng; use std::fs::File; use std::io::Read; use image::{ImageBuffer, Luma}; use imageproc::stats::root_mean_squared_error...
extern crate rand; #[macro_use] extern crate log; extern crate image; extern crate imageproc; extern crate rusttype; extern crate simplelog; extern crate darwin_rs; use std::sync::Arc; use rand::Rng; use std::fs::File; use std::io::Read; use image::{ImageBuffer, Luma}; use imageproc::stats::root_mean_squared_error...
fn calculate_fitness(&mut self) -> f64 { let mut constructed_img: ImageBuffer<Luma<u8>, Vec<u8>> = ImageBuffer::new(120, 70); draw_text_line(&mut constructed_img, &self.config.font_config, self.content[0].x as i32, self.content[0].y as i32, str::from_utf8(&self.content[0]....
match operation { 0 => { let new_char = rng.gen_range(32, 127); self.content[content_line].text[index1] = new_char; }, 1 => { let index2 = rng.gen_range(0, self.content[content_line].text.len()); ...
function_block-function_prefix_line
[ { "content": "fn make_all_populations2<'a>(individuals: u32, config: &OCRConfig<'a>, populations: u32) -> Vec<Population<OCRItem<'a>>> {\n\n let mut result = Vec::new();\n\n let mut rng = rand::thread_rng();\n\n\n\n let initial_population = make_population(individuals, &config);\n\n\n\n for i in 1.....
Rust
pkmnapi-db/src/db/pokedex_text.rs
kevinselwyn/pkmnapi
170e6b6c9a74e85c377137bc086793898c415125
use crate::error::{self, Result}; use crate::patch::*; use crate::string::*; use crate::PkmnapiDB; use std::collections::HashMap; impl PkmnapiDB { pub fn get_pokedex_text_all(&self, pokedex_ids: &Vec<u8>) -> Result<HashMap<u8, PokedexText>> { self.get_all(pokedex_ids, |id| self.get_pokedex_text(id)) } ...
use crate::error::{self, Result}; use crate::patch::*; use crate::string::*; use crate::PkmnapiDB; use std::collections::HashMap; impl PkmnapiDB { pub fn get_pokedex_text_all(&self, pokedex_ids: &Vec<u8>) -> Result<HashMap<u8, PokedexText>> { self.get_all(pokedex_ids, |id| self.get_pokedex_text(id)) } ...
c![0x5F]].concat() } }
napiDB::ROM_PAGE * 0x0F; let pointer_offset = (offset_base + 0x447E) + ((internal_id as usize) * 2); let pointer = offset_base + self.get_pointer(pointer_offset); let pointer_offset = pointer + { self.rom[pointer..].iter().position(|&r| r == 0x50).unwrap() } + 0x06; let po...
random
[ { "content": "#[allow(dead_code)]\n\n#[allow(non_snake_case)]\n\npub fn load_sav() -> Vec<u8> {\n\n let PKMN_SAV = env::var(\"PKMN_SAV\")\n\n .expect(\"Set the PKMN_SAV environment variable to point to the SAV location\");\n\n\n\n fs::read(PKMN_SAV).unwrap()\n\n}\n\n\n", "file_path": "pkmnapi-a...
Rust
src/blocks/audio/audio_sink.rs
LongHairedHacker/FutureSDR
1a716e49b525fac789646c8307840d12367a5922
use anyhow::Result; use async_io::block_on; use async_trait::async_trait; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::BufferSize; use cpal::SampleRate; use cpal::Stream; use cpal::StreamConfig; use crate::runtime::AsyncKernel; use crate::runtime::Block; use crate::runtime::BlockMeta; use crate::...
use anyhow::Result; use async_io::block_on; use async_trait::async_trait; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::BufferSize; use cpal::SampleRate; use cpal::Stream; use cpal::StreamConfig; use crate::runtime::AsyncKernel; use crate::runtime::Block; use crate::runtime::BlockMeta; use crate::...
stream.play()?; self.rx = Some(rx); self.stream = Some(stream); Ok(()) } async fn work( &mut self, io: &mut WorkIo, sio: &mut StreamIo, _mio: &mut MessageIo<Self>, _meta: &mut BlockMeta, ) -> Result<()> { if let Some((mut b...
let stream = device.build_output_stream( &config, move |data: &mut [f32], _: &cpal::OutputCallbackInfo| { let (my_tx, my_rx) = oneshot::channel::<Box<[f32]>>(); let samples = block_on(async { tx.send((data.len(), my_tx)).await.unwrap(); ...
assignment_statement
[ { "content": "#[inline]\n\nfn o(sio: &mut StreamIo, id: usize) -> &mut WriterD2H {\n\n sio.output(id).try_as::<WriterD2H>().unwrap()\n\n}\n\n\n", "file_path": "src/blocks/vulkan.rs", "rank": 0, "score": 212103.99402769626 }, { "content": "#[inline]\n\nfn i(sio: &mut StreamIo, id: usize) -...
Rust
src/channel_status.rs
LukeMathWalker/lapin
d5b19da4f82ddaa5d54186ccbe87e997efa4ee38
use crate::{ channel_receiver_state::ChannelReceiverStates, types::{ShortString, ShortUInt}, Result, }; use log::trace; use parking_lot::Mutex; use std::{fmt, sync::Arc}; #[derive(Clone, Default)] pub struct ChannelStatus(Arc<Mutex<Inner>>); impl ChannelStatus { pub fn initializing(&self) -> bool { ...
use crate::{ channel_receiver_state::ChannelReceiverStates, types::{ShortString, ShortUInt}, Result, }; use log::trace; use parking_lot::Mutex; use std::{fmt, sync::Arc}; #[derive(Clone, Default)] pub struct ChannelStatus(Arc<Mutex<Inner>>); impl ChannelStatus { pub fn initializing(&self) -> bool { ...
} struct Inner { confirm: bool, send_flow: bool, state: ChannelState, receiver_state: ChannelReceiverStates, } impl Default for Inner { fn default() -> Self { Self { confirm: false, send_flow: true, state: ChannelState::default(), receiver_s...
let mut debug = f.debug_struct("ChannelStatus"); if let Some(inner) = self.0.try_lock() { debug .field("state", &inner.state) .field("receiver_state", &inner.receiver_state) .field("confirm", &inner.confirm) .field("send_flow", &inner.s...
function_block-function_prefix_line
[ { "content": "struct Inner {\n\n connection_step: Option<ConnectionStep>,\n\n state: ConnectionState,\n\n vhost: String,\n\n username: String,\n\n blocked: bool,\n\n}\n\n\n\nimpl Default for Inner {\n\n fn default() -> Self {\n\n Self {\n\n connection_step: None,\n\n ...
Rust
src/lib.rs
Plecra/utf16_l
8b2d43b61c7dd95177748a9281260ec322c1bc39
#![allow(bad_style)] extern crate proc_macro; use proc_macro::{TokenStream, TokenTree}; use core::str::FromStr; use std::fmt::Write; #[proc_macro] pub fn utf16(stream: TokenStream) -> TokenStream { const USAGE: &str = "Usage: utf16!(string_lit)"; let mut tt_iter = stream.into_iter(); let lit = match tt_ite...
#![allow(bad_style)] extern crate proc_macro; use proc_macro::{TokenStream, TokenTree}; use core::str::FromStr; use std::fmt::Write; #[proc_macro] pub fn utf16(stream: TokenStream) -> TokenStream { const USAGE: &str = "Usage: utf16!(string_lit)"; let mut tt_iter = stream.into_iter(); let lit = match tt_ite...
#[derive(Debug, Clone, Copy, PartialEq, Eq)] enum CharEscape { Literal(char), Escaped(char), Improper(char), DanglingBackslash, } #[derive(Debug, Clone, Copy)] struct CharEscapeIterator<I> { it: I, } impl<I> CharEscapeIterator<I> where I: Iterator<Item = char>, { fn new(it: I) -> Self { Self { it ...
f) { let _cant_fail = write!(buf, "{},", unit); } }, other => panic!("Illegal character escape sequence: {:?}", other), } } buf.push_str("]"); TokenStream::from_str(&buf).unwrap() }
function_block-function_prefixed
[]
Rust
src/flow/primal_dual.rs
katandps/rust_lib_for_comp
8375ce89a31ecc9a87f11b71727b6eccaf888c03
use crate::graph::adjacency_list::Graph; use crate::graph::GraphTrait; use crate::prelude::*; macro_rules! chmin {($base:expr, $($cmps:expr),+ $(,)*) => {{let cmp_min = min!($($cmps),+);if $base > cmp_min {$base = cmp_min;true} else {false}}};} macro_rules! min { ($a:expr $(,)*) => {{$a}}; ($a:expr, $b:expr ...
use crate::graph::adjacency_list::Graph; use crate::graph::GraphTrait; use crate::prelude::*; macro_rules! chmin {($base:expr, $($cmps:expr),+ $(,)*) => {{let cmp_min = min!($($cmps),+);if $base > cmp_min {$base = cmp_min;true} else {false}}};} macro_rules! min { ($a:expr $(,)*) => {{$a}}; ($a:expr, $b:expr ...
es[self.rev[j]]; println!("{} -> {} (flow: {}/{})", src, dst, rev_cap, rev_cap + cap); } } } }
continue; } if let Some(m) = min_cost[src] { let next_cost = m + cost + potential[src] - potential[dst]; if min_cost[dst].is_none() || min_cost[dst] > Some(next_cost) { min_cost[dst] = Some(next_cost); ...
random
[ { "content": "#[snippet(name = \"compress\", doc_hidden)]\n\npub fn compress<T: Ord>(source: &[T]) -> Vec<usize> {\n\n let n = source.len();\n\n let mut idx: Vec<usize> = (0..n).collect();\n\n idx.sort_by_key(|&i| &source[i]);\n\n let mut ret = vec![0; n];\n\n let mut cur = 0;\n\n for i in 0.....
Rust
src/instrumentation/state_counters.rs
chridou/reool
e8661777f84b9be931fede4624fbd069e0220884
use std::io::{self, Write}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use std::time::Duration; use log::info; use crate::instrumentation::PoolId; use crate::PoolState; use super::Instrumentation; #[derive(Clone, Default)] pub struct StateCounters { connections: Arc<AtomicUsize>, idle...
use std::io::{self, Write}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use std::time::Duration; use log::info; use crate::instrumentation::PoolId; use crate::PoolState; use super::Instrumentation; #[derive(Clone, Default)] pub struct StateCounters { connections: Arc<AtomicUsize>, idle...
ory_failed(&self, pool: PoolId) { if self.output_required() { self.output(&format!("[{}] connection factory failed", pool)); } } fn internal_message_received(&self, _latency: Duration, _pool: PoolId) {} fn checkout_message_received(&self, _latency: Duration, _pool: PoolId) {} ...
time: Duration, _pool: PoolId) { } fn idle_inc(&self, pool: PoolId) { self.idle.fetch_add(1, Ordering::SeqCst); if self.output_required() { self.output(&format!("[{}] idle +1: {}", pool, self.idle())); } } fn idle_dec(&self, pool: PoolId) { self.idle.fetch_s...
random
[ { "content": "struct MyConnectionFactory(Arc<String>, AtomicUsize);\n\n\n\nimpl ConnectionFactory for MyConnectionFactory {\n\n type Connection = MyConn;\n\n\n\n fn create_connection(&self) -> BoxFuture<Result<Self::Connection, Error>> {\n\n let count = self.1.fetch_add(1, Ordering::SeqCst);\n\n ...
Rust
src/lib.rs
simon-bourne/sbash
e4bc3fd8f466bb664a77865d13a1213034306505
use std::{ collections::{HashMap, HashSet}, fmt::{self, Display}, io, process, }; use clap::{App, Arg, ArgEnum, ArgMatches}; use clap_complete::{generate, Shell}; use indoc::indoc; use parser::Description; use thiserror::Error; mod parser; #[derive(Debug)] pub struct Script<'a> { description: Descrip...
use std::{ collections::{HashMap, HashSet}, fmt::{self, Display}, io, process, }; use clap::{App, Arg, ArgEnum, ArgMatches}; use clap_complete::{generate, Shell}; use indoc::indoc; use parser::Description; use thiserror::Error; mod parser; #[derive(Debug)] pub struct Script<'a> { description: Descrip...
const FORWARDED_ARGS_NAME: &str = "$@"; impl<'a> Display for Script<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut script = String::new(); for item in &self.items { script.push_str(&item.script(count_newlines(&script))); } write!(f, "{}", sc...
n() }) .into_iter() .flatten(); positional_args .chain(forwarded_args) .map(|arg| arg.to_owned()) .collect() }
function_block-function_prefixed
[ { "content": "pub fn parse(input: &str) -> Result<(Description, Vec<Item>), ParseError> {\n\n let input_span = Span::new(input);\n\n\n\n let (_, script) = match script(input_span).finish() {\n\n Ok(ok) => Ok(ok),\n\n Err(e) => Err(ParseError(convert_error(input, e))),\n\n }?;\n\n\n\n O...
Rust
src/widget/title_bar.rs
zummenix/conrod
0c9133757eb20e5e5e81ec7c9efeb6695f3a93b9
use { Align, Backend, Color, Colorable, Dimension, FontSize, Frameable, FramedRectangle, IndexSlot, Labelable, Positionable, Scalar, Sizeable, Text, TextWrap, Ui, }; use widget::{self, Widget}; pub struct TitleBar<'a> { pub common: widget::Common...
use { Align, Backend, Color, Colorable, Dimension, FontSize, Frameable, FramedRectangle, IndexSlot, Labelable, Positionable, Scalar, Sizeable, Text, TextWrap, Ui, }; use widget::{self, Widget}; pub struct TitleBar<'a> { pub common: widget::Common...
pub fn align_text_left(mut self) -> Self { self.style.text_align = Some(Align::Start); self } pub fn align_text_middle(mut self) -> Self { self.style.text_align = Some(Align::Middle); self } pub fn align_text_right(mut self) -> Self { self.s...
pub fn new<I>(label: &'a str, idx: I) -> Self where I: Into<widget::Index> + Copy, { TitleBar { common: widget::CommonBuilder::new(), style: Style::new(), label: label, }.w_of(idx).mid_top_of(idx) }
function_block-full_function
[ { "content": "/// Attempts to infer the parent of a widget from its *x*/*y* `Position`s and the current state of\n\n/// the `Ui`.\n\n///\n\n/// If no parent can be inferred via the `Position`s, the `maybe_current_parent_idx` will be used.\n\n///\n\n/// If `maybe_current_parent_idx` is `None`, the `Ui`'s `window...
Rust
src/value/mod.rs
bytebuddha/rolodex
a7e5406f8382e2013d17d73364383d7ddf0cc052
use std::borrow::Cow; use std::fmt::{Debug, Display}; mod ty; pub use self::ty::TypeOrRaw; mod at_least; pub use self::at_least::AtLeastOne; use crate::types::{Address, Email, FormattedName, Gender, GeoPosition, Image, Kind, Url}; #[cfg(feature = "serde")] pub trait PropertyValue: Debug + PartialEq + Clone + Displa...
use std::borrow::Cow; use std::fmt::{Debug, Display}; mod ty; pub use self::ty::TypeOrRaw; mod at_least; pub use self::at_least::AtLeastOne; use crate::types::{Address, Email, FormattedName, Gender, GeoPosition, Image, Kind, Url}; #[cfg(feature = "serde")] pub trait PropertyValue: Debug + PartialEq + Clone + Displa...
}
pub fn name_label(&self) -> &str { match self { Value::Begin => "Begin", Value::End => "End", Value::Source(_) => "Source", Value::Kind(_) => "Kind", Value::Xml(_) => "Xml", Value::Fn(_) => "Formatted Name", Value::N(_) => "Name...
function_block-full_function
[ { "content": "fn name() -> types::Url<'static> {\n\n types::Url::builder()\n\n .schema(\"http\")\n\n .domain(\"www.example.com\")\n\n .path(\"/dir_photos/my_photo.gif\")\n\n .build()\n\n}\n\n\n", "file_path": "tests/types/url.rs", "rank": 2, "score": 122972.22287192129...
Rust
src/main.rs
StoneDot/system_monitor
1c2669d0cb713012e7517a6765cfd9f708b947d9
extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate regex; extern crate procinfo; extern crate libc; extern crate itertools; extern crate fnv; use std::time::SystemTime; use std::time::UNIX_EPOCH; use std::ops; use std::path::{Path, PathBuf}; use std::thread; use std::ti...
extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate regex; extern crate procinfo; extern crate libc; extern crate itertools; extern crate fnv; use std::time::SystemTime; use std::time::UNIX_EPOCH; use std::ops; use std::path::{Path, PathBuf}; use std::thread; use std::ti...
p()); if let Ok(pid) = pid { let stat = procinfo::pid::stat(pid); if let Ok(stat) = stat { return Some(stat); } } return None; } fn retrieve_process_stats(target_process_names: &[&str]) -> FnvHashMap<String, Vec<Stat>> { let escaped = target_process_names.iter().map(...
me: self.stime - other.stime, cutime: self.cutime - other.cutime, cstime: self.cstime - other.cstime, minflt: self.minflt - other.minflt, cminflt: self.cminflt - other.cminflt, majflt: self.majflt - other.majflt, cmajflt: self.cmajflt - other.cmajf...
random
[]
Rust
src/nn/linear.rs
coreylowman/stag
21c068c2b44b43dbf38ab49887d85e7472f1e5a2
use crate::prelude::*; use rand::{distributions::Distribution, Rng}; #[derive(Default, Debug, Clone)] pub struct Linear<const I: usize, const O: usize> { pub weight: Tensor2D<I, O, NoTape>, pub bias: Tensor1D<O, NoTape>, } impl<const I: usize, const O: usize> CanUpdateWithGradients for Linear<I, O>...
use crate::prelude::*; use rand::{distributions::Distribution, Rng}; #[derive(Default, Debug, Clone)] pub struct Linear<const I: usize, const O: usize> { pub weight: Tensor2D<I, O, NoTape>, pub bias: Tensor1D<O, NoTape>, } impl<const I: usize, const O: usize> CanUpdateWithGradients for Linear<I, O>...
10, 2.03129911]); let y = model.forward(x.trace()); assert_eq!(y.data(), &[-0.93430865, 0.08624211]); let loss = y.square().mean(); let gradients = loss.backward(); assert_eq!( gradients.ref_gradient(&model.weight), &[ [0.82293916, -0.0759...
st_forward_1d() { let model: Linear<5, 2> = Linear { weight: Tensor2D::new(W), bias: Tensor1D::new(B), }; let x = Tensor1D::new([-0.88080013, 2.41853333, 2.24783349, 0.056521
function_block-random_span
[ { "content": "/// Randomly drops out elements from `t` with probability `p`, and multiplies all elements by `1 / (1 - p)`.\n\n///\n\n/// If the `t: T` passed in does **not** have a tape, then no dropout is applied. See [Tape::OWNS_TAPE].\n\n///\n\n/// Described in paper: [Improving neural networks by preventing...
Rust
src/core/msgf_part.rs
hasebems/Musical_Sound_Generator_Framework_by_Rust
32cf38d46e739f1e693dbf9ea4472e1fad35ccc4
use crate::*; use crate::core::*; pub struct Part { cc0_msb: u8, cc1_modulation_wheel: u8, cc5_portamento_time: u8, cc7_volume: u8, cc10_pan: u8, cc11_expression: u8, cc12_note_shift: u8, cc13_tune: u8, cc32_lsb: u8, cc64_sustain: u8, cc65_portamento: u8, cc66...
use crate::*; use crate::core::*; pub struct Part { cc0_msb: u8, cc1_modulation_wheel: u8, cc5_portamento_time: u8, cc7_volume: u8, cc10_pan: u8, cc11_expression: u8, cc12_note_shift: u8, cc13_tune: u8, cc32_lsb: u8, cc64_sustain: u8, cc65_portamento: u8, cc66...
pan = self.cc10_pan; let exp = self.cc11_expression; let pb = self.pitch_bend_value; let ns = self.cc12_note_shift; let tn = self.cc13_tune; self.inst = app::get_inst(self.program_number as usize,vol,pan,exp); self.inst.pitch(pb, ns, tn); println!("Program Change...
value; let pb = self.pitch_bend_value; let tn = self.cc13_tune; self.inst.pitch(pb, value, tn); } 13 => { self.cc13_tune = value; let pb = self.pitch_bend_value; let ns = self.cc12_note_shift; ...
random
[ { "content": "pub fn get_inst(inst_number:usize, vol:u8, pan:u8, exp:u8) -> Box<dyn msgf_inst::Inst> {\n\n if inst_number < 8 {\n\n println!(\"Changed Va: {}\",inst_number);\n\n Box::new(va_inst::InstVa::new(inst_number,vol,pan,exp))\n\n }\n\n else if inst_number < 16 {\n\n println...
Rust
game/src/render/traffic_signal.rs
cyrex562/abstreet
e361cd19f30e3a3b8c782f76d282359b4053cdd0
use crate::options::TrafficSignalStyle; use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS}; use crate::ui::UI; use ezgui::{ Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_mo...
use crate::options::TrafficSignalStyle; use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS}; use crate::ui::UI; use ezgui::{ Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_mo...
pub fn current_phase(&self) -> usize { self.current_phase } pub fn draw(&self, g: &mut GfxCtx) { self.composite.draw(g); } } fn make_diagram(i: IntersectionID, selected: usize, ui: &UI, ctx: &EventCtx) -> Composite { let bounds = ui.primary.map.get_i(i).polygon.get_boun...
te.preserve_scroll(ctx); self.current_phase = idx; self.composite = make_diagram(self.i, self.current_phase, ui, ctx); self.composite.restore_scroll(ctx, preserve_scroll); } }
function_block-function_prefixed
[ { "content": "fn make_crosswalk(batch: &mut GeomBatch, turn: &Turn, cs: &ColorScheme) {\n\n // Start at least LANE_THICKNESS out to not hit sidewalk corners. Also account for the\n\n // thickness of the crosswalk line itself. Center the lines inside these two boundaries.\n\n let boundary = LANE_THICKNE...
Rust
src/crypto/openssl.rs
zhtluo/rust-pvss
673ef2a13b9f368dc26224cedb3b81629c1f7304
use openssl::bn::*; use openssl::ec::*; use std::ops::Add; use std::ops::Mul; use std::ops::Sub; pub const CURVE: openssl::nid::Nid = openssl::nid::Nid::X9_62_PRIME256V1; pub struct Scalar { bn: BigNum, } pub struct Point { point: EcPoint, } #[derive(PartialEq)] pub struct PrivateKey { pub scalar: Scala...
use openssl::bn::*; use openssl::ec::*; use std::ops::Add; use std::ops::Mul; use std::ops::Sub; pub const CURVE: openssl::nid::Nid = openssl::nid::Nid::X9_62_PRIME256V1; pub struct Scalar { bn: BigNum, } pub struct Point { point: EcPoint, } #[derive(PartialEq)] pub struct PrivateKey { pub scalar: Scala...
pub fn multiplicative_identity() -> Scalar { Self::from_u32(1) } pub fn hash_points(points: Vec<Point>) -> Scalar { let mut data = Vec::new(); for p in points { data.extend_from_slice(p.to_bytes().as_slice()); } let dig = openssl::sha::sha256(data.as_sl...
pub fn generate() -> Scalar { let order = get_order(); let mut r = BigNum::new().unwrap(); order.rand_range(&mut r).unwrap(); Scalar { bn: r } }
function_block-full_function
[ { "content": "pub fn create_keypair() -> (PublicKey, PrivateKey) {\n\n let s = Scalar::generate();\n\n let p = Point::from_scalar(&s);\n\n (PublicKey { point: p }, PrivateKey { scalar: s })\n\n}\n\n\n", "file_path": "src/crypto/ark.rs", "rank": 1, "score": 122248.08213523233 }, { "c...
Rust
crates/interledger-store/tests/redis/routing_test.rs
pradovic/interledger-rs
285f42377ab6bf91a1cbdd45966c0579722070f5
use super::{fixtures::*, redis_helpers::*, store_helpers::*}; use interledger_api::{AccountDetails, NodeStore}; use interledger_ccp::CcpRoutingStore; use interledger_packet::Address; use interledger_router::RouterStore; use interledger_service::{Account as AccountTrait, AddressStore, Username}; use interledger_store::...
use super::{fixtures::*, redis_helpers::*, store_helpers::*}; use interledger_api::{AccountDetails, NodeStore}; use interledger_ccp::CcpRoutingStore; use interledger_packet::Address; use interledger_router::RouterStore; use interledger_service::{Account as AccountTrait, AddressStore, Username}; use interledger_store::...
t, accs) = test_store().await.unwrap(); store .set_static_routes(vec![ ("example.a".to_string(), accs[0].id()), ("example.b".to_string(), accs[0].id()), ]) .await .unwrap(); let account1_id = Uuid::new_v4(); let account1 = Account::try_from( a...
o_string()); assert_eq!(routes["example.b"], account0_id.to_string()); assert_eq!(routes["example.c"], account1_id.to_string()); assert_eq!(routes.len(), 3); let routes = store.routing_table(); assert_eq!(routes["example.a"], account0_id); assert_eq!(routes["example.b"], account0_id); ...
random
[ { "content": "/// Domain separator for accounts\n\nfn accounts_key(prefix: &str, account_id: Uuid) -> String {\n\n prefixed_key(prefix, &format!(\"accounts:{}\", account_id)).into_owned()\n\n}\n\n\n\n// TODO: Add descriptive errors inside the lua scripts!\n\n\n\n// The following are Lua scripts that are used...
Rust
nestadia-gui/src/sdl_window.rs
GoldenKain/nestadia
33c44084970ea3a72336312c7dedafc6031931a0
use std::{ sync::{Arc, RwLock}, time::{Duration, Instant}, }; use sdl2::{event::Event, keyboard::Keycode}; use super::rgb_value_table::RGB_VALUE_TABLE; use super::{EmulationState, NES_HEIGHT, NES_WIDTH}; pub(crate) fn start_game(emulation_state: Arc<RwLock<EmulationState>>) { let sdl_context = sdl2::init...
use std::{ sync::{Arc, RwLock}, time::{Duration, Instant}, }; use sdl2::{event::Event, keyboard::Keycode}; use super::rgb_value_table::RGB_VALUE_TABLE; use super::{EmulationState, NES_HEIGHT, NES_WIDTH}; pub(crate) fn start_game(emulation_state: Arc<RwLock<EmulationState>>) { let sdl_context = sdl2::init...
controller_state |= 0x08, Event::KeyDown { keycode: Some(Keycode::Down), .. } => controller_state |= 0x04, Event::KeyDown { keycode: Some(Keycode::Left), .. } => controller_sta...
function_block-function_prefix_line
[ { "content": "pub fn frame_to_rgb(frame: &PpuFrame, output: &mut [u8; 256 * 240 * 3]) {\n\n for i in 0..frame.len() {\n\n let f = RGB_PALETTE[(frame[i] & 0x3f) as usize];\n\n output[i * 3] = f[0];\n\n output[i * 3 + 1] = f[1];\n\n output[i * 3 + 2] = f[2];\n\n }\n\n}\n\n\n", ...
Rust
src/chat_service.rs
allevo/yac
5af91045f9486d7fb673ba3454c9d77af2a4471e
use std::{ collections::{HashMap, HashSet}, sync::Arc, }; use futures::{ channel::mpsc::{UnboundedReceiver, UnboundedSender}, lock::Mutex, SinkExt, StreamExt, }; use hyperid::HyperId; use crate::models::*; #[derive(Debug)] pub enum ChatServiceError { ChatNotFound, YouAreNotAPartecipant, ...
use std::{ collections::{HashMap, HashSet}, sync::Arc, }; use futures::{ channel::mpsc::{UnboundedReceiver, UnboundedSender}, lock::Mutex, SinkExt, StreamExt, }; use hyperid::HyperId; use crate::models::*; #[derive(Debug)] pub enum ChatServiceError { ChatNotFound, YouAreNotAPartecipant, ...
if auth_user_id != user_id { return Err(ChatServiceError::PermissionError); } let chat = match self.chats.get_mut(&add_to_chat.chat_id) { Some(chat) => chat, None => return Err(ChatServiceError::ChatNotFound), }; chat.user_ids...
, chats: HashMap<ChatId, Chat>, item_sender: UnboundedSender<Item>, chat_id_generator: HyperId, } impl ChatService { pub fn new(item_sender: UnboundedSender<Item>) -> Self { Self { user_devices: Default::default(), chats: Default::default(), chat_id_gene...
random
[ { "content": "struct CredentialRow {\n\n username: String,\n\n password: String,\n\n user_id: UserId,\n\n}\n\nimpl CredentialRow {\n\n fn get_user_id(&self) -> &UserId {\n\n &self.user_id\n\n }\n\n}\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::models::UserId;\n\n\n\n#[deri...
Rust
examples/egui/src/main.rs
dasifefe/rend3
e6d19773bdc4754a566f6d803f06314fa59329aa
use std::{sync::Arc, time::Instant}; use egui_winit_platform::{Platform, PlatformDescriptor}; use glam::UVec2; use winit::{event::Event::*, event_loop::ControlFlow}; fn main() { env_logger::init(); let event_loop = winit::event_loop::EventLoop::new(); let window = { let mut builder = wi...
use std::{sync::Arc, time::Instant}; use egui_winit_platform::{Platform, PlatformDescriptor}; use glam::UVec2; use winit::{event::Event::*, event_loop::ControlFlow}; fn main() { env_logger::init(); let event_loop = winit::event_loop::EventLoop::new(); let window = { let mut builder = wi...
12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20, ]; rend3::types::MeshBuilder::new(vertex_positions.to_vec()) .with_indices(index_data.to_vec()) .build() }
function_block-function_prefix_line
[ { "content": "fn create_quad(size: f32) -> rend3::types::Mesh {\n\n let vertex_positions = [\n\n vertex([-size * 0.5, size * 0.5, 0.0]),\n\n vertex([size * 0.5, size * 0.5, 0.0]),\n\n vertex([size * 0.5, -size * 0.5, 0.0]),\n\n vertex([-size * 0.5, -size * 0.5, 0.0]),\n\n ];\n\...
Rust
sdk/lookoutvision/src/json_ser.rs
StevenBlack/aws-sdk-rust
f4a1458f0154318c47d7e6a4ac55226f400fbfbc
pub fn serialize_structure_crate_input_create_dataset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDatasetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_1) = &input.dataset_source { let mut object_2 = object....
pub fn serialize_structure_crate_input_create_dataset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDatasetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_1) = &input.dataset_source { let mut object_2 = object....
pub fn serialize_structure_crate_model_target_platform( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::TargetPlatform, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_52) = &input.os { object.key("Os").string(var_52.as_str()); ...
pub fn serialize_structure_crate_model_input_s3_object( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::InputS3Object, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_49) = &input.bucket { object.key("Bucket").string(var_49.as_str())...
function_block-full_function
[]
Rust
third_party/rust_crates/vendor/derivative/src/ast.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
use attr; use proc_macro2; use syn; use syn::spanned::Spanned as SynSpanned; #[derive(Debug)] pub struct Input<'a> { pub attrs: attr::Input, pub body: Body<'a>, pub generics: &'a syn::Generics, pub ident: syn::Ident, pub span: proc_macro2::Span, } #[derive(Debug)] pub enum Body<'a> { Enum(Vec<...
use attr; use proc_macro2; use syn; use syn::spanned::Spanned as SynSpanned; #[derive(Debug)] pub struct Input<'a> { pub attrs: attr::Input, pub body: Body<'a>, pub generics: &'a syn::Generics, pub ident: syn::Ident, pub span: proc_macro2::Span, } #[derive(Debug)] pub enum Body<'a> { Enum(Vec<...
ident: field.ident.clone(), ty: &field.ty, span: field.span(), }) }) .collect() }
:Named(ref fields) => { Ok((Style::Struct, fields_from_ast(&fields.named, errors)?)) } syn::Fields::Unnamed(ref fields) => { Ok((Style::Tuple, fields_from_ast(&fields.unnamed, errors)?)) } syn::Fields::Unit => Ok((Style::Unit, Vec::new())), } } fn fields_from...
random
[]
Rust
src/main.rs
wdvxdr1123/silicon-api
f8fcda180d074b5fc17ab528a92a9757c3a954ea
mod ecy; mod hitokoto; use std::{borrow::Borrow, fs, io}; use actix_web::{ middleware::Logger, web::{get, post, Json}, App, Error, HttpResponse, HttpServer, Result, }; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use silicon::formatter::{ImageFormatter, ImageFormatterBuilder}; use si...
mod ecy; mod hitokoto; use std::{borrow::Borrow, fs, io}; use actix_web::{ middleware::Logger, web::{get, post, Json}, App, Error, HttpResponse, HttpServer, Result, }; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use silicon::formatter::{ImageFormatter, ImageFormatterBuilder}; use si...
#[derive(Debug, Deserialize)] pub struct SiliconReq { code: String, #[serde(default)] format: Format, } #[derive(Debug, Serialize)] pub struct SiliconResp { code: u32, err: Option<String>, url: Option<String>, } pub async fn code_to_image(input: Json<SiliconReq>) -> Result<HttpResponse> { ...
code: 100, err: Some("bad format!".to_string()), url: None, }) .into() }) }
function_block-function_prefix_line
[ { "content": " ];\n\n static ref CATEGORY_RANDOM: Vec<&'static str> = vec![\n\n \"anime\",\n\n \"comic\",\n\n \"game\",\n\n \"literature\",\n\n \"original\",\n\n \"internet\",\n\n \"video\",\n\n ];\n\n static ref REDIS_CLIENT: Client = Client::open(\"...
Rust
src/game.rs
XBagon/bevy_jam_one
7c55242e884a80ba4d2c7707900eb6ff969e4c45
use crate::{ nalgebra::Isometry2, AppState, Monster, SlimeBall, TargetStatus, HALF_HEIGHT, HALF_WIDTH, PHYSICS_SCALE, }; use bevy::{ input::{keyboard::KeyboardInput, ElementState}, prelude::*, }; use bevy_ase::asset::AseFileMap; use bevy_rapier2d::prelude::*; use std::path::Path; pub struct Game { ...
use crate::{ nalgebra::Isometry2, AppState, Monster, SlimeBall, TargetStatus, HALF_HEIGHT, HALF_WIDTH, PHYSICS_SCALE, }; use bevy::{ input::{keyboard::KeyboardInput, ElementState}, prelude::*, }; use bevy_ase::asset::AseFileMap; use bevy_rapier2d::prelude::*; use std::path::Path; pub struct Game { ...
pub fn detect_round_over( mut game: ResMut<Game>, removed_slime_ball: RemovedComponents<SlimeBall>, q_slime_ball: Query<(), With<SlimeBall>>, ) { if removed_slime_ball.iter().next().is_some() && q_slime_ball.iter().next().is_none() { match game.phase { ...
else { game.phase = Phase::Main; } } Phase::TransEnd => { let (overlay, mut handle, mut visibility) = q_overlay.single_mut(); *handle = overlay.memory_overflow_overlay.clone(); visibility.is_visible = true; ...
function_block-function_prefix_line
[ { "content": "// Wait until all sprites are loaded.\n\npub fn check_loading_sprites(mut state: ResMut<State<AppState>>, ase_loader: Res<Loader>) {\n\n if ase_loader.is_loaded() {\n\n info!(\"All Aseprite files loaded\");\n\n state.set(AppState::Ready).unwrap()\n\n }\n\n}\n", "file_path":...
Rust
src/sys/appmgr/integration_tests/component_events/component_events_integration_test.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { anyhow::{format_err, Context, Error}, fdio, fidl::endpoints::DiscoverableProtocolMarker, fidl_fuchsia_inspect::TreeMarker, fidl_fuchsia_sys::{ ComponentControllerEvent, EnvironmentControllerEvent, EnvironmentControllerProxy, EnvironmentMarker, EnvironmentOptions, EnvironmentP...
use { anyhow::{format_err, Context, Error}, fdio, fidl::endpoints::DiscoverableProtocolMarker, fidl_fuchsia_inspect::TreeMarker, fidl_fuchsia_sys::{ ComponentControllerEvent, EnvironmentControllerEvent, EnvironmentControllerProxy, EnvironmentMarker, EnvironmentOptions, EnvironmentP...
fn get_launcher(env: &EnvironmentProxy) -> Result<LauncherProxy, Error> { let (launcher, launcher_server_end) = fidl::endpoints::create_proxy().context("could not create proxy")?; env.get_launcher(launcher_server_end).context("could not get isolated environment launcher")?; Ok(launcher) } #[fasyn...
fn listen_for_component_events( env: &EnvironmentProxy, ) -> Result<ComponentEventListenerRequestStream, Error> { let (service_provider, server_end) = fidl::endpoints::create_proxy::<ServiceProviderMarker>().context("create proxy")?; env.get_services(server_end)?; let (event_provider, server_en...
function_block-full_function
[]
Rust
src/utils.rs
DPIclimate/pilot-reports
1e3b01e02840178af120167ae272124871af9517
pub mod time { extern crate chrono; use chrono::prelude::*; use log::info; pub fn unix_to_local(unix_time: &i64) -> DateTime<Local> { let datetime_ts = Utc.timestamp(unix_time / 1000, 0); DateTime::<Local>::from(datetime_ts) } pub fn next_10_days() -> (i64, i64) { ...
pub mod time { extern crate chrono; use chrono::prelude::*; use log::info; pub fn unix_to_local(unix_time: &i64) -> DateTime<Local> { let datetime_ts = Utc.timestamp(unix_time / 1000, 0); DateTime::<Local>::from(datetime_ts) } pub fn next_10_days() -> (i64, i64) { ...
) - 1] ); col_names } pub fn unix_range_to_timestring((start, end): &(i64, i64)) -> (String, String) { let start_unix = Utc.timestamp(start.to_owned(), 0); let start_local = DateTime::<Local>::from(start_unix) .format("%Y%m%d%H%M%S") .to_string(); ...
let local_day = unix_to_local(&unix_time).date().format("%A"); col_names.push(local_day.to_string()); unix_time += 86400000; } info!( "Column names range from {} to {}", col_names[0], col_names[col_names.len(
function_block-random_span
[]
Rust
src/bin/monolith-server.rs
TommyCpp/monolith
945c4ea73eeb93f975053e977455cd1cc3b4bcc5
#![allow(unused_must_use)] use clap::{App, Arg}; use monolith::indexer::*; use monolith::option::{DbOpts, ServerOpts}; use monolith::server::MonolithServer; use monolith::storage::*; use monolith::*; use std::process::exit; #[macro_use] extern crate log; fn main() { env_logger::init(); let default_port = D...
#![allow(unused_must_use)] use clap::{App, Arg}; use monolith::indexer::*; use monolith::option::{DbOpts, ServerOpts}; use monolith::server::MonolithServer; use monolith::storage::*; use monolith::*; use std::process::exit; #[macro_use] extern crate log; fn main() { env_logger::init(); let default_port = D...
long(WORKER_NUM) .default_value(default_worker_num.as_str()), Arg::with_name(TIKV_CONFIG).long(TIKV_CONFIG), ]) .get_matches(); let db_opts = DbOpts::get_config(&matches).expect("Cannot read db config"); let server_opts = ServerOpts::get_config(&matches).expect("Cann...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_get_time_series() -> Result<()> {\n\n let temp_dir = TempDir::new()?;\n\n let storage = SledStorage::new(temp_dir.path())?;\n\n\n\n let ingester = Ingester::new(None, None, None, 10);\n\n for (idx, series) in ingester.data.iter().enumerate() {\n\n for tp in se...
Rust
sadness-generator/src/lib.rs
EmbarkStudios/crash-handling
729dcef2c7c8fd13ce2d217581e02b7061bf9d85
#![allow(unsafe_code)] use std::arch::asm; #[derive(Copy, Clone, Debug)] pub enum SadnessFlavor { #[cfg(unix)] Abort, Segfault, DivideByZero, Illegal, #[cfg(unix)] Bus, Trap, ...
#![allow(unsafe_code)] use std::arch::asm; #[derive(Copy, Clone, Debug)] pub enum SadnessFlavor { #[cfg(unix)] Abort, Segfault, DivideByZero, Illegal, #[cfg(unix)] Bus, Trap, ...
ise(libc::SIGFPE); 0 } }; println!("we won't get here because we've raised a floating point exception: {ohno}"); std::process::abort() } pub unsafe fn raise_illegal_instruction() -> ! { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] asm!("ud2"); #[cfg(any(target_...
pub unsafe fn make_sad(self) -> ! { match self { #[cfg(unix)] Self::Abort => raise_abort(), Self::Segfault => raise_segfault(), Self::DivideByZero => raise_floating_point_exception(), Self::Illegal => raise_illegal_instruction(), ...
random
[ { "content": "pub fn run_client(id: &str, signal: Signal, use_thread: bool) {\n\n use std::env;\n\n\n\n // Adapted from\n\n // https://github.com/rust-lang/cargo/blob/485670b3983b52289a2f353d589c57fae2f60f82/tests/testsuite/support/mod.rs#L507\n\n let mut cmd_path = env::current_exe().expect(\"faile...
Rust
pallets/couple/src/tests.rs
XPredictMarket/NodePredict
b544651399e439efffb434146a3bc95465f18eda
use crate::{mock::*, Error}; use frame_support::{assert_noop, assert_ok, traits::Time}; use xpmrl_traits::{pool::LiquidityPool, ProposalStatus as ProposalState}; fn create_proposal( account: AccountId, currency_id: CurrencyIdOf<Test>, number: BalanceOf<Test>, rate: u32, step: MomentOf<Test>, ) -> ...
use crate::{mock::*, Error}; use frame_support::{assert_noop, assert_ok, traits::Time}; use xpmrl_traits::{pool::LiquidityPool, ProposalStatus as ProposalState}; fn create_proposal( account: AccountId, currency_id: CurrencyIdOf<Test>, number: BalanceOf<Test>, rate: u32, step: MomentOf<Test>, ) -> ...
#[test] fn test_set_result() { new_test_ext().execute_with(|| { let id = create_proposal(1, 1, 100000, 200, 10); assert_ok!( <ProposalsWrapper as LiquidityPool<Test>>::set_proposal_state( id, ProposalState::WaitingForResults ) ); ...
let account: AccountId = 1; let other_account: AccountId = 2; let currency_id: CurrencyIdOf<Test> = 1; let id = create_proposal(account, currency_id, number, 2000, 10); assert_noop!( CoupleModule::retrieval(Origin::signed(account), id + 1, 3, number), Error::<Test...
function_block-function_prefix_line
[ { "content": "pub fn get_account_id_from_address(address: &str) -> AccountId {\n\n if let Ok(account) = AccountId::from_ss58check(address) {\n\n account\n\n } else {\n\n Default::default()\n\n }\n\n}\n\n\n", "file_path": "node/src/chain_spec.rs", "rank": 0, "score": 139973.895...
Rust
src/core/index/merge/merge_rate_limiter.rs
unix1986/rucene
bf4de84dafb58eeedfc2b975556890ed3e5dc1f6
use core::store::RateLimiter; use core::index::ErrorKind::MergeAborted; use error::{ErrorKind, Result}; use std::f64; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Condvar, Mutex}; use std::time::{Duration, SystemTime}; use core::util::external::Volatile; pub struct MergeRateLimiter { ...
use core::store::RateLimiter; use core::index::ErrorKind::MergeAborted; use error::{ErrorKind, Result}; use std::f64; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Condvar, Mutex}; use std::time::{Duration, SystemTime}; use core::util::external::Volatile; pub struct MergeRateLimiter { ...
lt::No); } if cur_pause_dur > Duration::from_millis(250) { cur_pause_dur = Duration::from_millis(250); } let _ = self.cond.wait_timeout(l, cur_pause_dur)?; let rate = self.mb_per_sec.read(); if rate == 0.0 { Ok(PauseRe...
bytes_written: AtomicU64, mb_per_sec: Volatile<f64>, last_time: Volatile<SystemTime>, min_pause_check_bytes: Volatile<u64>, abort: AtomicBool, total_paused_dur: Volatile<Duration>, total_stopped_dur: Volatile<Duration>, lock: Mutex<()>, cond: Condvar, } #[derive(Debug, Eq, PartialE...
random
[ { "content": "pub fn check_version(version: i32) -> Result<()> {\n\n if version < VERSION_START {\n\n bail!(IllegalArgument(format!(\n\n \"Version is too old, should be at least {} (got {})\",\n\n VERSION_START, version\n\n )))\n\n } else if version > VERSION_CURRENT {\...
Rust
ramneryd/src/io/event.rs
NiklasJonsson/ramneryd
d9d02a7f57667cf51ec36e17861c66f41ff69582
use super::input; use input::ExternalInput; use std::sync::Arc; use winit::dpi::LogicalPosition; use winit::event::DeviceEvent; use winit::event::ElementState; use winit::event::MouseScrollDelta; use winit::event::WindowEvent; #[derive(Debug)] pub enum Event { Quit, Focus, Unfocus, Resize(trekanten::u...
use super::input; use input::ExternalInput; use std::sync::Arc; use winit::dpi::LogicalPosition; use winit::event::DeviceEvent; use winit::event::ElementState; use winit::event::MouseScrollDelta; use winit::event::WindowEvent; #[derive(Debug)] pub enum Event { Quit, Focus, Unfocus, Resize(trekanten::u...
} use std::sync::mpsc; pub fn event_thread_work( event_manager: &mut EventManager, event_queue: Arc<super::EventQueue>, command_queue: &super::CommandQueue, winit_event: winit::event::Event<()>, control_flow: &mut winit::event_loop::ControlFlow, ) { match command_queue.try_recv() { Er...
WinEvent::WindowEvent { event: WindowEvent::MouseInput { state, button, .. }, .. } => { log::debug!("Captured mouse button: {:?}", button); let is_pressed = state == ElementState::Pressed; let ei = if is_pressed { ...
function_block-function_prefix_line
[ { "content": "pub fn insertion_10000(c: &mut Criterion) {\n\n c.bench_with_input(BenchmarkId::new(\"insertion\", &N_OPS), &N_OPS, |b, &size| {\n\n b.iter(|| {\n\n let mut storage: Storage<usize> = Storage::with_capacity(size as u32);\n\n for _ in 0..size {\n\n stor...
Rust
src/raw.rs
lepelog/zeldaevent
4b5767dad75989e454b811592431fa07ce2a22d8
use byteorder::{ReadBytesExt, WriteBytesExt, BE}; use std::io::{Read, Write}; use crate::zevfile::ZevParseError; fn read_null_term_string<R: Read>(r: &mut R, max_len: usize) -> Result<String, ZevParseError> { let mut buf = vec![0; max_len]; r.read_exact(&mut buf)?; if let Some(end) = buf.iter().posit...
use byteorder::{ReadBytesExt, WriteBytesExt, BE}; use std::io::{Read, Write}; use crate::zevfile::ZevParseError; fn read_null_term_string<R: Read>(r: &mut R, max_len: usize) -> Result<String, ZevParseError> { let mut buf = vec![0; max_len]; r.read_exact(&mut buf)?;
fn write_null_term_pad_string<W: Write>( w: &mut W, s: &String, max_len: usize, ) -> Result<(), std::io::Error> { let as_bytes = s.as_bytes(); if as_bytes.len() > max_len { panic!("string too long!"); } w.write_all(as_bytes)?; let pad_left = max_len.checked_su...
if let Some(end) = buf.iter().position(|c| *c == 0) { String::from_utf8(buf[0..end].to_vec()) } else { String::from_utf8(buf) } .map_err(|_| ZevParseError::InvalidFile(format!("invalid string"))) }
function_block-function_prefix_line
[ { "content": "pub fn main() {\n\n let filename = env::args().skip(1).next().expect(\"no filename\");\n\n let eventname = env::args().skip(2).next().expect(\"no eventname\");\n\n let mut file = File::open(filename).expect(\"file not found\");\n\n let mut buf = Vec::new();\n\n file.read_to_end(&mut...
Rust
src/pwlp/server.rs
pixelspark/pwlp
33efeadc584860b3859f0e2a59e78e339beee416
use super::program::Program; use super::protocol::{Message, MessageType}; use eui48::MacAddress; use serde::{Deserialize, Serialize, Serializer}; use std::collections::HashMap; use std::net::{SocketAddr, UdpSocket}; use std::sync::{Arc, Mutex}; use std::time::Instant; #[derive(Serialize, Deserialize, Debug, Clone)] pu...
use super::program::Program; use super::protocol::{Message, MessageType}; use eui48::MacAddress; use serde::{Deserialize, Serialize, Serializer}; use std::collections::HashMap; use std::net::{SocketAddr, UdpSocket}; use std::sync::{Arc, Mutex}; use std::time::Instant; #[derive(Serialize, Deserialize, Debug, Clone)] pu...
if let Err(t) = socket .send_to(&run.signed(secret.as_bytes()), source_address) { println!("Send pong failed: {:?}", t); } } MessageType::Pong => { } _ => {} } m.devices.insert(mac_identifier, new_status...
} } else { self.default_program.clone() }; let run = Message { message_type: MessageType::Run, unix_time: msg.unix_time, mac_address: MacAddress::nil(), payload: Some(device_program.clone().code), }; new_status.p...
function_block-random_span
[ { "content": "fn build_server(config: &Config, serve_matches: &ArgMatches<'_>) -> std::io::Result<Server> {\n\n\tlet mut global_secret = String::from(\"secret\");\n\n\tlet mut default_program_path: Option<String> = None;\n\n\tlet mut devices: HashMap<String, DeviceConfig> = HashMap::new();\n\n\tlet mut bind_add...
Rust
src/models/r5/DeviceDefinition_Guideline.rs
itsbalamurali/rust-fhir
be43a387214586b6d8c5c5bf1d1f082a15c362b0
#![allow(unused_imports, non_camel_case_types)] use crate::models::r5::CodeableReference::CodeableReference; use crate::models::r5::Element::Element; use crate::models::r5::Extension::Extension; use crate::models::r5::RelatedArtifact::RelatedArtifact; use crate::models::r5::UsageContext::UsageContext; use serde_json::...
#![allow(unused_imports, non_camel_case_types)] use crate::models::r5::CodeableReference::CodeableReference; use crate::models::r5::Element::Element; use crate::models::r5::Extension::Extension; use crate::models::r5::RelatedArtifact::RelatedArtifact; use crate::models::r5::UsageContext::UsageContext; use serde_json::...
} #[derive(Debug)] pub struct DeviceDefinition_GuidelineBuilder { pub(crate) value: Value, } impl DeviceDefinition_GuidelineBuilder { pub fn build(&self) -> DeviceDefinition_Guideline { DeviceDefinition_Guideline { value: Cow::Owned(self.value.clone()), } } pub fn with(ex...
self._intended_use() { if !_val.validate() { return false; } } if let Some(_val) = self._usage_instruction() { if !_val.validate() { return false; } } if let Some(_val) = self.contraindication() { ...
function_block-function_prefixed
[ { "content": "fn is_numeric_char(c: char) -> bool {\n\n c.is_numeric() || c == '.'\n\n}\n\n\n", "file_path": "build_script.rs", "rank": 0, "score": 127903.19181758292 }, { "content": "fn write_string_to_file(contents: &str, path_string: &str) -> bool {\n\n if contents.len() == 0 {\n\n ...
Rust
AnimalCenter/model/src/animal/animalmodel.rs
futugyou/AnimalDeCompagnieNoSu
46cfe6a1ca91f1b9e390f276e9e04980dcf1f184
use async_graphql::validators::*; use async_graphql::*; use chrono::{DateTime, Utc}; #[derive(Debug, InputObject)] pub struct AnimalUpdateRequest { pub id: String, #[graphql(validator(and(StringMinLength(length = "2"), StringMaxLength(length = "20"))))] pub name: String, #[graphql(validator(and(String...
use async_graphql::validators::*; use async_graphql::*; use chrono::{DateTime, Utc}; #[derive(Debug, InputObject)] pub struct AnimalUpdateRequest { pub id: String, #[graphql(validator(and(StringMinLength(length = "2"), StringMaxLength(length = "20"))))] pub name: String, #[graphql(validator(and(String...
(StringMinLength(length = "2"), StringMaxLength(length = "20"))))] pub animal_type: String, #[graphql(validator(and(StringMinLength(length = "2"), StringMaxLength(length = "20"))))] pub sub_type: String, #[graphql(default)] pub birthday: Option<DateTime<Utc>>, #[graphql(default)] pub photoes...
ring>, pub rescue_date: Option<DateTime<Utc>>, } #[Object] impl AnimalUpdateResponse { async fn id(&self) -> &str { &self.id } async fn name(&self) -> &str { &self.name } async fn animal_type(&self) -> &str { &self.animal_type } async fn sub_type(&self) -> &str {...
random
[ { "content": "pub fn getutcnowwithformat() -> DateTime<Utc> {\n\n let date_string = Utc::now().format(FORMAT).to_string();\n\n let date = Utc.datetime_from_str(&date_string, FORMAT).unwrap();\n\n date\n\n}\n\n\n", "file_path": "AnimalCenter/tool/src/lib.rs", "rank": 0, "score": 115780.67010...
Rust
src/engine/operators/fuse_nulls.rs
Joylei/LocustDB
e3f5b5d351c30b2063ff858c28dff4d5d4e893d2
use crate::bitvec::*; use crate::engine::*; use std::i64; pub struct FuseNullsI64 { pub input: BufferRef<Nullable<i64>>, pub fused: BufferRef<i64>, } impl<'a> VecOperator<'a> for FuseNullsI64 { fn execute(&mut self, stream: bool, scratchpad: &mut Scratchpad<'a>) -> Result<(), QueryError> { let (in...
use crate::bitvec::*; use crate::engine::*; use std::i64; pub struct FuseNullsI64 { pub input: BufferRef<Nullable<i64>>, pub fused: BufferRef<i64>, } impl<'a> VecOperator<'a> for FuseNullsI64 { fn execute(&mut self, stream: bool, scratchpad: &mut Scratchpad<'a>) -> Result<(), QueryError> { let (in...
fn init(&mut self, _: usize, batch_size: usize, scratchpad: &mut Scratchpad<'a>) { scratchpad.set(self.fused, Vec::with_capacity(batch_size)); } fn inputs(&self) -> Vec<BufferRef<Any>> { vec![self.input.any()] } fn outputs(&self) -> Vec<BufferRef<Any>> { vec![self.fused.any()] } fn can_st...
t).is_set(i) { fused.push(input[i] + self.offset); } else { fused.push(T::zero()); } } Ok(()) }
function_block-function_prefixed
[ { "content": "fn is_uppercase_hex(string: &str) -> bool {\n\n string.len() & 1 == 0\n\n && string.chars().all(|c| {\n\n c == '0'\n\n || c == '1'\n\n || c == '2'\n\n || c == '3'\n\n || c == '4'\n\n || c == '5'\n\n ...
Rust
src/core/logpump/mod.rs
blastoise186/GearBot-2
3a51e950eb9ee0d4596fc0863f85c528a5a58775
mod log_data; mod log_filter; mod log_type; const GEARBOT_LOGO: &str = include_str!("../../../assets/logo"); const GEARBOT_EMBED_SENDER: &str = "GearBot moderation logs"; const DISCORD_SIZE_LIMIT: usize = 2000; const BATCH_SIZE: usize = 20; const RECV_TIMEOUT: Duration = Duration::from_secs(4); pub use log_data::LogD...
mod log_data; mod log_filter; mod log_type; const GEARBOT_LOGO: &str = include_str!("../../../assets/logo"); const GEARBOT_EMBED_SENDER: &str = "GearBot moderation logs"; const DISCORD_SIZE_LIMIT: usize = 2000; const BATCH_SIZE: usize = 20; const RECV_TIMEOUT: Duration = Duration::from_secs(4); pub use log_data::LogD...
out.push(embed); if out.len() == 10 { break; } } Err(e) => { gearbot_error!("Failed to create logging embed: {} (data: {:?})", e, data); } ...
}; let mut extra = format!( "{} {} {}", timestamp, item.log_type.emoji().for_chat(), item.log_type.to_text(&ctx, language, &user, &item.source_channel) ); extra.truncate(DISCORD_S...
random
[ { "content": "fn async_wrapper(todo: impl Future<Output = GearResult<()>> + Send + 'static, name: &'static str) {\n\n tokio::spawn(async move {\n\n if let Err(e) = todo.await {\n\n if e.is_user_error() {\n\n error!(\n\n \"A user error instead of a system er...
Rust
src/refine.rs
zentner-kyle/deltalog
8815901ac06b8ca78d469f42a402ee45f4621163
use bottom_up::evaluate_bottom_up; use fact_table::FactTable; use generate::Generator; use mutate::{MutationOpGenerator, MutationState}; use optimize::{Adjustment, compute_adjustments}; use program::Program; use rand::{Rng, XorShiftRng}; use reconstrain::compute_constraint_measure; use selector::Selector; use std::cmp:...
use bottom_up::evaluate_bottom_up; use fact_table::FactTable; use generate::Generator; use mutate::{MutationOpGenerator, MutationState}; use optimize
s = false; for _ in 0..10 { if let Ok(body_op) = gen.generate_body(&mut self.rng, &mut selector, &self.program, ...
::{Adjustment, compute_adjustments}; use program::Program; use rand::{Rng, XorShiftRng}; use reconstrain::compute_constraint_measure; use selector::Selector; use std::cmp::Ordering; use std::cmp::PartialOrd; use std::mem::swap; use truth_value::TruthValue; use uniform_selector::UniformPlusKSelector; pub struct Refiner...
random
[ { "content": " &mut apparent_fact_adjustments,\n\n &mut latent_fact_adjustments,\n\n max_iters);\n\n }\n\n return Adjustment {\n\n clause_adjustments,\n\n apparent_fact_adjustments,\n\n latent_fact_adj...
Rust
src/cube/connection.rs
kaz399/rs_toio_core_cube
f2347c975d8db328ff32c16888cba41ac492ce0d
use crate::ble::BleInterface; use crate::cube::uuid::CoreCubeUuid; use crate::handler::{HandlerFunction, NotifyManager}; use crate::scanner; use async_trait::async_trait; use btleplug::api::{ BDAddr, CharPropFlags, Characteristic, Peripheral as _, ScanFilter, ValueNotification, WriteType, }; use btleplug::platf...
use crate::ble::BleInterface; use crate::cube::uuid::CoreCubeUuid; use crate::handler::{HandlerFunction, NotifyManager}; use crate::scanner; use async_trait::async_trait; use btleplug::api::{ BDAddr, CharPropFlags, Characteristic, Peripheral as _, ScanFilter, ValueNotification, WriteType, }; use btleplug::platf...
async fn register_notify_handler( &mut self, func: Self::NotifyHandler, ) -> Result<Uuid, Box<dyn Error + Send + Sync + 'static>> { let id_handler = self.root_notify_manager.register(func)?; Ok(id_handler) } async fn unregister_notify_handler( &mut self, ...
async fn write( &self, uuid: Uuid, bytes: &[u8], ) -> Result<bool, Box<dyn Error + Send + Sync + 'static>> { if let Some(ble) = &self.ble_peripheral { let characteristic = self.ble_characteristics.get(&uuid).unwrap(); ble.write(characteristic, bytes, WriteType...
function_block-function_prefix_line
[ { "content": "#[derive(Serialize, Debug, Copy, Clone)]\n\nstruct MotorControlAcceleration {\n\n command: CommandId,\n\n acceleration: Acceleration,\n\n angle_velocity: AngleVelocity,\n\n moving_direction: MovingDirection,\n\n priority: Priority,\n\n period: Period,\n\n}\n\n\n\nimpl ToPayload<V...
Rust
src/folding/ascii.rs
artichoke/focaccia
2640fb9ec042b4a496181582259bbbbb448e1ef0
use core::cmp::Ordering; #[inline] #[must_use] pub fn casecmp(left: &[u8], right: &[u8]) -> Ordering { let mut left = left.iter().copied(); let mut right = right.iter().copied(); loop { match (left.next(), right.next()) { (None, None) => return Ordering::Equal, (None, Some(_...
use core::cmp::Ordering; #[inline] #[must_use] pub fn casecmp(left: &[u8], right: &[u8]) -> Ordering { let mut left = left.iter().copied(); let mut right = right.iter().copied(); loop { match (left.next(), right.next()) { (None, None) => return Ordering::Equal, (None, Some(_...
}
fn exhaustive() { let lower = 'a'..'z'; let upper = 'A'..'Z'; let mut l_buf = [0; 4]; let mut r_buf = [0; 4]; for (left, right) in lower.zip(upper) { let left = left.encode_utf8(&mut l_buf); let right = right.encode_utf8(&mut r_buf); assert!(ma...
function_block-full_function
[ { "content": "#[inline]\n\n#[must_use]\n\npub fn eq(left: &str, right: &str) -> bool {\n\n let left = left.chars().flat_map(|c| lookup(c, Mode::Full));\n\n let right = right.chars().flat_map(|c| lookup(c, Mode::Full));\n\n left.eq(right)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{casecm...
Rust
shipyard_rapier2d/examples/despawn2.rs
lucaspoffo/shipyard_rapier
9e26f9899d1c63ece03d633ff9985251cc0d40c8
use macroquad::prelude::*; use rapier2d::{dynamics::RigidBodyBuilder, geometry::ColliderBuilder, pipeline::PhysicsPipeline}; use shipyard::{AllStoragesViewMut, EntityId, UniqueViewMut, World}; use shipyard_rapier2d::{ physics::{ create_body_and_collider_system, create_joints_system, destroy_body_and_collide...
use macroquad::prelude::*; use rapier2d::{dynamics::RigidBodyBuilder, geometry::ColliderBuilder, pipeline::PhysicsPipeline}; use shipyard::{AllStoragesViewMut, EntityId, UniqueViewMut, World}; use shipyard_rapier2d::{ physics::{ create_body_and_collider_system, create_joints_system, destroy_body_and_collide...
pub fn despawn(time: f64, mut all_storages: AllStoragesViewMut) { if time > 5.0 { let despawn_entities = { let mut despawn = all_storages .borrow::<UniqueViewMut<DespawnResource>>() .unwrap(); let entities = despawn.entities.clone(); desp...
let collider = ColliderBuilder::cuboid(rad, rad).density(1.0); all_storages.add_entity((body, collider)); } } let despawn = DespawnResource { entities: despawn_entities, }; all_storages.add_unique(despawn); }
function_block-function_prefix_line
[ { "content": "/// System responsible for creating a Rapier rigid-body and collider from their\n\n/// builder resources.\n\npub fn create_body_and_collider_system(\n\n entities: EntitiesView,\n\n mut bodies: UniqueViewMut<RigidBodySet>,\n\n mut colliders: UniqueViewMut<ColliderSet>,\n\n mut rigid_bod...
Rust
src/cc_host_rgf/host_iot_lcs.rs
cvetaevvitaliy/nrf52840-pac
bf07243a5a043883d915999f0f8ccd6cbf6229b8
#[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::HOST_IOT_LCS { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, ...
#[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::HOST_IOT_LCS { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, ...
_from({ const MASK: u8 = 7; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 8 - This field is read-only and indicates if CRYPTOCELL LCS has been successfully configured since last reset"] #[inline] pub fn lcs_is_valid(&self)...
bit(variant._bits()) } } #[doc = "A valid LCS is not yet retained in the CRYPTOCELL AO power domain"] #[inline] pub fn invalid(self) -> &'a mut W { self.variant(LCS_IS_VALIDW::INVALID) } #[doc = "A valid LCS is successfully retained in the CRYPTOCELL AO power domain"] #[inlin...
random
[ { "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::POWER {\n\n #[doc = r\" Modifies the contents of the register\"]\n\n #[inline]\n\n pub fn modify<F>...
Rust
examples/console-producer.rs
flier/tokio-kafka
0ae7e34766832f6bc3d0df52042f4ebb5f9d107f
#[macro_use] extern crate error_chain; #[macro_use] extern crate log; extern crate getopts; extern crate pretty_env_logger; extern crate futures; extern crate tokio_core; #[cfg(not(target_os = "windows"))] extern crate tokio_file_unix; extern crate tokio_io; extern crate tokio_kafka; use std::env; use std::fs; use s...
#[macro_use] extern crate error_chain; #[macro_use] extern crate log; extern crate getopts; extern crate pretty_env_logger; extern crate futures; extern crate tokio_core; #[cfg(not(target_os = "windows"))] extern crate tokio_file_unix; extern crate tokio_io; extern crate tokio_kafka; use std::env; use std::fs; use s...
plit(',').map(|s| s.trim().to_owned()).collect(), ); let (api_version_request, broker_version) = m.opt_str("broker-version").map_or((false, None), |s| { if s == "auto" { (true, None) } else { (false, Some(s.parse().unwrap())) } ...
ring>, batch_size: usize, compression: Compression, required_acks: RequiredAcks, idle_timeout: Duration, ack_timeout: Duration, linger: Duration, } impl Config { fn parse_cmdline() -> Result<Self> { let args: Vec<String> = env::args().collect(); let program = Path::new(&args...
random
[ { "content": "#[derive(Clone, Debug)]\n\nstruct Config {\n\n brokers: Vec<String>,\n\n client_id: String,\n\n topics: Vec<String>,\n\n group_id: String,\n\n offset: SeekTo,\n\n no_commit: bool,\n\n skip_message_on_error: bool,\n\n}\n\n\n\nimpl Config {\n\n fn parse_cmdline() -> Result<Se...
Rust
src/polynomial.rs
ebfull/schoof-demo
05d9c6ce77e4ba31aacd595b77f264838f2398d4
use num_bigint::BigUint; use num_traits::identities::{One, Zero}; use crate::util::{modinv, one, zero}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Polynomial<'a> { pub(crate) coeffs: Vec<BigUint>, pub(crate) modulus: &'a BigUint, } impl<'a> Polynomial<'a> { pub fn new(modulus: &'a BigU...
use num_bigint::BigUint; use num_traits::identities::{One, Zero}; use crate::util::{modinv, one, zero}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Polynomial<'a> { pub(crate) coeffs: Vec<BigUint>, pub(crate) modulus: &'a BigUint, } impl<'a> Polynomial<'a> { pub fn new(modulus: &'a BigU...
for (divisor_coeff, remainder_coeff) in divisor .coeffs .iter() .zip(remainder.coeffs.iter_mut().skip(power)) { let tmp = (&q * divisor_coeff) % modulus; let tmp = modulus - tmp; ...
trim += 1; } else { break; } } let newlen = self.coeffs.len() - trim; self.coeffs.truncate(std::cmp::max(1, newlen)); } pub fn eval(&self, point: &BigUint) -> BigUint { let point = &(point % self.modulus); let mut acc = zero()...
random
[ { "content": "/// Returns the additive identity.\n\npub fn zero() -> BigUint {\n\n BigUint::zero()\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 96211.89232563693 }, { "content": "/// Returns the multiplicative identity.\n\npub fn one() -> BigUint {\n\n BigUint::one()\n\...
Rust
src/cargo/ops/cargo_package.rs
BurntSushi/cargo
492bc86063b377e0badd87e6aff188e5b0d770ea
use std::io::{fs, File}; use std::io::fs::PathExtensions; use std::path; use tar::Archive; use flate2::{GzBuilder, BestCompression}; use flate2::reader::GzDecoder; use core::source::{Source, SourceId}; use core::{Package, MultiShell}; use sources::PathSource; use util::{CargoResult, human, internal, ChainError, Requi...
use std::io::{fs, File}; use std::io::fs::PathExtensions; use std::path; use tar::Archive; use flate2::{GzBuilder, BestCompression}; use flate2::reader::GzDecoder; use core::source::{Source, SourceId}; use core::{Package, MultiShell}; use sources::PathSource; use util::{CargoResult, human, internal, ChainError, Requi...
fn run_verify(pkg: &Package, shell: &mut MultiShell, tar: &Path) -> CargoResult<()> { try!(shell.status("Verifying", pkg)); let f = try!(GzDecoder::new(try!(File::open(tar)))); let dst = pkg.get_root().join("target/package"); if dst.exists() { try!(fs::rmdir_recursive(&dst)); ...
s() { return Err(human(format!("destination already exists: {}", dst.display()))) } let tmpfile = try!(File::create(dst)); let encoder = GzBuilder::new().filename(dst.filename().unwrap()) .writer(tmpfile, BestCompression); ...
function_block-function_prefixed
[ { "content": "fn transmit(pkg: &Package, tarball: &Path, registry: &mut Registry)\n\n -> CargoResult<()> {\n\n let deps = pkg.get_dependencies().iter().map(|dep| {\n\n NewCrateDependency {\n\n optional: dep.is_optional(),\n\n default_features: dep.uses_default_features...
Rust
mempool/src/tests/integration_tests.rs
watssec/diem
d386dccba440966a5fa11d71aa1616deac9b5a5e
use crate::tests::test_framework::{test_transactions, MempoolNode, MempoolTestFrameworkBuilder}; use diem_config::network_id::PeerNetworkId; use netcore::transport::ConnectionOrigin; use network::{ testutils::{ test_framework::TestFramework, test_node::{ pfn_pfn_mock_connection, pfn_vf...
use crate::tests::test_framework::{test_transactions, MempoolNode, MempoolTestFrameworkBuilder}; use diem_config::network_id::PeerNetworkId; use netcore::transport::ConnectionOrigin; use network::{ testutils::{ test_framework::TestFramework, test_node::{ pfn_pfn_mock_connection, pfn_vf...
#[tokio::test] async fn single_inbound_node_test() { for (mut node, (other_peer_network_id, other_metadata)) in inbound_node_combinations() { let all_txns = test_transactions(0, 2); let all_txns = all_txns.as_slice(); node.connect_self(other_peer_network_id.network_id(), other_metadata); ...
fn outbound_node_combinations() -> [(MempoolNode, (PeerNetworkId, ConnectionMetadata)); 6] { [ ( MempoolTestFrameworkBuilder::single_validator(), validator_mock_connection(ConnectionOrigin::Inbound, &ALL_PROTOCOLS), ), ( MempoolTestFrameworkBuilder::single...
function_block-full_function
[]
Rust
src/transforms/normalize_end_tags.rs
mernen/sgmlish
26a75b0cacbc54bb16a10ba9b5487a2093d8979a
use crate::transforms::Transform; use crate::{text, SgmlEvent, SgmlFragment}; #[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum NormalizationError { #[error("unpaired end tag: </{0}>")] UnpairedEndTag(String), #[error("empty tags (<> and </>) are not supported")] EmptyTagNotSupported, } pu...
use crate::transforms::Transform; use crate::{text, SgmlEvent, SgmlFragment}; #[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum NormalizationError { #[error("unpaired end tag: </{0}>")] UnpairedEndTag(String), #[error("empty tags (<> and </>) are not supported")] EmptyTagNotSupported, } pu...
let result = normalize_end_tags(fragment).unwrap(); assert_eq!(result, expected,); } #[test] fn test_normalize_end_tags_xml_empty() { let fragment = parse( r##" <foo> <bar/> <baz>Hello <foo x='1...
transform.insert_at(insertion_point, SgmlEvent::EndTag { name: name.clone() }); } next_insertion_point = i; } SgmlEvent::XmlCloseEmptyElement => { *event = SgmlEvent::CloseStartTag; end_xml_empty_element = Some(i + 1); ...
random
[ { "content": "pub fn open_start_tag<'a, E>(\n\n input: &'a str,\n\n config: &ParserConfig,\n\n) -> IResult<&'a str, SgmlEvent<'a>, E>\n\nwhere\n\n E: ParseError<&'a str> + ContextError<&'a str>,\n\n{\n\n map(raw::open_start_tag, |name| SgmlEvent::OpenStartTag {\n\n name: config.name_normaliza...
Rust
src/kani-compiler/src/main.rs
celinval/rmc-dev
d7a574d0d2364010c86851cf57000b2da439d873
#![feature(rustc_private, once_cell)] extern crate rustc_codegen_ssa; extern crate rustc_driver; extern crate rustc_session; use clap::{ app_from_crate, crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg, ArgMatches, }; use kani_queries::{QueryDb, UserInput}; use rustc_driver:...
#![feature(rustc_private, once_cell)] extern crate rustc_codegen_ssa; extern crate rustc_driver; extern crate rustc_session; use clap::{ app_from_crate, crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg, ArgMatches, }; use kani_queries::{QueryDb, UserInput}; use rustc_driver:...
.long("--restrict-vtable-fn-ptrs") .help("Restrict the targets of virtual table function pointer calls."), ) .arg( Arg::with_name("sysroot") .long("--sysroot") .help("Override the system root.") .long_help( ...
.long("--symbol-table-passes") .value_name("PASS") .help("Transformations to perform to the symbol table after it has been generated.") .takes_value(true) .use_delimiter(true) .multiple(true), ) .arg( A...
random
[ { "content": "/// Parse a config toml string and extract the cargo-kani arguments we should try injecting.\n\n/// This returns two different vectors since all cbmc-args have to be at the end.\n\n/// We currently support the following entries:\n\n/// - flags: Flags that get directly passed to Kani.\n\n/// - unst...
Rust
accumulator/src/subroutines.rs
tetcoin/stateless-blockchain
88aceb543b88a23bd93122224d48b3de4bbbeb9e
use runtime_io::blake2_256; use rstd::prelude::Vec; use super::U2048; use crate::BezoutPair; pub fn mod_exp(mut base: U2048, mut exp: U2048, modulus: U2048) -> U2048 { let mut result: U2048 = U2048::from(1); base = base % modulus; while exp > U2048::from(0) { if exp % U2048::from(2) == U2048::fro...
use runtime_io::blake2_256; use rstd::prelude::Vec; use super::U2048; use crate::BezoutPair; pub fn mod_exp(mut base: U2048, mut exp: U2048, modulus: U2048) -> U2048 { let mut result: U2048 = U2048::from(1); base = base % modulus; while exp > U2048::from(0) { if exp % U2048::from(2) == U2048::fro...
#[test] fn test_hash_to_prime() { } #[test] fn test_root_factor() { assert_eq!(root_factor(U2048::from(2), &vec![U2048::from(3), U2048::from(5), U2048::from(7), U2048::from(11)]), vec![U2048::from(2), U2048::from(8), U2048::from(5), U2048::from(5)]); ...
assert_eq!(miller_rabin(U2048::from(48131)), true); assert_eq!(miller_rabin(U2048::from(76463)), true); assert_eq!(miller_rabin(U2048::from(4222234741u64)), true); assert_eq!(miller_rabin(U2048::from(187278659180417234321u128)), true); assert_eq!(miller_rabin(U2048::from(21)), false); ...
function_block-function_prefix_line
[ { "content": "/// Creates a non-membership witness relative to some previous state. The current state should equal \"old_state\"\n\n/// raised to the \"agg_elems\" power(represents product of added elements). The second value of the\n\n/// tuple is the sign of the first value since the Bezout coefficient may be...
Rust
qualinvest_server/src/accounts.rs
xemwebe/qualinvest
49e7e5fb2ce521ed451a49ec0c96a47bf215e097
use std::collections::HashMap; use std::collections::HashSet; use super::{rocket_uri_macro_login}; use rocket::form::{Form, FromForm}; use rocket::response::Redirect; use rocket::State; use rocket_dyn_templates::Template; use super::ServerState; use crate::layout::layout; use crate::user::UserCookie; use qualinvest_...
use std::collections::HashMap; use std::collections::HashSet; use super::{rocket_uri_macro_login}; use rocket::form::{Form, FromForm}; use rocket::response::Redirect; use rocket::State; use rocket_dyn_templates::Template; use super::ServerState; use crate::layout::layout; use crate::user::UserCookie; use qualinvest_...
pub async fn user_accounts( form: Form<UserAccountsForm>, user: UserCookie, state: &State<ServerState>, ) -> Result<Redirect, Redirect> { if !user.is_admin { return Err(Redirect::to(uri!(ServerState::base(), accounts( Some("You must be admin user to change other users accounts; to ch...
function_block-full_function
[ { "content": "/// Used to remove all non-hexadecimal characters from passwords\n\n/// Passwords must be only hex characters as it is expecting a hash, like sha-256 or md5 for example\n\npub fn sanitize_password(string: &str) -> String {\n\n filter_non_characters(string)\n\n}\n\n\n", "file_path": "qualinv...
Rust
src/parsers/statement/if_clause.rs
Lehona/Parsiphae
5cfb63ab29df99073a9fcc551d42652bdb130c74
use inner_errors::ParserError; use nom::ErrorKind; use parsers::{expression, replacements::*, statement_block}; use types::{IfBranch, IfStatement, Input, Statement}; named!(pub if_branch<Input, IfBranch, ParserError>, do_parse!( tag_no_case_e!("if") >> multispace0 >> branch: return_error!(ErrorKind::Custom(Par...
use inner_errors::ParserError; use nom::ErrorKind; use parsers::{expression, replacements::*, statement_block}; use types::{IfBranch, IfStatement, Input, Statement}; named!(pub if_branch<Input, IfBranch, ParserError>, do_parse!( tag_no_case_e!("if") >> multispace0 >> branch: return_error!(ErrorKind::Custom(Par...
#[test] fn else_branch_empty() { let input = Input(b"else{}"); let expected: Vec<Statement> = Vec::new(); let actual = else_branch(input).unwrap().1; assert_eq!(expected, actual); } #[test] fn else_branch_single_statement() { let input = Input(b"else{5;}"...
ment::Exp(Expression::Int(6)), ], }; let actual = if_branch(input).unwrap().1; assert_eq!(expected, actual); }
function_block-function_prefixed
[ { "content": "fn convert_identifier(input: Input) -> Identifier {\n\n Identifier::new(&input.0)\n\n}\n\n\n\nconst IDENTIFIER_BEGIN: &'static [u8] =\n\n b\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890\";\n\nconst IDENTIFIER_END: &'static [u8] =\n\n b\"abcdefghijklmnopqrstuvwxyzABCDEFG...
Rust
src/lib.rs
aywrite/bloom
cc485ff20e61e2eaea74d691cc33df54a32581ec
extern crate fnv; use fnv::FnvHasher; use std::hash::Hash; use std::hash::Hasher; #[derive(PartialEq, Eq, Hash, Debug, Clone)] pub struct BloomFilter { data: Vec<bool>, size: usize, num_hashers: usize, } impl Default for BloomFilter { fn default() -> BloomFilter { let size = 100; Bl...
extern crate fnv; use fnv::FnvHasher; use std::hash::Hash; use std::hash::Hasher; #[derive(PartialEq, Eq, Hash, Debug, Clone)] pub struct BloomFilter { data: Vec<bool>, size: usize, num_hashers: usize, } impl Default for BloomFilter { fn default() -> BloomFilter { let size = 100; Bl...
} return true; } pub fn is_empty(&mut self) -> bool { self.data.iter().all(|x| *x == false) } pub fn clear(&mut self) { for i in 0..self.data.len() {...
let hash = self.hash(&value, i + 1); if !self.data[hash] { return false; }
function_block-random_span
[ { "content": "#[test]\n\nfn test_new_is_empty() {\n\n let mut bf = BloomFilter::new();\n\n assert_eq!(bf.is_empty(), true);\n\n}\n\n\n", "file_path": "tests/lib.rs", "rank": 0, "score": 26800.35268113902 }, { "content": "#[test]\n\nfn test_insert_and_contains() {\n\n let mut bf = Bl...
Rust
convert-all-flts/src/main.rs
mrkline/flt2vhs
eb22872cea9c4af71126806aea06ee90bc1d05de
use std::env; use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use anyhow::*; use chrono::prelude::*; use log::*; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(verbatim_doc_comment)] struct Args { #[structopt(short, long, parse(from_occurrences))] verbose: u8, #[...
use std::env; use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use anyhow::*; use chrono::prelude::*; use log::*; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(verbatim_doc_comment)] struct Args { #[structopt(short, long, parse(from_occurrences))] verbose: u8, #[...
fn path_list(paths: &[PathBuf]) -> String { paths .iter() .map(|p| p.to_string_lossy()) .collect::<Vec<_>>() .join(", ") } fn convert_flts(args: &Args, flts: &[PathBuf]) -> Result<()> { debug!( "Converting {:?} with {}", path_list(flts), args.converter....
const TICKS_PER_SECOND: u64 = 1_000_000_000 / 100; if ts == 0 { None } else { let seconds = ts / TICKS_PER_SECOND; let nanos = (ts % TICKS_PER_SECOND) * 100; Some( Utc.ymd(1601, 1, 1).and_hms(0, 0, 0) + chrono::Duration::seconds(seconds as i64) ...
function_block-function_prefix_line
[ { "content": "fn output_name(input: &Path) -> Result<PathBuf> {\n\n // Path::with_extension just replaces the last one.\n\n // Replace ALL THE EXTENISONS!\n\n let name = input\n\n .file_name()\n\n .ok_or_else(|| anyhow!(\"{} isn't a file name!\", input.display()))?;\n\n let as_str = na...
Rust
src/parser/nodes.rs
endoli/commands.rs
dc8761ab9f3a17dc31722ec6424d014deb8da840
use std::rc::Rc; use super::{Completion, Parser}; use super::constants::*; use tokenizer::Token; pub enum Node { Command(CommandNode), Parameter(ParameterNode), ParameterName(ParameterNameNode), Root(RootNode), } pub trait NodeOps { fn accept<'text>(&self, par...
use std::rc::Rc; use super::{Completion, Parser}; use super::constants::*; use tokenizer::Token; pub enum Node { Command(CommandNode), Parameter(ParameterNode), ParameterName(ParameterNameNode), Root(RootNode), } pub trait NodeOps { fn accept<'text>(&self, par...
} impl NodeOps for CommandNode { fn accept<'text>(&self, parser: &mut Parser<'text>, _token: Token, node_ref: &Rc<Node>) { if self.handler.is_some() { parser.commands.push(Rc::clone(node_ref)) } } fn acceptable(&self, parser: &Parser, node_ref: &Rc<Node>) -> bool { ...
pub fn new( name: &str, help_text: Option<&str>, hidden: bool, priority: i32, successors: Vec<Rc<Node>>, handler: Option<fn(node: &Node) -> ()>, parameters: Vec<Rc<Node>>, ) -> Self { CommandNode { node: TreeNode { name: nam...
function_block-full_function
[ { "content": "/// A command\n\npub trait Command {\n\n /// Execute the command\n\n fn execute(&self);\n\n}\n\n\n\n/// Information about a command in a command table.\n\npub struct CommandTableEntry {\n\n /// Name of a command. This is used for command line entry.\n\n pub name: String,\n\n /// The...
Rust
tests/test_exec.rs
64/riscv-sim
293c5bec94a4654da58fb14c3a5751abb8e1000c
use aca::{ cpu::Cpu, emulated::Emulated, inst::ArchReg, mem::MainMemory, out_of_order::OutOfOrder, parse_and_exec, util::Addr, }; #[generic_tests::define] mod t { use aca::regs::RegSet; use super::*; #[test] fn test_loop<C: Cpu>() { let initial_regs = RegSet::from([ (ArchR...
use aca::{ cpu::Cpu, emulated::Emulated, inst::ArchReg, mem::MainMemory, out_of_order::OutOfOrder, parse_and_exec, util::Addr, }; #[generic_tests::define] mod t { use aca::regs::RegSet; use super::*; #[test] fn test_loop<C: Cpu>() { let initial_regs = RegSet::from([ (ArchR...
#[test] fn test_fibonnaci<C: Cpu>() { fn fib(n: u32) -> u32 { if n <= 1 { 1 } else { fib(n - 1) + fib(n - 2) } } let run = |x| { let val = parse_and_exec::<C>( "fibonnaci", ...
m([(ArchReg::A0, x)]), MainMemory::new(), ) .regs .get(ArchReg::A0); let expected: u32 = (1..=x).product(); assert_eq!(val, expected); }; for i in 0..10 { run(i); } }
function_block-function_prefixed
[ { "content": "pub fn parse_and_exec<C: Cpu>(name: &'static str, regs: RegSet, mem: MainMemory) -> ExecResult {\n\n let contents = std::fs::read_to_string(format!(\"asm/{}.asm\", name)).unwrap();\n\n let prog = contents\n\n .parse::<Program>()\n\n .expect(\"failed to parse assembly\");\n\n ...
Rust
app/src/board.rs
andreyk0/cardiac-monitor
dfb37b68d40d45ea5ec47745f64380cff5831419
use max3010x::Max3010x; use stm32f1xx_hal::prelude::*; use crate::{consts::*, delay::*, lcd::*, types::*}; use stm32f1xx_hal::i2c; use stm32f1xx_hal::i2c::blocking::BlockingI2c; pub struct Board { pub test_pin: TestPin, pub beeper: BeeperPin, pub max30102_sensor: Max30102Sensor, pub lcd: Lcd<AsmDel...
use max3010x::Max3010x; use stm32f1xx_hal::prelude::*; use crate::{consts::*, delay::*, lcd::*, types::*}; use stm32f1xx_hal::i2c; use stm32f1xx_hal::i2c::blocking::BlockingI2c; pub struct Board { pub test_pin: TestPin, pub beeper: BeeperPin, pub max30102_sensor: Max30102Sensor, pub lcd: Lcd<AsmDel...
.pll2() .prediv1() .div5() }); device.RCC.cr.modify(|_, w| w.pll2on().set_bit()); let rcc = device.RCC.constrain(); let clocks = rcc .cfgr .use_hse(8.mhz()) .hcl...
evice: stm32f1::stm32f107::Peripherals, ) -> Self { let mut flash = device.FLASH.constrain(); let mut gpioa = device.GPIOA.split(); let mut gpiob = device.GPIOB.split(); let mut gpioc = device.GPIOC.split(); let mut gpiod = device.GPIOD.split(); let lcd = Lcd::new( ...
random
[ { "content": "pub trait DelayCycles {\n\n fn delay_cycles(&mut self, cs: u32);\n\n}\n\n\n\nimpl DelayCycles for AsmDelay {\n\n #[inline]\n\n fn delay_cycles(&mut self, cs: u32) {\n\n asm::delay(cs)\n\n }\n\n}\n", "file_path": "app/src/delay.rs", "rank": 0, "score": 55897.921437683...
Rust
src/visitors.rs
smbolton/abcdb
fad19eee745cdadb895185bef8f729ef2764ec3b
extern crate pest; extern crate phf; use std::char; use std::iter::FromIterator; use pest::prelude::*; use grammar::{Rdp,Rule}; #[derive(Clone,Debug)] struct RSlice { start: usize, end: usize } #[derive(Clone,Debug)] enum RString { Slice(RSlice), Str(String) } impl RString { fn from_slice(st...
extern crate pest; extern crate phf; use std::char; use std::iter::FromIterator; use pest::prelude::*; use grammar::{Rdp,Rule}; #[derive(Clone,Debug)] struct RSlice { start: usize, end: usize } #[derive(Clone,Debug)] enum RString { Slice(RSlice), Str(String) } impl RString { fn from_slice(st...
Rule::note_length_slashes => { let slashes = &input[q[i].start..q[i].end]; match slashes { "/" | "//" => (RString::from_token(&q[i]), i + 1), _ => { let n = 1 << (q[i].end - q[i].start); (RString::Str(...
= "r") { if let Some(replacement) = decode_abc_text_string(&rstr.clone().to_string(input)) { return (RString::Str(replacement), new_i); } } (rstr, new_i) } Rule::invisible_barline => { if &input[q[i].start..q[i].end...
random
[ { "content": "fn parse_get_error_message(parser: &mut Rdp<pest::StringInput>) -> String {\n\n let expected = parser.expected();\n\n let mut message = format!(\"ABC parse failed at character {}, \", expected.1);\n\n if expected.1 > 10 {\n\n message.push_str(&format!(\"matched '...{}', \", parser....
Rust
src/lib/vm/object.rs
loalang/loalang
745edc192564b3f362ad1623fbb8853fcefa876e
use crate::syntax::characters_to_string; use crate::vm::*; use crate::*; use std::f64::INFINITY; use std::ptr::null; pub static mut STRING_CLASS: *const Class = null(); pub static mut CHARACTER_CLASS: *const Class = null(); pub static mut SYMBOL_CLASS: *const Class = null(); pub static mut U8_CLASS: *const Class = nu...
use crate::syntax::characters_to_string; use crate::vm::*; use crate::*; use std::f64::INFINITY; use std::ptr::null; pub static mut STRING_CLASS: *const Class = null(); pub static mut CHARACTER_CLASS: *const Class = null(); pub static mut SYMBOL_CLASS: *const Class = null(); pub static mut U8_CLASS: *const Class = nu...
} pub fn set_variable(&self, variable: &Variable, value: Arc<Object>) -> Arc<Object> { Arc::new(Object { class: self.class.clone(), const_value: match self.const_value { ConstValue::InstanceVariables(ref v) => { let mut v = v.clone(); ...
match self.const_value { ConstValue::InstanceVariables(ref v) => v.get(&variable.id).cloned(), _ => None, }
if_condition
[ { "content": "pub fn is_valid_symbol(string: &String) -> bool {\n\n let source = Source::new(SourceKind::Module, URI::Exact(\"tmp\".into()), string.clone());\n\n let tokens = tokenize(source);\n\n\n\n tokens.len() == 2 && matches!(tokens[0].kind, TokenKind::SimpleSymbol(_))\n\n}\n\n\n", "file_path"...