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
crates/mun_codegen/src/ir/function.rs
tdejager/mun
769bfe5a3a921bcc5289217e692f7f8cf19648ab
use super::try_convert_any_to_basic; use crate::ir::dispatch_table::DispatchTable; use crate::values::{ BasicValueEnum, CallSiteValue, FloatValue, FunctionValue, InstructionOpcode, IntValue, }; use crate::{IrDatabase, Module, OptimizationLevel}; use inkwell::builder::Builder; use inkwell::passes::{PassManager, Pass...
use super::try_convert_any_to_basic; use crate::ir::dispatch_table::DispatchTable; use crate::values::{ BasicValueEnum, CallSiteValue, FloatValue, FunctionValue, InstructionOpcode, IntValue, }; use crate::{IrDatabase, Module, OptimizationLevel}; use inkwell::builder::Builder; use inkwell::passes::{PassManager, Pass...
Resolution::Def(_) => panic!("no support for module definitions"), } } fn gen_binary_op(&mut self, lhs: ExprId, rhs: ExprId, op: BinaryOp) -> BasicValueEnum { let lhs_value = self.gen_expr(lhs).expect("no lhs value"); let rhs_value = self.gen_expr(rhs).expect("no rhs value"); ...
ck() .expect("at this stage there must be a block"); if let Some(first_instruction) = block.get_first_instruction() { temp_builder.position_before(&first_instruction); } else { temp_builder.position_at_end(&block); } temp_builder } fn gen...
random
[ { "content": "/// Build the declared type of a function. This should not need to look at the\n\n/// function body.\n\nfn type_for_fn(_db: &impl HirDatabase, def: Function) -> Ty {\n\n Ty::simple(TypeCtor::FnDef(def))\n\n}\n\n\n", "file_path": "crates/mun_hir/src/ty/lower.rs", "rank": 0, "score": ...
Rust
src/algebra.rs
doxxx/raytracer
21c92437ffd07d0434f8e095ce787fe23f42658c
/* Transcribed from http://cosinekitty.com/raytrace/rtsource.zip. Original written by Don Cross. Adapted to Rust by Gordon Tyler. */ #![allow(non_snake_case)] use num_complex::Complex; use std::f64::consts::PI; const TOLERANCE: f64 = 1.0e-8; const TWO_PI: f64 = 2.0 * PI; fn complex(re: f64) -> Complex<f64> { ...
/* Transcribed from http://cosinekitty.com/raytrace/rtsource.zip. Original written by Don Cross. Adapted to Rust by Gordon Tyler. */ #![allow(non_snake_case)] use num_complex::Complex; use std::f64::consts::PI; const TOLERANCE: f64 = 1.0e-8; const TWO_PI: f64 = 2.0 * PI; fn complex(re: f64) -> Complex<f64> { ...
complex(5.0)); test_known_quartic_roots(complex(1.0), complex(3.2), complex(2.5), complex(53.0), complex(-8.7)); test_known_quartic_roots(complex2(-2.3,4.8), complex2(3.2,-4.1), complex2(-2.5,7.7), complex2(53.0,-23.9), complex2(-9.2,-8.7)); } }
0), complex(4.0)); test_known_cubic_roots(complex2(-2.3,4.8), complex2(3.2,-4.1), complex2(-2.5,7.7), complex2(53.0,-23.9)); } #[test] pub fn quartic() { test_known_quartic_roots(complex(1.0), complex(2.0), complex(3.0), complex(4.0),
random
[ { "content": "fn solve_quadratic(a: f64, b: f64, c: f64) -> Option<(f64, f64)> {\n\n let discr = b * b - 4.0 * a * c;\n\n if discr < 0.0 {\n\n return None;\n\n } else if discr == 0.0 {\n\n let x = -0.5 * b / a;\n\n return Some((x, x));\n\n } else {\n\n let q = if b > 0.0 ...
Rust
src/tables/parts.rs
jaredwolff/eagle-plm
aae5fd8f0ca6d30d295af99eed038b2195fa073b
extern crate diesel; use prettytable::{row, Table}; use serde::Deserialize; use crate::{models::*, *}; use diesel::prelude::*; use std::fs::File; use std::io::BufReader; #[derive(Debug, Deserialize)] struct Record { pn: String, mpn: String, desc: String, } pub fn create(app: &mut crate::Application) { ...
extern crate diesel; use prettytable::{row, Table}; use serde::Deserialize; use crate::{models::*, *}; use diesel::prelude::*; use std::fs::File; use std::io::BufReader; #[derive(Debug, Deserialize)] struct Record { pn: String, mpn: String, desc: String, } pub fn create(app: &mut crate::Application) { ...
pub fn delete(app: &mut crate::Application) { let part = app.prompt.ask_text_entry("Part Number: "); let part = find_part_by_pn(&app.conn, &part).expect("Unable to find part!"); let question = format!("Would you like to delete {}?", part.pn); let delete = app.prompt.ask_yes_no_question(&qu...
update_part(&app.conn, &found.id, &part).expect("Unable to update part!"); println!("{} updated!", part.pn); } } } else { println!("Creating: {:?}", part); create_part(&app.conn, &part).expect("Unable to create part!")...
function_block-function_prefix_line
[ { "content": "/// Function used to show parts in BOM\n\npub fn show(app: &mut crate::Application, part_number: &str, version: &Option<i32>) {\n\n use crate::schema::*;\n\n\n\n // Find the part\n\n let part = find_part_by_pn(&app.conn, &part_number);\n\n\n\n if part.is_err() {\n\n println!(\"{...
Rust
2018/dec03/rs/src/main.rs
henrywallace/advent-of-code
f50d00b47603117e25c18d4f645fadd451fb6be2
extern crate clap; #[macro_use] extern crate lazy_static; extern crate regex; use std::error::Error; use std::fs::File; use std::io::{BufReader, BufRead}; use clap::{Arg, App}; use std::collections::{HashMap, HashSet}; use std::str::FromStr; use regex::Regex; #[derive(Debug)] struct Claim { id: u32, offset: ...
extern crate clap; #[macro_use] extern crate lazy_static; extern crate regex; use std::error::Error; use std::fs::File; use std::io::{BufReader, BufRead}; use clap::{Arg, App}; use std::collections::{HashMap, HashSet}; use std::str::FromStr; use regex::Regex; #[derive(Debug)] struct Claim { id: u32, offset: ...
} println!("{:?}", alone.difference(&not_alone)); Ok(()) } fn main() { let matches = App::new("dec01") .arg(Arg::with_name("input").required(true)) .arg(Arg::with_name("part").long("part").required(true) .takes_value(true) .possible_values(&["1", "2"])) ...
not_alone: HashSet<u32> = HashSet::new(); for v in fabric.values() { if v.len() == 1 { alone.insert(v[0]); } else { for id in v.iter() { not_alone.insert(*id); } }
function_block-random_span
[ { "content": "type GuardID = u32;\n\n\n", "file_path": "2018/dec04/rs/src/main.rs", "rank": 1, "score": 92777.30177134293 }, { "content": "fn part1(input: &str) -> Result<(), Box<Error>> {\n\n let f = File::open(input)?;\n\n let buf = BufReader::new(f);\n\n let mut records = vec![];...
Rust
src/post.rs
Lonami/pagong
bb5b24c733c435e8c041e5a91112e3ae5ad8cacc
use crate::config::{ Config, DATE_FMT, META_KEY_CATEGORY, META_KEY_CREATION_DATE, META_KEY_MODIFIED_DATE, META_KEY_TAGS, META_KEY_TEMPLATE, META_KEY_TITLE, META_TAG_SEPARATOR, META_VALUE_SEPARATOR, SOURCE_META_KEY, }; use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag}; use std::collections::HashMap; u...
use crate::config::{ Config, DATE_FMT, META_KEY_CATEGORY, META_KEY_CREATION_DATE, META_KEY_MODIFIED_DATE, META_KEY_TAGS, META_KEY_TEMPLATE, META_KEY_TITLE, META_TAG_SEPARATOR, META_VALUE_SEPARATOR, SOURCE_META_KEY, }; use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag}; use std::collections::HashMap; u...
}
pub fn new(config: &Config, root: &Path, path: PathBuf) -> io::Result<Self> { let mut markdown = fs::read_to_string(&path)?.replace(ZWNBSP, ""); let mut meta = HashMap::new(); if let Some((Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(lang))), st...
function_block-full_function
[ { "content": "pub fn get_relative_uri(relative_to: &str, uri: &str) -> String {\n\n let relative_to = relative_to.as_bytes();\n\n let uri = uri.as_bytes();\n\n\n\n let mut count_after = relative_to.len();\n\n let mut last_shared_slash = 0;\n\n for i in 0..relative_to.len().max(uri.len()) {\n\n ...
Rust
src/args/arg_builder/flag.rs
Nemo157/clap-rs
01994467d5808903907012c26953ebde72594137
use std::convert::From; use std::fmt::{Display, Formatter, Result}; use std::rc::Rc; use std::result::Result as StdResult; use vec_map::VecMap; use Arg; use args::{AnyArg, DispOrder}; use args::settings::{ArgFlags, ArgSettings}; #[derive(Debug)] #[doc(hidden)] pub struct FlagBuilder<'n, 'e> { pub name: &'n str,...
use std::convert::From; use std::fmt::{Display, Formatter, Result}; use std::rc::Rc; use std::result::Result as StdResult; use vec_map::VecMap; use Arg; use args::{AnyArg, DispOrder}; use args::settings::{ArgFlags, ArgSettings}; #[derive(Debug)] #[doc(hidden)] pub struct FlagBuilder<'n, 'e> { pub name: &'n str,...
; assert_eq!(&*format!("{}", f), "-f"); } }
Some(vec![ ("alias_not_visible", false), ("f2", true), ("f3", true), ("f4", true) ])
call_expression
[ { "content": "fn compare_app_str(l: &App, right: &str) -> bool {\n\n let left = build_new_help(&l);\n\n // Strip out any mismatching \\r character on windows that might sneak in on either side\n\n let b = left.trim().replace(\"\\r\", \"\") == right.replace(\"\\r\", \"\");\n\n if !b {\n\n prin...
Rust
src/rest_api/routes/consortium.rs
arsulegai/splinter-admin-ops-daemon
8511d0ce2505eb9bfe4bfa973a31bbf87b1f4bf4
use std::collections::HashMap; use actix_web::{client::Client, error, http::StatusCode, web, Error, HttpResponse}; use futures::{Future, IntoFuture}; use openssl::hash::{hash, MessageDigest}; use protobuf::Message; use splinter::admin::messages::{ AuthorizationType, CreateCircuit, DurabilityType, PersistenceType...
use std::collections::HashMap; use actix_web::{client::Client, error, http::StatusCode, web, Error, HttpResponse}; use futures::{Future, IntoFuture}; use openssl::hash::{hash, MessageDigest}; use protobuf::Message; use splinter::admin::messages::{ AuthorizationType, CreateCircuit, DurabilityType, PersistenceType...
fn fetch_node_information( node_ids: &[String], splinterd_url: &str, client: web::Data<Client>, ) -> Box<dyn Future<Item = Vec<Node>, Error = RestApiResponseError>> { let node_ids = node_ids.to_owned(); Box::new( client .get(&format!("{}/nodes?limit={}", splinterd_url, std::i64...
id, Uuid::new_v4().to_string() ), roster, members, authorization_type: AuthorizationType::Trust, persistence: PersistenceType::Any, durability: DurabilityType::NoDurability, routes: RouteType::Any, circuit_ma...
function_block-function_prefixed
[ { "content": "pub fn fetch_node(\n\n identity: web::Path<String>,\n\n client: web::Data<Client>,\n\n splinterd_url: web::Data<String>,\n\n) -> impl Future<Item = HttpResponse, Error = Error> {\n\n client\n\n .get(&format!(\"{}/nodes/{}\", splinterd_url.get_ref(), identity))\n\n .send()...
Rust
src/lib.rs
pudnax/chonker
dff08090f23322631ea60fe13d5dd3789f926577
#![feature(get_mut_unchecked)] use std::{ path::{Path, PathBuf}, time::Instant, }; pub mod camera; pub mod context; mod utils; mod watcher; pub use camera::{Camera, CameraBinding}; pub use context::{ Context, GlobalUniformBinding, HdrBackBuffer, PipelineHandle, Uniform, VolumeTexture, }; pub use utils::{...
#![feature(get_mut_unchecked)] use std::{ path::{Path, PathBuf}, time::Instant, }; pub mod camera; pub mod context; mod utils; mod watcher; pub use camera::{Camera, CameraBinding}; pub use context::{ Context, GlobalUniformBinding, HdrBackBuffer, PipelineHandle, Uniform, VolumeTexture, }; pub use utils::{...
pub fn print_help(info: impl std::fmt::Display, ffmpeg_version: &str) { println!("{}", info); println!("{}", ffmpeg_version); println!( "Default shader path:\n\t{}\n", Path::new(SHADER_FOLDER).canonicalize().unwrap().display() ); println!(...
function_block-full_function
[ { "content": "pub fn save_screenshot(frame: Vec<u8>, image_dimentions: ImageDimentions) -> Result<()> {\n\n let now = Instant::now();\n\n let screenshots_folder = Path::new(SCREENSHOTS_FOLDER);\n\n create_folder(screenshots_folder)?;\n\n let path = screenshots_folder.join(format!(\n\n \"scree...
Rust
benches/crit_bench.rs
arthurprs/lz4_flex
4953936f618dc7b644b2f30a612149d466005718
extern crate criterion; use self::criterion::*; use lz4::block::compress as lz4_linked_block_compress; use lz_fear::raw::compress2; use lz_fear::raw::decompress_raw; use lz_fear::raw::U16Table; use lz_fear::raw::U32Table; const COMPRESSION1K: &'static [u8] = include_bytes!("compression_1k.txt"); const COMPRESSION34K:...
extern crate criterion; use self::criterion::*; use lz4::block::compress as lz4_linked_block_compress; use lz_fear::raw::compress2; use lz_fear::raw::decompress_raw; use lz_fear::raw::U16Table; use lz_f
g = PlotConfiguration::default().summary_scale(AxisScale::Linear); let mut group = c.benchmark_group("Decompress"); group.plot_config(plot_config); for input in ALL.iter() { let input_bytes = input.len() as u64; group.throughput(Throughput::Bytes(input_bytes)); ...
ear::raw::U32Table; const COMPRESSION1K: &'static [u8] = include_bytes!("compression_1k.txt"); const COMPRESSION34K: &'static [u8] = include_bytes!("compression_34k.txt"); const COMPRESSION65K: &'static [u8] = include_bytes!("compression_65k.txt"); const COMPRESSION66K: &'static [u8] = include_bytes!("compression_66k_...
random
[ { "content": "use lz4_flex::block::DecompressError;\n\nuse tokio::fs::File;\n\nuse tokio::prelude::*; // for write_all()\n\nuse argh::FromArgs;\n\n\n\n#[macro_use]\n\nextern crate quick_error;\n\n\n\n#[derive(FromArgs, Debug)]\n\n/// Reach new heights.\n", "file_path": "lz4_bin/src/main.rs", "rank": 2, ...
Rust
src/record.rs
phip1611/beat-detector
ad00de5348bb0325298abd5a1e31d59d5f34845e
/* MIT License Copyright (c) 2021 Philipp Schuster Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publis...
/* MIT License Copyright (c) 2021 Philipp Schuster Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publis...
#[inline(always)] fn u16_data_to_i16(data: &[u16]) -> Vec<i16> { data.iter() .map(|x| *x as i32) .map(|x| x - i16::MAX as i32 / 2) .map(|x| x as i16) .collect() } #[inline(always)] fn f32_data_to_i16(data: &[f32]) -> Vec<i16> { data.iter() .map(|x| x * i16::MAX as f32)...
stream.play().unwrap(); loop { if !keep_recording.load(Ordering::SeqCst) { break; } } }); Ok(handle) }
function_block-function_prefix_line
[ { "content": "fn select_strategy() -> StrategyKind {\n\n println!(\"Available beat detection strategies:\");\n\n StrategyKind::values()\n\n .into_iter()\n\n .enumerate()\n\n .for_each(|(i, s)| {\n\n println!(\" [{}] {} - {}\", i, s.name(), s.description());\n\n });\...
Rust
tests/defaults_encode_decode.rs
OragonEfreet/sage_mqtt
092cf0494e5c602d712591a4fb87e5cd713b7282
use sage_mqtt::{ Auth, ConnAck, Connect, Disconnect, Error, Packet, PubAck, PubComp, PubRec, PubRel, Publish, ReasonCode, SubAck, Subscribe, UnSubAck, UnSubscribe, }; use std::io::Cursor; #[tokio::test] async fn default_connect() { let mut encoded = Vec::new(); let send_packet: Packet = Connect::defaul...
use sage_mqtt::{ Auth, ConnAck, Connect, Disconnect, Error, Packet, PubAck, PubComp, PubRec, PubRel, Publish, ReasonCode, SubAck, Subscribe, UnSubAck, UnSubscribe, }; use std::io::Cursor; #[tokio::test] async fn default_connect() { let mut encoded = Vec::new(); let send_packet: Packet = Connect::defaul...
} #[tokio::test] async fn default_connack() { let mut encoded = Vec::new(); let send_packet: Packet = ConnAck::default().into(); let send_size = send_packet .encode(&mut encoded) .await .expect("Cannot encode ConnAck packet"); assert!(send_size > 0); let mut cursor = Curso...
if let Packet::Connect(receive_packet) = receive_result { assert_eq!( receive_packet, Connect { authentication: Some(Default::default()), ..Default::default() } ); } else { panic!("Incorrect packet type"); }
if_condition
[ { "content": "use crate::QoS;\n\n\n\n/// The control packet type is present as the first element of the fixed header\n\n/// in an MQTT paquet. It is encoded in a 8bit flag set where the 4 most\n\n/// significant bits represent the type of the paquet and the 4 least are flags\n\n/// where values depend on the ty...
Rust
exchanges/binance/src/exchange.rs
rcjmurillo/crypto-portfolio
3032bb100159875b5730da440b008d1e46df7539
use chrono::{DateTime, Utc}; use std::collections::HashSet; use anyhow::Result; use async_trait::async_trait; use futures::future::join_all; use crate::{ api_model::{Deposit, FiatOrder, MarginLoan, MarginRepay, Trade, Withdraw}, client::{BinanceFetcher, EndpointsGlobal, EndpointsUs, RegionGlobal, RegionUs}, }...
use chrono::{DateTime, Utc}; use std::collections::HashSet; use anyhow::Result; use async_trait::async_trait; use futures::future::join_all; use crate::{ api_model::{Deposit, FiatOrder, MarginLoan, MarginRepay, Trade, Withdraw}, client::{BinanceFetcher, EndpointsGlobal, EndpointsUs, RegionGlobal, RegionUs}, }...
ance".to_string(), asset: r.asset, amount: r.principal, interest: r.interest, time: r.timestamp, status: match r.status.as_str() { "CONFIRMED" => exchange::Status::Success, _ => exchange::Status::Failure, }, ...
set: d.fiat_currency, amount: d.amount, fee: Some(d.platform_fee), time: d.create_time, is_fiat: true, } } } impl From<FiatOrder> for exchange::Withdraw { fn from(d: FiatOrder) -> Self { Self { source_id: d.id, source: "bin...
random
[ { "content": "pub fn get_asset_price_bucket(bucket: u16, asset: &AssetPair) -> Result<Option<Vec<Candle>>> {\n\n let conn = Connection::open(DB_NAME)?;\n\n\n\n let mut stmt =\n\n conn.prepare(\"SELECT prices FROM asset_price_buckets WHERE bucket = ?1 AND asset = ?2\")?;\n\n let mut iter = stmt.q...
Rust
deps/stb-image/image.rs
tomaka/declmagic
df3abdcd89cd1515f93c369401ac93581c3d4382
use stb_image::bindgen::*; use std::any::Any; use libc; use libc::{c_void, c_int}; use std::slice::raw::buf_as_slice; pub struct Image<T> { pub width : uint, pub height : uint, pub depth : uint, pub data : Vec<T>, } pub fn new_image<T>(width: uint, height: uint, depth: uint, data: Vec<T>) -...
use stb_image::bindgen::*; use std::any::Any; use libc; use libc::{c_void, c_int}; use std::slice::raw::buf_as_slice; pub struct Image<T> { pub width : uint, pub height : uint, pub depth : uint, pub data : Vec<T>, } pub fn new_image<T>(width: uint, height: uint, depth: uint, data: Vec<T>) -...
pub fn load_with_depth(path: &Path, force_depth: uint, convert_hdr: bool) -> LoadResult { unsafe { let mut width = 0 as c_int; let mut height = 0 as c_int; let mut depth = 0 as c_int; let path_as_str = match path.as_str() { Some(s) => s, None => return Error...
libc::free(buf as *mut c_void); Image::<T>{ width : w as uint, height : h as uint, depth : d as uint, data : data} } }
function_block-function_prefixed
[ { "content": "/// Load each OpenGL symbol using a custom load function. This allows for the\n\n/// use of functions like `glfwGetProcAddress` or `SDL_GL_GetProcAddress`.\n\n///\n\n/// ~~~\n\n/// let gl = gl::load_with(glfw::get_proc_address);\n\n/// ~~~\n\npub fn load_with(loadfn: |symbol: &str| -> *const libc:...
Rust
keyvalues-parser/src/text/parse.rs
LovecraftianHorror/vdf-pest
a9f3966b7ec7b389a18351d6469749ce8c93253d
#![allow(renamed_and_removed_lints)] #![allow(clippy::unknown_clippy_lints)] #![allow(clippy::upper_case_acronyms)] use pest::{iterators::Pair as PestPair, Parser}; use pest_derive::Parser; use std::borrow::Cow; use crate::{error::Result, Obj, PartialVdf as Vdf, Value}; macro_rules! common_parsing { ($parser:t...
#![allow(renamed_and_removed_lints)] #![allow(clippy::unknown_clippy_lints)] #![allow(clippy::upper_case_acronyms)] use pest::{iterators::Pair as PestPair, Parser}; use pest_derive::Parser; use std::borrow::Cow; use crate::{error::Result, Obj, PartialVdf as Vdf, Value}; macro_rules! common_parsing { ($parser:t...
rser)] #[grammar = "grammars/escaped.pest"] struct EscapedParser; pub type PestError = pest::error::Error<Rule>; common_parsing!(EscapedParser, Rule, true); } mod raw { use super::*; #[derive(Parser)] #[grammar = "grammars/raw.pest"] struct RawParser; pub type PestError = pest::...
push('\r'), Some('t') => escaped.push('\t'), Some('\\') => escaped.push('\\'), Some('\"') => escaped.push('\"'), _ => unreachable!("Prevented by grammar"), } } else...
random
[ { "content": "/// Serialize the `value` into an IO stream of VDF text with a custom top level VDF key\n\n///\n\n/// # Errors\n\n///\n\n/// This will return an error if the input can't be represented with valid VDF\n\npub fn to_writer_with_key<W, T>(writer: &mut W, value: &T, key: &str) -> Result<()>\n\nwhere\n\...
Rust
agent/test-agent/tests/mock.rs
webern/bottlerocket-test-system
6b523be719c79449784ae75b7bc18056d857aa89
/*! The purpose of this test is to demonstrate the mocking of a [`Client`] and a [`Bootstrap`] in order to test a [`Runner`] with the [`TestAgent`]. !*/ use async_trait::async_trait; use model::{Configuration, Outcome}; use serde::{Deserialize, Serialize}; use std::fmt::{Debug, Display}; use std::path::PathBuf; use ...
/*! The purpose of this test is to demonstrate the mocking of a [`Client`] and a [`Bootstrap`] in order to test a [`Runner`] with the [`TestAgent`]. !*/ use async_trait::async_trait; use model::{Configuration, Outcome}; use serde::{Deserialize, Serialize}; use std::fmt::{Debug, Display}; use std::path::PathBuf; use ...
_main.run().await.unwrap(); assert!(std::path::Path::new(&agent_main.results_file().await.unwrap()).is_file()); Ok(()) }
tResults, Self::E> { println!("MyRunner::run"); for i in 1..=5 { println!("Hello {}", i); sleep(Duration::from_millis(50)).await; } Ok(TestResults { outcome: Outcome::Pass, ..TestResults::default() }) } async fn terminate(...
random
[ { "content": "/// Print a value using `serde_json` `to_string_pretty` for types that implement Serialize.\n\npub fn json_display<T: Serialize>(object: T) -> String {\n\n serde_json::to_string_pretty(&object).unwrap_or_else(|e| format!(\"Serialization failed: {}\", e))\n\n}\n\n\n\n/// Implement `Display` usin...
Rust
demo/src/features/mesh/jobs/write.rs
jlowry/rafx
515aeeae3e57e1c520e320316197326294fc099e
use rafx::render_feature_write_job_prelude::*; use rafx::api::RafxPrimitiveTopology; use rafx::framework::{VertexDataLayout, VertexDataSetLayout}; use serde::{Deserialize, Serialize}; #[derive(Copy, Clone, Debug, Serialize, Deserialize, Default)] #[repr(C)] pub struct MeshVertex { pub position: [f32; 3], pub ...
use rafx::render_feature_write_job_prelude::*; use rafx::api::RafxPrimitiveTopology; use rafx::framework::{VertexDataLayout, VertexDataSetLayout}; use serde::{Deserialize, Serialize}; #[derive(Copy, Clone, Debug, Serialize, Deserialize, Default)] #[repr(C)] pub struct MeshVertex { pub position: [f32; 3], pub ...
} impl WriteJob for MeshWriteJob { fn render_element( &self, write_context: &mut RenderJobWriteContext, _view: &RenderView, render_phase_index: RenderPhaseIndex, index: SubmitNodeId, ) -> RafxResult<()> { profiling::scope!(super::RENDER_ELEMENT_SCOPE_NAME); ...
pub fn set_extracted_frame_node_mesh_data( &mut self, extracted_frame_node_mesh_data: Vec<Option<ExtractedFrameNodeMeshData>>, ) { self.extracted_frame_node_mesh_data = extracted_frame_node_mesh_data; }
function_block-full_function
[ { "content": "pub fn default_daemon() -> distill::daemon::AssetDaemon {\n\n use crate::assets::*;\n\n\n\n distill::daemon::AssetDaemon::default()\n\n .with_importer(\"sampler\", SamplerImporter)\n\n .with_importer(\"material\", MaterialImporter)\n\n .with_importer(\"materialinstance\"...
Rust
src/transforms/rename_fields.rs
zcapper/vector
560fd106fc9a60c12ddf2c32e31ad4f2031ff1f5
use super::Transform; use crate::{ event::Event, topology::config::{DataType, TransformConfig, TransformContext, TransformDescription}, }; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use snafu::Snafu; use string_cache::DefaultAtom as Atom; use toml::value::Value as TomlValue; #[derive(Des...
use super::Transform; use crate::{ event::Event, topology::config::{DataType, TransformConfig, TransformContext, TransformDescription}, }; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use snafu::Snafu; use string_cache::DefaultAtom as Atom; use toml::value::Value as TomlValue; #[derive(Des...
} } #[derive(Debug, Eq, PartialEq, Snafu)] enum FlattenError { #[snafu(display( "The key {:?} cannot be flattened. Is it a plain string or a `a.b.c` style map?", key ))] CannotFlatten { key: String }, } fn flatten(kv: (String, TomlValue), prequel: Option<String>) -> crate::Result<(Ato...
Ok(RenameFields { fields: fields .into_iter() .map(|kv| flatten(kv, None)) .collect::<crate::Result<_>>()?, })
call_expression
[ { "content": "/// Iterates over all paths in form \"a.b[0].c[1]\" in alphabetical order.\n\n/// It is implemented as a wrapper around `all_fields` to reduce code\n\n/// duplication.\n\npub fn keys<'a>(fields: &'a BTreeMap<Atom, Value>) -> impl Iterator<Item = Atom> + 'a {\n\n all_fields(fields).map(|(k, _)| ...
Rust
src/netlink-generic/message.rs
qinqon/nispor
86e8a54cba6ad8161bfa78fa683bd114a3ed7799
use anyhow::Context; use netlink_packet_core::{ DecodeError, NetlinkDeserializable, NetlinkHeader, NetlinkPayload, NetlinkSerializable, }; use netlink_packet_utils::{ nla::{DefaultNla, NlasIterator}, Emitable, Parseable, ParseableParametrized, }; use crate::{ buffer::GENL_ID_CTRL, CtrlAttr, Gener...
use anyhow::Context; use netlink_packet_core::{ DecodeError, NetlinkDeserializable, NetlinkHeader, NetlinkPayload, NetlinkSerializable, }; use netlink_packet_utils::{ nla::{DefaultNla, NlasIterator}, Emitable, Parseable, ParseableParametrized, }; use crate::{ buffer::GENL_ID_CTRL, CtrlAttr, Gener...
} } } impl NetlinkSerializable<GenericNetlinkMessage> for GenericNetlinkMessage { fn message_type(&self) -> u16 { self.message_type } fn buffer_len(&self) -> usize { <Self as Emitable>::buffer_len(self) } fn serialize(&self, buffer: &mut [u8]) { self.emit(buff...
uffer); match &self.nlas { GenericNetlinkAttr::Ctrl(nlas) => nlas .as_slice() .emit(&mut buffer[self.header.buffer_len()..]), GenericNetlinkAttr::Other(nlas) => nlas .as_slice() .emit(&mut buffer[self.header.buffer_len()..])...
function_block-random_span
[ { "content": "fn feature_bits_emit(_feature_bits: &[FeatureBit], _buffer: &mut [u8]) {\n\n todo!(\"Does not support changing ethtool feature yet\")\n\n}\n\n\n\n#[derive(Debug, PartialEq, Eq, Clone)]\n\npub enum FeatureAttr {\n\n Header(Vec<EthtoolHeader>),\n\n Hw(Vec<FeatureBit>),\n\n Wanted(Vec<Fea...
Rust
src/response/mod.rs
ferrum-rs/ferrum
2bda0743d84632e95925d687d8cc03ef15e0ecc4
use std::fmt::{self, Debug}; use std::mem::replace; use mime::Mime; use typemap::{TypeMap, TypeMapInner}; use plugin::Extensible; use hyper::{Body, HttpVersion}; use hyper::header::{ContentLength, ContentType, Location, Raw}; use {Plugin, Header, Headers, StatusCode}; pub use hyper::Response as HyperResponse; pub...
use std::fmt::{self, Debug}; use std::mem::replace; use mime::Mime; use typemap::{TypeMap, TypeMapInner}; use plugin::Extensible; use hyper::{Body, HttpVersion}; use hyper::header::{ContentLength, ContentType, Location, Raw}; use {Plugin, Header, Headers, StatusCode}; pub use hyper::Response as HyperResponse; pub...
#[inline] pub fn with_mime(mut self, mime: Mime) -> Self { self.set_mime(mime); self } #[inline] pub fn set_mime(&mut self, mime: Mime) { self.headers.set(ContentType(mime)); } } impl From<HyperResponse> for Response { fn from(mut from_response...
pub fn set_content<C: Into<Content>>(&mut self, content: C, mime: Mime) { let content = content.into(); self.headers.set(ContentType(mime)); self.headers.set(ContentLength(content.len() as u64)); self.body = Some(content.into()); self.status = StatusCode::Ok; }
function_block-full_function
[ { "content": "struct DefaultContentType;\n\n\n\nimpl AfterMiddleware for DefaultContentType {\n\n // This is run for every requests, AFTER all handlers have been executed\n\n fn after(&self, _: &mut Request, mut response: Response) -> FerrumResult<Response> {\n\n if response.headers.get::<ContentTy...
Rust
src/scu_reset/prclr1.rs
austinglaser/xmc4700
12e1d2b638af5ff0e7088605a4299590a2cd60eb
#[doc = "Writer for register PRCLR1"] pub type W = crate::W<u32, super::PRCLR1>; #[doc = "Register PRCLR1 `reset()`'s with value 0"] impl crate::ResetValue for super::PRCLR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "CCU43 Reset Clear\n\nValue on reset: ...
#[doc = "Writer for register PRCLR1"] pub type W = crate::W<u32, super::PRCLR1>; #[doc = "Register PRCLR1 `reset()`'s with value 0"] impl crate::ResetValue for super::PRCLR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "CCU43 Reset Clear\n\nValue on reset: ...
"USIC1 Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USIC1RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<USIC1RS_AW> for bool { #[inline(always)] fn from(variant: USIC1RS_AW) -> Self { variant as u...
3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "MultiCAN Reset Clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MCAN0RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: De-assert reset"] VALUE2 = 1, } impl From<MCAN0RS_AW> for bool { #[inline(a...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/main.rs
0x4c37373230/BDumper
fac8b161d544bccdc26f9f3607ebcafcf3c53f39
#![windows_subsystem = "windows"] extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use { bedrock_dumper::*, nwd::NwgUi, nwg::{CheckBoxState, NativeUi}, }; #[derive(Default, NwgUi)] pub struct BedrockDumper { #[nwg_control(size: (590, 225), position: (300, 300), title...
#![windows_subsystem = "windows"] extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use { bedrock_dumper::*, nwd::NwgUi, nwg::{CheckBoxState, NativeUi}, }; #[derive(Default, NwgUi)] pub struct BedrockDumper { #[nwg_control(size: (590, 225), position: (300, 300), title...
ath, file_type, dump_file) { Err(str) => { nwg::simple_message("Error", &str); } _ => {} }, Err(str) => { nwg::simple_message("Error", &str); } } } fn exit_program(&self) { nw...
} impl BedrockDumper { fn dump(&self) { let pdb_path: &str = &self.pdb_path.text(); let file_type: &str = &self.file_type.text(); let demangle = if &self.should_demangle.check_state() == &CheckBoxState::Checked { true } else { false }; match ...
random
[ { "content": "# BDumper\n\nA windows BDS .pdb dumper written in rust which dumps symbols, reconstructed function prototypes from demangled symbols and RVAs (Relative Virtual Addresses) into either a C++ header (.hpp) or a text file (.txt) and can also find data corresponding to specific functions. This project ...
Rust
kosem-gui/src/work_on_procedure.rs
idanarye/kosem
c72198c1f78855cfd49d1d0fa1bc848ac0c8f9cc
use actix::prelude::*; use gtk::prelude::*; use kosem_webapi::Uuid; use kosem_webapi::pairing_messages; use kosem_webapi::phase_control_messages; use crate::internal_messages::gui_control::{ ProcedureScreenAttach, UserClickedButton, ShowJoinMenu, }; #[derive(woab::Factories)] pub struct WorkOnProcedureFa...
use actix::prelude::*; use gtk::prelude::*; use kosem_webapi::Uuid; use kosem_webapi::pairing_messages; use kosem_webapi::phase_control_messages; use crate::internal_messages::gui_control::{ ProcedureScreenAttach, UserClickedButton, ShowJoinMenu, }; #[derive(woab::Factories)] pub struct WorkOnProcedureFa...
}
ordinal) = *msg.tag(); let phase_row = if let Some(p) = self.phases.get(&phase_uid) { p } else { log::warn!("Unknown phase {}", phase_uid); return Ok(None); }; let component = if let Some(c) = phase_row.msg.components.get(component_ordinal) { ...
function_block-function_prefixed
[ { "content": "pub fn start_gtk(settings: client_config::ClientConfig) -> anyhow::Result<()> {\n\n let factories = Factories::new(FactoriesInner {\n\n join_menu: join_menu::JoinMenuFactories::read(&*Asset::get(\"join_menu.glade\").unwrap())?,\n\n work_on_procedure: work_on_procedure::WorkOnProce...
Rust
src/main.rs
codahale/veil-rs
45e3a32ad522b4ce68425442a39ccc76d92bf43c
use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::{fs, result}; use anyhow::Result; use clap::{App, IntoApp, Parser}; use clap::{AppSettings, Subcommand, ValueHint}; use clap_complete::generate_to; use clap_complete::Shell; use clio::{Input, Output}; use mimalloc::MiMalloc; use veil::{PublicKe...
use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::{fs, result}; use anyhow::Result; use clap::{App, IntoApp, Parser}; use clap::{AppSettings, Subcommand, ValueHint}; use clap_complete::generate_to; use clap_complete::Shell; use clio::{Input, Output}; use mimalloc::MiMalloc; use veil::{PublicKe...
} #[derive(Debug, Parser)] struct PublicKeyArgs { #[clap(value_hint = ValueHint::FilePath)] secret_key: PathBuf, key_id: OsString, #[clap(parse(try_from_os_str = output_from_os_str), value_hint = ValueHint::FilePath, default_value="-")] output: Output, #[clap(long, value...
fn run(self) -> Result<()> { let passphrase = prompt_passphrase(&self.passphrase_file)?; let secret_key = SecretKey::new(); let ciphertext = secret_key.encrypt(&passphrase, self.time, self.space); fs::write(self.output, ciphertext)?; Ok(()) }
function_block-function_prefix_line
[ { "content": "fn init(passphrase: &[u8], salt: &[u8], time: u32, space: u32) -> Strobe {\n\n let mut pbenc = Strobe::new(b\"veil.pbenc\", SecParam::B128);\n\n\n\n // Initialize protocol with metadata.\n\n pbenc.meta_ad_u32(DELTA as u32);\n\n pbenc.meta_ad_u32(N as u32);\n\n pbenc.meta_ad_u32(MAC_...
Rust
src/lib.rs
phaylon/resorb
4b36e3da17b66c97e28b86ee23f7db9d77d8a38d
use std::rc; use std::sync; use std::error; use std::fmt; macro_rules! assert_parse_ok { ($parser:expr, $input:expr, $expected:expr $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Ok($expected) ); ...
use std::rc; use std::sync; use std::error; use std::fmt; macro_rules! assert_parse_ok { ($parser:expr, $input:expr, $expected:expr $(,)*) => {{ let input: String = ($input).into(); assert_eq!( ::apply(&input, ::Options::default(), $parser), Ok($expected) ); ...
pub fn line(&self) -> usize { self.line } pub fn column(&self) -> usize { self.column } pub fn offset(&self) -> usize { self.offset } fn advance(&self, parsed: &str) -> Location { let nl_count = parsed .chars() .filter(|c| *c == '\n') .count(); let ...
pub fn new(line: usize, column: usize, offset: usize) -> Location { Location { line: line, column: column, offset: offset, } }
function_block-full_function
[ { "content": "pub fn fail<E>(location: ::Location, error: E) -> ::Fail<E> {\n\n ::Fail::Error(::Error::new(location, error))\n\n}\n", "file_path": "src/util.rs", "rank": 0, "score": 211455.97158554505 }, { "content": "pub fn no_custom_error<'src, P>(parser: P) -> P where P: ::Parser<'src,...
Rust
src/config.rs
drogue-iot/drogue-event-source
6f96f14d95de0bd914f523c6cb2b284bd24cf57b
use anyhow::Result; use reqwest::Method; use serde::Deserialize; use serde_with::serde_as; use std::collections::HashMap; use std::time::Duration; pub trait ConfigFromEnv<'de>: Sized + Deserialize<'de> { fn from_env() -> Result<Self, config::ConfigError> { Self::from(config::Environment::default()) } ...
use anyhow::Result; use reqwest::Method; use serde::Deserialize; use serde_with::serde_as; use std::collections::HashMap; use std::time::Duration; pub trait ConfigFromEnv<'de>: Sized + Deserialize<'de> { fn from_env() -> Result<Self, config::ConfigError> { Self::from(config::Environment::default()) } ...
} #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] #[serde(tag = "mode")] #[serde(rename_all = "lowercase")] pub enum Mode { Kafka(KafkaConfig), #[serde(alias = "ws")] Websocket(WebsocketConfig), } #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] pub struct KafkaConfig { pub topic: String, ...
let cfg = config::Config::builder() .add_source(env.separator("__")) .build()?; cfg.try_deserialize() }
function_block-function_prefix_line
[ { "content": "use crate::EndpointConfig;\n\nuse anyhow::bail;\n\nuse cloudevents::binding::reqwest::RequestBuilderExt;\n\nuse reqwest::{Certificate, Url};\n\nuse std::time::Duration;\n\nuse thiserror::Error;\n\n\n\npub struct Sender {\n\n config: EndpointConfig,\n\n url: Url,\n\n client: reqwest::Clien...
Rust
src/lib.rs
DomWilliams0/panik-rs
493ac556522b245c54e070bc44119fc1c99a488c
use backtrace::Backtrace; use std::borrow::Cow; use std::fmt::Debug; use std::panic::{PanicInfo, UnwindSafe}; use std::thread::ThreadId; use std::cmp::Ordering; use std::ops::DerefMut; #[cfg(feature = "use-parking-lot")] use parking_lot::Mutex; #[cfg(not(feature = "use-parking-lot"))] use std::sync::Mutex; const...
use backtrace::Backtrace; use std::borrow::Cow; use std::fmt::Debug; use std::panic::{PanicInfo, UnwindSafe}; use std::thread::ThreadId; use std::cmp::Ordering; use std::ops::DerefMut; #[cfg(feature = "use-parking-lot")] use parking_lot::Mutex; #[cfg(not(feature = "use-parking-lot"))] use std::sync::Mutex; const...
; if *backtrace_resolved { log_crit!( &state, "panic on thread {:?}: {:?}\n{:?}", thread, message, backtrace ); } else { log_crit!(&state, "panic on thread {:?}: {:?}", threa...
match i.cmp(&backtrace_resolution_limit) { Ordering::Less => { backtrace.resolve(); *backtrace_resolved = true; } Ordering::Equal => { #[cfg(feature = "use-log")] log::warn!( "handling more than {limi...
if_condition
[ { "content": "pub fn panik_builder() -> panik::Builder {\n\n #[cfg(feature = \"use-log\")]\n\n env_logger::builder()\n\n .is_test(true)\n\n .filter_level(log::LevelFilter::Debug)\n\n .init();\n\n\n\n #[cfg(feature = \"use-slog\")]\n\n {\n\n use slog::{slog_o, Drain};\n\n\...
Rust
2021/src/day19.rs
shrugalic/advent_of_code
8d18a3dbdcf847a667ab553f5441676003b9362a
use std::collections::{HashMap, HashSet, VecDeque}; const INPUT: &str = include_str!("../input/day19.txt"); pub(crate) fn day19_part1() -> usize { System::from(INPUT).beacon_count() } pub(crate) fn day19_part2() -> usize { System::from(INPUT).max_manhattan_distance() } type Coordinate = isize; type Vector =...
use std::collections::{HashMap, HashSet, VecDeque}; const INPUT: &str = include_str!("../input/day19.txt"); pub(crate) fn day19_part1() -> usize { System::from(INPUT).beacon_count() } pub(crate) fn day19_part2() -> usize { System::from(INPUT).max_manhattan_distance() } type Coordinate = isize; type Vector =...
} impl Scanner { fn align_with(&mut self, ref_beacons: &[Vector]) -> Option<Vector> { for orientation in Orientation::all() { let mut offset_frequencies: HashMap<Vector, usize> = HashMap::new(); let aligned_beacons = self.aligned_beacons(&orientation); for own_beacon in...
fn from(lines: &str) -> Self { let to_position = |line: &str| { let pos: Vec<Coordinate> = line.split(',').map(|n| n.parse().unwrap()).collect(); [pos[0], pos[1], pos[2]] }; let mut lines = lines.trim().lines(); let header = lines.next().unwrap(); let id =...
function_block-full_function
[ { "content": "fn max_distance_to_origin(input: Vec<&str>) -> usize {\n\n curr_and_max_distances_to_origin(input).1\n\n}\n\n\n", "file_path": "2017/src/day11.rs", "rank": 0, "score": 388208.4410849393 }, { "content": "fn sum_of_valid_sector_ids(input: Vec<&str>) -> usize {\n\n input\n\n...
Rust
src/update_status.rs
FutureTVGroup/update-broker
2d8468473b5b72a228a5bdae95f50789e0bbf3b4
use futures::Future; use futures::Stream; use inotify::wrapper::Event; use slog::Logger; use std::ffi::OsString; use std::io::Result; use std::io::{Error, ErrorKind}; use std::ops::Deref; use std::path::Path; use std::process::Command; use std::rc::Rc; use std::time::{SystemTime, UNIX_EPOCH}; use tokio_core::reactor:...
use futures::Future; use futures::Stream; use inotify::wrapper::Event; use slog::Logger; use std::ffi::OsString; use std::io::Result; use std::io::{Error, ErrorKind}; use std::ops::Deref; use std::path::Path; use std::process::Command; use std::rc::Rc; use std::time::{SystemTime, UNIX_EPOCH}; use tokio_core::reactor:...
cINotify::init(handle) .and_then(|stream| UpdateStatusNotifier::add_watch(stream, path)) .map(|stream| { stream.filter(move |event: &Event| event.name.as_os_str() == sentinel_file) }).map(|stream| { stream .m...
>, logger: Rc<Logger>, ) -> Result<Box<Future<Item = (), Error = Error>>> { if let Some(sentinel_file) = UpdateStatusNotifier::get_file_name_os_string(path) { Asyn
random
[ { "content": "pub fn engine(path: &Path, logger: Rc<Logger>) -> Result<(), IoError> {\n\n let owned_path = path.to_owned();\n\n let connection_r = Connection::get_private(BusType::System);\n\n if connection_r.is_err() {\n\n return connection_r.map(|_| ()).map_err(|e| {\n\n IoError::ne...
Rust
src/pwasm.rs
jakelang/libeci
a4add3d49ec631dbb9c7f65f50655f6ec3ca5f2e
/* * libeci: Ethereum WebAssembly ABI compliance library * * Copyright (c) 2018 Jake Lang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limit...
/* * libeci: Ethereum WebAssembly ABI compliance library * * Copyright (c) 2018 Jake Lang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limit...
pub fn get_imports(module: &Module) -> Option<Vec<(&str, &str)>> { if !has_import_section(module) { return None; } else { let imports_list: Option<Vec<(&str, &str)>> = Some( module .import_section() .unwrap() .entries() ...
pub fn resolve_export_by_name(module: &Module, name: &str) -> Option<(u32, Internal)> { if !has_export_section(module) { None } else { let idx: Option<(u32, Internal)> = match module .export_section() .unwrap() .entries() .iter() .find(...
function_block-full_function
[ { "content": "/// Utility function checking that a module has an exported function with a given signature.\n\npub fn has_func_export(module: &Module, name: &str, sig: FunctionType) -> CheckStatus {\n\n match resolve_export_by_name(module, name) {\n\n Some((index, reference)) => if reference == Interna...
Rust
contracts/farms/spectrum_pylon_farm/src/compound.rs
spectrumprotocol/contract
eee411acc13ed999a9718c096aef93b586941c02
use cosmwasm_std::{attr, to_binary, Attribute, CanonicalAddr, Coin, CosmosMsg, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, QueryRequest, WasmQuery}; use crate::{ bond::deposit_farm_share, state::{read_config, state_store}, }; use crate::querier::query_pylon_reward_info; use cw...
use cosmwasm_std::{attr, to_binary, Attribute, CanonicalAddr, Coin, CosmosMsg, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, QueryRequest, WasmQuery}; use crate::{ bond::deposit_farm_share, state::{read_config, state_store}, }; use crate::querier::query_pylon_reward_info; use cw...
], slippage_tolerance: None, receiver: None, })?, funds: vec![Coin { denom: config.base_denom, amount: net_reinvest_ust, }], }); messages.push(provide_liquidity); let stake = CosmosM...
_store(deps.storage).save(&state)?; attributes.push(attr("net_commission", net_commission_amount)); messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: deps.api.addr_humanize(&config.anchor_market)?.to_string(), msg: to_binary(&MoneyMarketExecuteMsg::DepositStable {...
random
[ { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> {\n\n match msg {\n\n ExecuteMsg::zap_to_bond {\n\n contract,\n\n provide_asset,\n\n swap_operations...
Rust
query-engine/core/src/metrics/formatters.rs
prisma-korea/prisma-engines
99ac5a5c95ba2f5308d84fc30a7110f606182d92
use super::common::{Histogram, Metric, MetricValue, Snapshot}; use metrics_exporter_prometheus::formatting::{ sanitize_description, sanitize_label_key, sanitize_label_value, write_help_line, write_metric_line, write_type_line, }; use serde_json::Value; use std::collections::HashMap; fn create_label_string(labels: ...
use super::common::{Histogram, Metric, MetricValue, Snapshot}; use metrics_exporter_prometheus::formatting::{ sanitize_description, sanitize_label_key, sanitize_label_value, write_help_line, write_metric_line, write_type_line, }; use serde_json::Value; use std::collections::HashMap; fn create_label_string(labels: ...
pub(crate) fn metrics_to_prometheus(snapshot: Snapshot) -> String { let Snapshot { counters, histograms, gauges, } = snapshot; let mut output = String::new(); for counter in counters { let desc = sanitize_description(counter.description.as_str()); write_help_l...
togram { buckets, sum: histogram_value.sum, count: histogram_value.count, }; normalised_histograms.push(Metric { key: histogram.key.clone(), labels: histogram.labels.clone(), description: histogram.d...
function_block-function_prefixed
[ { "content": "// Todo: Sanitizing might need to be adjusted to also change the fields in the RelationInfo\n\nfn sanitize_models(ctx: &mut Context) -> HashMap<String, (String, Option<String>)> {\n\n let mut enum_renames = HashMap::new();\n\n let sql_family = ctx.sql_family();\n\n\n\n for model in ctx.da...
Rust
sdk/tests/t_nft_contract.rs
fgfm999/trampoline
e7c2f0172087973f8fc0b4884e459fdd5855c235
use std::path::Path; use ckb_hash::blake2b_256; use trampoline_sdk::ckb_types::packed::{CellInput, CellOutput}; use ckb_jsonrpc_types::JsonBytes; use trampoline_sdk::chain::{MockChain, MockChainTxProvider as ChainRpc}; use trampoline_sdk::ckb_types::{ self, bytes::Bytes, core::{TransactionBuilder, Transa...
use std::path::Path; use ckb_hash::blake2b_256; use trampoline_sdk::ckb_types::packed::{CellInput, CellOutput}; use ckb_jsonrpc_types::JsonBytes; use trampoline_sdk::chain::{MockChain, MockChainTxProvider as ChainRpc}; use trampoline_sdk::ckb_types::{ self, bytes::Bytes, core::{TransactionBuilder, Transa...
fn genesis_id_from(input: OutPoint) -> GenesisId { let seed_tx_hash = input.tx_hash(); let seed_idx = input.index(); let mut seed = Vec::with_capacity(36); seed.extend_from_slice(seed_tx_hash.as_slice()); seed.extend_from_slice(seed_idx.as_slice()); let hash = blake2b_256(&seed); GenesisI...
s>, ) -> TransactionView { TransactionBuilder::default() .inputs(inputs) .outputs(outputs) .outputs_data(outputs_data) .build() }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn test_contract_pack_and_unpack_data() {\n\n let mut sudt_contract = gen_sudt_contract(None, None);\n\n\n\n sudt_contract.set_args(OwnerLockHash::from_mol(Byte32::default()));\n\n sudt_contract.set_data(SudtAmount::from_mol(1200_u128.pack()));\n\n\n\n let uint128_data: u128...
Rust
libs/editor/libs/paths/src/paths.rs
Ryan1729IsParanoidAboutWriteAccess/rote
fbe20e4627c1b63d2af7141dcffd424563b8fe9f
use std::path::{Path, PathBuf}; pub fn find_in<'path, I: Iterator<Item = &'path Path>>( paths: I, needle: &str, ) -> Vec<PathBuf> { if needle.is_empty() { return Vec::new(); } let len = { if let (_, Some(l)) = paths.size_hint() { l } else { 128 ...
use std::path::{Path, PathBuf}; pub fn find_in<'path, I: Iterator<Item = &'path Path>>( paths: I, needle: &str, ) -> Vec<PathBuf> { if needle.is_empty() { return Vec::new(); } let len = { if let (_, Some(l)) = paths.size_hint() { l } else { 128 ...
rom("C:\\Users\\ryan1729\\Documents\\beans.txt"), ]; assert_eq!( find_in(searched_paths.iter().map(|p| p.as_path()), needle), expected ); } #[test] fn find_in_paths_sorts_things_with_multiple_needles_higher() { let needle = "b"; let searched...
n1729\\Documents\\bartog.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\beans.txt"), PathBuf::from("C:\\Users\\ryan1729\\Documents\\unrelated.txt"), ]; let expected = vec![ PathBuf::from("C:\\Users\\ryan1729\\Documents\\bartog.txt"), PathBuf::f
function_block-random_span
[]
Rust
src/mesh.rs
ArvinSKushwaha/dynamics_engine
a1189653d3dc5c9b4dfd4eee3eee75b7b6f3b9ed
use crate::object::{Ray, RayCollision}; use crate::{Float, Mat3, Point3, UnitVec3, Vec3, EPSILON}; use na::{point, vector}; use nalgebra as na; use std::io::{BufRead, BufReader}; #[derive(Debug, Clone)] pub struct MeshOptions { pub smooth_normals: bool, } #[derive(Debug, Clone)] pub struct PolygonMesh...
use crate::object::{Ray, RayCollision}; use crate::{Float, Mat3, Point3, UnitVec3, Vec3, EPSILON}; use na::{point, vector}; use nalgebra as na; use std::io::{BufRead, BufReader}; #[derive(Debug, Clone)] pub struct MeshOptions { pub smooth_normals: bool, } #[derive(Debug, Clone)] pub struct PolygonMesh...
* (std::f64::consts::PI as Float)); } mesh.vertex_normals[i] = na::Unit::new_normalize(normal); } } for i in 0..mesh.get_face_count() { assert_eq!(mesh.faces_to_vertices[i].len(), 3); } mesh.smooth_transform_matrices = Some(smooth_transform_matrices); ...
std::panic::panic_any("Yikes, the normals didn't compute right?!"); } for i in 0..face_vertices.len() - 2 { mesh.vertices_to_faces[face_vertices[0]].push(mesh.faces_to_vertices.len()); mesh.vertices_to_faces[face_vertices[i ...
random
[]
Rust
pallets/root-of-trust/src/lib.rs
NodleCode/PKI
748aaddb8ce3ab7c90cfa3fd2610275f00f5cb7b
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod tests; use codec::{Decode, Encode}; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure, traits::{ChangeMembers, Currency, ExistenceRequirement, Get, OnUnbalanced, WithdrawReasons}, Par...
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod tests; use codec::{Decode, Encode}; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure, traits::{ChangeMembers, Currency, ExistenceRequirement, Get, OnUnbalanced, WithdrawReasons}, Par...
} impl<T: Trait> ChangeMembers<T::AccountId> for Module<T> { fn change_members_sorted( _incoming: &[T::AccountId], _outgoing: &[T::AccountId], new: &[T::AccountId], ) { <Members<T>>::put(new); } }
pub fn is_child_certificate_valid(root: &T::CertificateId, child: &T::CertificateId) -> bool { let equals = root == child; let root_valid = Self::is_root_certificate_valid(root); let revoked = <Slots<T>>::get(root).child_revocations.contains(child); !equals && root_valid && !r...
function_block-full_function
[ { "content": "#[test]\n\nfn child_certificate_not_valid_if_revoked_in_root_certificate() {\n\n new_test_ext().execute_with(|| {\n\n allocate_balances();\n\n do_register();\n\n\n\n let now = <system::Module<Test>>::block_number();\n\n <Slots<Test>>::insert(\n\n &OFFCHAIN...
Rust
src/particle.rs
n3f4s/particule_generator
731ee8d834f5a458b3ee78b7849b60ccb81d659b
use vec3d::Vec3; use point3d::Point3; use drawable::Drawable; use sdl2::render::Canvas; use sdl2::video::Window; use sdl2::surface::Surface; use sdl2::gfx::primitives::DrawRenderer; static PARTICLE_DENSITY : f64 = 1.0; #[derive(Debug, Default, PartialEq, Copy, Clone)] pub struct Particle { position: Point3<i16>...
use vec3d::Vec3; use point3d::Point3; use drawable::Drawable; use sdl2::render::Canvas; use sdl2::video::Window; use sdl2::surface::Surface; use sdl2::gfx::primitives::DrawRenderer; static PARTICLE_DENSITY : f64 = 1.0; #[derive(Debug, Default, PartialEq, Copy, Clone)] pub struct Particle { position: Point3<i16>...
pub fn set_position(&mut self, pos: Point3<i16>) { self.position = pos; } pub fn is_alive(&self) -> bool { self.alive } pub fn get_position(&self) -> Point3<i16> { self.position } pub fn get_direction(&self) -> Vec3<i16> { self.direction } pub fn get_...
fetime: 250, max_lifetime: 250, radius: 5, mass: 5.0 * PARTICLE_DENSITY } }
function_block-function_prefixed
[ { "content": "pub fn dot(v1: &Vec3, v2: &Vec3) -> f64 {\n\n v1.x * v2.x + v1.y * v2.y + v1.z * v2.z\n\n}\n\n\n", "file_path": "src/vec3.rs", "rank": 0, "score": 83669.11190807322 }, { "content": "pub fn unit_vector(v: Vec3) -> Vec3 {\n\n let mut tmp = v;\n\n tmp.make_unit();\n\n ...
Rust
src/keychain/mod.rs
mikelodder7/keychain-services.rs
6c68371b199d9d450d185681d80720ed4561b8d0
pub mod item; pub mod key; use self::item::MatchLimit; pub use self::{item::Item, key::Key}; use crate::dictionary::*; use crate::error::Error; use crate::ffi::*; use core_foundation::base::{CFTypeRef, TCFType}; use std::{ffi::CString, os::raw::c_char, os::unix::ffi::OsStrExt, path::Path, ptr}; declare_TCFType! { ...
pub mod item; pub mod key; use self::item::MatchLimit; pub use self::{item::Item, key::Key}; use crate::dictionary::*; use crate::error::Error; use crate::ffi::*; use core_foundation::base::{CFTypeRef, TCFType}; use std::{ffi::CString, os::raw::c_char, os::unix::ffi::OsStrExt, path::Path, ptr}; declare_TCFType! { ...
unsafe { SecItemAdd(Dictionary::from(attrs).as_concrete_TypeRef(), &mut result) }; if let Some(e) = Error::maybe_from_OSStatus(status) { Err(e) } else { Ok(unsafe { Item::wrap_under_create_rule(result) }) } } } impl Default for Keychain { fn default() -> Keycha...
) }; if let Some(e) = Error::maybe_from_OSStatus(status) { return Err(e); } Ok(unsafe { Item::wrap_under_create_rule(result) }) } fn add_item(&self, mut attrs: DictionaryBuilder) -> Result<Item, Error> { at...
random
[ { "content": "#[test]\n\nfn generate_and_use_rsa_keys() {\n\n let acl =\n\n AccessControl::create_with_flags(AttrAccessible::WhenUnlocked, Default::default()).unwrap();\n\n\n\n let generate_params = KeyPairGenerateParams::new(AttrKeyType::Rsa, 2048).access_control(&acl);\n\n\n\n let keypair = Ke...
Rust
kailua_types/src/ty/tag.rs
nxgtri/kailua
17eb0750ff8bbe4237d75f31f9b8aa23170c3c28
use std::fmt; use kailua_env::Spanned; use kailua_diag::{Result, Reporter}; use kailua_syntax::ast::{Attr, AttrValue}; use super::{Display, DisplayState, TypeResolver, ClassSystemId}; use message as m; #[derive(Copy, Clone, PartialEq, Eq)] pub enum Tag { #[doc(hidden)] _Subtype, #[doc(hidden)] _NoSubtype,...
use std::fmt; use kailua_env::Spanned; use kailua_diag::{Result, Reporter}; use kailua_syntax::ast::{Attr, AttrValue}; use super::{Display, DisplayState, TypeResolver, ClassSystemId}; use message as m; #[derive(Copy, Clone, PartialEq, Eq)] pub enum Tag { #[doc(hidden)] _Subtype, #[doc(hidden)] _NoSubtype,...
pub fn needs_subtype(&self) -> bool { match *self { Tag::_Subtype => true, Tag::_NoSubtype => false, Tag::_NoSubtype2 => false, Tag::PackagePath | Tag::PackageCpath => false, _ => true, }...
pub fn scope_local(&self) -> bool { match *self { Tag::Type | Tag::Assert | Tag::AssertNot | Tag::AssertType | Tag::GenericPairs | Tag::MakeClass(_) | Tag::KailuaGenTvar | Tag::KailuaAssertTvar => true, _...
function_block-full_function
[ { "content": "pub fn get_defs(name: &str) -> Option<&'static [Def]> {\n\n match name {\n\n \"lua51\" => Some(LUA51_DEFS),\n\n \"lua51_base\" => Some(LUA51_BASE_DEFS),\n\n \"lua51_package\" => Some(LUA51_PACKAGE_DEFS),\n\n \"lua51_string\" => Some(LUA51_STRING_DEFS),\n\...
Rust
src/api/reddit/repository.rs
tigorlazuardi/ridit-rs
bae8b50db3237df03e925048bf5c5eb6d575b2af
use std::{convert::TryInto, path::PathBuf, sync::Arc, time::Duration, usize}; use anyhow::{bail, Context, Error, Result}; use imagesize::blob_size; use reqwest::{header::RANGE, Client, Response}; use tokio::{ fs::{self, File}, io::AsyncWriteExt, sync::{mpsc::UnboundedSender, Semaphore}, }; use tokio_retry::{ stra...
use std::{convert::TryInto, path::PathBuf, sync::Arc, time::Duration, usize}; use anyhow::{bail, Context, Error, Result}; use imagesize::blob_size; use reqwest::{header::RANGE, Client, Response}; use tokio::{ fs::{self, File}, io::AsyncWriteExt, sync::{mpsc::UnboundedSender, Semaphore}, }; use tokio_retry::{ stra...
async fn poke_image_size(&self, meta: &mut DownloadMeta) -> Result<()> { const LIMIT: usize = 1024 * 2 * 10; let retry_strategy = FixedInterval::from_millis(100).map(jitter).take(3); let mut resp = Retry::spawn(retry_strategy, || async { let res = self .client .get(&meta.url) .header(RANGE, ...
async fn ensure_download_dir(&self, meta: &DownloadMeta) -> Result<()> { for profile in &meta.profile { let download_dir = self.config.path.join(profile).join(&meta.subreddit_name); fs::create_dir_all(&download_dir).await.with_context(|| { format!( "failed to create download directory on: {}", dow...
function_block-full_function
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n\ttonic_build::compile_protos(\"proto/server.proto\")?;\n\n\tOk(())\n\n}\n", "file_path": "src/build.rs", "rank": 0, "score": 114218.0222370955 }, { "content": "fn project_dir() -> ProjectDirs {\n\n\tProjectDirs::from(\"i...
Rust
src/ed25519/mod.rs
acw/simple_crypto
82bb499be36f17957e7f5e14755f5e67a2931fb4
mod constants; mod fe; mod loads; mod point; mod scalars; use rand::Rng; use sha::{Hash,SHA512}; use self::scalars::{curve25519_scalar_mask,x25519_sc_muladd,x25519_sc_reduce}; use self::point::{Point,Point2}; #[cfg(test)] use testing::run_test; #[cfg(test)] use std::collections::HashMap; use super::KeyPair; #[deriv...
mod constants; mod fe; mod loads; mod point; mod scalars; use rand::Rng; use sha::{Hash,SHA512}; use self::scalars::{curve25519_scalar_mask,x25519_sc_muladd,x25519_sc_reduce}; use self::point::{Point,Point2}; #[cfg(test)] use testing::run_test; #[cfg(test)] use std::collections::HashMap; use super::KeyPair; #[deriv...
fn digest_scalar(digest: &[u8]) -> Vec<u8> { assert_eq!(digest.len(), 512/8); let mut copy = [0; 512/8]; copy.copy_from_slice(digest); x25519_sc_reduce(&mut copy); copy[..32].to_vec() } #[cfg(test)] fn run_signing_testcase(case: HashMap<String,(bool,Vec<u8>)>) { let (negr, rbytes) = case.get(...
fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> Vec<u8> { let mut ctx = SHA512::new(); ctx.update(signature_r); ctx.update(public_key); ctx.update(msg); ctx.finalize() }
function_block-full_function
[ { "content": "pub fn curve25519_scalar_mask(a: &mut [u8])\n\n{\n\n assert_eq!(a.len(), 32);\n\n a[0] &= 248;\n\n a[31] &= 127;\n\n a[31] |= 64;\n\n}\n\n\n", "file_path": "src/ed25519/scalars.rs", "rank": 0, "score": 295214.22511977865 }, { "content": "pub fn x25519_sc_reduce(s: &...
Rust
src/parallelhash.rs
quininer/sp800-185
04472c21e6b92956983fff9178452ee38a9d9c80
use tiny_keccak::{ Keccak, XofReader }; use rayon::prelude::*; use ::cshake::CShake; use ::utils::{ left_encode, right_encode }; #[derive(Clone)] pub struct ParallelHash { inner: CShake, buf: Vec<u8>, n: u64, rate: usize, blocksize: usize } impl ParallelHash { #[inline] pub fn new_parallel...
use tiny_keccak::{ Keccak, XofReader }; use rayon::prelude::*; use ::cshake::CShake; use ::utils::{ left_encode, right_encode }; #[derive(Clone)] pub struct ParallelHash { inner: CShake, buf: Vec<u8>, n: u64, rate: usize, blocksize: usize } impl ParallelHash { #[inline] pub fn new_parallel...
let mut encbuf = [0; 9]; let pos = right_encode(&mut encbuf, self.n); self.inner.update(&encbuf[pos..]); let pos = right_encode(&mut encbuf, bitlength); self.inner.update(&encbuf[pos..]); } }
e.finalize(&mut encbuf); self.inner.update(&encbuf); self.buf.clear(); self.n += 1; } len } else { 0 }; let bufs = buf[pos..].par_chunks(self.blocksize) .map(|chunk| if chunk.len() < self.blocksize {...
random
[ { "content": "/// `left_encode(x)` encodes the integer x as a byte string in a way that can be unambiguously parsed\n\n/// from the beginning of the string by inserting the length of the byte string before the byte string\n\n/// representation of x.\n\npub fn left_encode(buf: &mut [u8; 9], value: u64) -> usize ...
Rust
src/mesh/model.rs
OllieBerzs/tegne-rs
be614c6b5091ffe476ffbe44ef4ea5b62d998078
use std::collections::HashSet; use std::slice::Iter; use super::Mesh; use crate::math::Mat4; use crate::pipeline::Descriptor; use crate::pipeline::Material; use crate::resources::Handle; pub struct Model { pub nodes: Vec<ModelNode>, } #[derive(Clone)] pub struct ModelNode { pub meshes: Vec<Handle...
use std::collections::HashSet; use std::slice::Iter; use super::Mesh; use crate::math::Mat4; use crate::pipeline::Descriptor; use crate::pipeline::Material; use crate::resources::Handle; pub struct Model { pub nodes: Vec<ModelNode>, } #[derive(Clone)] pub struct ModelNode { pub meshes: Vec<Handle...
pub fn meshes(&self) -> impl Iterator<Item = &Handle<Mesh>> { self.nodes.iter().map(|node| node.meshes()).flatten() } pub fn materials(&self) -> impl Iterator<Item = &Handle<Material>> { self.nodes.iter().map(|node| node.materials()).flatten() } } impl ModelNode { pub(c...
pub fn fix_color_space(&mut self) { let mut fixed = HashSet::new(); self.nodes .iter_mut() .for_each(|n| n.fix_color_space(&mut fixed)); }
function_block-full_function
[ { "content": "struct Cache {\n\n shader: Option<Handle<Shader>>,\n\n material: Option<Handle<Material>>,\n\n font: Option<Handle<Font>>,\n\n\n\n // colors\n\n background: Rgb,\n\n fill: Rgb,\n\n stroke: Rgb,\n\n tint: Rgb,\n\n\n\n // shadows\n\n shadows: bool,\n\n\n\n // other\n...
Rust
src/socket.rs
caizixian/streamdeck-rs
3848d18fa4bf48b95ccb77c6cf689d422145509e
use super::{Message, MessageOut}; use failure::Fail; use futures::prelude::*; use serde::{de, ser}; use serde_derive::Serialize; use std::marker::PhantomData; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::net::TcpStream; use tokio_tungstenite::{self, WebSocketStream, MaybeTlsStream}; use url::Url; pub ...
use super::{Message, MessageOut}; use failure::Fail; use futures::prelude::*; use serde::{de, ser}; use serde_derive::Serialize; use std::marker::PhantomData; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::net::TcpStream; use tokio_tungstenite::{self, WebSocketStream, MaybeTlsStream}; use url::Url; pub ...
} Poll::Ready(None) => break Poll::Ready(None), Poll::Pending => break Poll::Pending, } } } } impl<G, S, MI, MO> Sink<MessageOut<G, S, MO>> for StreamDeckSocket<G, S, MI, MO> where G: ser::Serialize, S: ser::Serialize, MO: ser::Serialize, { type E...
(error))) => { break Poll::Ready(Some(Err(StreamDeckSocketError::WebSocketError(error))))
function_block-random_span
[ { "content": "struct Serializer {\n\n stack: Vec<String>,\n\n}\n\n\n\nimpl slog::Serializer for Serializer {\n\n fn emit_none(&mut self, key: Key) -> slog::Result {\n\n self.stack.push(format!(\"{}: None\", key));\n\n Ok(())\n\n }\n\n fn emit_unit(&mut self, key: Key) -> slog::Result {...
Rust
src/commands/install.rs
RyosukeNAKATA/mamimi
347583f657f0f8a4df2d91df86e05d6113251f44
use crate::alias::create_alias; use crate::archive::{self, extract::Error as ExtractError, extract::Extract}; use crate::config::MamimiConfig; use crate::current_python_version::current_python_version; use crate::input_version::InputVersion; use crate::outln; use crate::python_version::PythonVersion; use crate::version...
use crate::alias::create_alias; use crate::archive::{self, extract::Error as ExtractError, extract::Extract}; use crate::config::MamimiConfig; use crate::current_python_version::current_python_version; use crate::input_version::InputVersion; use crate::outln; use crate::python_version::PythonVersion; use crate::version...
.expect("Cannot generate a temp directory"); extract_archive_into(&tmp_dir, response)?; outln!( config, Error, "{} Building {}", "==>".green(), format!("Python {}", current_version).green() ); let installed_directory = std:...
.ok_or(MamimiError::VersionNotFound { version: current_version, })? .clone() } }; let installations_dir = config.python_versions_dir(); let installation_dir = PathBuf::from(&installations_dir).join(ver...
random
[ { "content": "pub fn current_python_version(config: &MamimiConfig) -> Result<Option<PythonVersion>, Error> {\n\n let multishell_path = config.multishell_path().ok_or(Error::EnvNotApplied)?;\n\n\n\n if multishell_path.read_link().ok() == Some(system_version::path()) {\n\n return Ok(Some(PythonVersio...
Rust
src/tests/live_mocker.rs
w3f/polkadot-registrar-bot
3c5aa36cf5de8edae0ac434947eb585b7ca92c75
use crate::adapters::tests::MessageInjector; use crate::adapters::AdapterListener; use crate::database::Database; use crate::primitives::{ ExpectedMessage, ExternalMessage, ExternalMessageType, JudgementState, MessageId, Timestamp, }; use crate::tests::F; use crate::{config_session_notifier, DatabaseConfig, Display...
use crate::adapters::tests::MessageInjector; use crate::adapters::AdapterListener; use crate::database::Database; use crate::primitives::{ ExpectedMessage, ExternalMessage, ExternalMessageType, JudgementState, MessageId, Timestamp, }; use crate::tests::F; use crate::{config_session_notifier, DatabaseConfig, Display...
r_test_{}", rng.gen_range(u32::MIN..u32::MAX)), }; let notifier_config = NotifierConfig { api_address: "localhost:8888".to_string(), display_name: DisplayNameConfig { enabled: true, limit: 0.85, }, }; info!("Starting mock adapter and session notifier ins...
function_block-function_prefixed
[ { "content": "fn try_decode_hex(display_name: &mut String) {\n\n if display_name.starts_with(\"0x\") {\n\n // Might be a false positive. Leave it as is if it cannot be decoded.\n\n if let Ok(name) = hex::decode(&display_name[2..]) {\n\n if let Ok(name) = String::from_utf8(name) {\n\n...
Rust
signature_benchmark/src/wots_aes.rs
qkniep/PQ-FIDO_sd-MSS
27c49bcb82d86057ae4b4c7a429fa55671735de0
use core::convert::TryInto; use core::hash::Hasher; use aes::cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher}; use aes::Aes128; use getrandom; use siphasher::sip128::{Hasher128, SipHasher}; pub const W: usize = 256; pub const X: usize = 1; pub const N: usize = 128 / 8; /*/// Message digest len...
use core::convert::TryInto; use core::hash::Hasher; use aes::cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher}; use aes::Aes128; use getrandom; use siphasher::sip128::{Hasher128, SipHasher}; pub const W: usize = 256; pub const X: usize = 1; pub const N: usize = 128 / 8; /*/// Message digest len...
)?; Ok(buf) } pub fn prng(seed: &mut [u8; N]) -> [u8; N] { let mut output = *GenericArray::from_slice(seed); let iv = GenericArray::from([0u8; N]); let cipher = Aes128::new(&iv); cipher.encrypt_block(&mut output); let s = u128::from_be_bytes(*seed); let o = u128::from_be_bytes(output.as_s...
lf) -> bool { let mut i = 0; let mut pk = Vec::<[u8; N]>::with_capacity(N * X); for b in &self.msg_hash { for s in base_w(*b) { let cycles = W - 1 - (s as usize); pk.push(chain(&self.signature[i], cycles)); i += 1; } ...
random
[ { "content": "/// Applies c cycles of the SHA-256/8N hash function to the input.\n\npub fn chain(input: &[u8; N], c: usize, chain: usize, start: usize, pk_seed: &[u8; N]) -> [u8; N] {\n\n let mut output = input.clone();\n\n\n\n for i in 0..c {\n\n let (key, bitmask) = prf2(&pk_seed, ((chain << 8) +...
Rust
src/stations.rs
danielrs/pandora-rs
494ab0aef0ddb9959cdae6c6a6fb5a8ab161a7d0
use super::Pandora; use error::Result; use method::Method; use music::{ToMusicToken, MusicType}; use playlist::Playlist; use serde_json; pub struct Stations<'a> { pandora: &'a Pandora, } impl<'a> Stations<'a> { pub fn new(pandora: &'a Pandora) -> Stations<'a> { Stations { pandora: pandora } ...
use super::Pandora; use error::Result; use method::Method; use music::{ToMusicToken, MusicType}; use playlist::Playlist; use serde_json; pub struct Stations<'a> { pandora: &'a Pandora, } impl<'a> Stations<'a> { pub fn new(pandora: &'a Pandora) -> Stations<'a> { Stations { pandora: pandora } ...
pub fn add_seed<S, T>(&self, station: &S, music_token: &T) -> Result<Seed> where S: ToStationToken, T: ToMusicToken { self.pandora .post(Method::StationAddMusic, Some(serde_json::to_value(AddSeedRequest { ...
where T: ToStationToken { self.pandora .post_noop(Method::StationDeleteStation, Some(serde_json::to_value(DeleteStationRequest { station_token: station.to_station_token(), ...
function_block-function_prefix_line
[ { "content": "/// Returns the encrypted input using the given key.\n\n///\n\n/// The returned string is encoded in hexadecimal notation,\n\n/// which is a UTF-8 string, so it's fine to return it using\n\n/// the `String` type.\n\npub fn encrypt(key: &str, input: &str) -> String {\n\n let cipherbytes = cipher...
Rust
src/main.rs
cerrno/winnow
f172e648a9b69ac6dd0bc42ac753c173d89ad962
use std::collections::HashMap; use std::env; use std::io; use std::path::Path; use std::process::Command; use winnow::detector; use winnow::winnowing::{parse_patch, Fingerprint}; use colored::*; use indicatif::ProgressIterator; struct Repo { name: String, path: String, patches: Vec<String>, } impl Repo ...
use std::collections::HashMap; use std::env; use std::io; use std::path::Path; use std::process::Command; use winnow::detector; use winnow::winnowing::{parse_patch, Fingerprint}; use colored::*; use indicatif::ProgressIterator; struct Repo { name: String, path: String, patches: Vec<String>, } impl Repo ...
fn git_clone(&self) -> io::Result<()> { let clone_cmd = Command::new("git") .arg("clone") .arg("--bare") .arg(&self.path) .output()?; if clone_cmd.status.code().unwrap() == 128 { println!("{}", format!("repo {} already exists", self.path)...
let repo_dir = Path::new(repo).file_name().unwrap(); let repo = Repo { name: repo_dir.to_str().unwrap().to_owned(), path: repo.to_owned(), patches: vec![], }; repo.git_clone()?; Ok(repo) }
function_block-function_prefix_line
[ { "content": "pub fn parse_patch(path: &str, repo: &str) -> Vec<Fingerprint> {\n\n let patch = fs::read_to_string(path).unwrap();\n\n let mut patchset = PatchSet::new();\n\n if let Err(e) = patchset.parse(&patch) {\n\n println!(\"{:?}\", e);\n\n return vec![];\n\n }\n\n let commit_h...
Rust
bindings/src/event_bindings.rs
stumptownlabs/beeper-android-seshat
2de21b9002f72ac083a143629e0ad3d806fd63ce
extern crate jni; extern crate seshat; use jni::sys::{jlong, jboolean, jstring}; use jni::JNIEnv; use jni::objects::{JObject, JString, JValue}; use seshat::{Event, EventType}; use crate::utils::*; /* * EVENT BINDINGS */ #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1new_1ev...
extern crate jni; extern crate seshat; use jni::sys::{jlong, jboolean, jstring}; use jni::JNIEnv; use jni::objects::{JObject, JString, JValue}; use seshat::{Event, EventType}; use crate::utils::*; /* * EVENT BINDINGS */ #[no_mangle] pub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1new_1ev...
{ let event = Box::from_raw(event_ptr as *mut Event); let option = event.msgtype.clone(); let message_type = match option{ None => {String::from("")} Some(msgtype) => { msgtype } }; Box::leak(event); let output = env.new_string(message_type).unwrap(); ...
ub unsafe extern "C" fn Java_com_beeper_android_1seshat_event_Event_n_1get_1event_1message_1type( env: JNIEnv, _: JObject, event_ptr: jlong, ) -> jstring
function_block-random_span
[ { "content": "pub fn event_to_json(event: Event) -> Result<String,serde_json::error::Error> {\n\n match serde_json::to_string(&event){\n\n Ok(json) => {\n\n Ok(json)\n\n }\n\n Err(error) => {\n\n Err(error)\n\n }\n\n }\n\n}\n\n\n", "file_path": "bindin...
Rust
src/traits.rs
dhylands/serial-framing-protocol-rs
2f8cee9611891e494023f797ecb847249dffca3f
use core::cmp::min; use core::fmt; use core::mem::size_of; use log::info; use pretty_hex::*; use crate::crc::{Crc, CrcAccum}; pub const SOF: u8 = 0x7e; pub const ESC: u8 = 0x7d; pub const ESC_FLIP: u8 = 0x20; pub trait PacketBuffer { fn capacity(&self) -> usize; fn len(&self) -> usize; ...
use core::cmp::min; use core::fmt; use core::mem::size_of; use log::info; use pretty_hex::*; use crate::crc::{Crc, CrcAccum}; pub const SOF: u8 = 0x7e; pub const ESC: u8 = 0x7d; pub const ESC_FLIP: u8 = 0x20; pub trait PacketBuffer { fn capacity(&self) -> usize; fn len(&self) -> usize; ...
] as CrcAccum); self.set_len(len); crc } fn dump(&self) { info!("{:?}", self.data().hex_dump()); } } impl fmt::Debug for dyn PacketBuffer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.data().hex_dump()) } } pub trait Packe...
et mut len = self.len(); if len < size_of::<CrcAccum>() { return 0; } len -= 2; let data = self.data(); let crc = ((data[len + 1] as CrcAccum) << 8) | (data[len
function_block-random_span
[ { "content": "// Parse a bunch of bytes and return the first return code that isn't\n\n// MoreDataNeeded. This means that this function will parse at most one\n\n// error or packet from the input stream, which is fine for testing.\n\npub fn parse_bytes(\n\n parser: &mut RawPacketParser,\n\n bytes: &[u8],\...
Rust
src/tokenizer/words.rs
naughie/kytea-tokenizer
8dd76fae807c2bd0d9f773cef2089b13b3ef7570
use super::Word; use crate::kytea::{DELIM, ESCAPE}; use std::num::NonZeroUsize; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct Words<'a> { inner: &'a str, } impl<'a> Iterator for Words<'a> { type Item = Word<'a>; fn next(&mut self) -> Option<Self::Item> { let pos = self.find_sow(); ...
use super::Word; use crate::kytea::{DELIM, ESCAPE}; use std::num::NonZeroUsize; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct Words<'a> { inner: &'a str, } impl<'a> Iterator for Words<'a> { type Item = Word<'a>; fn next(&mut self) -> Option<Self::Item> { let pos = self.find_sow(); ...
Words::from(s).rev(); assert_eq!(words.next(), Some(Word::from("a"))); assert_eq!(words.next(), Some(Word::from("\\\\"))); assert_eq!(words.next(), None); } #[test] fn test_words_mixed() { let s = "吾輩/名詞\tは/助詞\t\t猫/名詞\t /補助記号"; let mut words = Words::from(s); ...
記号"))); assert_eq!(words.next(), Some(Word::from("猫/名詞"))); assert_eq!(words.next(), Some(Word::from("は/助詞"))); assert_eq!(words.next(), Some(Word::from("吾輩/名詞"))); assert_eq!(words.next(), None); let s = "\t\tab\t\\\t/補助記号\t\\/\\\t\t\\\\\\\t/\\\\\t"; let mut words = Wor...
random
[ { "content": "type WordsFrom<'a> = fn(&'a str) -> Words<'a>;\n", "file_path": "src/tokenizer/mod.rs", "rank": 0, "score": 100778.44098460334 }, { "content": "pub fn strip(out: impl AsRef<str>) -> String {\n\n let mut stripped = String::new();\n\n\n\n for line in out.as_ref().lines() {\...
Rust
src/auth.rs
FamiizCEO/modio-rs
101460ef3ba1c197025ba80cd01568defbc2d7e9
use std::fmt; use futures::Future as StdFuture; use url::form_urlencoded; use crate::Future; use crate::Modio; use crate::ModioMessage; #[derive(Clone, Debug, PartialEq)] pub enum Credentials { ApiKey(String), Token(String), } impl fmt::Display for Credentials { fn fmt(&self, f: &mut fmt::Formatter<'_>...
use std::fmt; use futures::Future as StdFuture; use url::form_urlencoded; use crate::Future; use crate::Modio; use crate::ModioMessage; #[derive(Clone, Debug, PartialEq)] pub enum Credentials { ApiKey(String), Token(String), } impl fmt::Display for Credentials { fn fmt(&self, f: &mut fmt::Formatter<'_>...
pub fn link(&self, email: &str, service: Service) -> Future<()> { token_required!(self.modio); let (service, id) = match service { Service::Steam(id) => ("steam", id.to_string()), Service::Gog(id) => ("gog", id.to_string()), }; let data = form...
pub fn security_code(&self, code: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("security_code", code) .finish(); Box::new( self.modio .post::<AccessToken, ...
function_block-full_function
[ { "content": "fn prompt(prompt: &str) -> io::Result<String> {\n\n print!(\"{}\", prompt);\n\n io::stdout().flush()?;\n\n let mut buffer = String::new();\n\n io::stdin().read_line(&mut buffer)?;\n\n Ok(buffer.trim().to_string())\n\n}\n\n\n", "file_path": "examples/auth.rs", "rank": 0, ...
Rust
kg-syntax/src/lexer/nfa.rs
kodegenix/kg-lang
baa79ac7fb8babe82b6b8eed2af34d869523d8f4
use super::*; #[derive(Debug, Clone)] pub struct Nfa { states: Vec<State>, } impl Nfa { pub fn from_program(prog: &Program) -> Nfa { Builder::new().build(prog) } pub fn states(&self) -> &[State] { &self.states } } impl std::fmt::Display for Nfa { fn fmt(&self, f: &mut std::fm...
use super::*; #[derive(Debug, Clone)] pub struct Nfa { states: Vec<State>, } impl Nfa { pub fn from_program(prog: &Program) -> Nfa { Builder::new().build(prog) } pub fn states(&self) -> &[State] { &self.states } } impl std::fmt::Display for Nfa { fn fmt(&self, f: &mut std::fm...
ates.iter().enumerate() { if *s == state { state_map[pc as usize] = i as u32; found = true; break; } } if !found { state_map[pc as usize] = states.len() as u32; states.push...
bool) { debug_assert!(!state.merged_states.contains(&pc)); match *prog.opcode(pc) { Opcode::Match(m) => { state.accepts.push(Accept::new(pc, m)); state.merged_states.insert(pc); } Opcode::Byte(g, b) => { ...
function_block-random_span
[ { "content": "#[derive(Debug, Clone, Copy)]\n\nstruct Proc(u32, u32);\n\n\n\nimpl Proc {\n\n fn is_empty(&self) -> bool {\n\n self.0 == EMPTY_GOTO\n\n }\n\n\n\n fn merge(&mut self, p: Proc) -> Proc {\n\n if self.is_empty() {\n\n *self = p;\n\n } else if !p.is_empty() {\n...
Rust
src/oneshot/timer_fd.rs
krircc/async-timer
c2cb75ab1d4624e8af280a1cdf8c3aa9f41f27bd
#[cfg(feature = "no_std")] core::compile_error!("no_std is not supported for timerfd implementation"); use crate::std::io; use core::future::Future; use core::pin::Pin; use core::{mem, ptr, task, time}; use libc::c_int; #[cfg(target_os = "android")] mod sys { #[repr(C)] pub struct itimerspec { pub ...
#[cfg(feature = "no_std")] core::compile_error!("no_std is not supported for timerfd implementation"); use crate::std::io; use core::future::Future; use core::pin::Pin; use core::{mem, ptr, task, time}; use libc::c_int; #[cfg(target_os = "android")] mod sys { #[repr(C)] pub struct itimerspec { pub ...
fn is_expired(&self) -> bool { match &self.state { State::Init(_) => false, State::Running(is_finished) => *is_finished, } } fn cancel(&mut self) { self.fd.get_mut().set(unsafe { mem::zeroed() }); } fn restart(&mut self, new_value: time::Duration, ...
match &self.state { State::Init(_) => false, State::Running(is_finished) => !*is_finished, } }
function_block-function_prefix_line
[ { "content": "fn time_create(timeout: time::Duration, state: *const TimerState) -> TimerHandle {\n\n let timeout = timeout.as_millis() as u32;\n\n\n\n let cb = wasm_bindgen::closure::Closure::once(move || unsafe {\n\n (*state).wake();\n\n });\n\n let handle = setTimeout(&cb, timeout);\n\n\n\n...
Rust
src/ingester/ingester.rs
pathivu/pathivu
09ac381630dceb578b8abc39a67030c521e404ce
/* * Copyright 2019 Balaji Jinnah and Contributors * * 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 applicabl...
/* * Copyright 2019 Balaji Jinnah and Contributors * * 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 applicabl...
pub fn start(&mut self) { info!("ingester {} started", self.id); loop { let ingester_request = block_on(async { self.receiver.next().await }); info!("received yo"); if !ingester_request.is_some() { continue; } let ingester...
pub fn new(receiver: Receiver<IngesterRequest>, cfg: Config, store: S) -> Ingester<S> { Ingester { receiver: receiver, id: 0, segment_writers: HashMap::new(), cfg: cfg, store: store, tailers: HashMap::default(), } }
function_block-full_function
[ { "content": "pub trait Store {\n\n fn merge(&mut self, key: &[u8], value: Vec<u8>);\n\n fn set(&mut self, key: &[u8], value: Vec<u8>);\n\n fn flush(&mut self) -> Result<usize, failure::Error>;\n\n fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, failure::Error>;\n\n fn flush_batch(&self, wb:...
Rust
src/bin/mv_files.rs
lukaspustina/clams-bin
14cf8732a4809b2003fbe255edffab448047b19a
use clams::prelude::*; use clams_bin::mv_files; use failure::{format_err, Error}; use std::path::{Path, PathBuf}; use structopt::StructOpt; use walkdir::WalkDir; #[derive(StructOpt, Debug)] #[structopt( name = "mv_files", about = "Move video files from a nested directory structure into another, flat directory"...
use clams::prelude::*; use clams_bin::mv_files; use failure::{format_err, Error}; use std::path::{Path, PathBuf}; use structopt::StructOpt; use walkdir::WalkDir; #[derive(StructOpt, Debug)] #[structopt( name = "mv_files", about = "Move video files from a nested directory structure into another, flat directory"...
} Ok(()) } fn main() { let args = Args::from_args(); clams::console::set_color(!args.no_color); let name = Args::clap().get_name().to_owned(); let level: Level = args.verbosity.into(); if !args.silent { eprintln!( "{} version={}, log level={:?}", name, ...
if dry { println!(" {}", "simulated.".blue()); } else { match std::fs::rename(from, to) { Ok(_) => println!(" {}.", "done".green()), Err(e) => eprintln!( "Failed to move {} because {}", from.to_str().unwrap().red(), ...
if_condition
[ { "content": " };\n\n\n\n let size = size.parse::<u64>().map_err(|_| MvFilesError::InvaildSize {\n\n arg: String::from(size),\n\n })?;\n\n\n\n let size = match scale {\n\n 'k' => size * 1024u64.pow(1),\n\n 'M' => size * 1024u64.pow(2),\n\n ...
Rust
benches/raid.rs
geky/gf256
57675335061b18e3614376981482fd7584454fd5
use criterion::criterion_group; use criterion::criterion_main; use criterion::Criterion; use criterion::BatchSize; use criterion::Throughput; use std::iter; use std::convert::TryFrom; #[allow(dead_code)] #[path = "../examples/raid.rs"] mod raid; fn bench_raid(c: &mut Criterion) { let mut group = c.benchmark_gro...
use criterion::criterion_group; use criterion::criterion_main; use criterion::Criterion; use criterion::BatchSize; use criterion::Throughput; use std::iter; use std::convert::TryFrom; #[allow(dead_code)] #[path = "../examples/raid.rs"] mod raid; fn bench_raid(c: &mut Criterion) { let mut group = c.benchmark_gro...
const SIZE: usize = 1024*1024; const COUNT: usize = 5; let mut xs = xorshift64(42).map(|x| x as u8); group.throughput(Throughput::Bytes((COUNT*SIZE) as u64)); group.bench_function("raid5_format", |b| b.iter_batched_ref( || {( iter::repeat_with(|| { (&...
fn xorshift64(seed: u64) -> impl Iterator<Item=u64> { let mut x = seed; iter::repeat_with(move || { x ^= x << 13; x ^= x >> 7; x ^= x << 17; x }) }
function_block-full_function
[ { "content": "fn bench_gfmul(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"gfmul\");\n\n\n\n // gf256 mul/div\n\n bench_mul!(group, \"gf256_naive_mul\", gf256_naive);\n\n bench_mul!(group, \"gf256_table_mul\", gf256_table);\n\n bench_mul!(group, \"gf256_rem_ta...
Rust
src/types/option_value.rs
aCLr/telegram-tdlib
40262849d87608931f22d0bbfd5baa0b410461ce
use crate::errors::*; use crate::types::*; use uuid::Uuid; use std::fmt::Debug; pub trait TDOptionValue: Debug + RObject {} #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "@type")] pub enum OptionValue { #[doc(hidden)] _Default, #[serde(rename(serialize = "getOption", deserialize = "g...
use crate::errors::*; use crate::types::*; use uuid::Uuid; use std::fmt::Debug; pub trait TDOptionValue: Debug + RObject {} #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "@type")] pub enum OptionValue { #[doc(hidden)] _Default, #[serde(rename(serialize = "getOption", deserialize = "g...
} #[doc(hidden)] fn client_id(&self) -> Option<i32> { match self { OptionValue::GetOption(t) => t.client_id(), OptionValue::Boolean(t) => t.client_id(), OptionValue::Empty(t) => t.client_id(), OptionValue::Integer(t) => t.client_id(), Opti...
match self { OptionValue::GetOption(t) => t.extra(), OptionValue::Boolean(t) => t.extra(), OptionValue::Empty(t) => t.extra(), OptionValue::Integer(t) => t.extra(), OptionValue::String(t) => t.extra(), _ => None, }
if_condition
[ { "content": "pub trait RFunction: Debug + RObject + Serialize {\n\n fn to_json(&self) -> RTDResult<String> {\n\n Ok(serde_json::to_string(self)?)\n\n }\n\n}\n\n\n\nimpl<'a, RObj: RObject> RObject for &'a RObj {\n\n fn extra(&self) -> Option<&str> {\n\n (*self).extra()\n\n }\n\n fn ...
Rust
crates/vkfft-sys/build.rs
semio-ai/vkfft-rs
2ee35297bdfef4aece8877f7b1c1c5b1c584766c
extern crate bindgen; extern crate cc; use std::error::Error; use std::path::{Path, PathBuf}; use bindgen::Bindings; fn build_lib<O, LD, L, const N: usize, const M: usize>(out_dir: O, library_dirs: LD, libraries: L, defines: &[(&str, &str); N], include_dirs: &[String; M]) -> Result<(), Box<dyn Error>> where O: AsR...
extern crate bindgen; extern crate cc; use std::error::Error; use std::path::{Path, PathBuf}; use bindgen::Bindings; fn build_lib<O, LD, L, const N: usize, const M: usize>(out_dir: O, library_dirs: LD, libraries: L, defines: &[(&str, &str); N], include_dirs: &[String; M]) -> Result<(), Box<dyn Error>> where O: AsR...
ings = gen_wrapper(&rw, &defines, &include_dirs)?; bindings.write_to_file(out_dir.join("bindings.rs"))?; Ok(()) }
{ let mut build = cc::Build::default(); build .cpp(true) .file("wrapper.cpp") .include(out_dir) .flag("-std=c++11") .flag("-w"); for library_dir in library_dirs { build.flag(format!("-L{}", library_dir.as_ref()).as_str()); } for library in libraries { build.flag(format!("-l{}",...
random
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n println!(\"VkFFT version: {}\", vkfft::version());\n\n\n\n let instance = Instance::new(\n\n None,\n\n &InstanceExtensions {\n\n ext_debug_utils: true,\n\n ..InstanceExtensions::none()\n\n },\n\n vec![\"VK_LAYER_KHRO...
Rust
examples/bgpdumper.rs
wladwm/zettabgp
85d8e21742e948907cf3fcc64552f40c9e852524
extern crate zettabgp; use std::env; use std::io::{Read, Write}; use std::net::{Shutdown, TcpStream}; use std::thread::{sleep, spawn}; use zettabgp::prelude::*; pub struct BgpDumper { pub params: BgpSessionParams, pub stream: TcpStream, } impl BgpDumper { pub fn new(bgp_params: BgpSessionParams, tcpstre...
extern crate zettabgp; use std::env; use std::io::{Read, Write}; use std::net::{Shutdown, TcpStream}; use std::thread::{sleep, spawn}; use zettabgp::prelude::*; pub struct BgpDumper { pub params: BgpSessionParams, pub stream: TcpStream, } impl BgpDumper { pub fn new(bgp_params: BgpSessionParams, tcpstre...
fn main() { if env::args().len() != 3 { eprintln!("Usage: bgpdumper PEER AS"); return; } let vargs: Vec<String> = env::args().map(|x| x).collect(); let targetip: std::net::IpAddr = match vargs[1].parse() { Ok(x) => x, Err(_) => { eprintln!("Invalid peer IP - {...
function_block-full_function
[ { "content": "/// Stores ipv4 address into the buffer.\n\npub fn encode_addrv4_to(addr: &std::net::Ipv4Addr, buf: &mut [u8]) -> Result<usize, BgpError> {\n\n if buf.len() < 4 {\n\n return Err(BgpError::static_str(\"Invalid addrv4 length\"));\n\n }\n\n buf[0..4].clone_from_slice(&addr.octets());\...
Rust
embassy-stm32/src/pwm/mod.rs
Liamolucko/embassy
4f4b19d920c103453b2b0f9ce7994ca830ddb2d7
use crate::gpio; use crate::rcc::RccPeripheral; use crate::time::Hertz; use core::marker::PhantomData; use embassy::util::Unborrow; use embassy_hal_common::unborrow; use stm32_metapac::timer::vals::Ocm; pub struct Pwm<'d, T: Instance> { phantom: PhantomData<&'d mut T>, } pub struct Ch1 {} pub struct Ch2 {} pub st...
use crate::gpio; use crate::rcc::RccPeripheral; use crate::time::Hertz; use core::marker::PhantomData; use embassy::util::Unborrow; use embassy_hal_common::unborrow; use stm32_metapac::timer::vals::Ocm; pub struct Pwm<'d, T: Instance> { phantom: PhantomData<&'d mut T>, } pub struct Ch1 {} pub struct Ch2 {} pub st...
pub fn get_max_duty(&self) -> u32 { let r = T::regs(); unsafe { r.arr().read().arr() as u32 } } pub fn set_duty(&mut self, channel: Channel, duty: u32) { use core::convert::TryInto; assert!(duty < self.get_max_duty()); let duty: u16 = duty.try_into().unwrap(); ...
pub fn set_freq<F: Into<Hertz>>(&mut self, freq: F) { use core::convert::TryInto; let clk = T::frequency(); let r = T::regs(); let freq: Hertz = freq.into(); let ticks: u32 = clk.0 / freq.0; let psc: u16 = (ticks / (1 << 16)).try_into().unwrap(); let arr: u16 = (t...
function_block-full_function
[ { "content": "/// Low power blocking wait loop using WFE/SEV.\n\npub fn low_power_wait_until(mut condition: impl FnMut() -> bool) {\n\n while !condition() {\n\n // WFE might \"eat\" an event that would have otherwise woken the executor.\n\n cortex_m::asm::wfe();\n\n }\n\n // Retrigger an ...
Rust
src/lib.rs
JerTH/elfy
2a761bcc4de002b72a538eae3e5ec1d5cc0f3ba8
#![warn(missing_docs)] use std::error::Error; use std::fmt::{ Display, Formatter }; use std::io::{ Read, Seek, SeekFrom }; use std::collections::HashMap; #[macro_use] mod macros; pub mod types; pub mod numeric; pub mod constants; use crate::types::*; pub type ParseElfResult<T> = std::result::Result<T, ParseElfErro...
#![warn(missing_docs)] use std::error::Error; use std::fmt::{ Display, Formatter }; use std::io::{ Read, Seek, SeekFrom }; use std::collections::HashMap; #[macro_use] mod macros; pub mod types; pub mod numeric; pub mod constants; use crate::types::*; pub type ParseElfResult<T> = std::result::Result<T, ParseElfErro...
0 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Phdr), 1 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Loadable), 2 => assert_eq!(h.header().program_header_type(), ProgramHeaderType::Loadable), 3 => assert_eq!(h.header().pr...
rse(reader, descriptor)?) } Ok(sections) } fn parse_segments<R: Read + Seek>(reader: &mut R, descriptor: &mut Descriptor, header: &ElfHeader) -> ParseElfResult<Vec<Segment>> { reader.seek(SeekFrom::Start(header.program_headers_offset()))?; let mut segments = Vec::new(); for _ in 0..header.program_h...
random
[ { "content": "}\n\n\n\nmacro_rules! read_u64 {\n\n ($reader:expr, $descriptor:expr) => {\n\n {\n\n let mut __bytes: [u8; 8] = [0; 8];\n\n let mut __temp: u64 = 0;\n\n $reader.read_exact(&mut __bytes)?;\n\n unsafe {\n\n __temp = std::mem::trans...
Rust
rs/2021/day20/src/main.rs
cs-cordero/advent-of-code
614b8f78b43c54ef180a7dc411a0d1366a62944f
use advent_of_code::read_input_as_string; use std::collections::HashSet; use std::fmt::{Display, Formatter}; type Point = (isize, isize); #[derive(Clone, Debug)] struct Rect { lo_row: isize, lo_col: isize, hi_row: isize, hi_col: isize, } impl Rect { fn contains(&self, point: &Point) -> bool { ...
use advent_of_code::read_input_as_string; use std::collections::HashSet; use std::fmt::{Display, Formatter}; type Point = (isize, isize); #[derive(Clone, Debug)] struct Rect { lo_row: isize, lo_col: isize, hi_row: isize, hi_col: isize, } impl Rect { fn contains(&self, point: &Point) -> bool { ...
fn main() { let raw = read_input_as_string("2021/day20/src/input.txt"); let image = { let (raw_algorithm, raw_image) = raw.split_once("\n\n").unwrap(); let algorithm = raw_algorithm.chars().collect::<Vec<_>>(); let image = raw_image .lines() .enumerate() ...
function_block-full_function
[ { "content": "fn find_monster(image: &[Vec<char>], row: usize, col: usize) -> bool {\n\n MONSTER_OFFSETS\n\n .iter()\n\n .copied()\n\n .all(|(offset_row, offset_col)| {\n\n let operator = match offset_row.cmp(&0) {\n\n Ordering::Less => usize::checked_sub,\n\n ...
Rust
rust/src/main.rs
tagadvance/chms_api_examples
b8335f5e5a9216afa357944b870edf29ad838243
#[macro_use] extern crate dotenv_codegen; extern crate dotenv; mod db; mod utils; use db::{TokenDatabase, TokenResponse}; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::future::Future; use std::pin::Pin; use tide::http::url::ParseError; use tide::utils::After; use tide::{Body, Next, Redirect, Request...
#[macro_use] extern crate dotenv_codegen; extern crate dotenv; mod db; mod utils; use db::{TokenDatabase, TokenResponse}; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::future::Future; use std::pin::Pin; use tide::http::url::ParseError; use tide::utils::After; use tide::{Body, Next, Redirect, Request...
rl("oauth/token"), &body)?; req.state().handle_token_response(&response)?; println!("Auth code successfully exchanged for tokens."); Ok(Redirect::new(params.state).into()) } async fn api_passthrough_handler(request: Request<TokenDatabase>) -> tide::Result<Response> { let path = request.param("path")?; matc...
direct_uri: String, client_id: String, client_secret: String, code: String, } #[derive(Deserialize, Serialize)] struct RefreshTokenBody { refresh_token: String, grant_type: String, client_id: String, client_secret: String, } fn build_auth_code_redirect_url(return_url: String) -> std::result::Result<Url,...
random
[ { "content": "pub fn get<R: DeserializeOwned>(url: &String, token: &String) -> Result<(R, reqwest::StatusCode)> {\n\n let response = reqwest::blocking::Client::new()\n\n .get(url)\n\n .header(\"Content-Type\", \"application/json\")\n\n .header(\"Accept\", \"application/vnd.ccbchurch.v2+json\")\n\n ...
Rust
src/lib.rs
Gingeh/brainfrick
bd7fe1a2cc7dbee0b1c81e2b585c66d320facac5
use std::collections::VecDeque; pub struct BrainFuck { memory: Vec<Cell>, pointer: usize, input: VecDeque<u8>, counter: usize, max_steps: usize, } impl BrainFuck { #[must_use] pub fn new(size: usize, input: &str, max_steps: usize) -> Self { BrainFuck { memory: vec![Cell...
use std::collections::VecDeque; pub struct BrainFuck { memory: Vec<Cell>, pointer: usize, input: VecDeque<u8>, counter: usize, max_steps: usize, } impl BrainFuck { #[must_use] pub fn new(size: usize, input: &str, max_steps: usize) -> Self { BrainFuck { memory: vec![Cell...
))); } #[test] fn test_max_steps() { let program = "+[]"; let mut engine = BrainFuck::new(256, "", 100); assert_eq!( engine.run(program), Err(String::from( "Exceeded maximum steps (100), the program may be stuck in a loop." )) ...
' => self.add(), '-' => self.sub(), '<' => self.left(), '>' => self.right(), '.' => output += &self.print(), ',' => self.read(), '[' => self.start(&program)?, ']' => self.end(&program)?, _ => ...
random
[ { "content": "#[derive(StructOpt)]\n\n#[structopt(name = \"brainfrick\", about = \"Rust implementation of Brainfuck\")]\n\nstruct Opt {\n\n /// Path to program [optional: will use stdin instead]\n\n #[structopt()]\n\n path: Option<path::PathBuf>,\n\n\n\n /// Input given to program\n\n #[structopt...
Rust
src/service.rs
kfastov/moleculer-rs
c59695f4567a53d24cc9b9072d67a21f104059ff
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::{collections::HashMap, marker::PhantomData}; use crate::{ channels::messages::incoming::{EventMessage, RequestMessage}, Error, ServiceBroker, }; pub type Callback<T> = fn(Context<T>) -> Result<(), Box<dyn std::error::Error>>; #[derive(Ser...
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::{collections::HashMap, marker::PhantomData}; use crate::{ channels::messages::incoming::{EventMessage, RequestMessage}, Error, ServiceBroker, }; pub type Callback<T> = fn(Context<T>) -> Result<(), Box<dyn std::error::Error>>; #[derive(Ser...
Self { phantom: PhantomData, broker: service_broker, id: event_message.id, params: event_message.data, action: None, event_type: Some(event_type), event_name: Some(event_message.event), event_groups: vec![], ...
let event_type = if event_message.broadcast.unwrap_or(false) { EventType::Broadcast } else { EventType::Emit };
assignment_statement
[ { "content": "fn broadcast_name(ctx: Context<Event>) -> Result<(), Box<dyn Error>> {\n\n let msg: PrintNameMessage = serde_json::from_value(ctx.params)?;\n\n println!(\"Received broadcastName in rust\");\n\n ctx.broker\n\n .broadcast(\"testWithParam\", serde_json::to_value(&msg)?);\n\n\n\n Ok...
Rust
tools/butler/src/db/photos/patch.rs
hsfzxjy/omoyde
6cda092c1f895ac03e1aea2c32e315a9bad06202
use crate::prelude::*; use paste::paste; use std::borrow::Cow; use std::ptr::NonNull; #[derive(Clone, Debug)] pub struct Diff<'a, T: Clone> { old: Cow<'a, T>, new: Option<Cow<'a, T>>, } impl<'a, T: Clone> From<T> for Diff<'a, T> { fn from(v: T) -> Self { Self { old: Cow::Owned(v), ...
use crate::prelude::*; use paste::paste; use std::borrow::Cow; use std::ptr::NonNull; #[derive(Clone, Debug)] pub struct Diff<'a, T: Clone> { old: Cow<'a, T>, new: Option<Cow<'a, T>>, } impl<'a, T: Clone> From<T> for Diff<'a, T> { fn from(v: T) -> Self { Self { old: Cow::Owned(v), ...
td::mem::transmute(rec as *const _)).unwrap() }; Self { commit_at_drop: true, rec_diff: PhotoRecordDiff::new(rec), rec: rec_ptr, ptr, } } }
elf .new .as_ref() .map(|x| Cow::Owned(x.clone().into_owned())), } } } impl<'a, T: Eq + Clone> Diff<'a, T> { fn changed(&self) -> bool { if matches!(self.old, Cow::Borrowed(_)) && matches!(self.new, None | Some(Cow::Borrowed(_))) { ...
random
[ { "content": "pub fn pt_access_mut<'a>() -> TableAccessMut<'a, PhotoTable> {\n\n PHOTO_TABLE.lock().unwrap().access_mut()\n\n}\n\n\n\n#[allow(dead_code)]\n\npub type PhotoTableAccess<'a> = TableAccess<'a, PhotoTable>;\n\npub type PhotoTableAccessMut<'a> = TableAccessMut<'a, PhotoTable>;\n\n\n\nimpl<'b, 'a: '...
Rust
examples/truck_loading.rs
cuviper/RsGenetic
dfbf22008072920f21f1f7c07c1bc7af689bc1f4
extern crate rand; extern crate rsgenetic; use rsgenetic::sim::*; use rsgenetic::sim::seq::Simulator; use rsgenetic::sim::select::*; use rsgenetic::pheno::*; use rand::Rng; type TruckIndex = usize; type PackageSize = i32; type Scheme = Vec<(TruckIndex, PackageSize)>; type SchemeFitness = i32; const NUM_TRUCKS: us...
extern crate rand; extern crate rsgenetic; use rsgenetic::sim::*; use rsgenetic::sim::seq::Simulator; use rsgenetic::sim::select::*; use rsgenetic::pheno::*; use rand::Rng; type TruckIndex = usize; type PackageSize = i32; type Scheme = Vec<(TruckIndex, PackageSize)>; type SchemeFitness = i32; const NUM_TRUCKS: us...
fn mutate(&self) -> LoadingScheme { let mut rng = ::rand::thread_rng(); LoadingScheme { scheme: self.scheme .iter() .map(|&(_, size)| (rng.gen::<usize>() % NUM_TRUCKS, size)) .collect(), } } } impl Clone for LoadingS...
for i in 0..crossover_indices.0 { crossed_over[i] = self.scheme[i]; } for i in crossover_indices.0..crossover_indices.1 { crossed_over[i] = other.scheme[i]; } for i in crossover_indices.1..PACKAGES.len() { crossed_over[i] = self.scheme[i]; } ...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let mut population = (-300..300).map(|i| MyData { x: f64::from(i) }).collect();\n\n let mut s = Simulator::builder(&mut population)\n\n .set_selector(Box::new(StochasticSelector::new(10)))\n\n .set_max_iters(50)\n\n .build();\n\n s.run();\n\n let re...
Rust
src/bin/cmd/wallet_tests.rs
icook/grin
5915580ab372dd85c0cc615d9df1c9aa6329f0f0
#[cfg(test)] mod wallet_tests { use chrono; use clap; use grin_util as util; use grin_wallet; use serde; use grin_wallet::test_framework::{self, LocalWalletClient, WalletProxy}; use clap::{App, ArgMatches}; use grin_util::Mutex; use std::sync::Arc; use std::thread; use std::time::Duration; use std::{env...
#[cfg(test)] mod wallet_tests { use chrono; use clap; use grin_util as util; use grin_wallet; use serde; use grin_wallet::test_framework::{self, LocalWalletClient, WalletProxy}; use clap::{App, ArgMatches}; use grin_util::Mutex; use std::sync::Arc; use std::thread; use std::time::Duration; use std::{env...
e_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "check_repair"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "txs"]; execute_command(&app, test_dir, "w...
ng", "send", "-m", "file", "-d", &file_name, "-g", "Love, Yeast, Smallest", "-s", "smallest", "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; let arg_vec = vec![ "grin", "wallet", "-p", "password", "-a", "mining", "receive", "-i", ...
random
[ { "content": "/// Returns a list of account to BIP32 path mappings\n\npub fn accounts<T: ?Sized, C, K>(wallet: &mut T) -> Result<Vec<AcctPathMapping>, Error>\n\nwhere\n\n\tT: WalletBackend<C, K>,\n\n\tC: NodeClient,\n\n\tK: Keychain,\n\n{\n\n\tOk(wallet.acct_path_iter().collect())\n\n}\n\n\n", "file_path": ...
Rust
diesel/src/serialize.rs
unvalley/diesel
fd723880db6887a859ffa691890fe964de7dd3f8
use std::error::Error; use std::fmt; use std::io::{self, Write}; use std::result; use crate::backend::{Backend, HasBindCollector}; use crate::query_builder::bind_collector::RawBytesBindCollector; use crate::query_builder::BindCollector; #[cfg(feature = "postgres_backend")] pub use crate::pg::serialize::*; pub type...
use std::error::Error; use std::fmt; use std::io::{self, Write}; use std::result; use crate::backend::{Backend, HasBindCollector}; use crate::query_builder::bind_collector::RawBytesBindCollector; use crate::query_builder::BindCollector; #[cfg(feature = "postgres_backend")] pub use crate::pg::serialize::*; pub type...
pub fn into_inner( self, ) -> <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer { self.out } pub fn metadata_lookup(&mut self) -> &mut DB::MetadataLookup { *self.metadata_lookup.as_mut().expect("Lookup is there") } ...
pub fn new( out: <crate::backend::BindCollector<'a, DB> as BindCollector<'a, DB>>::Buffer, metadata_lookup: &'b mut DB::MetadataLookup, ) -> Self { Output { out, metadata_lookup: Some(metadata_lookup), } }
function_block-full_function
[]
Rust
components/front_matter/src/lib.rs
zoosky/zola
b359cca4fe46a7abc8ce10620561d48d685b86ef
use lazy_static::lazy_static; use serde_derive::{Deserialize, Serialize}; use errors::{bail, Error, Result}; use regex::Regex; use std::path::Path; mod page; mod section; pub use page::PageFrontMatter; pub use section::SectionFrontMatter; lazy_static! { static ref PAGE_RE: Regex = Regex::new(r"^[[:space...
use lazy_static::lazy_static; use serde_derive::{Deserialize, Serialize}; use errors::{bail, Error, Result}; use regex::Regex; use std::path::Path; mod page; mod section; pub use page::PageFrontMatter; pub use section::SectionFrontMatter; lazy_static! { static ref PAGE_RE: Regex = Regex::new(r"^[[:space...
frontmatter() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-12"#; let res = split_page_content(Path::new(""), content); assert!(res.is_err()); } }
Ok((meta, content)) } #[cfg(test)] mod tests { use std::path::Path; use super::{split_page_content, split_section_content}; #[test] fn can_split_page_content_valid() { let content = r#" +++ title = "Title" description = "hey there" date = 2002-10-12 +++ Hello "#; let (front_matter...
random
[ { "content": "/// Return the content of a file, with error handling added.\n\n/// The default error message is overwritten by the message given.\n\n/// That means it is allocation 2 strings, oh well\n\npub fn read_file_with_error(path: &Path, message: &str) -> Result<String> {\n\n let res = read_file(&path);...
Rust
near-sdk/src/collections/lookup_set.rs
nearprotocol/near-sdk-rs
8a2b2e19b27a764abf43df05bd0e530c3ad91d6c
use std::marker::PhantomData; use borsh::{BorshDeserialize, BorshSerialize}; use crate::collections::append_slice; use crate::{env, IntoStorageKey}; const ERR_ELEMENT_SERIALIZATION: &str = "Cannot serialize element with Borsh"; #[derive(BorshSerialize, BorshDeserialize)] pub struct LookupSet<T> { element_pref...
use std::marker::PhantomData; use borsh::{BorshDeserialize, BorshSerialize}; use crate::collections::append_slice; use crate::{env, IntoStorageKey}; const ERR_ELEMENT_SERIALIZATION: &str = "Cannot serialize element with Borsh"; #[derive(BorshSerialize, BorshDeserialize)] pub struct LookupSet<T> { element_pref...
> std::fmt::Result { f.debug_struct("LookupSet").field("element_prefix", &self.element_prefix).finish() } } #[cfg(not(target_arch = "wasm32"))] #[cfg(test)] mod tests { use crate::collections::LookupSet; use rand::seq::SliceRandom; use rand::{Rng, SeedableRng}; use std::collections::HashSet...
impl<T> std::fmt::Debug for LookupSet<T> where T: std::fmt::Debug + BorshSerialize, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -
random
[ { "content": "// ###############\n\n// # Storage API #\n\n// ###############\n\n/// Writes key-value into storage.\n\n/// If another key-value existed in the storage with the same key it returns `true`, otherwise `false`.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use near_sdk::env::{storage_write, stora...
Rust
src/encrypted_stream.rs
GWBasic/bounce
2d8a86b8c33bf408ad5d5b20c440233c0746b13a
/* use async_std::io; use async_std::io::{Read, Result, Write}; use async_std::task::{Context, Poll}; use std::marker::Unpin; use std::pin::Pin; use rand_core::{CryptoRng, RngCore}; pub struct EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { wrapped_stream: TStream...
/* use async_std::io; use async_std::io::{Read, Result, Write}; use async_std::task::{Context, Poll}; use std::marker::Unpin; use std::pin::Pin; use rand_core::{CryptoRng, RngCore}; pub struct EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { wrapped_stream: TStream...
^ self.write_xor.next_byte(); } Pin::new(&mut self.wrapped_stream).poll_write(cx, &encrypted) } fn poll_flush( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_> ) -> std::task::Poll<std::result::Result<(), std::io::Error>> { Pin::new(&mut self.wra...
ream, TRng> Unpin for EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore {} impl<TStream, TRng> EncryptedStream<TStream, TRng> where TStream: Read + Write, TRng: CryptoRng + RngCore { pub fn new(wrapped_stream: TStream, write_rng: TRng, read_rng: TRng) -> EncryptedStream...
random
[ { "content": "pub fn run_bridge<TRng>(xors: Xors<TRng>, clear_stream: TcpStream, clear_stream_name: String, encrypted_stream: TcpStream, encrypted_stream_name: String) where\n\nTRng: CryptoRng + RngCore + Clone + Any {\n\n\n\n match clear_stream.set_nodelay(true) {\n\n Err(err) => {\n\n log...
Rust
src/routes/proxy/img_proxy.rs
Marc3842h/gitarena
c8c53a7331d4ebc12ea69dfbf6220c11c40526cd
use crate::die; use crate::prelude::HttpRequestExtensions; use crate::utils::reqwest_actix_stream::ResponseStream; use actix_web::http::header::CONTENT_LENGTH; use actix_web::{HttpRequest, HttpResponse, Responder, web}; use anyhow::{Context, Result}; use gitarena_macros::route; use log::debug; use reqwest::Client; use...
use crate::die; use crate::prelude::HttpRequestExtensions; use crate::utils::reqwest_actix_stream::ResponseStream; use actix_web::http::header::CONTENT_LENGTH; use actix_web::{HttpRequest, HttpResponse, Responder, web}; use anyhow::{Context, Result}; use gitarena_macros::route; use log::debug; use reqwest::Client; use...
#[derive(Deserialize)] pub(crate) struct ProxyRequest { pub(crate) url: String }
se.append_header((name.as_str(), value_str)); } if lowered_name == "content-type" && !ACCEPTED_MIME_TYPES.contains(&value_str) { die!(BAD_GATEWAY, "Response was not an image"); } } Ok(response.streaming(ResponseStream { stream: gateway_response.bytes_stream() })...
function_block-function_prefixed
[ { "content": "fn extract_ip(request: &HttpRequest) -> IpNetwork {\n\n let connection_info = request.connection_info();\n\n let ip_str = connection_info.realip_remote_addr().unwrap_or(\"No user agent sent\");\n\n\n\n match IpNetwork::from_str(ip_str) {\n\n Ok(ip_network) => ip_network,\n\n ...
Rust
fusequery/query/src/datasources/local/csv_table_test.rs
leiysky/fuse-query
49e268ba7938469c2a3c0541a0c713ef447ccffb
use std::sync::Arc; #[tokio::test] async fn test_csv_table() -> anyhow::Result<()> { use std::env; use common_datavalues::*; use common_planners::*; use futures::TryStreamExt; use crate::datasources::local::*; let options: TableOptions = [( "location".to_string(), env::curr...
use std::sync::Arc; #[tokio::test] async fn test_csv_table() -> anyhow::Result<()> { use std::env; use common_datavalues::*; use common_planners::*; use futures::TryStreamExt; use crate::datasources::local::*; let options: TableOptions = [( "location".to_string(), env::curr...
async fn test_csv_table_parse_error() -> anyhow::Result<()> { use std::env; use common_datavalues::*; use common_planners::*; use futures::TryStreamExt; use pretty_assertions::assert_eq; use crate::datasources::local::*; let options: TableOptions = [( "location".to_string(), ...
function_block-full_function
[ { "content": "fn build_boolean_column(values: &DataArrayRef) -> Result<Vec<Option<u8>>> {\n\n let values = as_boolean_array(values);\n\n\n\n Ok(match values.null_count() {\n\n //faster path\n\n 0 => (0..values.len())\n\n .map(|i| Some(values.value(i) as u8))\n\n .collec...
Rust
crates/bevy_winit/src/winit_windows.rs
Schell-0x52/bevy
39224eed1716a9a069ff2f19c4dc93dcd9f88452
use bevy_math::IVec2; use bevy_utils::HashMap; use bevy_window::{Window, WindowDescriptor, WindowId, WindowMode}; use raw_window_handle::HasRawWindowHandle; use winit::dpi::LogicalSize; #[derive(Debug, Default)] pub struct WinitWindows { pub windows: HashMap<winit::window::WindowId, winit::window::Window>, pub...
use bevy_math::IVec2; use bevy_utils::HashMap; use bevy_window::{Window, WindowDescriptor, WindowId, WindowMode}; use raw_window_handle::HasRawWindowHandle; use winit::dpi::LogicalSize; #[derive(Debug, Default)] pub struct WinitWindows { pub windows: HashMap<winit::window::WindowId, winit::window::Window>, pub...
pub fn get_window(&self, id: WindowId) -> Option<&winit::window::Window> { self.window_id_to_winit .get(&id) .and_then(|id| self.windows.get(id)) } pub fn get_window_id(&self, id: winit::window::WindowId) -> Option<WindowId> { self.winit_to_window_id.get(&id).clone...
pub fn create_window( &mut self, event_loop: &winit::event_loop::EventLoopWindowTarget<()>, window_id: WindowId, window_descriptor: &WindowDescriptor, ) -> Window { #[cfg(target_os = "windows")] let mut winit_window_builder = { use winit::platform::windows...
function_block-full_function
[ { "content": "/// An ordered &str->ReflectValue mapping where &str is a \"field\".\n\n/// This corresponds to rust struct types.\n\npub trait Struct: Reflect {\n\n fn field(&self, name: &str) -> Option<&dyn Reflect>;\n\n fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect>;\n\n fn field_at(&...
Rust
src/cargo/sources/registry/remote.rs
Aelnor/cargo
b1684e28490a111b4956b40377abb2b961bfd4b3
use crate::core::{GitReference, PackageId, SourceId}; use crate::sources::git; use crate::sources::registry::MaybeLock; use crate::sources::registry::{ RegistryConfig, RegistryData, CRATE_TEMPLATE, LOWER_PREFIX_TEMPLATE, PREFIX_TEMPLATE, VERSION_TEMPLATE, }; use crate::util::errors::CargoResult; use crate::util...
use crate::core::{GitReference, PackageId, SourceId}; use crate::sources::git; use crate::sources::registry::MaybeLock; use crate::sources::registry::{ RegistryConfig, RegistryData, CRATE_TEMPLATE, LOWER_PREFIX_TEMPLATE, PREFIX_TEMPLATE, VERSION_TEMPLATE, }; use crate::util::errors::CargoResult; use crate::util...
th::new(""), Path::new("config.json"), &mut |json| { config = Some(serde_json::from_slice(json)?); Ok(()) })?; trace!("config loaded"); Ok(config) } fn update_index(&mut self) -> CargoResult<()> { if self.config.offline() { return Ok(()); ...
loading config"); self.prepare()?; self.config.assert_package_cache_locked(&self.index_path); let mut config = None; self.load(Pa
function_block-random_span
[ { "content": "/// Commit changes to the git repository.\n\npub fn commit(repo: &git2::Repository) -> git2::Oid {\n\n let tree_id = t!(t!(repo.index()).write_tree());\n\n let sig = t!(repo.signature());\n\n let mut parents = Vec::new();\n\n if let Some(parent) = repo.head().ok().map(|h| h.target().un...
Rust
game/src/sandbox/mod.rs
jvolker/abstreet
7d4cf4cd5b27bce37cf35d3d8aecf0e3d5148a2f
mod dashboards; pub mod gameplay; mod misc_tools; mod speed; mod uber_turns; use self::misc_tools::{RoutePreview, ShowTrafficSignal, TurnExplorer}; use crate::app::App; use crate::common::{tool_panel, CommonState, ContextualActions, Minimap}; use crate::debug::DebugMode; use crate::edit::{ apply_map_edits, can_edi...
mod dashboards; pub mod gameplay; mod misc_tools; mod speed; mod uber_turns; use self::misc_tools::{RoutePreview, ShowTrafficSignal, TurnExplorer}; use crate::app::App; use crate::common::{tool_panel, CommonState, ContextualActions, Minimap}; use crate::debug::DebugMode; use crate::edit::{ apply_map_edits, can_edi...
} impl State for SandboxMode { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition { if self.gameplay.can_move_canvas() { ctx.canvas_movement(); } if let Some(t) = self.gameplay.event(ctx, app, &mut self.controls) { return t; } ...
unwrap_or(true), can_interact: self.gameplay.can_examine_objects(), gameplay: self.gameplay_mode.clone(), } }
function_block-function_prefix_line
[ { "content": "// TODO Well, there goes the nice consolidation of stuff in BtnBuilder. :\\\n\npub fn hotkey_btn<I: Into<String>>(ctx: &EventCtx, app: &App, label: I, key: Key) -> Widget {\n\n let label = label.into();\n\n let mut txt = Text::new();\n\n txt.append(Line(key.describe()).fg(ctx.style().hotk...
Rust
src/sim2/training.rs
ryotaok/genshin
4f3778b787e59220853ae8cce4f7e7b94d34ac54
use crate::sim2::state::State; use crate::sim2::timeline::{Timeline}; use crate::sim2::attack::{WeaponAttack}; use crate::sim2::types::{WeaponType, SCORE}; use crate::sim2::record::{WeaponRecord, Artifact}; use WeaponType::*; pub enum TrainingWeaponUnion { TrainingSword(TrainingSword), TrainingClaymore(Traini...
use crate::sim2::state::State; use crate::sim2::timeline::{Timeline}; use crate::sim2::attack::{WeaponAttack}; use crate::sim2::types::{WeaponType, SCORE}; use crate::sim2::record::{WeaponRecord, Artifact}; use WeaponType::*; pub enum TrainingWeaponUnion { TrainingSword(TrainingSword), TrainingClaymore(Traini...
} pub fn artifacts() -> Vec<(Artifact, TrainingArtifactUnion)> { vec![ (TrainingArtifact0::record(), TrainingArtifactUnion::TrainingArtifact0(TrainingArtifact0)), (TrainingArtifact1::record(), TrainingArtifactUnion::TrainingArtifact1(TrainingArtifact1)), (TrainingArtifact2::record(), TrainingArtifactU...
TrainingArtifact2(x) => x, TrainingArtifact3(x) => x, TrainingArtifact4(x) => x, TrainingArtifact5(x) => x, TrainingArtifact6(x) => x, TrainingArtifact7(x) => x, TrainingArtifact8(x) => x, TrainingArtifact9(x) => x, } }
function_block-function_prefix_line
[]
Rust
common/functions/src/scalars/dates/date.rs
flaneur2020/databend
b2758473f59bd23f1a278699e6cf292724c204cd
use common_datavalues::DataValueArithmeticOperator; use common_exception::Result; use super::interval_function::MonthsArithmeticFunction; use super::interval_function::SecondsArithmeticFunction; use super::now::NowFunction; use super::RoundFunction; use super::ToStartOfISOYearFunction; use super::ToStartOfMonthFunct...
use common_datavalues::DataValueArithmeticOperator; use common_exception::Result; use super::interval_function::MonthsArithmeticFunction; use super::interval_function::SecondsArithmeticFunction; use super::now::NowFunction; use super::RoundFunction; use super::ToStartOfISOYearFunction; use super::ToStartOfMonthFunct...
}); map.insert("toStartOfFifteenMinutes".into(), |display_name| { RoundFunction::try_create(display_name, 15 * 60) }); map.insert("timeSlot".into(), |display_name| { RoundFunction::try_create(display_name, 30 * 60) }); ma...
tOfWeekFunction; use super::ToStartOfYearFunction; use super::ToYYYYMMDDFunction; use super::ToYYYYMMDDhhmmssFunction; use super::ToYYYYMMFunction; use super::TodayFunction; use super::TomorrowFunction; use super::YesterdayFunction; use crate::scalars::FactoryFuncRef; #[derive(Clone)] pub struct DateFunction {} impl ...
random
[ { "content": "-- {ErrorCode 3, but it not work, because it's trimed in msql-srv}\n\nUSE not_exists_db;\n\nUSE default;\n\nUSE system;\n", "file_path": "tests/suites/0_stateless/07_0000_use_database.sql", "rank": 0, "score": 56735.32093857074 }, { "content": "use common_streams::SendableDataB...
Rust
src/raycasting_engine.rs
N-Hoque/rustenstein3D
97a483eeb20977a4d241d7b68e5be12e673fcad9
use rsfml::{ graphics::{ Color, PrimitiveType, RenderStates, RenderTarget, RenderWindow, Vertex, VertexArray, }, system::{Vector2f, Vector2i}, window::Key, }; use crate::{event_handler::EventHandler, map::Map, texture_loader::TextureLoader}; pub struct RaycastEngine { player_position: Ve...
use rsfml::{ graphics::{ Color, PrimitiveType, RenderStates, RenderTarget, RenderWindow, Vertex, VertexArray, }, system::{Vector2f, Vector2i}, window::Key, }; use crate::{event_handler::EventHandler, map::Map, texture_loader::TextureLoader}; pub struct RaycastEngine { player_position: Ve...
fn hit_wall( &self, map_pos: &mut Vector2i, side_dist: &mut Vector2f, step: &mut Vector2i, delta_dist: &mut Vector2f, side: &mut i32, ) { let mut hit: bool = false; while !hit { if side_dist.x < side_dist.y { side_dist...
fn calculate_step( &self, ray_dir: &Vector2f, step: &mut Vector2i, ray_pos: &Vector2f, map_pos: &Vector2i, delta_dist: &Vector2f, side_dist: &mut Vector2f, ) { if ray_dir.x < 0. { step.x = -1; side_dist.x = (ray_pos.x - map_pos....
function_block-full_function
[ { "content": "pub fn parse_arguments() -> ParsedResult {\n\n let args = std::env::args().collect::<Vec<String>>();\n\n let arg_length = args.len();\n\n\n\n let mut arguments = Arguments {\n\n window_dimensions: (768, 480),\n\n no_ground: false,\n\n framerate_limit: 30,\n\n };\n\...
Rust
datafusion/src/logical_plan/window_frames.rs
cube-js/arrow-datafusion
4e9d31e05b69017d972ae4c1ffbeeaab163fd654
use crate::error::{DataFusionError, Result}; use crate::execution::context::ExecutionContextState; use crate::logical_plan::Expr; use crate::scalar::ScalarValue; use crate::sql::planner::SqlToRel; use serde_derive::{Deserialize, Serialize}; use sqlparser::ast; use sqlparser::ast::DateTimeField; use std::cmp::Ordering...
use crate::error::{DataFusionError, Result}; use crate::execution::context::ExecutionContextState; use crate::logical_plan::Expr; use crate::scalar::ScalarValue; use crate::sql::planner::SqlToRel; use serde_derive::{Deserialize, Serialize}; use sqlparser::ast; use sqlparser::ast::DateTimeField; use std::cmp::Ordering...
) } } impl From<ast::WindowFrameUnits> for WindowFrameUnits { fn from(value: ast::WindowFrameUnits) -> Self { match value { ast::WindowFrameUnits::Range => Self::Range, ast::WindowFrameUnits::Groups => Self::Groups, ast::WindowFrameUnits::Rows => Self::Rows, ...
match self { WindowFrameUnits::Rows => "ROWS", WindowFrameUnits::Range => "RANGE", WindowFrameUnits::Groups => "GROUPS", }
if_condition
[ { "content": "fn handle<F, R>(args: &[ColumnarValue], op: F, name: &str) -> Result<ColumnarValue>\n\nwhere\n\n R: AsRef<[u8]>,\n\n F: Fn(&str) -> R,\n\n{\n\n match &args[0] {\n\n ColumnarValue::Array(a) => match a.data_type() {\n\n DataType::Utf8 => {\n\n Ok(ColumnarVal...
Rust
src/runtime/thread/continuation.rs
jamesbornholt/shuttle
24ffc0aa2a2c30059c263ea7e5516f90af1c828b
#![allow(deprecated)] use crate::runtime::execution::ExecutionState; use generator::{Generator, Gn}; use scoped_tls::scoped_thread_local; use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::ops::Deref; use std::ops::DerefMut; use std::rc::Rc; scoped_thread_local! { pub(crate) static CONTINU...
#![allow(deprecated)] use crate::runtime::execution::ExecutionState; use generator::{Generator, Gn}; use scoped_tls::scoped_thread_local; use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::ops::Deref; use std::ops::DerefMut; use std::rc::Rc; scoped_thread_local! { pub(crate) static CONTINU...
pub fn resume(&mut self) -> bool { debug_assert!(self.state == ContinuationState::Ready || self.state == ContinuationState::Running); let ret = self.resume_with_input(ContinuationInput::Resume); debug_assert_ne!( ret, ContinuationOutput::Exited, "c...
pub fn initialize(&mut self, fun: Box<dyn FnOnce() + Send>) { debug_assert_eq!( self.state, ContinuationState::NotReady, "shouldn't replace a function before it runs" ); let old = self.function.0.replace(Some(fun)); debug_assert!(old.is_none(), "shoul...
function_block-function_prefix_line
[ { "content": "/// Run the given function under a randomized concurrency scheduler for some number of iterations.\n\n/// Each iteration will run a (potentially) different randomized schedule.\n\npub fn check_random<F>(f: F, iterations: usize)\n\nwhere\n\n F: Fn() + Send + Sync + 'static,\n\n{\n\n use crate...
Rust
fyrox-sound/src/dsp/filters.rs
Libertus-Lab/Fyrox
c925304f42744659fd3a6be5c4a1a8609556033a
use crate::dsp::DelayLine; use fyrox_core::{ inspect::{Inspect, PropertyInfo}, visitor::{Visit, VisitResult, Visitor}, }; #[derive(Debug, Clone, Visit)] pub struct OnePole { a0: f32, b1: f32, last: f32, } impl Default for OnePole { fn default() -> Self { Self { a0: 1.0, ...
use crate::dsp::DelayLine; use fyrox_core::{ inspect::{Inspect, PropertyInfo}, visitor::{Visit, VisitResult, Visitor}, }; #[derive(Debug, Clone, Visit)] pub struct OnePole { a0: f32, b1: f32, last: f32, } impl Default for OnePole { fn default() -> Self { Self { a0: 1.0, ...
}
fn default() -> Self { Self { b0: 1.0, b1: 0.0, b2: 0.0, a1: 0.0, a2: 0.0, prev1: 0.0, prev2: 0.0, } }
function_block-full_function
[ { "content": "fn write_node(name: &str, node: &mut Node, visitor: &mut Visitor) -> VisitResult {\n\n let mut region = visitor.enter_region(name)?;\n\n\n\n let mut id = node.id();\n\n id.visit(\"TypeUuid\", &mut region)?;\n\n\n\n node.visit(\"NodeData\", &mut region)?;\n\n\n\n Ok(())\n\n}\n\n\n\ni...
Rust
vm-bindings/build_support/builder.rs
feenkcom/gtoolkit-vm
0647fe53203d614d776cb5af4f228cddc4a5f29d
use file_matcher::{FileNamed, OneEntry, OneEntryCopier}; use std::fmt::Debug; use std::path::{Path, PathBuf}; use std::{env, fmt, fs}; const VM_CLIENT_VMMAKER_VM_VAR: &str = "VM_CLIENT_VMMAKER"; const VM_CLIENT_VMMAKER_IMAGE_VAR: &str = "VM_CLIENT_VMMAKER_IMAGE"; pub trait Builder: Debug { fn is_compiled(&self) -...
use file_matcher::{FileNamed, OneEntry, OneEntryCopier}; use std::fmt::Debug; use std::path::{Path, PathBuf}; use std::{env, fmt, fs}; const VM_CLIENT_VMMAKER_VM_VAR: &str = "VM_CLIENT_VMMAKER"; const VM_CLIENT_VMMAKER_IMAGE_VAR: &str = "VM_CLIENT_VMMAKER_IMAGE"; pub trait Builder: Debug { fn is_compiled(&self) -...
(), &self.is_compiled()) .entry( &"output_directory".to_string(), &self.output_directory().display(), ) .entry(&"vm_binary".to_string(), &self.vm_binary().display()) .entry( &"vm_sources_directory".to_string(), ...
wrap() } fn is_debug(&self) -> bool { self.profile() == "debug" } fn ensure_build_tools(&self) {} fn vmmaker_vm(&self) -> Option<PathBuf> { std::env::var(VM_CLIENT_VMMAKER_VM_VAR).map_or(None, |path| { let path = Path::new(&path); if path.exists() { ...
random
[ { "content": "#[no_mangle]\n\npub fn gtoolkit_vm_is_on_worker_thread(gt_vm_ptr: *const Mutex<Option<GToolkitVM>>) -> bool {\n\n gt_vm_ptr.with(|| false, |gt_vm| gt_vm.is_on_worker_thread())\n\n}\n\n\n", "file_path": "experimental/src/lib.rs", "rank": 1, "score": 118262.39327501913 }, { "c...
Rust
src/mock.rs
fossabot/client-rust
4540c1cdfa9a4d17ac15a1242daf32ef53a17133
use crate::{ pd::{PdClient, PdRpcClient, RetryClient}, request::DispatchHook, Config, Error, Key, Result, Timestamp, }; use fail::fail_point; use futures::future::{ready, BoxFuture, FutureExt}; use grpcio::CallOption; use kvproto::{errorpb, kvrpcpb, metapb, tikvpb::TikvClient}; use std::{future::Future, s...
use crate::{ pd::{PdClient, PdRpcClient, RetryClient}, request::DispatchHook, Config, Error, Key, Result, Timestamp, }; use fail::fail_point; use futures::future::{ready, BoxFuture, FutureExt}; use grpcio::CallOption; use kvproto::{errorpb, kvrpcpb, metapb, tikvpb::TikvClient}; use std::{future::Future, s...
_ => Err(Error::region_not_found(id)), }; Box::pin(ready(result)) } fn get_timestamp(self: Arc<Self>) -> BoxFuture<'static, Result<Timestamp>> { unimplemented!() } } impl DispatchHook for kvrpcpb::ResolveLockRequest { fn dispatch_hook( &self, _opt: CallO...
atic str, _fut: grpcio::Result<RpcFuture>, ) -> BoxFuture<'static, Result<Resp>> where RpcFuture: Future<Output = std::result::Result<Resp, ::grpcio::Error>>, Resp: HasError + Sized + Clone + Send + 'static, RpcFuture: Send + 'static, { unimplemented!() } fn ...
random
[ { "content": "pub fn new_mvcc_get_request(key: impl Into<Key>, timestamp: Timestamp) -> kvrpcpb::GetRequest {\n\n let mut req = kvrpcpb::GetRequest::default();\n\n req.set_key(key.into().into());\n\n req.set_version(timestamp.version());\n\n req\n\n}\n\n\n\nimpl KvRequest for kvrpcpb::BatchGetReques...
Rust
2021/05_hydrothermal-venture/src/main.rs
macisamuele/adventofcode
34d8994493446f951afc4584d6da7f83e85fd8f8
use helpers::input_lines; use scan_fmt::scan_fmt; use std::collections::HashMap; use std::str::FromStr; const INPUT: &str = include_str!("../input.txt"); #[derive(Debug, PartialEq, Eq, Hash)] struct Point { x: usize, y: usize, } #[derive(Debug, PartialEq, Eq, Hash)] struct Line { point1: Point, point...
use helpers::input_lines; use scan_fmt::scan_fmt; use std::collections::HashMap; use std::str::FromStr; const INPUT: &str = include_str!("../input.txt"); #[derive(Debug, PartialEq, Eq, Hash)] struct Point { x: usize, y: usize, } #[derive(Debug, PartialEq, Eq, Hash)] struct Line { point1: Point, point...
} impl Line { fn to_horizontal_points(&self) -> impl Iterator<Item = Point> { let y: usize = self.point1.y; let (min_x, max_x): (usize, usize) = if self.point1.y == self.point2.y { if self.point1.x < self.point2.x { (self.point1.x, self.point2.x + 1) } else ...
fn from_str(line: &str) -> Result<Self, Self::Err> { let (x1, y1, x2, y2) = scan_fmt!(line, "{},{} -> {},{}", usize, usize, usize, usize)?; Ok(Self { point1: Point { x: x1, y: y1 }, point2: Point { x: x2, y: y2 }, }) }
function_block-full_function
[ { "content": "type Point = (usize, usize);\n\n\n", "file_path": "2021/15_chiton/src/main.rs", "rank": 0, "score": 208321.5886531291 }, { "content": "fn part02(line: &str) -> usize {\n\n let mut game = GameTable::new(\n\n line.as_bytes()\n\n .iter()\n\n .map(|b...
Rust
src/connectivity/network/tests/dhcp_interop/dhcp_validity/src/lib.rs
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
use { anyhow::{format_err, Context as _, Error}, fidl_fuchsia_net as fnet, fidl_fuchsia_net_dhcpv6 as fdhcpv6, fidl_fuchsia_net_interfaces as finterfaces, fidl_fuchsia_net_name as fnetname, fidl_fuchsia_net_stack as fstack, fidl_fuchsia_net_stack_ext::FidlReturn as _, fidl_fuchsia_netemul_gues...
use { anyhow::{format_err, Context as _, Error}, fidl_fuchsia_net as fnet, fidl_fuchsia_net_dhcpv6 as fdhcpv6, fidl_fuchsia_net_interfaces as finterfaces, fidl_fuchsia_net_name as fnetname, fidl_fuchsia_net_stack as fstack, fidl_fuchsia_net_stack_ext::FidlReturn as _, fidl_fuchsia_netemul_gues...
pub async fn verify_v6_dns_servers( interface_id: u64, want_dns_servers: Vec<fnetname::DnsServer_>, ) -> Result<(), Error> { let stack = client::connect_to_service::<fstack::StackMarker>() .context("connecting to stack service")?; let info = stack .get_interface_info(interface_id) ...
pub async fn verify_v4_addr_present(addr: fnet::IpAddress, timeout: Duration) -> Result<(), Error> { let interface_state = client::connect_to_service::<finterfaces::StateMarker>()?; let mut if_map = std::collections::HashMap::new(); fidl_fuchsia_net_interfaces_ext::wait_interface( fidl_fuchsia_net_i...
function_block-full_function
[]
Rust
src/csv2json/mod.rs
perzanko/csv2json
aae4c50856f73fc0f88450dd2f38ad8fc6ffaeae
extern crate serde_json; use std::collections::HashMap; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::process; use std::time::Instant; type Lines = Vec<String>; type Nav = String; type NavKeys = Vec<String>; type Args = Vec<String>; type Rows = Vec<HashMap<String, String>>; type Hash...
extern crate serde_json; use std::collections::HashMap; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::process; use std::time::Instant; type Lines = Vec<String>; type Nav = String; type NavKeys = Vec<String>; type Args = Vec<String>; type Rows = Vec<HashMap<String, String>>; type Hash...
fn read_file(file_path: &String) -> Result<(Nav, Lines), io::Error> { let file = File::open(file_path)?; let buf_reader = io::BufReader::new(file); let mut lines = Vec::new(); let mut nav = String::new(); for (i, line) in buf_reader.lines().enumerate() { let line = line.unwrap(); i...
let mut input_file = String::new(); let mut output_file = String::new(); let mut args: Args = args.clone(); args.remove(0); args.chunks(2).for_each(|x| match x[0].as_ref() { "--input" => { input_file = x[1].clone(); } "-i" => { input_file = x[1].clone(); ...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n csv2json::new();\n\n}\n", "file_path": "src/main.rs", "rank": 15, "score": 25552.07465452124 }, { "content": "# csv2json\n\n\n\nThis tool provides simple and efficient csv to json converting, written in Rust.\n\n\n\n## Getting Started\n\n\n\nYou need to have ...
Rust
python/src/lib.rs
kngwyu/rogue-gym
00de77e6c9f3d2b9ed602f93abb5526c13791ca9
#[macro_use] extern crate failure; extern crate ndarray; extern crate numpy; extern crate pyo3; extern crate rect_iter; extern crate rogue_gym_core; #[cfg(unix)] extern crate rogue_gym_devui; mod fearures; mod state_impls; mod thread_impls; use fearures::{MessageFlagInner, StatusFlagInner}; use ndarray::{Array2, Axis...
#[macro_use] extern crate failure; extern crate ndarray; extern crate numpy; extern crate pyo3; extern crate rect_iter; exter
sage: MessageFlagInner, is_terminal: bool, } impl PlayerState { fn new(w: X, h: Y, symbols: u8) -> Self { let (w, h) = (w.0 as usize, h.0 as usize); PlayerState { map: vec![vec![b' '; w]; h], history: Array2::from_elem([h, w], false), status: Status::default(...
n crate rogue_gym_core; #[cfg(unix)] extern crate rogue_gym_devui; mod fearures; mod state_impls; mod thread_impls; use fearures::{MessageFlagInner, StatusFlagInner}; use ndarray::{Array2, Axis, Zip}; use numpy::PyArray3; use pyo3::{ basic::{PyObjectProtocol, PyObjectReprProtocol, PyObjectStrProtocol}, except...
random
[ { "content": "#![cfg_attr(test, feature(test))]\n\n#[macro_use]\n\nextern crate bitflags;\n\n#[macro_use]\n\nextern crate derive_more;\n\n#[macro_use]\n\nextern crate enum_iterator;\n\n#[macro_use]\n\nextern crate failure;\n\nextern crate fixedbitset;\n\nextern crate ndarray;\n\nextern crate num_traits;\n\n#[ma...
Rust
src/bin/2019_day20.rs
ibookstein/aoc
6beb8369f80d47eef95022ced9a9b9a9bccc7d99
use aoc::aoc_input::get_input; use itertools::iproduct; use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use std::ops::Index; use std::str::FromStr; type Vertex = usize; type Label = (usize, usize); type LabelMap = HashMap<Label, Vertex>; type VertexSet = HashSet<Vertex>; type AdjacencyL...
use aoc::aoc_input::get_input; use itertools::iproduct; use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use std::ops::Index; use std::str::FromStr; type Vertex = usize; type Label = (usize, usize); type LabelMap = HashMap<Label, Vertex>; type VertexSet = HashSet<Vertex>; type AdjacencyL...
nsert_vertex(&point)) } else if *key == end_portal { end = Some(graph.get_or_insert_vertex(&point)) } else { return Err("Bad portal"); } } [point1, point2] => graph.add_bidirection...
mpty() { match func(depth, &current_layer) { BfsReply::Halt => return, BfsReply::Continue => (), } let new_layer: VertexSet = current_layer .iter() .flat_map(|v| &self.adj_list[*v]) .cloned() ...
random
[ { "content": "pub fn digits<T>(mut num: T, radix: T) -> impl Iterator<Item = T>\n\nwhere\n\n T: UnsignedDigits<T>,\n\n{\n\n let zero = T::zero();\n\n\n\n let mut divisor = T::one();\n\n while num >= divisor * radix {\n\n divisor *= radix;\n\n }\n\n\n\n std::iter::from_fn(move || {\n\n ...
Rust
src/cli/commands/color_commands.rs
dandycheung/pastel
3719824a56fb9eb92eb960068e513b95486756a7
use crate::colorspace::get_mixing_function; use crate::commands::prelude::*; use pastel::ColorblindnessType; use pastel::Fraction; fn clamp(lower: f64, upper: f64, x: f64) -> f64 { f64::max(f64::min(upper, x), lower) } macro_rules! color_command { ($cmd_name:ident, $config:ident, $matches:ident, $color:ident...
use crate::colorspace::get_mixing_function; use crate::commands::prelude::*; use pastel::ColorblindnessType; use pastel::Fraction; fn clamp(lower: f64, upper: f64, x: f64) -> f64 { f64::max(f64::min(upper, x), lower) } macro_rules! color_command { ($cmd_name:ident, $config:ident, $matches:ident, $color:ident...
match property { "hsl-hue" => { hsla.h = value; } "hsl-saturation" => { hsla.s = value; } "hsl-lightness" => { hsla.l = value; } _ => unreacha...
) -> Result<()> { let output = $body; out.show_color($config, &output) } } }; } color_command!(SaturateCommand, _config, matches, color, { let amount = number_arg(matches, "amount")?; color.saturate(amount) }); color_command!(DesaturateCommand, _config...
random
[ { "content": "/// Trim a number such that it fits into the range [lower, upper].\n\npub fn clamp(lower: Scalar, upper: Scalar, x: Scalar) -> Scalar {\n\n Scalar::max(Scalar::min(upper, x), lower)\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub struct Fraction {\n\n f: Scalar,\n\n}\n\n\n\nimpl Fraction {\...
Rust
mshv-ioctls/src/ioctls/system.rs
russell-islam/mshv
99da566389546aedb56fc3d279e01c5dbde79bce
use crate::ioctls::vm::{new_vmfd, VmFd}; use crate::ioctls::Result; use crate::mshv_ioctls::*; use libc::{open, O_CLOEXEC, O_NONBLOCK}; use mshv_bindings::*; use std::fs::File; use std::os::raw::c_char; use std::os::unix::io::{FromRawFd, RawFd}; use vmm_sys_util::errno; use vmm_sys_util::ioctl::ioctl_with_ref; pub s...
use crate::ioctls::vm::{new_vmfd, VmFd}; use crate::ioctls::Result; use crate::mshv_ioctls::*; use libc::{open, O_CLOEXEC, O_NONBLOCK}; use mshv_bindings::*; use std::fs::File; use std::os::raw::c_char; use std::os::unix::io::{FromRawFd, RawFd}; use vmm_sys_util::errno; use vmm_sys_util::ioctl::ioctl_with_ref; pub s...
pub fn check_stable(&self) -> Result<bool> { let cap: u32 = MSHV_CAP_CORE_API_STABLE; let ret = unsafe { ioctl_with_ref(&self.hv, MSHV_CHECK_EXTENSION(), &cap) }; match ret { 0 => Ok(false), r if r > 0 => Ok(true), _ => Err(errno::E...
pub fn create_vm(&self) -> Result<VmFd> { let creation_flags: u64 = HV_PARTITION_CREATION_FLAG_LAPIC_ENABLED as u64; let mut pr = mshv_create_partition { partition_creation_properties: hv_partition_creation_properties { disabled_processor_features: hv_partit...
function_block-full_function
[ { "content": "/// Helper function to create a new `VmFd`.\n\n///\n\n/// This should not be exported as a public function because the preferred way is to use\n\n/// `create_vm` from `Mshv`. The function cannot be part of the `VmFd` implementation because\n\n/// then it would be exported with the public `VmFd` in...
Rust
src/test/debuginfo/recursive-struct.rs
komaeda/rust
b2c6b8c29f13f8d1f242da89e587960b95337819
#![allow(unused_variables)] #![feature(box_syntax)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] use self::Opt::{Empty, Val}; enum Opt<T> { Empty, Val { val: T } } struct UniqueNode<T> { next: Opt<Box<UniqueNode<T>>>, value: T } struct LongCycle1<T> { next: ...
#![allow(unused_variables)] #![feature(box_syntax)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] use self::Opt::{Empty, Val}; enum Opt<T> { Empty, Val { val: T } } struct UniqueNode<T> { next: Opt<Box<UniqueNode<T>>>, value: T } struct LongCycle1<T> { next: ...
let vec_unique: [UniqueNode<f32>; 1] = [UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 7.5, } }, value: 6.5, }]; let borrowed_unique: &UniqueNode<f64> = &UniqueNode { next: Val { val: b...
let unique_unique: Box<UniqueNode<u32>> = box UniqueNode { next: Val { val: box UniqueNode { next: Empty, value: 3, } }, value: 2, };
assignment_statement
[]
Rust
shared/rust/src/api/endpoints/jig.rs
corinnewo/ji-cloud
58fc898703ca0fc5b962e644dfcfbcce8547c525
use crate::{ api::Method, domain::{ jig::{ JigBrowseQuery, JigBrowseResponse, JigCountResponse, JigCreateRequest, JigId, JigResponse, JigSearchQuery, JigSearchResponse, JigUpdateDraftDataRequest, JigUpdateRequest, }, CreateResponse, }, error::{...
use crate::{ api::Method, domain::{ jig::{ JigBrowseQuery, JigBrowseResponse, JigCountResponse, JigCreateRequest, JigId, JigResponse, JigSearchQuery, JigSearchResponse, JigUpdateDraftDataRequest, JigUpdateRequest, }, CreateResponse, }, error::{...
ApiEndpoint for Browse { type Req = JigBrowseQuery; type Res = JigBrowseResponse; type Err = EmptyError; const PATH: &'static str = "/v1/jig/browse"; const METHOD: Method = Method::Get; } pub struct Search; impl ApiEndpoint for Search { type Req = JigSearchQuery; type Res = JigSearchRespons...
mod module; pub mod additional_resource; pub mod player; pub struct Create; impl ApiEndpoint for Create { type Req = JigCreateRequest; type Res = CreateResponse<JigId>; type Err = MetadataNotFound; const PATH: &'static str = "/v1/jig"; const METHOD: Method = Method::Post; } pub struct Update; i...
random
[ { "content": "pub fn delete_jig(state: Rc<State>, jig_id: JigId) {\n\n state.loader.load(clone!(state => async move {\n\n let path = Delete::PATH.replace(\"{id}\",&jig_id.0.to_string());\n\n match api_with_auth_empty::<EmptyError, ()>(&path, Delete::METHOD, None).await {\n\n Ok(_) =>...
Rust
src/columnar_transposition.rs
sula0/embedo
fa3ddcc54ea481ecffe5c765706aa6e1b42a6be1
use crate::util; const META_ROWS: usize = 2; const EMPTY_CHAR: u32 = 32; pub fn encrypt(text: &str, key: &str) -> String { let mut result = String::new(); let cols = key.len(); let required_rows = text.len() as f32 / cols as f32; let rows = META_ROWS + (required_rows as f32).ceil() as usize; le...
use crate::util; const META_ROWS: usize = 2; const EMPTY_CHAR: u32 = 32; pub fn encrypt(text: &str, key: &str) -> String { let mut result = String::new(); let cols = key.len(); let required_rows = text.len() as f32 / cols as f32; let rows = META_ROWS + (required_rows as f32).ceil() as usize; le...
f i == 1 { let alphabetized_char = util::alphabetize_char(key_chars[j] as u32, true); matrix[i][j] = alphabetized_char; keys.push((j as u32, alphabetized_char)); } } } keys.sort_by(|a, b| a.1.cmp(&b.1)); let mut char_index: usize = ...
ypt(text: &str, key: &str) -> String { let mut result = String::new(); let cols = key.len(); let required_rows = text.len() as f32 / cols as f32; let rows = META_ROWS + (required_rows as f32).ceil() as usize; let mut matrix = vec![vec![32; cols]; rows]; let key_chars: Vec<char> = key.to_uppe...
function_block-random_span
[ { "content": "pub fn encrypt(text: &str, n: u32) -> String {\n\n let mut result = String::new();\n\n\n\n for c in text.chars() {\n\n let is_upper = c.is_uppercase();\n\n\n\n let encrypted = (util::alphabetize_char(c as u32, is_upper) + n) % 26;\n\n result += std::str::from_utf8(&[util...
Rust
experiments/src/bin/graphs.rs
petrosagg/differential-dataflow
2e38abbb62aedf02cb9b6b5debb73c29b6e97dbb
extern crate rand; extern crate timely; extern crate differential_dataflow; use std::rc::Rc; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::trace::Trace...
extern crate rand; extern crate timely; extern crate differential_dataflow; use std::rc::Rc; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::trace::Trace...
fn bfs<G: Scope<Timestamp = ()>> ( graph: &mut TraceHandle, roots: Collection<G, Node> ) -> Collection<G, (Node, u32)> { let graph = graph.import(&roots.scope()); let roots = roots.map(|r| (r,0)); roots.iterate(|inner| { let graph = graph.enter(&inner.scope()); let roots = roots...
r.scope()); let roots = roots.enter(&inner.scope()); graph.join_core(&inner.arrange_by_self(), |_src,&dst,&()| Some(dst)) .concat(&roots) .distinct_total() }) }
function_block-function_prefixed
[ { "content": "fn dump_cursor<Tr>(round: u32, index: usize, trace: &mut Tr)\n\nwhere\n\n Tr: TraceReader,\n\n Tr::Key: Debug + Clone,\n\n Tr::Val: Debug + Clone,\n\n Tr::Time: Debug + Clone,\n\n Tr::R: Debug + Clone,\n\n{\n\n let (mut cursor, storage) = trace.cursor();\n\n for ((k, v), diffs...
Rust
boa/src/exec/mod.rs
RageKnify/boa
7d318f0582a2aac5a01af762635000c686452ab4
mod array; mod block; mod break_node; mod call; mod conditional; mod declaration; mod field; mod identifier; mod iteration; mod new; mod object; mod operator; mod return_smt; mod spread; mod statement_list; mod switch; mod throw; mod try_node; #[cfg(test)] mod tests; use crate::{ syntax::ast::{constant::Const, ...
mod array; mod block; mod break_node; mod call; mod conditional; mod declaration; mod field; mod identifier; mod iteration; mod new; mod object; mod operator; mod return_smt; mod spread; mod statement_list; mod switch; mod throw; mod try_node; #[cfg(test)] mod tests; use crate::{ syntax::ast::{constant::Const, ...
}
p) => while_loop.run(interpreter), Node::DoWhileLoop(ref do_while) => do_while.run(interpreter), Node::ForLoop(ref for_loop) => for_loop.run(interpreter), Node::If(ref if_smt) => if_smt.run(interpreter), Node::ConditionalOp(ref op) => op.run(interpreter), Node...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn this_time_value(value: &Value, ctx: &mut Context) -> Result<Date> {\n\n if let Value::Object(ref object) = value {\n\n if let ObjectData::Date(ref date) = object.borrow().data {\n\n return Ok(*date);\n\n }\n\n }\n\n Err(ctx.construct_type_error...
Rust
term/src/test/csi.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
use super::*; #[test] fn test_vpa() { let mut term = TestTerm::new(3, 4, 0); term.assert_cursor_pos(0, 0, None); term.print("a\r\nb\r\nc"); term.assert_cursor_pos(1, 2, None); term.print("\x1b[d"); term.assert_cursor_pos(1, 0, None); term.print("\r\n\r\n"); term.assert_cursor_pos(0, 2, ...
use super::*; #[test] fn test_vpa() { let mut term = TestTerm::new(3, 4, 0); term.assert_cursor_pos(0, 0, None); term.print("a\r\nb\r\nc"); term.assert_cursor_pos(1, 2, None); term.print("\x1b[d"); term.assert_cursor_pos(1, 0, None); term.print("\r\n\r\n"); term.assert_cursor_pos(0, 2, ...
#[test] fn test_ech() { let mut term = TestTerm::new(3, 4, 0); term.print("hey!wat?"); term.cup(1, 0); term.print("\x1b[2X"); assert_visible_contents(&term, file!(), line!(), &["h !", "wat?", " "]); term.print("\x1b[12X"); assert_visible_contents(&term, file!(), line!(), &["h ",...
assert_visible_contents(&term, file!(), line!(), &["h e", "wat?", " "]); term.print("\x1b[12@"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); term.print("\x1b[-12@"); assert_visible_contents(&term, file!(), line!(), &["h ", "wat?", " "]); }
function_block-function_prefix_line
[ { "content": "fn assert_all_contents(term: &Terminal, file: &str, line: u32, expect_lines: &[&str]) {\n\n print_all_lines(&term);\n\n let screen = term.screen();\n\n\n\n let expect: Vec<Line> = expect_lines.iter().map(|s| (*s).into()).collect();\n\n\n\n assert_lines_equal(file, line, &screen.all_lin...
Rust
src/materialized/src/bin/materialized/sys.rs
bobbyiliev/materialize
44e3bcae151179075232ad436ae72f5883361fd1
use std::alloc::{self, Layout}; use std::io::{self, Write}; use std::process; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering}; use anyhow::{bail, Context}; use nix::errno; use nix::sys::signal; use tracing::trace; #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "ios")))] pub fn adju...
use std::alloc::{self, Layout}; use std::io::{self, Write}; use std::process; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering}; use anyhow::{bail, Context}; use nix::errno; use nix::sys::signal; use tracing::trace; #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "ios")))] pub fn adju...
pub fn enable_sigusr2_coverage_dump() -> Result<(), anyhow::Error> { let action = signal::SigAction::new( signal::SigHandler::Handler(handle_sigusr2_signal), signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK, signal::SigSet::empty(), ); unsafe { signal::sigaction(signal::S...
t { ss_sp: buf as *mut libc::c_void, ss_flags: 0, ss_size: STACK_SIZE, }; let ret = unsafe { libc::sigaltstack(&stack, ptr::null_mut()) }; if ret == -1 { let errno = errno::from_i32(errno::errno()); bail!("failed to configure alternate signal stack: {}", err...
function_block-function_prefixed
[ { "content": "fn encode_element(buf: &mut BytesMut, elem: Option<&Value>, ty: &Type) -> Result<(), io::Error> {\n\n match elem {\n\n None => buf.put_i32(-1),\n\n Some(elem) => {\n\n let base = buf.len();\n\n buf.put_i32(0);\n\n elem.encode_binary(ty, buf)?;\n\n ...