lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/commitment/blake2s/constraints.rs
stechu/crypto-primitives
fd9a0decc470a7c92d2ed2ef7a5fffa6952c9c83
use ark_relations::r1cs::{Namespace, SynthesisError}; use crate::{ commitment::{blake2s, CommitmentGadget}, prf::blake2s::constraints::{evaluate_blake2s, OutputVar}, Vec, }; use ark_ff::{Field, PrimeField}; use ark_r1cs_std::prelude::*; use core::borrow::Borrow; #[derive(Clone)] pub struct ParametersVar;...
use ark_relations::r1cs::{Namespace, SynthesisError}; use crate::{ commitment::{blake2s, CommitmentGadget}, prf::blake
ss_var = RandomnessVar(randomness_var); let parameters_var = <TestCOMMGadget as CommitmentGadget<TestCOMM, Fr>>::ParametersVar::new_witness( ark_relations::ns!(cs, "gadget_parameters"), || Ok(&parameters), ) .unwrap(); let result_var =...
2s::constraints::{evaluate_blake2s, OutputVar}, Vec, }; use ark_ff::{Field, PrimeField}; use ark_r1cs_std::prelude::*; use core::borrow::Borrow; #[derive(Clone)] pub struct ParametersVar; #[derive(Clone)] pub struct RandomnessVar<F: Field>(pub Vec<UInt8<F>>); pub struct CommGadget; impl<F: PrimeField> Commitme...
random
[ { "content": "pub trait CommitmentGadget<C: CommitmentScheme, ConstraintF: Field> {\n\n type OutputVar: EqGadget<ConstraintF>\n\n + ToBytesGadget<ConstraintF>\n\n + AllocVar<C::Output, ConstraintF>\n\n + R1CSVar<ConstraintF>\n\n + Clone\n\n + Sized\n\n + Debug;\n\n ...
Rust
crates/kas-wgpu/src/draw/draw_pipe.rs
dhardy/kas
bb46d25616024a8df1d66eee6d2428763fae8c3b
use std::f32::consts::FRAC_PI_2; use wgpu::util::DeviceExt; use super::*; use kas::cast::traits::*; use kas::draw::color::Rgba; use kas::draw::*; use kas::geom::{Quad, Rect, Size, Vec2}; use kas::text::{Effect, TextDisplay}; use kas_theme::DrawShadedImpl; impl<C: CustomPipe> DrawPipe<C> { pub fn new<CB: Cu...
use std::f32::consts::FRAC_PI_2; use wgpu::util::DeviceExt; use super::*; use kas::cast::traits::*; use kas::draw::color::Rgba; use kas::draw::*; use kas::geom::{Quad, Rect, Size, Vec2}; use kas::text::{Effect, TextDisplay}; use kas_theme::DrawShadedImpl; impl<C: CustomPipe> DrawPipe<C> { pub fn new<CB: Cu...
fn draw_text_effects( &mut self, draw: &mut Self::Draw, pass: PassId, pos: Vec2, text: &TextDisplay, effects: &[Effect<Rgba>], ) { let rects = draw .text .text_effects(&mut self.text, pass, pos, text, effects); for (rect, ...
fn draw_text_col_effects( &mut self, draw: &mut Self::Draw, pass: PassId, pos: Vec2, text: &TextDisplay, col: Rgba, effects: &[Effect<()>], ) { let rects = draw .text .text_col_effects(&mut self.text, pass, pos, text, col, effec...
function_block-full_function
[ { "content": "type Scale = [f32; 4];\n\n\n\n/// Shared pipeline data\n\npub struct DrawPipe<C> {\n\n pub(crate) device: wgpu::Device,\n\n queue: wgpu::Queue,\n\n local_pool: futures::executor::LocalPool,\n\n staging_belt: wgpu::util::StagingBelt,\n\n bgl_common: wgpu::BindGroupLayout,\n\n ligh...
Rust
rute_header_def_gen/src/doc_parser.rs
emoon/Rute
b8981fa9fb0508691399b0aa9a565686ebcc0a69
use pest::Parser; use std::fs::File; use std::io::Read; use std::path::Path; use pest::iterators::Pair; use pest; use std::fmt; use std::fmt::Write; #[cfg(debug_assertions)] const _GRAMMAR: &str = include_str!("qdoc.pest"); #[derive(Parser)] #[grammar = "qdoc.pest"] pub struct DocParser; #[derive(Debug, Clone, Defau...
use pest::Parser; use std::fs::File; use std::io::Read; use std::path::Path; use pest::iterators::Pair; use pest; use std::fmt; use std::fmt::Write; #[cfg(debug_assertions)] const _GRAMMAR: &str = include_str!("qdoc.pest"); #[derive(Parser)] #[grammar = "qdoc.pest"] pub struct DocParser; #[derive(Debug, Clone, Defau...
ffer: &str, filename: &str) { let chunks = Self::parse(Rule::chunk, buffer) .unwrap_or_else(|e| panic!("APiParser: {} {}", filename, e)); let mut docs = DocInfo::default(); for chunk in chunks { match chunk.as_rule() { Rule::doc_start ...
et mut buffer = String::new(); let pathname = path.as_ref().to_str().unwrap(); let mut f = File::open(pathname) .unwrap_or_else(|e| panic!("ApiParser: Unable to open {}: {}", pathname, e)); f.read_to_string(&mut buffer) .unwrap_or_else(|e| panic!("ApiParser: Unable to r...
random
[ { "content": "///\n\n/// Print enums\n\n///\n\nfn print_enums<W: Write>(dest: &mut W, entry: &Entity, struct_name: &str, org_class_name: &str, docs: &HashMap<String, QDocFile>) {\n\n let mut hash_lookup = HashMap::new();\n\n\n\n writeln!(dest, \"[org_name({})]\", org_class_name);\n\n\n\n if let Some(en...
Rust
src/owl/thick_triple.rs
ontodev/wiring.rs
2a8044f325d02c5514f067cd2120c20cfb8de729
use serde::{Deserialize, Serialize}; #[derive(Debug,Serialize, Deserialize)] pub struct RDFList { #[serde(rename = "rdf:first")] pub rdf_first: Vec<Object>, #[serde(rename = "rdf:rest")] pub rdf_rest: Vec<Object>, } impl RDFList { pub fn rdf_first(&self) -> &Vec<Object> { &self...
use serde::{Deserialize, Serialize}; #[derive(Debug,Serialize, Deserialize)] pub struct RDFList { #[serde(rename = "rdf:first")] pub rdf_first: Vec<Object>, #[serde(rename = "rdf:rest")] pub rdf_rest: Vec<Object>, } impl RDFList { pub fn rdf_first(&self) -> &Vec<Object> { &self...
ementOf")] pub owl_complement_of: Vec<Object>, } #[derive(Debug,Serialize, Deserialize)] pub struct InverseOf { #[serde(rename = "owl:inverseOf")] pub owl_inverse_of: Vec<Object>, } #[derive(Debug,Serialize, Deserialize)] pub struct Object { pub object: OWL, pub datatype: String, pub meta: Opt...
e(rename = "owl:oneOf")] pub owl_one_of: Vec<Object>, } #[derive(Debug,Serialize, Deserialize)] pub struct ComplementOf { #[serde(rename = "rdf:type")] pub rdf_type: Option<Vec<Object>>, #[serde(rename = "owl:compl
random
[ { "content": "pub fn translate_members(s: &owl::Members) -> Value { \n\n\n\n translate(&s.members[0].object)\n\n\n\n}\n\n\n", "file_path": "src/ldtab2ofn/class_translation.rs", "rank": 0, "score": 142442.21792610554 }, { "content": "//TODO: this translation is for an AXIOM (and needs to b...
Rust
src/mesh.rs
solidiquis/three.rs
e688c153cfc616f06efc4aa414dc690fdba18892
use crate::shader::Shader; use js_sys::{Float32Array, Uint16Array}; use wasm_bindgen::JsValue; use web_sys::WebGlProgram; use web_sys::WebGlRenderingContext as GL; type MeshResult<T> = Result<T, JsValue>; pub enum BufferUsage { Static, Dynamic, Stream, } impl BufferUsage { pub fn as_u32(&self) -> u32...
use crate::shader::Shader; use js_sys::{Float32Array, Uint16Array}; use wasm_bindgen::JsValue; use web_sys::WebGlProgram; use web_sys::WebGlRenderingContext as GL; type MeshResult<T> = Result<T, JsValue>; pub enum BufferUsage { Static, Dynamic, Stream, } impl BufferUsage { pub fn as_u32(&self) -> u32...
} fn init_vertex_data( gl: &GL, shader: &Shader, mesh_name: &str, attr: &Attribute ) -> MeshResult<()> { let vbo = gl.create_buffer() .ok_or_else(|| JsValue::from(format!["Failed to initialize VBO for {}", mesh_name]))?; let buffer_data = Float3...
Ok(Self { name, shader, position_attr, normal_attr, color_attr, texture_attr, indices, })
call_expression
[]
Rust
MBExtender/rust/mbx/src/con_/command.rs
RandomityGuy/MBExtender
5b5a4b5f8f9aafe76c6f50ab75f8a214ef22cb3c
use super::SimObject; use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::ptr; use std::slice; pub type Argv = *const *const c_char; pub type BoolFn = extern "C" fn(obj: *mut SimObject, argc: i32, argv: Argv) -> bool; pub type FloatFn = extern "C" fn(obj: *mut SimObject, argc: i32, argv: Argv) -> f32; p...
use super::SimObject; use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::ptr; use std::slice; pub type Argv = *const *const c_char; pub type BoolFn = extern "C" fn(obj: *mut SimObject, argc: i32, argv: Argv) -> bool; pub type FloatFn = extern "C" fn(obj: *mut SimObject, argc: i32, argv: Argv) -> f32; p...
} tge_functions! { pub fn tge_add_command_bool(name: *const c_char, cb: BoolFn, usage: *const c_char, min_args: i32, max_args: i32) = tge_addr!(0x407527, 0x3A1F0); pub fn tge_add_command_float(name: *const c_char, cb: FloatFn, usage: *const c_char, min_args: i32, max_args: i32) = tge_addr!(0x408972, 0x3A2B0);...
match cmd.class { Some(class) => match cmd.func { CommandFn::Bool(func) => add_method_bool(class, name, func, usage, min, max), CommandFn::Float(func) => add_method_float(class, name, func, usage, min, max), CommandFn::Int(func) => add_method_int(class, name, func, usage, min...
if_condition
[ { "content": "#[command(args = 2, usage = \"rustReverse(str)\")]\n\nfn rustReverse(_obj: *mut SimObject, argc: i32, argv: con::Argv) -> *const c_char {\n\n let args = con::collect_args(argc, argv);\n\n let reversed: String = args[1].chars().rev().collect();\n\n con::get_return_buffer(&reversed)\n\n}\n\...
Rust
alvr/experiments/gui/src/dashboard/pretty/dashboard.rs
korejan/ALVR
8fac21ce3acdf0b866d22fbf4c1bbc83a81ecf5e
use super::{ tabs::{ConnectionEvent, ConnectionPanel, SettingsEvent, SettingsPanel}, theme::{ContainerStyle, ACCENT, BACKGROUND_SECONDARY, FOREGROUND}, }; use crate::dashboard::RequestHandler; use alvr_session::{ServerEvent, SessionDesc}; use iced::{ alignment::Horizontal, button, image, Alignment, Button, ...
use super::{ tabs::{ConnectionEvent, ConnectionPanel, SettingsEvent, SettingsPanel}, theme::{ContainerStyle, ACCENT, BACKGROUND_SECONDARY, FOREGROUND}, }; use crate::dashboard::RequestHandler; use alvr_session::{ServerEvent, SessionDesc}; use iced::{ alignment::Horizontal, button, image, Alignment, Button, ...
} #[derive(Clone, Debug)] pub enum DashboardEvent { ServerEvent(ServerEvent), TabClick(usize), LanguageClick, ConnectionEvent(ConnectionEvent), SettingsEvent(SettingsEvent), } pub struct TabState { icon: (), display_name: String, state: button::State, } impl Default for TabState { ...
TabLabelStyle::Normal => normal, TabLabelStyle::Selected => button::Style { background: ACCENT.into(), ..normal }, } }
function_block-function_prefix_line
[ { "content": "#[cfg(not(target_os = \"macos\"))]\n\npub fn to_vulkan_images(textures: &[Texture]) -> Vec<vk::Image> {\n\n textures\n\n .iter()\n\n .map(|tex| unsafe {\n\n let mut handle = vk::Image::null();\n\n tex.as_hal::<hal::api::Vulkan, _>(|tex| {\n\n h...
Rust
src/package.rs
sudormrfbin/pac
2fe06bd07ed706c58faa913fc7e87c30dff6b815
use crate::git::GitRepo; use crate::{Error, Result}; use std::env; use std::fmt; use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::process; use lazy_static::lazy_static; use yaml_rust::yaml::Hash; use yaml_rust::{Yaml, YamlEmitter, YamlLoader}; const PAC_PLUGIN_FILENAME:...
use crate::git::GitRepo; use crate::{Error, Result}; use std::env; use std::fmt; use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::process; use lazy_static::lazy_static; use yaml_rust::yaml::Hash; use yaml_rust::{Yaml, YamlEmitter, YamlLoader}; const PAC_PLUGIN_FILENAME:...
} pub fn into_yaml(self) -> Yaml { let mut doc = Hash::new(); macro_rules! yaml_insert { ($key:ident) => { doc.insert(Yaml::from_str(stringify!($key)), Yaml::from_str(&self.$key)); }; } yaml_insert!(remote); if !self.remot...
Ok(Package { name, idname: Self::idname_from_remote(&remote), remote, revision, category, opt, load_command: cmd, for_types: types, build_command: build, })
call_expression
[ { "content": "fn list_detached(category: &Option<String>, start: bool, opt: bool) -> Result<()> {\n\n let installed = package::fetch()?;\n\n let pack_names: Vec<&str> = installed.iter().map(|p| &*p.name).collect();\n\n\n\n package::walk_packs(category, start, opt, |cate, option, name| {\n\n if !...
Rust
libstainless_macros/implementation.rs
youroff/rust-stainless
b33eea22d8d683ae33d967f43ed653d7a509e9dd
use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::{parse_quote, Attribute, Expr, FnArg, Item, ItemFn, Result, ReturnType, Stmt, Type}; use std::convert::TryFrom; use std::iter; #[derive(Debug, PartialEq, Eq)] pub enum SpecType { Pre, Post, Measure, } impl SpecTyp...
use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::{parse_quote, Attribute, Expr, FnArg, Item, ItemFn, Result, ReturnType, Stmt, Type}; use std::convert::TryFrom; use std::iter; #[derive(Debug, PartialEq, Eq)] pub enum SpecType { Pre, Post, Measure, } impl SpecTyp...
{ #expr }), }; parse_quote! { #[doc(hidden)] #[allow(unused_variables)] fn #spec_ident#fn_generics(#fn_arg_tys#ret_param) -> #return_type { #body } } }; let specs = specs.into_iter().enumerate().map(make_spec_fn); let has_self_param = item_fn .sig .inputs ...
return Err(err.clone()); } let specs: Vec<Spec> = specs .into_iter() .map(|(typ, cond)| Spec { typ, expr: cond.unwrap(), }) .collect(); Ok((item_fn, specs)) } fn generate_fn_with_spec(mut item_fn: ItemFn, specs: Vec<Spec>) -> Vec<ItemFn> { let fn_generics = &item_fn.sig.generics;...
random
[ { "content": "type Result<T> = std::result::Result<T, &'static str>;\n\n\n\n/// Extraction of bodies (i.e., expressions, for the most part)\n\nimpl<'a, 'l, 'tcx> BodyExtractor<'a, 'l, 'tcx> {\n\n pub(super) fn extract_expr(&mut self, expr: Expr<'tcx>) -> st::Expr<'l> {\n\n match expr.kind {\n\n ExprKin...
Rust
src/spatial_coverage.rs
hirnimeshrampuresoftware/mocpy
4ed42b7f07ca3931379b884c49fd26eed1ec812b
use std::ops::Range; use rayon::prelude::*; use pyo3::exceptions; use pyo3::prelude::PyResult; use moc::qty::{MocQty, Hpx}; use moc::elem::valuedcell::{valued_cells_to_moc, valued_cells_to_moc_with_opt}; use moc::elemset::range::{ HpxRanges, uniq::HpxUniqRanges }; use moc::ranges::SNORanges; use moc::moc::...
use std::ops::Range; use rayon::prelude::*; use pyo3::exceptions; use pyo3::prelude::PyResult; use moc::qty::{MocQty, Hpx}; use moc::elem::valuedcell::{valued_cells_to_moc, valued_cells_to_moc_with_opt}; use moc::elemset::range::{ HpxRanges, uniq::HpxUniqRanges }; use moc::ranges::SNORanges; use moc::moc::...
if depth > Hpx::<u64>::MAX_DEPTH { return Err(exceptions::PyValueError::new_err(format!( "Depth must be comprised between in [0, {0}]", Hpx::<u64>::MAX_DEPTH ))); } let mut data = Vec::<Range<u64>>::with_capacity(lon.len()); data.resize(lon.len(), 0..1); le...
if lon.len() != lat.len() { return Err(exceptions::PyValueError::new_err( "Longitudes and Latitudes \ do not have the same shapes.", )); }
if_condition
[ { "content": "/// Flatten cells to a specific depth (depth = max_depth - delta_depth).\n\n///\n\n/// # Arguments\n\n///\n\n/// * ``coverage`` - The coverage\n\n/// * ``dim`` - The dimension of the quantity in the coverage (1 for Time, 2 for Coordinates on the unit sphere).\n\n/// * ``delta_depth`` - Difference ...
Rust
studio/src/editors.rs
rohankumardubey/makepad
2248d20bd8e1431616acc89846a841abc36dffb7
use { crate::{ editor_state::{ EditorState, DocumentId, SessionId, }, code_editor::{ code_editor_impl::{ CodeEditorAction }, protocol::{Notification, Request, Response}, }, design_editor::...
use { crate::{ editor_state::{ EditorState, DocumentId, SessionId, }, code_editor::{ code_editor_impl::{ CodeEditorAction }, protocol::{Notification, Request, Response}, }, design_editor::...
pub fn redraw_views_for_document( &mut self, cx: &mut Cx, state: &EditorState, document_id: DocumentId, ) { let document = &state.documents[document_id]; for session_id in &document.session_ids { let session = &state.sessions[*session_id]; ...
pub fn handle_notification( &mut self, cx: &mut Cx, state: &mut EditorState, notification: Notification, ) { match notification { Notification::DeltaWasApplied(file_id, delta) => { let document_id = state.handle_delta_applied_notification(file_id, ...
function_block-full_function
[ { "content": "pub fn live_register(cx: &mut Cx){\n\n crate::design_editor::inline_widget::inline_color_picker::live_register(cx);\n\n crate::design_editor::inline_widget::inline_registry::live_register(cx);\n\n crate::design_editor::live_editor::live_register(cx);\n\n}\n", "file_path": "studio/src/...
Rust
src/x509_parser.rs
spd-mfa/x509-parser
3511cc65420f7f111d0e49c37cda92824f3ad225
use crate::error::{X509Error, X509Result}; use crate::time::ASN1Time; use crate::x509::*; use chrono::offset::TimeZone; use chrono::{DateTime, Datelike, Utc}; use nom::branch::alt; use nom::bytes::complete::take; use nom::combinator::{all_consuming, complete, map_opt, map_res, opt}; use nom::multi::{many0, many1}; us...
use crate::error::{X509Error, X509Result}; use crate::time::ASN1Time; use crate::x509::*; use chrono::offset::TimeZone; use chrono::{DateTime, Datelike, Utc}; use nom::branch::alt; use nom::bytes::complete::take; use nom::combinator::{all_consuming, complete, map_opt, map_res, opt}; use nom::multi::{many0, many1}; us...
(i) } fn der_to_utctime(obj: DerObject) -> Result<ASN1Time, X509Error> { if let BerObjectContent::UTCTime(s) = obj.content { let dt = if s.ends_with('Z') { if s.len() == 11 { Utc.datetime_from_str(s, "%y%m%d%H%MZ") } els...
alt(( complete(parse_der_utctime), complete(parse_der_generalizedtime), complete(parse_malformed_date), ))
call_expression
[ { "content": "/// Read a PEM-encoded structure, and decode the base64 data\n\n///\n\n/// Return a structure describing the PEM object: the enclosing tag, and the data.\n\n/// Allocates a new buffer for the decoded data.\n\n///\n\n/// For X.509 (`CERTIFICATE` tag), the data is a certificate, encoded in DER. To p...
Rust
src/parser/pfunction.rs
skalamark/gl-core
fad6b4655f15eec4f0e8de67b8f76a43c09b7eb6
use crate::preludes::*; impl Parser { pub fn is_fn_statement_anonymous(&mut self) -> Result<&str, Exception> { if let TokenType::IDENTIFIER(_) = &self.ntoken.typer { return Ok("statement"); } else if self.ntoken.typer.is(TokenType::LeftParen) { return Ok("anonymous"); } let mut tc: Vec<Token> = Vec::...
use crate::preludes::*; impl Parser { pub fn is_fn_statement_anonymous(&mut self) -> Result<&str, Exception> { if let TokenType::IDENTIFIER(_) = &self.ntoken.typer { return Ok("statement"); } else if self.ntoken.typer.is(TokenType::LeftParen) { return Ok("anonymous"); } let mut tc: Vec<Token> = Vec::...
}, TokenType::RightParen => {}, _ => { let mut exception: Exception = Exception::not_runtime(Except::invalid_syntax("expected ',' or ')'")); exception .push(ExceptionPoint::new(&self.module, self.ctoken.position.start.copy())); return Err(exception); }, } } self.next_token...
ion); } self.next_token(true)?; while !self.ctoken.typer.is(TokenType::RightParen) { if let TokenType::IDENTIFIER(argument) = self.ctoken.typer.clone() { params.push(argument); self.next_token(true)?; } match &self.ctoken.typer { TokenType::COMMA => { if params.len() > 0 { self...
random
[ { "content": "pub fn big_rational_to_string(mut n: BigRational) -> String {\n\n\tlet neg: bool = if n.is_negative() {\n\n\t\tn = -n;\n\n\t\ttrue\n\n\t} else {\n\n\t\tfalse\n\n\t};\n\n\tlet mut fraction: String = String::new();\n\n\tlet mut map: HashMap<BigInt, usize> = HashMap::new();\n\n\tlet mut rem: BigInt =...
Rust
core/tests/loadnext/src/executor.rs
AlmavivA/zksync
3af534ce40ed064bcd558af325e34133501b0848
use futures::{channel::mpsc, future::join_all}; use tokio::task::JoinHandle; use zksync::{ error::ClientError, ethereum::PriorityOpHolder, operations::SyncTransactionHandle, provider::Provider, types::TransactionInfo, }; use zksync_types::{tx::TxHash, TransactionReceipt, TxFeeTypes, U256}; use crate::{ ac...
use futures::{channel::mpsc, future::join_all}; use tokio::task::JoinHandle; use zksync::{ error::ClientError, ethereum::PriorityOpHolder, operations::SyncTransactionHandle, provider::Provider, types::TransactionInfo, }; use zksync_types::{tx::TxHash, TransactionReceipt, TxFeeTypes, U256}; use crate::{ ac...
TIMEOUT) .wait_for_commit() .await?; assert!( result.fail_reason.is_none(), "Unable to set signing key on the main wallet" ); vlog::info!("Master Account: Signing key is OK"); Ok(()) } async fn send_initial_transfers_batch( ...
assert!( self.pool.master_wallet.account_id().is_some(), "Account ID for master account was not set", ); vlog::info!("Master Account: Deposit is OK"); Ok(()) } async fn set_signing_key(&mut self) -> anyhow::Result<()> { vlog::info!("Master Accou...
random
[ { "content": "pub fn parse_ether(eth_value: &str) -> Result<BigUint, anyhow::Error> {\n\n let split = eth_value.split('.').collect::<Vec<&str>>();\n\n ensure!(split.len() == 1 || split.len() == 2, \"Wrong eth value\");\n\n let string_wei_value = if split.len() == 1 {\n\n format!(\"{}000000000000...
Rust
npp/benches/cuda_resize_image_with_imageops.rs
vansweej/npp-rs
da302cf830cbc84d82c0079e0a6f2a7260c41ef3
use criterion::Criterion; use image::io::Reader as ImageReader; use image::ColorType; use npp_rs::image::*; use npp_rs::imageops::*; use rustacuda::error::CudaError; use rustacuda::prelude::*; use std::convert::TryFrom; pub fn cuda_nearest_neighbor_resize_image_with_imageops(c: &mut Criterion) { rustacuda::init(ru...
use criterion::Criterion; use image::io::Reader as ImageReader; use image::ColorType; use npp_rs::image::*; use npp_rs::imageops::*; use rustacuda::error::CudaError; use rustacuda::prelude::*; use std::convert::TryFrom; pub fn cuda_nearest_neighbor_resize_image_with_imageops(c: &mut Criterion) { rustacuda::init(ru...
pub fn cuda_linear_resize_image_with_imageops(c: &mut Criterion) { rustacuda::init(rustacuda::CudaFlags::empty()).unwrap(); let device = Device::get_device(0).unwrap(); let _ctx = Context::create_and_push(ContextFlags::MAP_HOST | ContextFlags::SCHED_AUTO, device) .unwrap(); let img_src = Image...
let _ctx = Context::create_and_push(ContextFlags::MAP_HOST | ContextFlags::SCHED_AUTO, device) .unwrap(); let img_src = ImageReader::open("test_resources/DSC_0003.JPG") .unwrap() .decode() .unwrap(); let img_layout = img_src.as_rgb8().unwrap().sample_layout(); let cuda_src =...
function_block-function_prefix_line
[ { "content": "// benchmark with rust image crate\n\npub fn resize_rust_image_crate_benchmark(c: &mut Criterion) {\n\n let img = ImageReader::open(\"test_resources/DSC_0003.JPG\")\n\n .unwrap()\n\n .decode()\n\n .unwrap();\n\n\n\n c.bench_function(\"resize with rust image crate\", |b| ...
Rust
src/shaders/pattern.rs
vmx/tiny-skia
58001e98b1ae267b5cd60dd681c88bb00a97ed16
use crate::{Shader, Transform, PixmapRef, SpreadMode}; use crate::floating_point::NormalizedF32; use crate::pipeline; use crate::pipeline::RasterPipelineBuilder; #[derive(Copy, Clone, PartialEq, Debug)] pub enum FilterQuality { Nearest, Bilinear, Bicubic, } #[derive(Clone, Debug)] pub st...
use crate::{Shader, Transform, PixmapRef, SpreadMode}; use crate::floating_point::NormalizedF32; use crate::pipeline; use crate::pipeline::RasterPipelineBuilder; #[derive(Copy, Clone, PartialEq, Debug)] pub enum FilterQuality { Nearest, Bilinear, Bicubic, } #[derive(Clone, Debug)] pub st...
}
pub(crate) fn push_stages(&self, p: &mut RasterPipelineBuilder) -> Option<()> { let ts = self.transform.invert()?; p.push(pipeline::Stage::SeedShader); p.push_transform(ts); let mut quality = self.quality; if ts.is_identity() || ts.is_translate() { quality = Filte...
function_block-full_function
[ { "content": "/// Return the float as a 2s compliment int. Just to be used to compare floats\n\n/// to each other or against positive float-bit-constants (like 0). This does\n\n/// not return the int equivalent of the float, just something cheaper for\n\n/// compares-only.\n\npub fn f32_as_2s_compliment(x: f32)...
Rust
src/usart1/ien.rs
lucab/efm32hg-pac
ca4230132f7ce087da064f6d7d613e262fef8e62
#[doc = "Reader of register IEN"] pub type R = crate::R<u32, super::IEN>; #[doc = "Writer for register IEN"] pub type W = crate::W<u32, super::IEN>; #[doc = "Register IEN `reset()`'s with value 0"] impl crate::ResetValue for super::IEN { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Reader of register IEN"] pub type R = crate::R<u32, super::IEN>; #[doc = "Writer for register IEN"] pub type W = crate::W<u32, super::IEN>; #[doc = "Register IEN `reset()`'s with value 0"] impl crate::ResetValue for super::IEN { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
&self) -> RXFULL_R { RXFULL_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - RX Overflow Interrupt Enable"] #[inline(always)] pub fn rxof(&self) -> RXOF_R { RXOF_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - RX Underflow Interrupt Enable"] #[inline(always...
pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { ...
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
backend/src/external_event_data_service.rs
pimpale/life-event-loop
8a69537632faae6fdab348658093bccc3cdda77d
use super::db_types::*; use super::utils::current_time_millis; use std::convert::From; use tokio_postgres::GenericClient; impl From<tokio_postgres::row::Row> for ExternalEventData { fn from(row: tokio_postgres::Row) -> ExternalEventData { ExternalEventData { external_event_data_id: row.get("external_eve...
use super::db_types::*; use super::utils::current_time_millis; use std::convert::From; use tokio_postgres::GenericClient; impl From<tokio_postgres::row::Row> for ExternalEventData { fn from(row: tokio_postgres::Row) -> ExternalEventData { ExternalEventData { external_event_data_id: row.get("external_eve...
, " WHERE 1 = 1", " AND ($1::bigint[] IS NULL OR eed.external_event_data_id = ANY($1))", " AND ($2::bigint IS NULL OR eed.creation_time >= $2)", " AND ($3::bigint IS NULL OR eed.creation_time <= $3)", " AND ($4::bigint[] IS NULL OR eed.creator_user_id = ANY($4))", " AND ($5::bigint[] IS NULL...
if props.only_recent { "SELECT eed.* FROM recent_external_event_data eed" } else { "SELECT eed.* FROM external_event_data eed" }
if_condition
[ { "content": "pub fn current_time_millis() -> i64 {\n\n let since_the_epoch = SystemTime::now()\n\n .duration_since(UNIX_EPOCH)\n\n .expect(\"time went backwards\");\n\n\n\n since_the_epoch.as_millis() as i64\n\n}\n\n\n\n// fun error handling stuff\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\n#...
Rust
src/dma.rs
rudihorn/rust-stm32f103
b7616dee63bd56cb64caae6174fdb4aed7d8cb2d
#![allow(dead_code)] use super::common; use super::common::{Register}; use ::core::ptr::{write_volatile, read_volatile}; pub struct DMAChannelRegister { pub ccr: Register, pub cndtr: Register, pub cpar: Register, pub cmar: Register, pub res: Register, } pub enum Prior...
#![allow(dead_code)] use super::common; use super::common::{Register}; use ::core::ptr::{write_volatile, read_volatile}; pub struct DMAChannelRegister { pub ccr: Register, pub cndtr: Register, pub cpar: Register, pub cmar: Register, pub res: Register, } pub enum Prior...
pub fn get_buffer(&mut self) -> &mut [u8] { match self.buffer { Some(ref mut x) => return x, None => panic!(), } } pub fn write(&mut self, val:u8) { while (self.end_write + 1 % self.get_buffer().len() as u32) == self.start { } self...
pub fn get_channel(&mut self) -> &mut DMAChannelRegister { match self.channel { Some(ref mut x) => return x, None => panic!() } }
function_block-function_prefix_line
[ { "content": "pub fn set(old : u32, bit : u32) -> u32 {\n\n return old | (1u32 << bit);\n\n}\n\n\n", "file_path": "src/common.rs", "rank": 0, "score": 98087.954220246 }, { "content": "pub fn clear(old : u32, bit : u32) -> u32 {\n\n return old & !(1u32 << bit);\n\n}\n\n\n\n#[macro_expor...
Rust
nimble/src/decode.rs
devashishdxt/nimble
1e49086ee7a0166369c467f0488a465ec9d3388a
use core::{ convert::TryFrom, hash::{BuildHasher, Hash}, marker::PhantomData, num::{ NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, }, }; use std::{ borrow::Cow, collections::...
use core::{ convert::TryFrom, hash::{BuildHasher, Hash}, marker::PhantomData, num::{ NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, }, }; use std::{ borrow::Cow, collections::...
} macro_rules! impl_seq { ( $ty: ident < T $(: $tbound1: ident $(+ $tbound2: ident)*)* $(, $typaram: ident : $bound1: ident $(+ $bound2: ident)*)* >, $len: ident, $create: expr, $insert: expr ) => { #[async_trait] impl<T $(, $typaram)*> Decode for $ty<T $(, $typ...
1 => E::decode_from(config, &mut reader).await.map(Err), _ => Err(Error::InvalidEnumVariant(option.into())), } }
function_block-function_prefix_line
[ { "content": "/// Returns default `Config`\n\npub fn config<'a>() -> &'a Config {\n\n &DEFAULT_CONFIG\n\n}\n\n\n\n/// Encodes a value in a `Vec` using default configuration\n\n#[inline]\n\npub async fn encode<E: Encode + ?Sized>(value: &E) -> Vec<u8> {\n\n DEFAULT_CONFIG.encode(value).await\n\n}\n\n\n\n//...
Rust
src/libstd/sys/windows/os.rs
rustyrazorblade/rust
f11f3e7baeba3f5acf08cc6fbfee559c00e9f96e
use prelude::v1::*; use fmt; use io::{IoResult, IoError}; use iter::repeat; use libc::{c_int, c_void}; use libc; use os; use path::BytesContainer; use ptr; use slice; use sys::fs::FileDesc; use os::TMPBUF_SZ; use libc::types::os::arch::extra::DWORD; const BUF_BYTES : uint = 2048u; pub fn truncate_utf16_at_nul<'a>...
use prelude::v1::*; use fmt; use io::{IoResult, IoError}; use iter::repeat; use libc::{c_int, c_void}; use libc; use os; use path::BytesContainer; use ptr; use slice; use sys::fs::FileDesc; use os::TMPBUF_SZ; use libc::types::os::arch::extra::DWORD; const BUF_BYTES : uint = 2048u; pub fn truncate_utf16_at_nul<'a>...
libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL) { true => Ok(()), false => Err(IoError::last_error()), } } } pub fn page_size() -> uint { use mem; unsafe { let mut info = mem::zeroed(); libc::GetSystemInfo(&mut info); return info.dwPageS...
wd) => Ok(Path::new(cwd)), Err(..) => Err(IoError { kind: OtherIoError, desc: "GetCurrentDirectoryW returned invalid UTF-16", detail: None, }), } } pub unsafe fn get_env_pairs() -> Vec<Vec<u8>> { use libc::funcs::extra::kernel32::{ GetEnvironmentStrin...
random
[ { "content": "/// Return the string corresponding to an `errno()` value of `errnum`.\n\n///\n\n/// # Example\n\n/// ```rust\n\n/// use std::os;\n\n///\n\n/// // Same as println!(\"{}\", last_os_error());\n\n/// println!(\"{}\", os::error_string(os::errno() as uint));\n\n/// ```\n\npub fn error_string(errnum: ui...
Rust
src/io/mod.rs
planet-s/tokio-core
dc5bc5253562d6df217db05262ca08052407b276
#![deprecated(note = "moved to the `tokio-io` crate")] #![allow(deprecated)] use std::io; use futures::{Async, Poll}; use futures::future::BoxFuture; use futures::stream::BoxStream; use iovec::IoVec; pub type IoFuture<T> = BoxFuture<T, io::Error>; pub type IoStream<T> = BoxStream<T, io::Error>; #[macro_export] m...
#![deprecated(note = "moved to the `tokio-io` crate")] #![allow(deprecated)] use std::io; use futures::{Async, Poll}; use futures::future::BoxFuture; use futures::stream::BoxStream; use iovec::IoVec; pub type IoFuture<T> = BoxFuture<T, io::Error>; pub type IoStream<T> = BoxStream<T, io::Error>; #[macro_export] m...
fn framed<C: Codec>(self, codec: C) -> Framed<Self, C> where Self: Sized, { frame::framed(self, codec) } fn split(self) -> (ReadHalf<Self>, WriteHalf<Self>) where Self: Sized { split::split(self) } } #[doc(hidden)] #[deprecated(since =...
d::{read_to_end, ReadToEnd}; pub use self::read::{read, Read}; pub use self::read_until::{read_until, ReadUntil}; pub use self::split::{ReadHalf, WriteHalf}; pub use self::window::Window; pub use self::write_all::{write_all, WriteAll}; pub trait Io: io::Read + io::Write { ...
random
[ { "content": "/// Encoding and decoding of frames via buffers.\n\n///\n\n/// This trait is used when constructing an instance of `Framed`. It provides\n\n/// two types: `In`, for decoded input frames, and `Out`, for outgoing frames\n\n/// that need to be encoded. It also provides methods to actually perform the...
Rust
src/main.rs
Dhghomon/demian-tool
15cc3fc69c160a609e9069d1813b2a04e481279a
use std::collections::VecDeque; use std::{fs, mem}; use std::io::{Write, BufWriter}; use ansi_term::Colour::{Cyan, Red}; use crossterm::{event::*, queue, terminal::*}; #[derive(Debug)] struct Content { english: VecDeque<VecDeque<String>>, german: VecDeque<VecDeque<String>>, current_work: (VecDeque<String...
use std::collections::VecDeque; use std::{fs, mem}; use std::io::{Write, BufWriter}; use ansi_term::Colour::{Cyan, Red}; use crossterm::{event::*, queue, terminal::*}; #[derive(Debug)] struct Content { english: VecDeque<VecDeque<String>>, german: VecDeque<VecDeque<String>>, current_work: (VecDeque<String...
content.up(); } #[rustfmt::skip] Delete => { while let Some(word) = content.ready_to_insert.0.pop() { content.current_work.0.push_front(word); } while let Some(word)...
function_block-function_prefix_line
[ { "content": "This tool is just a little thing I put together to speed up the reformatting of my interlinear translation of the book Demian from German to English. The book has been [available since 2012](https://www.lulu.com/shop/hermann-hesse-and-david-macleod/demian-an-interlinear-translation/paperback/produ...
Rust
chain/client/src/lib.rs
sunshine-protocol/sunshine-keybase
c9b21a14328d110a5bab71be1113f5d1b62ba442
pub mod error; mod subxt; pub use subxt::*; use crate::error::{AddAuthority, AuthorBlock, CreateChain, RemoveAuthority}; use core::marker::PhantomData; use libipld::alias; use libipld::block::Block; use libipld::cid::Cid; use libipld::store::{dyn_alias, Store, StoreParams}; use parity_scale_codec::{Decode, Encode}; u...
pub mod error; mod subxt; pub use subxt::*; use crate::error::{AddAuthority, AuthorBlock, CreateChain, RemoveAuthority}; use core::marker::PhantomData; use libipld::alias; use libipld::block::Block; use libipld::cid::Cid; use libipld::store::{dyn_alias, Store, StoreParams}; use parity_scale_codec::{Decode, Encode}; u...
} struct NewBlockSubscription<R: Runtime + Chain> { sub: ChainEventSubscription<R, NewBlockEvent<R>>, chain_id: R::ChainId, next: R::Number, } impl<R: Runtime + Chain> NewBlockSubscription<R> { async fn subscribe( client: &substrate_subxt::Client<R>, chain_id: R::ChainId, star...
async fn next(&mut self) -> Option<Result<E>> { match self.subscription.next().await { Some(Ok(raw)) => Some(E::decode(&mut &raw.data[..]).map_err(Into::into)), Some(Err(err)) => Some(Err(err.into())), None => None, } }
function_block-full_function
[ { "content": "pub fn cli_instructions() -> String {\n\n format!(\n\n include_str!(\"../github-proof-instructions.md\"),\n\n gist_name = GIST_NAME,\n\n )\n\n}\n", "file_path": "identity/client/src/github.rs", "rank": 2, "score": 136907.81000238756 }, { "content": "#[module...
Rust
examples_readme/src/lib.rs
jakoschiko/dicetest
93397c87bd97c4688315e0d31ac0a1529cf8c2aa
#![allow(dead_code)] #![allow(unused_variables)] mod section_example { fn bubble_sort<T: Ord>(slice: &mut [T]) { let len = slice.len(); for _ in 0..len { for j in 1..len - 1 { let jpp = j + 1; if slice[j] > slice[jpp] { slice.swap(j, ...
#![allow(dead_code)] #![allow(unused_variables)] mod section_example { fn bubble_sort<T: Ord>(slice: &mut [T]) { let len = slice.len(); for _ in 0..len { for j in 1..len - 1 { let jpp = j + 1; if slice[j] > slice[jpp] { slice.swap(j, ...
let up_to_ten_bytes_die = dice::vec(dice::u8(..), ..=10); struct WrappedByte(u8); let wrapped_byte_die = dice::u8(..).map(WrappedByte); let permutation_die = dice::length(0..).flat_map(|n| { let vec = (0..=n).collect::<Vec<_>>(); dice...
t loaded_die = dice::weighted_one_of().six::<u8>((1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 6)); let die_from_fn = dice::from_fn(|_| 42); let foo_die = dice::just("foo".to_string()); let byte_die = dice::u8(..); let non_zero_byte_die =...
random
[ { "content": "/// Runs the test once with the given configuration.\n\n///\n\n/// If the test panics the error will be caught and added to the report.\n\npub fn run<T>(mut prng: Prng, config: &Config, test: T) -> Report\n\nwhere\n\n T: FnOnce(Fate) + UnwindSafe,\n\n{\n\n let ((test_result, hints), stats) =...
Rust
src/middleware/errhandlers.rs
wilhg/actix-web2
53c1b578de3c984bff54067f1ac51db60056b867
use hashbrown::hash_map::HashMap; use std::rc::Rc; use futures::{Async, Future, Poll}; use actix_http::error::Result; use actix_http::{Response, http::StatusCode}; use actix_service::{IntoNewTransform, Service, Transform}; use crate::service::ServiceRequest; use crate::middleware::MiddlewareFactory; type ErrorHandle...
use hashbrown::hash_map::HashMap; use std::rc::Rc; use futures::{Async, Future, Poll}; use actix_http::error::Result; use actix_http::{Response, http::StatusCode}; use actix_service::{IntoNewTransform, Service, Transform}; use crate::service::ServiceRequest; use crate::middleware::MiddlewareFactory; type ErrorHandle...
} #[cfg(test)] mod tests { use super::*; use error::{Error, ErrorInternalServerError}; use http::header::CONTENT_TYPE; use http::StatusCode; use httpmessage::HttpMessage; use middleware::Started; use test::{self, TestRequest}; fn render_500<P>(_: &ServiceRequest<P>, resp: Response) ->...
fn call(&mut self, req: ServiceRequest<P>, srv: &mut S) -> Self::Future { let x = srv.call(req).map(move |mut resp| { if let Some(handler) = self.handlers.get(&resp.status()) { handler(&req, resp) } else { Ok(resp) } }); unimple...
function_block-full_function
[ { "content": "struct HttpNewService<P: 'static, T: NewService<Request = ServiceRequest<P>>>(T);\n\n\n\nimpl<P, T> HttpNewService<P, T>\n\nwhere\n\n T: NewService<Request = ServiceRequest<P>, Response = ServiceResponse, Error = ()>,\n\n T::Future: 'static,\n\n <T::Service as Service>::Future: 'static,\n...
Rust
libsplinter/src/biome/rest_api/mod.rs
ltseeley/splinter
b4ba4f450a4d59f8e448efcacee89fd0a26cdc31
mod config; mod error; use std::sync::Arc; use crate::database::ConnectionPool; use crate::rest_api::{Resource, RestResourceProvider}; #[cfg(feature = "biome-key-management")] use super::key_management::{ rest_resources::make_key_management_route, store::postgres::PostgresKeyStore, }; use super::secrets::{Auto...
mod config; mod error; use std::sync::Arc; use crate::database::ConnectionPool; use crate::rest_api::{Resource, RestResourceProvider}; #[cfg(feature = "biome-key-management")] use super::key_management::{ rest_resources::make_key_management_route, store::postgres::PostgresKeyStore, }; use super::secrets::{Auto...
}
e => { debug!("Building BiomeRestResourceManager without credentials store"); None } }, }) }
function_block-function_prefixed
[ { "content": "#[cfg(feature = \"proposal-read\")]\n\npub fn make_list_proposals_resource<A: AdminCommands + Clone + 'static>(\n\n admin_commands: A,\n\n) -> Resource {\n\n Resource::build(\"admin/proposals\").add_method(Method::Get, move |r, _| {\n\n list_proposals(r, web::Data::new(admin_commands....
Rust
ocl-core/src/tests/depricated/test_events.rs
Henning-K/ocl
536580acdc1cd3cadb3c1dfe27bbe5ce3b563d89
use ffi::{cl_event, cl_int, c_void}; use standard::{ProgramBuilder, Buffer, SpatialDims, ProQue, EventList}; const PRINT_DEBUG: bool = false; struct TestEventsStuff { seed_env: *const Buffer<u32>, res_env: *const Buffer<u32>, data_set_size: usize, addend: u32, itr: usize, } extern fn _test_event...
use ffi::{cl_event, cl_int, c_void}; use standard::{ProgramBuilder, Buffer, SpatialDims, ProQue, EventList}; const PRINT_DEBUG: bool = false; struct TestEventsStuff { seed_env: *const Buffer<u32>, res_env: *const Buffer<u32>, data_set_size: usize, addend: u32, itr: usize, } extern fn _test_event...
if PRINT_DEBUG { println!("Enqueuing read buffer [itr:{}]...", itr); } unsafe { result_buffer.enqueue_fill_vec(false, None, Some(&mut read_event)).unwrap(); } let last_idx = buncha_stuffs.len() - 1; unsafe { if PRINT_DEBUG { println!("Setting callback (verify_result, buncha_stuff[{...
function_block-function_prefix_line
[ { "content": "fn kernel<V>(context: &Context, src: &str, buffer: &Mem, addend: V) -> Kernel\n\n where V: OclVec\n\n{\n\n // Create program:\n\n let src_cstring = CString::new(src).unwrap();\n\n let program = crate::create_program_with_source(context, &[src_cstring]).unwrap();\n\n crate::build...
Rust
src/engine.rs
Arthamys/pay-engine
33a482810fa5bf18c61a4b675dcdba5be1083e67
use std::time::Instant; use crate::client::{Client, ClientWallets}; use crate::transaction::{Transaction, TransactionLog, Type::*}; pub fn run<S: Iterator>( transactions: &mut S, /*stream of transactions*/ ) -> (ClientWallets, TransactionLog) where S::Item: Into<Transaction>, { let mut tx_log = Transactio...
use std::time::Instant; use crate::client::{Client, ClientWallets}; use crate::transaction::{Transaction, TransactionLog, Type::*}; pub fn run<S: Iterator>( transactions: &mut S, /*stream of transactions*/ ) -> (ClientWallets, TransactionLog) where S::Item: Into<Transaction>, { let mut tx_log = Transactio...
"client {} tried to withdraw more than available balance", client.id() ); return false; } log::trace!("withdrew {} from client {}'s balance", amount, client.id()); true } fn dispute(client: &mut Client, tx: u32, tx_hist: &mut TransactionLog) -> bool { match tx_hist.fi...
ets, tx_log) } pub fn execute_transaction(t: &Transaction, tx_log: &mut TransactionLog, client: &mut Client) { let tx_exists = tx_log.contains(t.id); let record_op = match t.r#type { Deposit if !tx_exists => deposit(client, t.amount), Withdrawal if !tx_exists => withdraw(client, t.amount), ...
random
[ { "content": "/// get a trait object for our transactions\n\nfn get_transaction_stream(\n\n filepath: &Option<String>,\n\n) -> Result<Box<dyn Iterator<Item = Transaction>>> {\n\n if let Some(file) = filepath {\n\n match Parser::new(&file) {\n\n Ok(p) => return Ok(Box::new(p)),\n\n ...
Rust
src/overlayfs.rs
Icenowy/ciel-rs
6e0f2305f29505d9c735f234b1f450f193fa2ca7
use crate::common; use anyhow::{anyhow, Result}; use libmount::{mountinfo::Parser, Overlay}; use nix::mount::{umount2, MntFlags}; use std::fs; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; use std::path::{Path, PathBuf}; use std::process::Command; use std::{ ff...
use crate::common; use anyhow::{anyhow, Result}; use libmount::{mountinfo::Parser, Overlay}; use nix::mount::{umount2, MntFlags}; use std::fs; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; use std::path::{Path, PathBuf}; use std::process::Command; use std::{ ff...
} impl LayerManager for OverlayFS { fn name() -> String where Self: Sized, { "overlay".to_owned() } fn from_inst_dir<P: AsRef<Path>>( dist_path: P, inst_path: P, inst_name: P, ) -> Result<Box<dyn LayerManager>> where ...
fn diff(&self) -> Result<Vec<Diff>> { let mut mods: Vec<Diff> = Vec::new(); let mut processed_dirs: Vec<PathBuf> = Vec::new(); for entry in walkdir::WalkDir::new(&self.upper).into_iter().skip(1) { let path: PathBuf = entry?.path().to_path_buf(); let rel_path...
function_block-full_function
[ { "content": "/// Get the container name (ns_name) of the instance\n\npub fn get_container_ns_name<P: AsRef<Path>>(path: P, legacy: bool) -> Result<String> {\n\n let current_dir = std::env::current_dir()?;\n\n let path = current_dir.join(path);\n\n if legacy {\n\n warn!(\"You are working in a le...
Rust
linkerd/stack/src/switch_ready.rs
JcdeA/linkerd2-proxy
8628541f5a2fc79067434f426b1f4fbc07b29d32
use super::NewService; use linkerd_error::Error; use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use tokio::time; use tower::util::Either; use tracing::{debug, trace}; #[derive(Debug)] pub struct SwitchReady<A, B> { primary: A, secondary: B, switch_after: time::Duration, slee...
use super::NewService; use linkerd_error::Error; use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use tokio::time; use tower::util::Either; use tracing::{debug, trace}; #[derive(Debug)] pub struct SwitchReady<A, B> { primary: A, secondary: B, switch_after: time::Duration, slee...
, }, State::Secondary => match self.primary.poll_ready(cx).map_err(Into::into) { Poll::Ready(ready) => { debug!(?ready, "Reverting to primary service"); self.state = St...
match self.primary.poll_ready(cx).map_err(Into::into) { Poll::Ready(ready) => { trace!(?ready, "Primary service became ready"); self.state = State::Primary; return Poll::Ready(ready); } ...
if_condition
[ { "content": "pub fn layer<M, N: Clone, R>(\n\n new_route: N,\n\n) -> impl layer::Layer<M, Service = NewRouteRequest<M, N, R>> {\n\n // This is saved so that the same `Arc`s are used and cloned instead of\n\n // calling `Route::default()` every time.\n\n let default = Route::default();\n\n layer:...
Rust
src/resp.rs
przygienda/rust-http2
ebad371307245b0add9ddd9bfb125d553081ffc3
use futures::future; use futures::future::Future; use futures::stream; use futures::stream::Stream; use bytes::Bytes; use message::SimpleHttpMessage; use solicit::header::Headers; use solicit_async::*; use error::Error; use data_or_headers::DataOrHeaders; use data_or_headers_with_flag::DataOrHeadersWithFlag; use da...
use futures::future; use futures::future::Future; use futures::stream; use futures::stream::Stream; use bytes::Bytes; use message::SimpleHttpMessage; use solicit::header::Headers; use solicit_async::*; use error::Error; use data_or_headers::DataOrHeaders; use data_or_headers_with_flag::DataOrHeadersWithFlag; use da...
, None => Err(Error::InvalidFrame( "empty response, expecting headers".to_owned(), )), }, )) } pub fn err(err: Error) -> Response { Response::new(future::err(err)) } pub fn into_stream_flag(self) -> HttpFutureStreamS...
match part.content { DataOrHeaders::Headers(headers) => { Ok((headers, HttpStreamAfterHeaders::from_parts(rem))) } DataOrHeaders::Data(..) => { Err(Error::InvalidFrame("data before headers".to_owned())) ...
if_condition
[ { "content": "pub fn send_frame<W: AsyncWrite + Send + 'static, F: FrameIR>(\n\n write: W,\n\n frame: F,\n\n) -> impl Future<Item = W, Error = error::Error> {\n\n let buf = frame.serialize_into_vec();\n\n debug!(\n\n \"send frame {}\",\n\n RawFrameRef { raw_content: &buf }.frame_type()...
Rust
i2c-testsuite/tests/test.rs
munin-space/stm32wl-hal
6e7fae62c2beb7838a28e34cfef9aeaed8821fdb
#![no_std] #![no_main] use defmt::unwrap; use defmt_rtt as _; use embedded_time::rate::Hertz; use panic_probe as _; use stm32wl_hal::{ cortex_m, embedded_hal::blocking::i2c::WriteRead, gpio::{pins, PortA, PortB}, i2c::{I2c1, I2c2}, pac::{self, interrupt}, rcc, }; const LOOPBACK_ADDR: u8 = 0x7...
#![no_std] #![no_main] use defmt::unwrap; use defmt_rtt as _; use embedded_time::rate::Hertz; use panic_probe as _; use stm32wl_hal::{ cortex_m, embedded_hal::blocking::i2c::WriteRead, gpio::{pins, PortA, PortB}, i2c::{I2c1, I2c2}, pac::{self, interrupt}, rcc, }; const LOOPBACK_ADDR: u8 = 0x7...
#[test] fn loopback(i2c: &mut I2c1<(pins::B8, pins::B7)>) { defmt::warn!("I2C1 pins B8 (SCL) and B7 (SDA) must be connected to I2C pins A12 (SCL) and A11 (SDA) for this test to pass"); let cmd: [u8; 1] = [LOOPBACK_DATA_IN]; let mut response: [u8; 1] = [0; 1]; let result = i2c...
ork"); let cmd: [u8; 2] = [0x2C, 0x06]; let mut response: [u8; 6] = [0; 6]; let result = i2c.write_read(0x44, &cmd, &mut response); match result { Ok(()) => defmt::info!("Bytes received: {:x}", response), Err(e) => defmt::error!("I2C error: {}", e), } ...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn enable_lsi(rcc: &mut pac::RCC) {\n\n rcc.csr.modify(|_, w| w.lsion().on());\n\n while rcc.csr.read().lsirdy().is_not_ready() {}\n\n}\n\n\n\n/// Reset the backup domain.\n\n///\n\n/// # Safety\n\n///\n\n/// 1. This will disable the LSE clock.\n\n/// Ensure no peripheral...
Rust
src/iter.rs
mov-rax/smart_buffer
1ab3f45f1c2021d0cd5e87f25852a24dc569e40c
use crate::SmartBuffer; use core::mem::size_of; use alloc::alloc::{dealloc}; use crate::__core::iter::Map; impl<T, const N: usize> IntoIterator for SmartBuffer<T,N> where T: Clone { type Item = T; type IntoIter = SmartBufferIter<T,N>; fn into_iter(mut self) -> Self::IntoIter { let stack_p...
use crate::SmartBuffer; use core::mem::size_of; use alloc::alloc::{dealloc}; use crate::__core::iter::Map; impl<T, const N: usize> IntoIterator for SmartBuffer<T,N> where T: Clone { type Item = T; type IntoIter = SmartBufferIter<T,N>; fn into_iter(mut self) -> Self::IntoIter { let stack_p...
}
self.count += 1; return unsafe {Some(&mut *((self.stack_ptr as usize + (self.count - 1) * size_of::<T>()) as *mut T))} } self.count += 1; return unsafe {Some(&mut *((self.heap_ptr.unwrap() as usize + (self.count - N - 1) * size_of::<T>()) as *mut T))} } ...
function_block-function_prefixed
[ { "content": "use crate::SmartBuffer;\n\nuse core::ops::Index;\n\nuse core::ops::IndexMut;\n\n\n\n\n\nimpl<T, const N:usize> Index<usize> for &SmartBuffer<T,N>\n\n where T: Clone\n\n{\n\n type Output = T;\n\n\n\n fn index(&self, index: usize) -> &Self::Output {\n\n unsafe {self.get_unchecked(ind...
Rust
src/collector/streamer.rs
Kenec/pipe
85e2b2a3d3035c5caae009f20e3e9235f4032b73
use crate::config::Config; use crate::ConfigPath; use async_std::channel; use async_std::fs::File; use async_std::io::prelude::BufReadExt; use async_std::io::BufReader; use async_std::task; use chrono::{DateTime, Utc}; use serde_json::json; use std::collections::HashMap; use std::path::PathBuf; use std::string::String;...
use crate::config::Config; use crate::ConfigPath; use async_std::channel; use async_std::fs::File; use async_std::io::prelude::BufReadExt; use async_std::io::BufReader; use async_std::task; use chrono::{DateTime, Utc}; use serde_json::json; use std::collections::HashMap; use std::path::PathBuf; use std::string::String;...
from_secs(1)).await; } } } }
{}/logs", destination_url, line.1.to_string()); eprintln!("{}", data); let res = reqwest::Client::new().post(url).json(&data).send().await; if let Err(e) = res { println!("Error {}", e) } ...
random
[ { "content": "struct Pipe {\n\n #[structopt(subcommand)]\n\n cmd: Command,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 4, "score": 20785.8346571162 }, { "content": "use crate::collector::streamer::Streamer;\n\nuse crate::validator::file_validator::file_path_validator;\n\nuse env_l...
Rust
src/game/runner.rs
Dream-Imperium/tachibana
4d55d25ef8aed3ee3b2947c64e7dd984ac411c98
use core::fmt::{Display, Formatter, Result as FmtResult}; use std::error::Error as StdError; use std::sync::mpsc::{sync_channel, SyncSender, TryRecvError, TrySendError}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use std::{cell::RefCell, sync::mpsc::Receiver}; use skulpin_renderer::{ash, Logi...
use core::fmt::{Display, Formatter, Result as FmtResult}; use std::error::Error as StdError; use std::sync::mpsc::{sync_channel, SyncSender, TryRecvError, TrySendError}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use std::{cell::RefCell, sync::mpsc::Receiver}; use skulpin_renderer::{ash, Logi...
} } Event::Crash(e) => { game.crash(e); feedback_tx .send(FeedbackEvent::Exit) .expect("Failed to send feedback event to draw thread"); return true; } } false ...
match r { EventHandleResult::Input(event) => game.input(event), EventHandleResult::Resized(size) => { game.set_size(Size::new(size.width, size.height)) } EventHandleResult::Exit => { ...
if_condition
[ { "content": "pub trait Game: 'static + Send {\n\n fn update(&mut self);\n\n fn draw(&mut self, canvas: &mut crate::skia::Canvas);\n\n fn set_size(&mut self, size: crate::skia::Size);\n\n fn input(&mut self, event: InputEvent);\n\n fn close(&mut self);\n\n fn crash(&mut self, err: runner::Erro...
Rust
src/stm32l0/peripherals/dbg.rs
adamgreig/stm32ral
d316aaad753fd427b1d9fe641ca9611f5f20053c
#![allow(non_snake_case, non_upper_case_globals)] #![allow(non_camel_case_types)] use crate::{RORegister, RWRegister}; #[cfg(not(feature = "nosync"))] use core::marker::PhantomData; pub mod IDCODE { pub mod DEV_ID { pub const offset: u32 = 0; pub const mask: u32 = 0xfff << ...
#![allow(non_snake_case, non_upper_case_globals)] #![allow(non_camel_case_types)] use crate::{RORegister, RWRegister}; #[cfg(not(feature = "nosync"))] use core::marker::PhantomData; pub mod IDCODE { pub mod DEV_ID { pub const offset: u32 = 0; pub const mask: u32 = 0xfff << ...
pub mod R {} pub mod W {} pub mod RW { pub const Continue: u32 = 0b0; pub const Stop: u32 = 0b1; } } pub mod DBG_WWDG_STOP { pub const offset: u32 = 11; pub const mas...
pub const Disabled: u32 = 0b0; pub const Enabled: u32 = 0b1; } } pub mod DBG_STANDBY { pub const offset: u32 = 2; pub const mask: u32 = 1 << offset; pub mod R {} pub mod W {} pub...
random
[ { "content": "#[cfg(any(feature=\"stm32g051\", feature=\"doc\"))]\n\npub mod stm32g051;\n\n\n\n#[cfg(any(feature=\"stm32g061\", feature=\"doc\"))]\n\npub mod stm32g061;\n\n\n\n#[cfg(any(feature=\"stm32g070\", feature=\"doc\"))]\n\npub mod stm32g070;\n\n\n\n#[cfg(any(feature=\"stm32g071\", feature=\"doc\"))]\n\n...
Rust
src/common/priority_queue.rs
zg9uagfv/Algorithm
ff0dcced85821ba0fd8925a3ddccf110ca38067b
use std::cmp::Ordering; type Comparator<T> = Box<dyn Fn(&T, &T) -> bool>; pub struct PQ<T> { pq: Vec<T>, n: usize, comparator: Comparator<T>, } pub struct IndexPQ<T> { n: usize, pq: Vec<i32>, qp: Vec<i32>, keys: Vec<Option<T>>, comparator: Comparator<Option<T>>, } impl<T...
use std::cmp::Ordering; type Comparator<T> = Box<dyn Fn(&T, &T) -> bool>; pub struct PQ<T> { pq: Vec<T>, n: usize, comparator: Comparator<T>, } pub struct IndexPQ<T> { n: usize, pq: Vec<i32>, qp: Vec<i32>, keys: Vec<Option<T>>, comparator: Comparator<Option<T>>, } impl<T...
f.keys[self.pq[i] as usize], &self.keys[self.pq[j] as usize], ) } fn exch(&mut self, i: usize, j: usize) { self.pq.swap(i, j); self.qp.swap(self.pq[i] as usize, self.pq[j] as usize); } }
ke(); self.pq[self.n + 1] = -1; Some(min) } } pub fn decrease_key(&mut self, i: usize, key: T) -> Result<(), &'static str> { if !self.contains(i) { Err("index is not in the priority queue") } else { match self.keys[i].partial_cmp(&Some(key...
random
[ { "content": "pub fn heapify<K>(keys: &mut [K], mut i: usize)\n\nwhere\n\n K: Ord,\n\n{\n\n let n = keys.len();\n\n loop {\n\n let l = left!(i);\n\n let r = right!(i);\n\n let mut m = i;\n\n\n\n if let Some(v) = keys.get(l) {\n\n if l < n && v >= &keys[m] {\n\n ...
Rust
src/document/time/ticket.rs
blurfx/yorkie-rust-sdk
be9175c9ef4bb0b8ed36c8f0ac95162f109c411e
use crate::document::time::actor_id::ActorID; use std::cmp::Ordering; use std::{u32, u64}; const MAX_LAMPORT: u64 = u64::MAX; const MAX_DELIMITER: u32 = u32::MAX; struct Ticket { lamport: u64, delimiter: u32, actor_id: ActorID, } impl Ticket { pub fn new(lamport: u64, delimiter: u32, actor_id: ActorI...
use crate::document::time::actor_id::ActorID; use std::cmp::Ordering; use std::{u32, u64}; const MAX_LAMPORT: u64 = u64::MAX; const MAX_DELIMITER: u32 = u32::MAX; struct Ticket { lamport: u64, delimiter: u32, actor_id: ActorID, } impl Ticket { pub fn new(lamport: u64, delimiter: u32, actor_id: ActorI...
}
let after_ticket = Ticket::new(1, 0, actor_id.clone()); assert!(!before_ticket.after(&after_ticket)); assert!(after_ticket.after(&before_ticket)); }
function_block-function_prefix_line
[ { "content": "#[cfg(test)]\n\nmod tests {\n\n use yorkie::{Client, ClientOptions};\n\n\n\n fn init_logger() {\n\n let _ = env_logger::builder().is_test(true).try_init();\n\n }\n\n\n\n #[tokio::test]\n\n async fn client_with_new() {\n\n init_logger();\n\n let mut cli = Client:...
Rust
src/config.rs
fastgitorg/fgit-rs
1a64b56637f598323b61bd39ae4cf04fc752a2c1
extern crate ini; use ini::Ini; use regex::Regex; use std::error::Error; use std::path::Path; use std::process; pub struct RemoteUrl { pub protocol: GitProtocol, pub base: GitSrc, pub repo: String, } impl RemoteUrl { pub fn to_url(&self) -> String { match self.protocol { GitProtoco...
extern crate ini; use ini::Ini; use regex::Regex; use std::error::Error; use std::path::Path; use std::process; pub struct RemoteUrl { pub protocol: GitProtocol, pub base: GitSrc, pub repo: String, } impl RemoteUrl { pub fn to_url(&self) -> String { match self.protocol { GitProtoco...
self { GitSrc::FastGit => "fastgit.org", GitSrc::GitHub => "github.com", } } } pub enum GitProtocol { HTTPS, SSH, } impl std::fmt::Display for GitSrc { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = match self { GitSrc:...
let repo_re = Regex::new(r":(.*)").unwrap(); let repo_got = repo_re.captures(url).unwrap().get(1).unwrap().as_str(); Ok(RemoteUrl { protocol: GitProtocol::SSH, base: b, repo: repo_got.to_string(), }) } else { ...
random
[ { "content": "pub fn replace_url(url: &str) -> Result<String, Box<dyn Error>> {\n\n let re = Regex::new(r\"https://(.*?)/\").unwrap();\n\n\n\n let base_url = re.captures(url).unwrap().get(1).unwrap().as_str();\n\n\n\n let url = match base_url {\n\n \"codeload.github.com\" => url.replace(\"codelo...
Rust
noodles-tabix/src/index/reference_sequence/builder.rs
veldsla/noodles
ac2916c6c4c547a266da3313e391a2991e2a8642
use std::{cmp, collections::HashMap, io}; use noodles_bgzf as bgzf; use noodles_core::Position; use noodles_csi::index::reference_sequence::bin::Chunk; use super::{bin, Bin, Metadata, ReferenceSequence, WINDOW_SIZE}; #[derive(Debug, Default)] pub struct Builder { bin_builders: HashMap<u32, bin::Builder>, int...
use std::{cmp, collections::HashMap, io}; use noodles_bgzf as bgzf; use noodles_core::Position; use noodles_csi::index::reference_sequence::bin::Chunk; use super::{bin, Bin, Metadata, ReferenceSequence, WINDOW_SIZE}; #[derive(Debug, Default)] pub struct Builder { bin_builders: HashMap<u32, bin::Builder>, int...
fn update_linear_index(&mut self, start: Position, end: Position, chunk: Chunk) { let linear_index_start_offset = (usize::from(start) - 1) / WINDOW_SIZE; let linear_index_end_offset = (usize::from(end) - 1) / WINDOW_SIZE; if linear_index_end_offset >= self.intervals.len() { se...
fn update_bins(&mut self, start: Position, end: Position, chunk: Chunk) { let bin_id = region_to_bin(start, end).unwrap() as u32; let builder = self.bin_builders.entry(bin_id).or_insert_with(|| { let mut builder = Bin::builder(); builder.set_id(bin_id); builder ...
function_block-full_function
[ { "content": "/// Optimizes a list of chunks into a list of non-overlapping chunks.\n\n///\n\n/// Unlike [`merge_chunks`], `min_offset` (typically from the linear index) is given to remove\n\n/// chunks that cannot be in the query.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use noodles_bgzf as bgzf;\n\n/...
Rust
brine/src/mir.rs
MattX/saltwater
8bdda49eb5e354b07ddb1c4f71d600748306b1ef
use itertools::Itertools; use lexpr::{Number, Value}; use saltwater_parser::get_str; use saltwater_parser::InternedStr; use serde::de::Visitor; use serde::export::Formatter; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_lexpr::{from_str, to_string}; use std::convert::TryFrom; #[derive(Debu...
use itertools::Itertools; use lexpr::{Number, Value}; use saltwater_parser::get_str; use saltwater_parser::InternedStr; use serde::de::Visitor; use serde::export::Formatter; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_lexpr::{from_str, to_string}; use std::convert::TryFrom; #[derive(Debu...
}, MirExpr::Ref(r) => Value::symbol(r.to_string()), MirExpr::Comment(comment, body) => { Value::list(vec![Value::string(comment.clone()), mir_to_lexpr(body)]) } } } pub fn parse_mir(s: &str) -> Result<MirExpr, String> { lexpr_to_mir(lexpr::from_str(s).map_err(|e| format...
e )) } }; MirExpr::Comment(comment, Box::new(body)) } _ => return Err(format!("unknown keyword: {}", kw)), }) } pub fn mir_to_lexpr(expr: &MirExpr) -> lexpr::Value { match expr { MirExpr::Let(l) => Value...
random
[ { "content": "fn write_struct_type(struct_type: &StructType, f: &mut Formatter) -> fmt::Result {\n\n match struct_type {\n\n StructType::Named(name, _) => {\n\n write!(f, \"{}\", name)?;\n\n }\n\n StructType::Anonymous(members) => {\n\n writeln!(f, \"{{\")?;\n\n ...
Rust
src/backend/jack_backend.rs
mgeier/rsynth
c4b75691f8d4b74c75d1660ba2f868390251fd5e
use crate::backend::{HostInterface, Stop}; use crate::buffer::AudioBufferInOut; use crate::event::{ ContextualEventHandler, EventHandler, Indexed, RawMidiEvent, SysExEvent, Timed, }; use crate::{ AudioHandler, CommonAudioPortMeta, CommonMidiPortMeta, CommonPluginMeta, ContextualAudioRenderer, }; use core:...
use crate::backend::{HostInterface, Stop}; use crate::buffer::AudioBufferInOut; use crate::event::{ ContextualEventHandler, EventHandler, Indexed, RawMidiEvent, SysExEvent, Timed, }; use crate::{ AudioHandler, CommonAudioPortMeta, CommonMidiPortMeta, CommonPluginMeta, ContextualAudioRenderer, }; use core:...
}; Self::handle_events( &self.midi_in_ports, &mut self.plugin, process_scope, &mut jack_host, ); let mut inputs = self.inputs.vec_guard(); for i in 0..cmp::min(self.audio_in_ports.len(), inputs.capacity()) { inputs.push(s...
idi_out_ports::<P>(&client, &plugin); let inputs = VecStorage::with_capacity(plugin.max_number_of_audio_inputs()); let outputs = VecStorage::with_capacity(plugin.max_number_of_audio_outputs()); let midi_writer = VecStorage::with_capacity(plugin.max_number_of_midi_outputs()); JackProce...
random
[ { "content": "/// Run an audio renderer with the given audio input, audio output, midi input and midi output.\n\n///\n\n/// Parameters\n\n/// ==========\n\n/// * `buffer_size_in_frames`: the buffer size in frames.\n\n///\n\n/// Panics\n\n/// ======\n\n/// Panics if `buffer_size_in_frames` is `0` or `> u32::MAX`...
Rust
src/strategies/ifunctions.rs
snigavik/bootfrost
b5e41ac38a12c293a08d71bf83c127a344b5115b
use crate::term::*; use crate::answer::*; use crate::misc::*; use crate::solver::*; use crate::strategies::environment::*; use crate::strategies::attributes::*; use crate::strategies::strategies::Strategy; use std::fs; use std::collections::HashMap; type IFunction = fn(&Vec<TermId>, &mut PEnv) -> TermId; fn plus(a:i...
use crate::term::*; use crate::answer::*; use crate::misc::*; use crate::solver::*; use crate::strategies::environment::*; use crate::strategies::attributes::*; use crate::strategies::strategies::Strategy; use std::fs; use std::collections::HashMap; type IFunction = fn(&Vec<TermId>, &mut PEnv) -> TermId; fn plus(a:i...
(ifunction_binary_integers!(gt, bool) as IFunction, Position::Infix)), ("<=".to_string(), (ifunction_binary_integers!(lteq, bool) as IFunction, Position::Infix)), (">=".to_string(), (ifunction_binary_integers!(gteq, bool) as IFunction, Position::Infix)), ("++".to_string(), (concat as IFunction, Position::Infix)),...
if args.len() != 1{ panic!(""); } let arg0 = env.psterms.get_term(&args[0]); let i = if let Term::Integer(i) = arg0{ i }else{ panic!(""); }; let b = if let LogItem::Matching{batom_i: b, ..} = env.answer.log[i as usize]{ b }else{ panic!(""); }; env.attributes.set_attribute(KeyObject::BaseIndex(b),...
random
[ { "content": "pub fn processing(tid:TermId, context: &Context, answer1: Option<&Answer>, env: &mut PEnv) -> ProcessingResult{\n\n\tlet t = &env.psterms.get_term(&tid);\n\n\tmatch t{\n\n\t\tTerm::AVariable(..) => {\n\n\t\t\tif let Some(new_tid) = context.get(&tid){\n\n\t\t\t\tProcessingResult::Existing(*new_tid)...
Rust
src/policies.rs
jemstep/captain-git-hook
c8a3be444887eb7b462ec6942c715818acad13f8
pub mod policy_result; use crate::config::VerifyGitCommitsConfig; use crate::fs::*; use crate::git::*; use crate::gpg::*; use crate::keyring::*; use crate::reference_update::ReferenceUpdate; use self::policy_result::PolicyResult; use git2::Oid; use rayon::prelude::*; use std::collections::HashSet; use std::error::Er...
pub mod policy_result; use crate::config::VerifyGitCommitsConfig; use crate::fs::*; use crate::git::*; use crate::gpg::*; use crate::keyring::*; use crate::reference_update::ReferenceUpdate; use self::policy_result::PolicyResult; use git2::Oid; use rayon::prelude::*; use std::collections::HashSet; use std::error::Er...
fn verify_tag_logging_errors<G: Git>( repo_path: &std::path::Path, tag: &Tag, keyring: &Keyring, ) -> bool { match G::verify_tag_signature(repo_path, tag, keyring) { Ok(result) => result, Err(e) => { error!( "Technical error occurred while trying to validate...
ing)) .filter_map(|t| t.tagger_email.as_ref()) .collect::<HashSet<_>>(); if verified_taggers.len() >= required_tags.into() { info!("Override tags found for {}. Tags created by {:?}. This commit, and it's ancestors, do not require validation.", c.id, verified_...
function_block-function_prefixed
[ { "content": "pub fn pre_receive<G: Git, P: Gpg>(\n\n git: &G,\n\n gpg: P,\n\n config: &Config,\n\n old_value: &str,\n\n new_value: &str,\n\n ref_name: &str,\n\n) -> Result<PolicyResult, Box<dyn Error>> {\n\n let ref_update = ReferenceUpdate::from_git_hook_format(old_value, new_value, ref_n...
Rust
src/camera/sensor/pixel.rs
joeftiger/rust-v2
42676758f0845488fc81aa3fb57ffca00a83616f
use core::ops::{Div, Index, IndexMut, Mul}; use core::slice::SliceIndex; use serde::{Deserialize, Serialize}; use crate::{Float, Spectrum, UVec2, PACKET_SIZE}; use serde_big_array::BigArray; #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Pixel { pub position: UVec2, pub average: ...
use core::ops::{Div, Index, IndexMut, Mul}; use core::slice::SliceIndex; use serde::{Deserialize, Serialize}; use crate::{Float, Spectrum, UVec2, PACKET_SIZE}; use serde_big_array::BigArray; #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Pixel { pub position: UVec2, pub average: ...
}
fn div(mut self, rhs: SampleCounter) -> Self::Output { for i in 0..Spectrum::size() { self[i] /= rhs[i] as Float; } self }
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn approx_eq(a: Float, b: Float) -> bool {\n\n approx_eq_epsilon(a, b, EPSILON)\n\n}\n\n\n", "file_path": "src/util/floats.rs", "rank": 0, "score": 227001.75450774093 }, { "content": "pub fn approx_eq_epsilon(a: Float, b: Float, epsilon: Float) -> bool {\n\n...
Rust
src/moves.rs
wbrbr/chess
7258038485eb1123a7d54653d4b1bfde135882e7
use crate::{ board::{ Color, Piece, PieceType, FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H, RANK_1, RANK_2, RANK_4, RANK_8, }, game::{ CastlingRights, Game, BLACK_KINGSIDE, BLACK_QUEENSIDE, WHITE_KINGSIDE, WHITE_QUEENSIDE, }, square::Square, }; #[derive(Cl...
use crate::{ board::{ Color, Piece, PieceType, FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H, RANK_1, RANK_2, RANK_4, RANK_8, }, game::{ CastlingRights, Game, BLACK_KINGSIDE, BLACK_QUEENSIDE, WHITE_KINGSIDE, WHITE_QUEENSIDE, }, square::Square, }; #[derive(Cl...
fn enumerate_queen(game: &Game, color: Color, from: Square, moves: &mut Vec<Move>) { for i in -1..=1 { for j in -1..=1 { if i == 0 && j == 0 { continue; } enumerate_straight_line(game, color, from, moves, (i, j)); } } } fn enumerate_rook(gam...
color => break, Some(p) if p.color != color => { moves.push(Move::new(game, from, sq, None)); break; } None => moves.push(Move::new(game, from, sq, None)), Some(_) => unreachable!(), } i += 1; } }
function_block-function_prefixed
[ { "content": "pub fn piece_square_value(p: Piece, file: u8, rank: u8) -> i32 {\n\n let index = match p.color {\n\n Color::White => rank * 8 + file,\n\n Color::Black => (7 - rank) * 8 + file,\n\n } as usize;\n\n\n\n match p.typ {\n\n PieceType::Knight => KNIGHT_TABLE[index],\n\n ...
Rust
src/image.rs
aloucks/imgui-rs
b0e37f7a22f91a6c0851cd7e945fcd2367536b90
use std::marker::PhantomData; use std::os::raw::c_void; use crate::render::renderer::TextureId; use crate::sys; use crate::Ui; #[must_use] pub struct Image<'ui> { texture_id: TextureId, size: [f32; 2], uv0: [f32; 2], uv1: [f32; 2], tint_col: [f32; 4], border_col: [f32; 4], _phantom: Phanto...
use std::marker::PhantomData; use std::os::raw::c_void; use crate::render::renderer::TextureId; use crate::sys; use crate::Ui; #[must_use] pub struct Image<'ui> { texture_id: TextureId, size: [f32; 2], uv0: [f32; 2], uv1: [f32; 2], tint_col: [f32; 4], border_col: [f32; 4], _phantom: Phanto...
}
o(), self.uv1.into(), self.frame_padding, self.bg_col.into(), self.tint_col.into(), ) } }
function_block-function_prefixed
[ { "content": "#[cfg(feature = \"directx\")]\n\npub fn run<F: FnMut(&Ui) -> bool>(title: String, clear_color: [f32; 4], mut run_ui: F) {\n\n use gfx::{self, Device};\n\n use gfx_window_dxgi;\n\n use glutin;\n\n\n\n let mut events_loop = glutin::EventsLoop::new();\n\n let window = glutin::WindowBui...
Rust
nftnl/src/set.rs
nightmared/nftnl-rs
d8dd7968852dd0f1f899a352361a1f8513ac0584
use crate::{table::Table, MsgType, ProtoFamily}; use nftnl_sys::{self as sys, libc}; use std::{ cell::Cell, ffi::{c_void, CStr, CString}, fmt::Debug, net::{Ipv4Addr, Ipv6Addr}, os::raw::c_char, rc::Rc, }; use tracing::trace; #[macro_export] macro_rules! nft_set { ($name:expr, $id:expr, $tab...
use crate::{table::Table, MsgType, ProtoFamily}; use nftnl_sys::{self as sys, libc}; use std::{ cell::Cell, ffi::{c_void, CStr, CString}, fmt::Debug, net::{Ipv4Addr, Ipv6Addr}, os::raw::c_char, rc::Rc, }; use tracing::trace; #[macro_export] macro_rules! nft_set { ($name:expr, $id:expr, $tab...
pub fn elems_iter(&'a self) -> SetElemsIter<'a, K> { SetElemsIter::new(self) } pub fn as_ptr(&self) -> *const sys::nftnl_set { self.set as *const sys::nftnl_set } pub fn as_mut_ptr(&self) -> *mut sys::nftnl_set { self.set } pub fn get_family(&self) -> P...
pub fn add(&mut self, key: &K) where K: SetKey, { unsafe { let elem = try_alloc!(sys::nftnl_set_elem_alloc()); let data = key.data(); let data_len = data.len() as u32; trace!("Adding key {:?} with len {}", data, data_len); sys::nftnl_s...
function_block-full_function
[ { "content": "/// A callback to parse the response for messages created with `get_tables_nlmsg`.\n\npub fn get_tables_cb(\n\n header: &libc::nlmsghdr,\n\n (_, tables): &mut (&(), &mut Vec<Table>),\n\n) -> libc::c_int {\n\n unsafe {\n\n let table = sys::nftnl_table_alloc();\n\n if table ==...
Rust
src/main.rs
michalsrb/rustc2duchain
7b3cd5288858bf7fef68141f6fba27f036af2ae2
/* * Copyright (c) 2016 Michal Srb <michalsrb@gmail.com> * * 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...
/* * Copyright (c) 2016 Michal Srb <michalsrb@gmail.com> * * 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...
s.opt_present("h") { print_usage(&program, opts); return; } if let Some(debug_input) = matches.opt_str("d") { let duchain_writer = DebugDUChainWriter::new(std::io::stdout()); analyze(&debug_input, &[], duchain_writer, box RealFileLoader); return; } println!("OK"...
} pub fn erase_file(&mut self, path: &Path) { self.stored_files.remove(path); } } impl FileLoader for MyFileLoader { fn file_exists(&self, path: &Path) -> bool { self.stored_files.contains_key(path) || self.real_file_loader.file_exists(path) } fn read_file(&self, path: &Path)...
random
[ { "content": "pub fn analyze<T, L>(file: &str, library_search_dirs: &[String], duchain_writer: T, loader: Box<L>) where\n\n T: DUChainWriter,\n\n L: FileLoader + 'static\n\n{\n\n let mut compiler_calls = MyCompilerCalls {\n\n duchain_writer: duchain_writer\n\n };\n\n\n\n let mut arguments ...
Rust
derive/src/component.rs
baajur/abscissa
5d0262a206182601e4f41fadd8e5c10584478cc4
use darling::{FromDeriveInput, FromMeta}; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use synstructure::Structure; pub fn derive_component(s: Structure<'_>) -> TokenStream { let attrs = ComponentAttributes::from_derive_input(s.ast()).unwrap_or_else(|e| { panic!("error parsing component...
use darling::{FromDeriveInput, FromMeta}; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use synstructure::Structure; pub fn derive_component(s: Structure<'_>) -> TokenStream { let attrs = ComponentAttributes::from_derive_input(s.ast()).unwrap_or_else(|e| { panic!("error parsing component...
:component::Id> { const DEPENDENCIES: &[#abscissa_core::component::Id] = &[#(#ids),*]; DEPENDENCIES.iter() } fn register_dependency( &mut self, handle: #abscissa_core::component::Handle, dependency: &mut dyn Compone...
enStream { if self.inject.is_empty() { return quote!(); } let abscissa_core = self.abscissa_core_crate(); let ids = self .inject .iter() .map(|inject| inject.id_tokens(&abscissa_core)); let match_arms = self.inject.iter().map(|inj...
random
[]
Rust
packages/yew/src/dom_bundle/fragment.rs
lostinspiration/yew
e68060afa7421149f2d6aacace67c65c33e81fe5
use std::collections::VecDeque; use std::ops::{Deref, DerefMut}; use web_sys::{Element, Node}; use crate::dom_bundle::BSubtree; use crate::html::NodeRef; use crate::virtual_dom::Collectable; #[derive(Default, Debug, Clone, PartialEq, Eq)] pub struct Fragment(VecDeque<Node>); impl Deref for Fragment { type Targe...
use std::collections::VecDeque; use std::ops::{Deref, DerefMut}; use web_sys::{Element, Node}; use crate::dom_bundle::BSubtree; use crate::html::NodeRef; use crate::virtual_dom::Collectable; #[derive(Default, Debug, Clone, PartialEq, Eq)] pub struct Fragment(VecDeque<Node>); impl Deref for Fragment { type Targe...
} } pub fn shift(&self, next_parent: &Element, next_sibling: NodeRef) -> NodeRef { for node in self.iter() { next_parent .insert_before(node, next_sibling.get().as_ref()) .unwrap(); } self.front() .cloned() .map(...
ame(), first_node.node_type() ); let mut nodes = VecDeque::new(); if !is_open_tag(&first_node) { panic!( "expected {} opening tag, found comment node", collect_for.name() ); } parent.remove_child(&fir...
random
[ { "content": "/// Hook for consuming context values in function components.\n\n/// The context of the type passed as `T` is returned. If there is no such context in scope, `None`\n\n/// is returned. A component which calls `use_context` will re-render when the data of the context\n\n/// changes.\n\n///\n\n/// M...
Rust
mkfs/src/main.rs
0x59616e/steinsOS
28438f91a372cbf6785233ab9b6df918e3e33c68
use std::env; use std::fs; use inode::*; use superblock::*; mod inode; mod superblock; const BLOCK_SIZE: usize = 1024; fn as_u8<T>(src: &T) -> &[u8] { let ptr = std::ptr::addr_of!(*src) as *const u8; let len = std::mem::size_of::<T>(); unsafe { std::slice::from_raw_parts(ptr, len) } } fn to...
use std::env; use std::fs; use inode::*; use superblock::*; mod inode; mod superblock; const BLOCK_SIZE: usize = 1024; fn as_u8<T>(src: &T) -> &[u8] { let ptr = std::ptr::addr_of!(*src) as *const u8; let len = std::mem::size_of::<T>(); unsafe { std::slice::from_raw_parts(ptr, len) } }
const DATA_BLOCK_COUNT: usize = 1000; const BITMAP_BLOCK: u32 = 1; const ROOT_INODE_BLOCK: u32 = 2; fn main() { let superblock = Superblock { root_inode: ROOT_INODE_BLOCK, bitmap_block: BITMAP_BLOCK, }; let inode_count = env::args().count() as u32; let mut resul...
fn to_block<T>(src: &T) -> Vec<u8> { let mut v = as_u8(src).to_vec(); assert!(v.len() <= BLOCK_SIZE); v.resize(BLOCK_SIZE, 0_u8); v }
function_block-full_function
[ { "content": "fn string_len(ptr: *const u8) -> usize {\n\n for i in 0..128 {\n\n unsafe {\n\n if ptr.add(i).read() == b'\\x00' {\n\n return i;\n\n }\n\n }\n\n }\n\n panic!(\"string too long !\");\n\n}\n\n\n", "file_path": "kernel/src/syscall/mod.rs...
Rust
src/rendering/bidimensional/scion2d.rs
juanapatankar/scion
fa537bfb589c875bd97d3ffd747b9def3cd84083
use std::{collections::HashMap, ops::Range, path::Path}; use legion::{storage::Component, Entity, IntoQuery, Resources, World}; use wgpu::{ util::{BufferInitDescriptor, DeviceExt}, BindGroup, BindGroupLayout, Buffer, CommandEncoder, Device, Queue, RenderPassColorAttachmentDescriptor, RenderPipeline, SwapCh...
use std::{collections::HashMap, ops::Range, path::Path}; use legion::{storage::Component, Entity, IntoQuery, Resources, World}; use wgpu::{ util::{BufferInitDescriptor, DeviceExt}, BindGroup, BindGroupLayout, Buffer, CommandEncoder, Device, Queue, RenderPassColorAttachmentDescriptor, RenderPipeline, SwapCh...
fn pre_render_component<T: Component + Renderable2D>( &mut self, world: &mut World, ) -> Vec<RenderingInfos> { let mut render_infos = Vec::new(); for (entity, component, material, transform) in <(Entity, &mut T, &Material2D, &Transform)>::query().iter_mut(world) ...
slice(..), wgpu::IndexFormat::Uint16, ); if let Some(path) = rendering_infos.texture_path { render_pass.set_pipeline(self.render_pipelines.get(path.as_str()).as_ref().unwrap()); render_pass.set_bind_group( 0, &self.diffuse_bind_groups....
function_block-function_prefix_line
[ { "content": "fn add_score_ui(world: &mut World) -> Entity {\n\n // First we add an UiText to the world\n\n let font = Font::Bitmap {\n\n texture_path: app_base_path()\n\n .expect(\"\")\n\n .join(\"assets\")\n\n .join(\"tetris\")\n\n .join(\"font.png\")\n...
Rust
src/cli.rs
tshepang/polonius
62944e1e170e32417253525dbc28ab779aea5903
use crate::dump; use crate::facts::{Loan, Point, Region, Variable}; use crate::intern; use crate::tab_delim; use failure::Error; use log::error; use polonius_engine::{Algorithm, AllFacts, Output}; use std::path::Path; use std::time::{Duration, Instant}; use structopt::StructOpt; type PoloniusFacts = AllFacts<Region, L...
use crate::dump; use crate::facts::{Loan, Point, Region, Variable}; use crate::intern; use crate::tab_delim; use failure::Error; use log::error; use polonius_engine::{Algorithm, AllFacts, Output}; use std::path::Path; use std::time::{Duration, Instant}; use structopt::StructOpt; type PoloniusFacts = AllFacts<Region, L...
}; match result { Ok((duration, all_facts, output)) => { println!("--------------------------------------------------"); println!("Directory: {}", facts_dir); if !opt.skip_timing { let seconds = duration.as_secs() as f64; ...
rectory = opt .output_directory .as_ref() .map(|x| Path::new(x).to_owned()); let graphviz_file = opt.graphviz_file.as_ref().map(|x| Path::new(x).to_owned()); let liveness_graph_file = opt .liveness_graph_file .as_ref() .map(|x| Path::new(x).to_owned()); for fa...
random
[ { "content": "pub fn main() -> Result<(), failure::Error> {\n\n env_logger::init();\n\n let opt = polonius::cli::Opt::from_args();\n\n polonius::cli::main(opt)\n\n}\n", "file_path": "src/main.rs", "rank": 3, "score": 189319.3324687931 }, { "content": "fn test_fn(dir_name: &str, fn_n...
Rust
examples/kafka.rs
ids1024/bollard
e50137a37b1b7ddc17a4047cee7f5041418c06a7
use bollard::container::{Config, CreateContainerOptions, LogsOptions, StartContainerOptions}; use bollard::image::CreateImageOptions; use bollard::models::*; use bollard::Docker; use futures_util::stream::select; use futures_util::stream::TryStreamExt; use tokio::runtime::Runtime; const KAFKA_IMAGE: &'static str = ...
use bollard::container::{Config, CreateContainerOptions, LogsOptions, StartContainerOptions}; use bollard::image::CreateImageOptions; use bollard::models::*; use bollard::Docker; use futures_util::stream::select; use futures_util::stream::TryStreamExt; use tokio::runtime::Runtime; const KAFKA_IMAGE: &'static str = ...
async fn run() -> Result<(), Box<dyn std::error::Error>> { #[cfg(unix)] let docker = Docker::connect_with_unix_defaults().unwrap(); #[cfg(windows)] let docker = Docker::connect_with_named_pipe_defaults().unwrap(); let sd1 = docker.clone(); let sd2 = docker.clone(); let zookeeper_config = Co...
function_block-full_function
[ { "content": "fn main() {\n\n let mut rt = Runtime::new().unwrap();\n\n #[cfg(unix)]\n\n let docker = Docker::connect_with_unix_defaults().unwrap();\n\n #[cfg(windows)]\n\n let docker = Docker::connect_with_named_pipe_defaults().unwrap();\n\n\n\n let mut build_image_args = HashMap::new();\n\n ...
Rust
src/optimizer.rs
taku-y/primitiv-rust
76edd080700683a458e43c89fff5579c090c3bc5
use model_internal; use primitiv_sys as _primitiv; use std::ffi::CString; use std::io; use std::path::Path; use ApiResult; use Model; use Parameter; use Wrap; pub trait Optimizer: Wrap<_primitiv::primitivOptimizer_t> + Default { fn load<P: AsRef<Path>>(&mut self, path: P) -> io::Result<()> { unsafe { ...
use model_internal; use primitiv_sys as _primitiv; use std::ffi::CString; use std::io; use std::path::Path; use ApiResult; use Model; use Parameter; use Wrap; pub trait Optimizer: Wrap<_primitiv::primitivOptimizer_t> + Default { fn load<P: AsRef<Path>>(&mut self, path: P) -> io::Result<()> { unsafe { ...
fn set_epoch(&mut self, epoch: u32) { unsafe { check_api_status!(_primitiv::primitivSetOptimizerEpoch( self.as_mut_ptr(), epoch, )); } } fn get_learning_rate_scaling(&self) -> f32 { unsafe { let mut retv...
h( self.as_ptr(), &mut retval as *mut _, )); retval } }
function_block-function_prefixed
[ { "content": "/// Gathers the set of words from space-separated corpus and makes a vocabulary.\n\npub fn make_vocab<P: AsRef<Path>>(path: P, size: usize) -> Result<HashMap<String, u32>, io::Error> {\n\n if size < 3 {\n\n eprintln!(\"Vocab size should be <= 3.\");\n\n exit(1);\n\n }\n\n le...
Rust
rvr/src/collections/mod.rs
Vengarioth/rust-vulkan-renderer
f24eac24f7088fd17ab87a168feaec72193cafb3
#[macro_export] macro_rules! impl_generational_list { ($GenerationalList:ident<$GenerationalKey:ident, $Item:ident>) => { #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub struct $GenerationalKey { index: usize, generation: usize, } impl $GenerationalKey...
#[macro_export] macro_rules! impl_generational_list { ($GenerationalList:ident<$GenerationalKey:ident, $Item:ident>) => { #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub struct $GenerationalKey { index: usize, generation: usize, } impl $GenerationalKey...
}
let mut data = TestDataList::new(); let key = list.insert(TestValue(0)); data.set(&key, TestData(0)); assert_eq!(data.get(&key), Some(&TestData(0))); assert_eq!(data.get_mut(&key), Some(&mut TestData(0))); assert_eq!(data.remove(&key), Some(TestData(0))); }
function_block-function_prefix_line
[ { "content": "pub fn load_index(path: &str) -> Result<AssetIndex, Error> {\n\n use bincode;\n\n\n\n let contents = std::fs::read(path)?;\n\n let result = bincode::deserialize::<rvr_assets::AssetIndex>(&contents)?;\n\n\n\n let mut assets = HashMap::new();\n\n\n\n for location in result.locations {...
Rust
timetrace2/src/main.rs
pauldoo/scratch
1c8703d8b8e5cc5a026bfd5f0b036b9632faf161
use crate::tracing::{create_photon_map, do_raytrace}; use geometry::vector::Vector4; use log::{info, warn}; use photonmap::PhotonMap; use scene::Scene; use std::fs; use std::path::PathBuf; use crate::geometry::normal::Normal; use clap::{App, Arg, ArgMatches}; mod camera; mod geometry; mod lights; mod photon; mod photo...
use crate::tracing::{create_photon_map, do_raytrace}; use geometry::vector::Vector4; use log::{info, warn}; use photonmap::PhotonMap; use scene::Scene; use std::fs; use std::path::PathBuf; use crate::geometry::normal::Normal; use clap::{App, Arg, ArgMatches}; mod camera; mod geometry; mod lights; mod photon; mod photo...
fn create_surfaces() -> Vec<Box<dyn surfaces::Surface>> { let floor = surfaces::StaticPlane::new( Vector4::create(0.0, -1.0, 0.0, 0.0), Normal::from_vec(Vector4::create(0.0, 1.0, 0.0, 0.0)), ); let wall = surfaces::StaticPlane::new( Vector4::create(-2.0, 0.0, 0.0, 0.0), No...
fn create_scene() -> scene::Scene { return Scene { surfaces: create_surfaces(), lights: create_lights(), camera: create_camera(), }; }
function_block-function_prefix_line
[ { "content": "pub fn do_raytrace(config: &Config, map: &PhotonMap, scene: &Scene) -> () {\n\n info!(\"Doing the raytrace\");\n\n assert!(config.max_t > config.min_t);\n\n\n\n let energy_total = scene.energy_total();\n\n let background_colour: Vector4 = Vector4::create(255.0, 128.0, 128.0, 0.0);\n\n\...
Rust
src/server/decode.rs
withoutboats/async-h1
2383cf294601ef71dfbbb1aeed394fa005544eb8
use std::str::FromStr; use async_std::io::{BufReader, Read, Write}; use async_std::prelude::*; use http_types::headers::{CONTENT_LENGTH, EXPECT, HOST, TRANSFER_ENCODING}; use http_types::{ensure, ensure_eq, format_err}; use http_types::{Body, Method, Request}; use crate::chunked::ChunkedDecoder; use crate::{MAX_HEA...
use std::str::FromStr; use async_std::io::{BufReader, Read, Write}; use async_std::prelude::*; use http_types::headers::{CONTENT_LENGTH, EXPECT, HOST, TRANSFER_ENCODING}; use http_types::{ensure, ensure_eq, format_err}; use http_types::{Body, Method, Request}; use crate::chunked::ChunkedDecoder; use crate::{MAX_HEA...
#[test] fn test_setting_host_with_no_port() { let mut request = request_with_host_header("subdomain.mydomain.tld"); set_url_and_port_from_host_header(&mut request).unwrap(); assert_eq!( request.url(), &url::Url::parse("http://subdomain.mydomain.tld/some/path").u...
request.append_header("expect", "110-extensions-not-allowed"); let mut io = async_std::io::Cursor::new(vec![]); let result = async_std::task::block_on(handle_100_continue(&request, &mut io)); assert_eq!(std::str::from_utf8(&io.into_inner()).unwrap(), ""); assert!(result.is_ok()); }
function_block-function_prefix_line
[ { "content": "fn decode_chunk_end(buffer: Block<'static>, pos: &Range<usize>) -> io::Result<DecodeResult> {\n\n if pos.len() < 2 {\n\n return Ok(DecodeResult::None(buffer));\n\n }\n\n\n\n if &buffer[pos.start..pos.start + 2] == b\"\\r\\n\" {\n\n // valid chunk end move on to a new header\...
Rust
benches/unordered.rs
eholk/unicycle
3377095f0d2adbb4fceafad5c7649a75f4f41620
#![feature(test)] extern crate test; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use crossbeam::queue::SegQueue; use futures::{channel::oneshot, executor::block_on, future, stream::StreamExt as _, task::Poll}; use std::{sync::Arc, thread}; pub fn polling_benchmark(c: &mut Criterion) { ...
#![feature(test)] extern crate test; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use crossbeam::queue::SegQueue; use futures::{channel::oneshot, executor::block_on, future, stream::StreamExt as _, task::Poll}; use std::{sync::Arc, thread}; pub fn polling_benchmark(c: &mut Criterion) { ...
rxs.push(rx); } let txs = Arc::new(txs); for _ in 0..threads { let txs = txs.clone(); thread::spawn(move || { while let Ok((n, tx)) = txs.pop() { let _ = tx.send(n); } }); } let result = b...
}); group.bench_with_input(BenchmarkId::new("futures-rs", i), i, |b, i| { b.iter(|| futures_rs(10000, *i)) }); } } fn unicycle(num: usize, threads: usize) -> usize { use unicycle::FuturesUnordered; let txs = SegQueue::new(); let mut rx...
random
[ { "content": "async fn test_spinning_unordered() {\n\n use unicycle::FuturesUnordered;\n\n\n\n let count = Cell::new(0);\n\n\n\n let mut futures = FuturesUnordered::new();\n\n futures.push(Spinner(&count));\n\n pin_utils::pin_mut!(futures);\n\n\n\n let _ = poll_fn::<(), _>(move |cx| {\n\n ...
Rust
rustfst/src/symbol_table.rs
noeddl/rustfst
6415fb4fbe067ce46ba8e4cb6f19651dd37791a5
use std::collections::hash_map::{Entry, Iter, Keys}; use std::collections::HashMap; use std::fmt; use std::fs::File; use std::io::{LineWriter, Write}; use std::path::Path; use itertools::Itertools; use failure::Fallible; use crate::parsers::text_symt::parsed_text_symt::ParsedTextSymt; use crate::{Label, Symbol, EPS_...
use std::collections::hash_map::{Entry, Iter, Keys}; use std::collections::HashMap; use std::fmt; use std::fs::File; use std::io::{LineWriter, Write}; use std::path::Path; use itertools::Itertools; use failure::Fallible; use crate::parsers::text_symt::parsed_text_symt::ParsedTextSymt; use crate::{Label, Symbol, EPS_...
} pub fn len(&self) -> usize { self.num_symbols } pub fn get_label<S: Into<String>>(&self, sym: S) -> Option<Label> { self.symbol_to_label.get(&sym.into()).cloned() }...
match self.symbol_to_label.entry(sym.clone()) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { e.insert(label); self.label_to_symbol.entry(label).or_insert(sym); self.num_symbols += 1; label } }
if_condition
[ { "content": "pub fn minimize<F>(ifst: &mut F, allow_nondet: bool) -> Fallible<()>\n\nwhere\n\n F: MutableFst + ExpandedFst,\n\n F::W: WeaklyDivisibleSemiring + WeightQuantize + 'static,\n\n <<F as CoreFst>::W as Semiring>::ReverseWeight: 'static,\n\n{\n\n let props = ifst.properties()?;\n\n\n\n ...
Rust
renet/src/channel/block.rs
lucaspoffo/renet
350f82bbeae51cd07edafe82eea47deb453c14bf
use std::{collections::VecDeque, mem, time::Duration}; use bincode::Options; use serde::{Deserialize, Serialize}; use crate::{ error::RenetError, packet::{BlockChannelData, Payload}, sequence_buffer::SequenceBuffer, timer::Timer, }; use log::{error, info}; #[derive(Debug, Clone, Serialize, Deserializ...
use std::{collections::VecDeque, mem, time::Duration}; use bincode::Options; use serde::{Deserialize, Serialize}; use crate::{ error::RenetError, packet::{BlockChannelData, Payload}, sequence_buffer::SequenceBuffer, timer::Timer, }; use log::{error, info}; #[derive(Debug, Clone, Serialize, Deserializ...
sage.data.len() != self.slice_size { error!( "Invalid slice_size for SliceMessage, expected {}, got {}.", self.slice_size, message.data.len() ); return None; } if !self.received[slice_id] { self.received[sli...
efault() -> Self { Self { channel_id: 2, slice_size: 400, resend_time: Duration::from_millis(300), sent_packet_buffer_size: 256, packet_budget: 2000, } } } impl PacketSent { fn new(slice_ids: Vec<u32>) -> Self { Self { acked: f...
random
[ { "content": "pub fn disconnect_packet(reason: DisconnectionReason) -> Result<Payload, bincode::Error> {\n\n let packet = Packet::Disconnect(reason);\n\n let packet = bincode::options().serialize(&packet)?;\n\n Ok(packet)\n\n}\n", "file_path": "renet/src/packet.rs", "rank": 0, "score": 1146...
Rust
src/connection.rs
wishawa/tftp
16ab1a85c7ebef924efe2c65756b7da99abb57c3
use std::io::{self, Read, Result, Write}; use std::net::UdpSocket; use crate::bytes::IntoBytes; use crate::packet::expect::ExpectPacket; use crate::packet::*; /* * TODO: Probably add support for timeouts and retransmissions */ pub const MIN_PORT_NUMBER: u16 = 1001; pub struct Connection { socket: UdpSocket, } ...
use std::io::{self, Read, Result, Write}; use std::net::UdpSocket; use crate::bytes::IntoBytes; use crate::packet::expect::ExpectPacket; use crate::packet::*; /* * TODO: Probably add support for timeouts and retransmissions */ pub const MIN_PORT_NUMBER: u16 = 1001; pub struct Connection { socket: UdpSocket, } ...
#[test] fn test_get_sends_invalid_packet_error() { test_blank_sends_invalid_packet_error(|conn| conn.get(Vec::new())) } #[test] fn test_put_sends_invalid_packet_error() { test_blank_sends_invalid_packet_error(|conn| conn.put(&b"wowzers"[..])) } }
if let Ok(_) = Packet::<Data>::from_bytes(&buf[..rcvd]) { continue; } break rcvd; }; let actual: io::Error = Packet::<Error>::from_bytes(&buf[..rcvd]).unwrap().into(); assert_eq!(actual.kind(), expected.kind()); }
function_block-function_prefix_line
[ { "content": "fn get<T: AsRef<str>, W: Write>(file: T, client: Client, write: W) -> Result<W> {\n\n client.get(file, Mode::NetAscii, write)\n\n}\n\n\n", "file_path": "examples/client.rs", "rank": 0, "score": 111246.93199723544 }, { "content": "/// Implementors can attempt to produce a pac...
Rust
src/objects/dict.rs
yuja/rust-cpython
e03f85190741b74a7d559cde761718e085eccb4f
use ffi; use python::{Python, PythonObject}; use conversion::ToPyObject; use objects::{PyObject, PyList}; use err::{self, PyResult, PyErr}; use std::{mem, collections, hash, cmp}; pub struct PyDict(PyObject); pyobject_newtype!(PyDict, PyDict_Check, PyDict_Type); impl PyDict { pub fn new(py: Pyth...
use ffi; use python::{Python, PythonObject}; use conversion::ToPyObject; use objects::{PyObject, PyList}; use err::{self, PyResult, PyErr}; use std::{mem, collections, hash, cmp}; pub struct PyDict(PyObject); pyobject_newtype!(PyDict, PyDict_Check, PyDict_Type); impl PyDict { pub fn new(py: Pyth...
#[test] fn test_items() { let gil = Python::acquire_gil(); let py = gil.python(); let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.to_py_object(py); let mut key_sum = 0; let mut value_sum =...
fn test_items_list() { let gil = Python::acquire_gil(); let py = gil.python(); let mut v = HashMap::new(); v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); let dict = v.to_py_object(py); let mut key_sum = 0; let mut value_sum = 0; f...
function_block-full_function
[ { "content": "#[inline]\n\n#[doc(hidden)]\n\npub fn is_ready(_py: Python, ty: &ffi::PyTypeObject) -> bool {\n\n (ty.tp_flags & ffi::Py_TPFLAGS_READY) != 0\n\n}\n\n\n", "file_path": "src/py_class/mod.rs", "rank": 0, "score": 326719.04099517275 }, { "content": "pub fn type_error_to_false(py...
Rust
src/array_deque.rs
aaneto/open-data-structures
ee0c6f7a88bfcfdeefd19d36bf3d5402f01b1197
use crate::array::Array; pub struct ArrayQueue<T> { arr: Array<T>, first_in: usize, size: usize, } impl<T: Sized> ArrayQueue<T> { pub fn with_capacity(capacity: usize) -> Option<ArrayQueue<T>> { Array::with_capacity(capacity).map(|arr| Self { arr, first_in: 0, ...
use crate::array::Array; pub struct ArrayQueue<T> { arr: Array<T>, first_in: usize, size: usize, } impl<T: Sized> ArrayQueue<T> { pub fn with_capacity(capacity: usize) -> Option<ArrayQueue<T>> { Array::with_capacity(capacity).map(|arr| Self { arr, first_in: 0, ...
pub fn remove(&mut self, idx: usize) -> Option<T> { if idx >= self.size { return None; } let el = self.peek(idx); if idx > self.size / 2 { for i in idx..self.size - 1 { unsafe { s...
self.arr.read_at(self.mod_index(i)).unwrap(), ); } j = i; } self.first_in = self.arr.capacity() - 1; } else { let mut j = self.first_in - 1; for i in 0..idx + 1 { ...
function_block-function_prefix_line
[]
Rust
src/font.rs
TianyiShi2001/fl
9b8f7cd0a2aaad06d93916e88d406d431a586806
use crate::alphabet::{Alphabet, Char}; use crate::output::OutputOpts; use bitflags::bitflags; use std::cmp::min; use std::collections::HashMap; use std::default::Default; #[derive(Debug)] pub struct Font { opts: FontOpts, comment: String, alphabet: Alphabet, } enum SmushStatus { Valid, End, In...
use crate::alphabet::{Alphabet, Char}; use crate::output::OutputOpts; use bitflags::bitflags; use std::cmp::min; use std::collections::HashMap; use std::default::Default; #[derive(Debug)] pub struct Font { opts: FontOpts, comment: String, alphabet: Alphabet, } enum SmushStatus { Valid, End, In...
...
pub fn parse(data: &str) -> Self { let mut lines = data.lines(); let header = lines.next().unwrap(); let opts = FontOpts::parse(header); let mut comment = String::new(); for _ in 0..opts.num_comment_lines { comment.push_str(lines.next().unwrap()); ...
function_block-full_function
[ { "content": "pub fn find_indexes(string: &'static str, c1: u8, c2: u8) -> (Option<usize>, Option<usize>) {\n\n (string.find(c1 as char), string.find(c2 as char))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n #[test]\n\n fn test_hrule3_smush() {\n\n assert_eq!(hrule3_smush(b'[...
Rust
src/lib.rs
spieglt/winage
aea439dcd8e8e6b2cb0c76ad7f8462154671e3f8
mod error; mod identity; use age::{ armor::{ArmoredReader, ArmoredWriter, Format}, cli_common::{file_io, read_identities, UiCallbacks}, plugin, Identity, IdentityFile, Recipient, }; use rand::{ distributions::{Distribution, Uniform}, rngs::OsRng, }; use secrecy::SecretString; use std::convert::Try...
mod error; mod identity; use age::{ armor::{ArmoredReader, ArmoredWriter, Format}, cli_common::{file_io, read_identities, UiCallbacks}, plugin, Identity, IdentityFile, Recipient, }; use rand::{ distributions::{Distribution, Uniform}, rngs::OsRng, }; use secrecy::SecretString; use std::convert::Try...
#[no_mangle] pub unsafe extern "C" fn free_rust_string(ptr: *mut c_char) { if ptr != null_mut() { drop(CString::from_raw(ptr)); } } #[no_mangle] pub unsafe extern "C" fn get_decryption_mode(input: *const c_char) -> *const c_char { let rust_input = CStr::from_ptr(input).to_string_lossy().into_owne...
pub extern "C" fn get_passphrase() -> *const c_char { let between = Uniform::from(0..2048); let mut rng = OsRng; let passphrase = (0..10) .map(|_| { BIP39_WORDLIST .lines() .nth(between.sample(&mut rng)) .expect("index is in range") ...
function_block-full_function
[ { "content": "pub fn generate(identity_path: &str) -> Result<()> {\n\n let sk = x25519::Identity::generate();\n\n let pk = sk.to_public();\n\n let mut out_file = File::create(identity_path)?;\n\n // TODO: internationalization\n\n writeln!(\n\n out_file,\n\n \"# created: {}\",\n\n ...
Rust
bee-node/src/plugins/dashboard/mod.rs
rajivshah3/bee
923016e0c453f073ff557ea36b92c24e7cf213f5
pub mod config; mod asset; mod websocket; mod workers; use crate::{ config::NodeConfig, plugins::dashboard::{ config::DashboardConfig, websocket::{ responses::{ confirmed_info, milestone, milestone_info, mps_metrics_updated, solid_info, sync_status, tip_info, ...
pub mod config; mod asset; mod websocket; mod workers; use crate::{ config::NodeConfig, plugins::dashboard::{ config::DashboardConfig, websocket::{ responses::{ confirmed_info, milestone, milestone_info, mps_metrics_updated, solid_info, sync_status, tip_info, ...
.map(|res| res), )) .or(warp::path!("analytics" / ..).and_then(serve_index)) .or(warp::path!("peers" / ..).and_then(serve_index)) .or(warp::path!("explorer" / ..).and_then(serve_index)) .or(warp::path!("visualizer" / .....
reverse_proxy_filter( "".to_string(), "http://localhost:".to_owned() + &rest_api_config.binding_socket_addr().port().to_string() + "/", )
call_expression
[ { "content": "fn topic_handler<N, E, T, P, F>(node: &mut N, topic: &'static str, f: F)\n\nwhere\n\n N: Node,\n\n E: Any + Clone + Send + Sync,\n\n T: Into<String> + Send,\n\n P: Into<Vec<u8>> + Send,\n\n F: 'static + Fn(&E) -> (T, P) + Send + Sync,\n\n{\n\n let bus = node.bus();\n\n let man...
Rust
external/sqrid/src/sqrid/qa.rs
lpenz/codingame-the-last-crusade
1e3b0cc342c59e42366e40f9e40c79759e6a2ba2
#![warn(missing_debug_implementations)] #![warn(missing_docs)] use std::borrow::Borrow; use std::convert; use std::convert::TryFrom; use std::fmt; use super::error::Error; macro_rules! const_assert { ($x:expr $(,)?) => { const ASSERT_FALSE: [(); 1] = [(); 1]; let _ = ASSERT_FALSE[$x as usize]; ...
#![warn(missing_debug_implementations)] #![warn(missing_docs)] use std::borrow::Borrow; use std::convert; use std::convert::TryFrom; use std::fmt; use super::error::Error; macro_rules! const_assert { ($x:expr $(,)?) => { const ASSERT_FALSE: [(); 1] = [(); 1]; let _ = ASSERT_FALSE[$x as usize]; ...
} /* QaIterInX/Y*/ #[derive(Debug, Clone, Copy)] pub struct QaIterInX<const W: u16, const H: u16>(Option<Qa<W, H>>); impl<const W: u16, const H: u16> Iterator for QaIterInX<W, H> { type Item = Qa<W, H>; #[inline] fn next(&mut self) -> Option<Self::Item> { if let Some(i) = self.0.take() { ...
t xrange = self.botright.0 - self.topleft.0 + 1; let yrange = self.botright.1 - self.topleft.1 + 1; let size = xrange as usize * yrange as usize; (size, Some(size)) }
function_block-function_prefixed
[ { "content": "/// Trait that abstracts maps with [`Qa`] indexes\n\n///\n\n/// The generic parameters allow us to support implementing [`Grid`].\n\npub trait MapQa<Item, const W: u16, const H: u16, const WORDS: usize, const SIZE: usize> {\n\n /// Create a new MapQa\n\n fn new() -> Self;\n\n /// Get the ...
Rust
src/main.rs
robaldwin9/rshtmllog
e015f15a75d681a84460d535b9d5bc868c6652c9
use doclib::html_file::*; use std::env; use std::fs::File; use std::io::{self, BufRead, Write}; use std::path::Path; fn main() { let args: Vec<String> = env::args().collect(); let mut html_doc = HtmlDoc::new(); html_doc.style = "<link rel=\"stylesheet\" href=\"src/css/rshtml.css\">".to_string(); h...
use doclib::html_file::*; use std::env; use std::fs::File; use std::io::{self, BufRead, Write}; use std::path::Path; fn main() { let args: Vec<String> = env::args().collect(); let mut html_doc = HtmlDoc::new(); html_doc.style = "<link rel=\"stylesheet\" href=\"src/css/rshtml.css\">".to_string(); h...
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } fn add_log_level_tag(propterty: Property, text: String, html_doc: &mut doclib::html_file::HtmlDoc) { let mut div = Tag::new( Tag...
c); } else if log_line.contains(ERROR) { if error_count == 0 { error_count += 1; } add_log_level_tag(error_class, lower_log_line, &mut html_doc); } else if log_line.contains(DEBUG) { i...
function_block-function_prefixed
[ { "content": " if self.propertyname.len() > 0 && self.propertyvalue.len() > 0 {\n\n println!( \" {}={} \", self.propertyname, self.propertyvalue)\n\n } else {\n\n println!(\"\")\n\n }\n\n \n\n }\n\n}\n\n\n\nimpl Display for Property {\n\n fn fmt(&se...
Rust
src/day09.rs
samhclark/advent-of-code
f8d62fd705e75f0bfd504c2f919b350600faf3fc
use std::{collections::HashSet, error::Error}; type Point = (usize, usize); type Heightmap = Vec<Vec<u32>>; #[allow(dead_code)] pub fn part1(puzzle_input: &str) -> Result<u32, Box<dyn Error>> { let heightmap: Heightmap = build_heightmap_from_input(puzzle_input); let lowpoints: Vec<Point> = get_low_points_f...
use std::{collections::HashSet, error::Error}; type Point = (usize, usize); type Heightmap = Vec<Vec<u32>>; #[allow(dead_code)]
fn build_heightmap_from_input(input: &str) -> Heightmap { let height = input.lines().count(); let width = input.lines().next().unwrap().len(); let mut heightmap: Heightmap = vec![vec![0; width]; height]; for (i, line) in input.lines().enumerate() { for (j, c) in line.chars().enumerate() { ...
pub fn part1(puzzle_input: &str) -> Result<u32, Box<dyn Error>> { let heightmap: Heightmap = build_heightmap_from_input(puzzle_input); let lowpoints: Vec<Point> = get_low_points_from_heightmap(&heightmap); let puzzle_answer: u32 = determine_risk_level(&heightmap, &lowpoints); println!("Puzzle answer: ...
function_block-full_function
[ { "content": "#[derive(Debug, Clone, Copy)]\n\nstruct Point {\n\n x: usize,\n\n y: usize,\n\n}\n\n\n\nimpl FromStr for Point {\n\n type Err = ParseIntError;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n let coords: Vec<u64> = s.split(',').map(|n| n.trim().parse().unwrap()).col...
Rust
src/api/screen.rs
Iyxan23/swrs
40073b305c4514b50612e1c3ca1d4f50caacf3f7
use crate::LinkedHashMap; use crate::api::block::{BlockConversionError, Blocks}; use crate::api::block::block_content::{BlockContent, BlockContentParseError}; use crate::api::component::{ComponentKind, UnknownComponentType}; use crate::api::view::{parse_raw_layout, ParseLayoutError, View}; use crate::parser::file::{Fil...
use crate::LinkedHashMap; use crate::api::block::{BlockConversionError, Blocks}; use crate::api::block::block_content::{BlockContent, BlockContentParseError}; use crate::api::component::{ComponentKind, UnknownComponentType}; use crate::api::view::{parse_raw_layout, ParseLayoutError, View}; use crate::parser::file::{Fil...
} type ParserEvent = crate::parser::logic::event::Event; impl TryFrom<ParserEvent> for Event { type Error = UnknownEventType; fn try_from(value: ParserEvent) -> Result<Self, Self::Error> { Ok(Event { event_type: EventType::from_parser_event(&value)?, name: value.event_na...
pub fn into_parser_event(self) -> (ParserEvent, Blocks) { let mut event = ParserEvent { event_name: self.name, event_type: 0, target_id: "".to_string(), target_type: 0 }; self.event_type.apply_to_parser_event(&mut event); (event, self.cod...
function_block-full_function
[ { "content": "/// Converts a parser's raw [`Layout`] into a tree of views, the returned vector of views is the\n\n/// children of the root view.\n\n///\n\n/// You might expect this function to return a single view because a layout only has one single\n\n/// root view, but no, sketchware hardcodes the root view ...
Rust
src/runtime/memory/gc.rs
svenslaggare/stackjit-rs
82316ef560f74a641ad42e8cfcfa4e29bab15a7f
use std::collections::HashMap; use crate::runtime::memory::heap::{Heap, HeapObjectsIterator}; use crate::runtime::stack_walker::{StackFrame, FrameValue}; use crate::compiler::jit::JitCompiler; use crate::model::binder::Binder; use crate::model::typesystem::TypeId; use crate::runtime::object::ObjectReference; use crate...
use std::collections::HashMap; use crate::runtime::memory::heap::{Heap, HeapObjectsIterator}; use crate::runtime::stack_walker::{StackFrame, FrameValue}; use crate::compiler::jit::JitCompiler; use crate::model::binder::Binder; use crate::model::typesystem::TypeId; use crate::runtime::object::ObjectReference; use crate...
clone())); } } } } impl MarkObjects for GarbageCollector {} impl UpdateReferences for GarbageCollector {} pub trait MarkObjects { fn mark_objects(&mut self, compiler: &JitCompiler, stack_frame: &StackFrame) { stack_frame.walk( com...
ted object: 0x{:0x}, type: {}", object_ref.ptr() as u64, object_ref.object_type().id); self.deleted_objects.push((object_ref.ptr() as u64, object_ref.object_type().id.clone())); object_ref.delete(); } else { object_ref.header_mut().unmark(); } ...
random
[ { "content": "pub fn align_size(size: i32) -> i32 {\n\n ((size + 15) / 16) * 16\n\n}\n\n\n", "file_path": "src/compiler/stack_layout.rs", "rank": 0, "score": 185448.37019127348 }, { "content": "pub fn optimize(compilation_result: &mut MIRCompilationResult,\n\n basic_blocks:...
Rust
src/device_manager/main_device_manager.rs
william-redenbaugh/ApartmentFrameworkRust
11be8ab9628b132fb85612d54557c40f6fa34caa
use std::net::UdpSocket; use std::{thread, time}; use std::time::Duration; use std::sync::{mpsc, Arc, Mutex}; use std::rc::Rc; use std::cell::{Cell, RefCell}; use std::io::prelude::*; use serial::prelude::*; use crate::udp_control; use crate::serial_control; extern crate serial; pub struct MatrixMessagePacket{ ...
use std::net::UdpSocket; use std::{thread, time}; use std::time::Duration; use std::sync::{mpsc, Arc, Mutex}; use std::rc::Rc; use std::cell::{Cell, RefCell}; use std::io::prelude::*; use serial::prelude::*; use crate::udp_control; use crate::serial_control; extern crate serial; pub struct MatrixMessagePacket{ ...
#[derive(Clone, Debug)] pub enum ClockControlMsg{ CLOCK_EN, HEART_SLEEP, HEART_LOCK, HEART_LAMP, HEART_BEEP } #[derive(Clone, Debug)] pub struct HeartClockMessagePacket{ pub msg_type: ClockControlMsg, pub val: bool } pub struct HeartClockReturnPacket{ pub request_status: bool } pub ...
pub fn temp_main(rx: mpsc::Receiver<RelayMessagePacket>, tx: mpsc::Sender<RelayReturnPacket>){ loop{ let relay_status = rx.recv().unwrap(); if(relay_status.relay_en){ } } }
function_block-full_function
[ { "content": "pub fn generate_messagedata_header(message_size: u32, message_type: messagedata::mod_MessageData::MessageType, return_message: bool) -> Vec<u8>{\n\n // Generate the struct of mesage\n\n let val = messagedata::MessageData{\n\n message_size: message_size, \n\n message_type: messa...
Rust
evm_loader/program/src/solidity_account.rs
neonlabsorg/solana-program-library
7bddd194bc37fac92d0c722c525971a1666f14f1
use crate::{ account_data::AccountData, hamt::Hamt, utils::{keccak256_h256, u256_to_h256}, }; use evm::backend::Basic; use evm::Code; use solana_program::{ account_info::AccountInfo, pubkey::Pubkey, program_error::ProgramError, }; use primitive_types::{H160, H256, U256}; use std::cell::RefCell; ...
use crate::{ account_data::AccountData, hamt::Hamt, utils::{keccak256_h256, u256_to_h256}, }; use evm::backend::Basic; use evm::Code; use solana_program::{ account_info::AccountInfo, pubkey::Pubkey, program_error::ProgramError, }; use primitive_types::{H160, H256, U256}; use std::cell::RefCell; ...
pub fn get_solana_address(&self) -> Pubkey { *self.solana_address } pub fn get_seeds(&self) -> (H160, u8) { (AccountData::get_account(&self.account_data).unwrap().ether, AccountData::get_account(&self.account_data).unwrap().nonce) } pub fn basic(&self) -> Basic { Basic { ...
Err(ProgramError::UninitializedAccount)*/ if self.code_data.is_none() { return Err(ProgramError::UninitializedAccount) } let contract_data = &self.code_data.as_ref().unwrap().0; let contract = AccountData::get_contract(&contract_data)?; let code_size = contract.code_...
function_block-function_prefix_line
[ { "content": "/// Create a `RecordInstruction::Write` instruction\n\npub fn write(record_account: &Pubkey, signer: &Pubkey, offset: u64, data: Vec<u8>) -> Instruction {\n\n Instruction::new_with_borsh(\n\n id(),\n\n &RecordInstruction::Write { offset, data },\n\n vec![\n\n Acc...
Rust
src/visitor/symbol.rs
jblondin/piske
a989113f9fd62c733f6f1b5ce192248e69d28cd4
use std::rc::Rc; use sindra::Node; use sindra::scope::{Stack, Scoped, SymbolStore}; use visitor::State; use Symbol; use ast::ast::*; type Result = ::std::result::Result<(), String>; pub trait SymbolDefineVisitor { fn visit(&self, &mut State) -> Result; } fn visit_block(block: &Node<Block>, state: &mut S...
use std::rc::Rc; use sindra::Node; use sindra::scope::{Stack, Scoped, SymbolStore}; use visitor::State; use Symbol; use ast::ast::*; type Result = ::std::result::Result<(), String>; pub trait SymbolDefineVisitor { fn visit(&self, &mut State) -> Result; } fn visit_block(
pop() { Some(parent_scope) => { state.scope = parent_scope; } None => { return Err("invalid descoping".to_string()); } } Ok(()) } impl SymbolDefineVisitor for Node<Program> { fn visit(&self, state: &mut State) -> Result { visit_block(&self.item.0, state)?; ...
block: &Node<Block>, state: &mut State) -> Result { state.scope = state.scope.push(); block.visit(state)?; match state.scope.
function_block-random_span
[ { "content": "/// Abstract syntax tree visitor pipeline\n\npub fn pipeline<T>(ast: &T, mut state: &mut State) -> Result<(), String>\n\n where T: visitor::symbol::SymbolDefineVisitor +\n\n visitor::type_visitor::TypeComputationVisitor {\n\n\n\n // define symbols\n\n match visitor::sy...
Rust
src/libsyntax/ext/tt/earley_parser.rs
jdm/rust
ac9df5841c09ca645638922365a9de56ac529251
import parse::token; import parse::token::{token, EOF, to_str, whole_nt}; import parse::lexer::*; import parse::parser::{parser,SOURCE_FILE}; import parse::common::*; import parse::parse_sess; import dvec::{dvec, extensions}; import ast::{matcher, mtc_tok, mtc_rep, mtc_bb, ident}; import ast_util::mk_sp; import st...
import parse::token; import parse::token::{token, EOF, to_str, whole_nt}; import parse::lexer::*; import parse::parser::{parser,SOURCE_FILE}; import parse::common::*; import parse::parse_sess; import dvec::{dvec, extensions}; import ast::{matcher, mtc_tok, mtc_rep, mtc_bb, ident}; import ast_util::mk_sp; import st...
{node: mtc_bb(bind_name, _, idx), span: sp} { if ret_val.contains_key(bind_name) { p_s.span_diagnostic.span_fatal(sp, ~"Duplicated bind name: " + *bind_name) } ret_val.insert(bind_name, res[idx]); } ...
fn nameize(p_s: parse_sess, ms: ~[matcher], res: ~[@arb_depth]) -> hashmap<ident,@arb_depth> { fn n_rec(p_s: parse_sess, m: matcher, res: ~[@arb_depth], ret_val: hashmap<ident, @arb_depth>) { alt m { {node: mtc_tok(_), span: _} { } {node: mtc_rep(more_ms, _, _, _, _), sp...
function_block-full_function
[ { "content": "fn test9() { let regs = @mut 0; alt check true { true { } } *regs += 1; }\n\n\n", "file_path": "src/test/pretty/block-disambig.rs", "rank": 1, "score": 594492.3440063719 }, { "content": "fn iterate(lo: uint, hi: uint, it: fn(uint) -> bool) -> bool {\n\n let mut i = lo;\n\n ...
Rust
src/storage/fs/category.rs
creinig/naday
975eb02a0e2e71bfe63ed8efd29141ddc5d77f7d
use crate::model::{Category, Config}; use crate::error::ParseError; use anyhow::{bail, Context, Result}; use std::fs; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::PathBuf; pub fn read_categories(cfg: &Config) -> Result<Vec<Category>> { let path = &(init_category_file(cfg)?); let conten...
use crate::model::{Category, Config}; use crate::error::ParseError; use anyhow::{bail, Context, Result}; use std::fs; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::PathBuf; pub fn read_categories(cfg: &Config) -> Result<Vec<Category>> { let path = &(init_category_file(cfg)?); let conten...
; assert_eq!(1.0, categories.get(0).unwrap().weight); assert_eq!( "Category (Pushups, 1, [\"pu\", \"push\"])", categories.get(0).unwrap().to_string() ); assert_eq!( "Category (Situps, 1, [\"si\"])", categories.get(1).unwrap().to_string() ...
le) = lines.next() { if preamble.trim() != PREAMBLE_CATEGORIES_V1 { bail!(ParseError::new( "No valid preamble found - unable to determine category file format", )); } } else { bail!(ParseError::new("Category file seems to be empty")); } for li...
random
[ { "content": "/// Read all categories and return a populated lookup structure\n\npub fn read_categories(cfg: &Config) -> Result<CategoryLookup> {\n\n let categories = category::read_categories(cfg)?;\n\n let mut lookup = CategoryLookup::new();\n\n\n\n for category in categories {\n\n lookup.add(...
Rust
day7/src/main.rs
LesnyRumcajs/AdventOfRust2018
f12b05d367c45de215510e116ded20f8faadf150
extern crate regex; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use regex::Regex; struct Relation { id: char, dep: char, } struct ComplexRelation { id: char, deps: Vec<char> } #[derive(Clone, Debug)] struct Worker { id: char, time: i32 } fn main() { first_part(); ...
extern crate regex; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use regex::Regex; struct Relation { id: char, dep: char, } struct ComplexRelation { id: char, deps: Vec<char> } #[derive(Clone, Debug)] struct Worker { id: char, time: i32 } fn main() { first_part(); ...
fn time_to_build(block: char) -> i32 { 60 + (block as i32) - 65 + 1 }
fn create_complex_relations(relations: &Vec<Relation>) -> Vec<ComplexRelation> { let mut complex_relations: Vec<ComplexRelation> = Vec::new(); let mut current_id = relations.first().unwrap().id; let mut current_deps: Vec<char> = Vec::new(); for relation in relations.iter() { if relation.id == c...
function_block-full_function
[ { "content": "fn patch_from_line(line: &str) -> Fabric {\n\n lazy_static! {\n\n static ref re: Regex = Regex::new(r\"^#(\\d+)\\s*@\\s*(\\d+),(\\d+):\\s*(\\d+)x(\\d+)$\").unwrap();\n\n }\n\n let caps = re.captures(line).unwrap(); \n\n Fabric {id: caps[1].parse().unwrap(),\n\n ...
Rust
src/server/connection_handler/response.rs
PrajwalCH/localdevmon
09203bb9e2c158bae704695f21a60d7c52a6bffb
use std::fmt; use std::fs; use std::io::Write; use std::net::TcpStream; use std::path::{Path, PathBuf}; use super::request::HTTPRequest; use crate::server::route_handler::DirNode; macro_rules! mimetype_new { ($ext:literal, $mtype:literal) => { MimeType { ext: $ext, mtype: $mtype, ...
use std::fmt; use std::fs; use std::io::Write; use std::net::TcpStream; use std::path::{Path, PathBuf}; use super::request::HTTPRequest; use crate::server::route_handler::DirNode; macro_rules! mimetype_new { ($ext:literal, $mtype:literal) => { MimeType { ext: $ext, mtype: $mtype, ...
title>404 not found</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> </head> <body> <center> <h2>404 Not Found</h2> </center> "; #[allow(unused)] const INTERNAL_SERVER_ERROR_BODY: &str = " <html> <head> <title>500 Internal Server Error</title> <meta name=...
!(".svg", "image/svg+xml"), mimetype_new!(".swf", "application/x-shockwave-flash"), mimetype_new!(".tar", "application/x-tar"), mimetype_new!(".tif", "image/tiff"), mimetype_new!(".tif", "image/tiff"), mimetype_new!(".ts", "ideo/mp2t"), mimetype_new!(".ttf", "font/ttf"), mimetype_new!(".txt"...
random
[]
Rust
src/endpoints/space/mod.rs
klaxit/heroku_rs
25941b8746463877d216b194d1e0f2752ba612fb
use crate::framework::response::ApiResult; pub mod delete; pub mod get; pub mod patch; pub mod post; pub mod put; pub use get::{ InboundRulesetCurrent, InboundRulesetDetails, InboundRulesetList, OutboundRulesetCurrent, OutboundRulesetDetails, OutboundRulesetList, SpaceAccessDetails, SpaceAccessList, SpaceDeta...
use crate::framework::response::ApiResult; pub mod delete; pub mod get; pub mod patch; pub mod post; pub mod put; pub use get::{ InboundRulesetCurrent, InboundRulesetDetails, InboundRulesetList, OutboundRulesetCurrent, OutboundRulesetDetails, OutboundRulesetList, SpaceAccessDetails, SpaceAccessList, SpaceDeta...
uct Organization { pub name: String, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct Team { pub id: String, pub name: String, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct Region { pub id: String, pub name: String, } } mod ...
b struct Organization { pub name: String, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct Team { pub id: String, pub name: String, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct Region { pub id: Stri...
random
[ { "content": "pub trait ApiResult: DeserializeOwned + Debug {}\n\n\n\n// This because Heroku returns a empty object in some responses.\n\n#[derive(Deserialize, Serialize, Debug)]\n\npub struct Empty {}\n", "file_path": "src/framework/response/mod.rs", "rank": 0, "score": 209047.11057621933 }, { ...
Rust
src/python/statehd.rs
feos-org/feos-core
58c82ca1eb27f1fbb377d80acf523f2a48a419f4
use crate::StateHD; use ndarray::Array1; use num_dual::python::{PyDual3Dual64, PyDual3_64, PyDual64, PyHyperDual64, PyHyperDualDual64}; use num_dual::{Dual, Dual3, Dual3_64, Dual64, DualVec64, HyperDual, HyperDual64}; use pyo3::prelude::*; use std::convert::From; #[pyclass(name = "StateF")] #[derive(Clone)] pub struct...
use crate::StateHD; use ndarray::Array1; use num_dual::python::{PyDual3Dual64, PyDual3_64, PyDual64, PyHyperDual64, PyHyperDualDual64}; use num_dual::{Dual, Dual3, Dual3_64, Dual64, DualVec64, HyperDual, HyperDual64}; use pyo3::prelude::*; use std::convert::From; #[pyclass(name = "StateF")] #[derive(Clone)] pub struct...
ual64, f64> );
rom(s: StateHD<HyperDual64>) -> Self { Self(s) } } #[pyclass(name = "StateHDD")] #[derive(Clone)] pub struct PyStateHDD(StateHD<HyperDual<Dual64, f64>>); impl From<StateHD<HyperDual<Dual64, f64>>> for PyStateHDD { fn from(s: StateHD<HyperDual<Dual64, f64>>) -> Self { Self(s) } } #[pyclass...
random
[ { "content": "pub fn critical_point_objective<E: EquationOfState>(\n\n eos: &Rc<E>,\n\n temperature: Dual64,\n\n density: Dual64,\n\n moles: &Array1<f64>,\n\n) -> EosResult<Array1<Dual64>> {\n\n // calculate second partial derivatives w.r.t. moles\n\n let t = HyperDual::from_re(temperature);\n...
Rust
src/builder.rs
hone/jvm-function-invoker-buildpack
8ea536ff8845767d6edaec40db74e7d1d4f515ac
use crate::util::{self, logger::Logger}; use libcnb::{build::GenericBuildContext, layer::Layer}; use std::{convert::TryFrom, fs, path::Path, process::Command}; pub const RUNTIME_JAR_FILE_NAME: &str = "runtime.jar"; pub struct Builder<'a, 'b> { logger: &'b Logger, ctx: &'a GenericBuildContext, } impl<'a, 'b> ...
use crate::util::{self, logger::Logger}; use libcnb::{build::GenericBuildContext, layer::Layer}; use std::{convert::TryFrom, fs, path::Path, process::Command}; pub const RUNTIME_JAR_FILE_NAME: &str = "runtime.jar"; pub struct Builder<'a, 'b> { logger: &'b Logger, ctx: &'a GenericBuildContext, } impl<'a, 'b> ...
} #[cfg(target_family = "unix")] fn set_executable(path: impl AsRef<Path>) -> anyhow::Result<()> { use std::os::unix::fs::OpenOptionsExt; fs::OpenOptions::new().mode(0o775).open(path)?; Ok(()) }
let function_bundle_toml: crate::data::function_bundle::Toml = toml::from_slice( &fs::read(&function_bundle_layer.as_path().join("function-bundle.toml"))?, )?; self.logger.header(format!( "Detected function: {}", function_bundle_toml.function.class ))?; ...
function_block-function_prefix_line
[ { "content": "pub fn error(header: impl Display, msg: impl Display) -> anyhow::Result<()> {\n\n let mut stderr = StandardStream::stderr(ColorChoice::Always);\n\n stderr.set_color(ColorSpec::new().set_fg(Some(Color::Red)).set_bold(true))?;\n\n writeln!(&mut stderr, \"\\n[ERROR: {}]\", header)?;\n\n s...
Rust
src/game.rs
AlexABallWebDev/rust_snake
b44298a4e1062e91e161c2d17ed84620adbee5ab
use piston_window::*; use piston_window::types::Color; use rand::{thread_rng, Rng}; use snake::{Direction, Snake}; use draw::{draw_block, draw_rectangle}; const FOOD_COLOR: Color = [0.80, 0.00, 0.00, 1.0]; const BORDER_COLOR: Color = [0.00, 0.00, 0.00, 1.0]; const GAMEOVER_COLOR: Color = [0.90, 0.00, 0.00, 0.5]; c...
use piston_window::*; use piston_window::types::Color; use rand::{thread_rng, Rng}; use snake::{Direction, Snake}; use draw::{draw_block, draw_rectangle}; const FOOD_COLOR: Color = [0.80, 0.00, 0.00, 1.0]; const BORDER_COLOR: Color = [0.00, 0.00, 0.00, 1.0]; const GAMEOVER_COLOR: Color = [0.90, 0.00, 0.00, 0.5]; c...
} self.waiting_time = 0.0; } fn restart(&mut self) { self.snake = Snake::new(2, 2); self.waiting_time = 0.0; self.food_exists = true; self.food_x = 6; self.food_y = 4; self.game_over = false; } }
_snake(&mut self, dir: Option<Direction>) { if self.is_snake_alive(dir) { self.snake.move_forward(dir); self.is_eating(); } else { self.game_over = true;
function_block-random_span
[ { "content": "/// Draw a block at the given coordinates.\n\npub fn draw_block(color: Color, x: i32, y: i32, con: &Context, g: &mut G2d) {\n\n let gui_x = to_coord(x);\n\n let gui_y = to_coord(y);\n\n\n\n rectangle(\n\n color,\n\n // coordinates of the rectangle, along with width and height.\n\n [gui...
Rust
rust/mandelbrot/src/main.rs
justanotherdot/lab
3c8c4701e253f487189be24802092df590308296
extern crate num; extern crate image; extern crate crossbeam; use image::ColorType; use image::png::PNGEncoder; use num::Complex; use std::fs::File; use std::io::Write; use std::str::FromStr; #[allow(dead_code)] fn write_image(filename: &str, pixels: &[u8], bounds: (usize, usize)) -> Result<(), std::io::Error> { ...
extern crate num; extern crate image; extern crate crossbeam; use image::ColorType; use image::png::PNGEncoder; use num::Complex; use std::fs::File; use std::io::Write; use std::str::FromStr; #[allow(dead_code)]
#[allow(dead_code)] fn parse_pair<T: FromStr>(s: &str, separator: char) -> Option<(T, T)> { match s.find(separator) { None => None, Some(index) => { match (T::from_str(&s[..index]), T::from_str(&s[index + 1..])) { (Ok(l), Ok(r)) => Some((l, r)), _ => Non...
fn write_image(filename: &str, pixels: &[u8], bounds: (usize, usize)) -> Result<(), std::io::Error> { let output = File::create(filename)?; let encoder = PNGEncoder::new(output); encoder.encode(&pixels, bounds.0 as u32, bounds.1 as u32, ColorType...
function_block-full_function
[ { "content": " long num_bytes;\n", "file_path": "c/utf8_parser.h", "rank": 0, "score": 24855.339400378645 }, { "content": "int num_bytes_follow(char c)\n\n{\n\n if (is_ascii(c) || is_cont(c)) {\n\n return 0;\n\n }\n\n\n\n // TODO\n\n // You want to make this more robust by actually c...
Rust
src/subcommands.rs
xylous/settle
268193628f89b48080f296bea386a8276a6e46b0
use rusqlite::Error; use clap::ArgMatches; use clap_complete::Shell::*; use rayon::prelude::*; use crate::Database; use crate::Zettel; use crate::config::ConfigOptions; use crate::io::file_exists; use crate::cli; fn print_zettel_info(zettel: &[Zettel]) { zettel.par_iter() .for_each(|z| { let ...
use rusqlite::Error; use clap::ArgMatches; use clap_complete::Shell::*; use rayon::prelude::*; use crate::Database; use crate::Zettel; use crate::config::ConfigOptions; use crate::io::file_exists; use crate::cli; fn print_zettel_info(zettel: &[Zettel]) { zettel.par_iter() .for_each(|z| { let ...
print_zettel_info(&results); Ok(()) } pub fn generate(cfg: &ConfigOptions) -> Result<(), Error> { let start = std::time::Instant::now(); let mem_db = Database::in_memory(&cfg.db_file())?; mem_db.init()?; mem_db.generate(cfg); mem_db.write_to(&cfg.db_file())?; println!("database generate...
= Database::new(&cfg.db_file())?; let path = matches.value_of("FILENAME").unwrap(); if file_exists(path) { let zettel = Zettel::from_file(path); db.update(cfg, &zettel)?; } else { eprintln!("error: provided path isn't a file"); } Ok(()) } pub fn query(matches: &ArgMatches...
random
[ { "content": "/// Generate the clap App by using a builer pattern\n\npub fn build() -> App<'static>\n\n{\n\n App::new(env!(\"CARGO_PKG_NAME\"))\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .author(\"xylous <xylous.e@gmail.com>\")\n\n .about(\"CLI tool to manage a digital Zettelkasten\")...
Rust
hooks/src/hooks.rs
lholznagel/rust-blockchain
dab9d5a01b5f94e0e31832badeb8ca8711e9f60b
use message_state::MessageState; use hook_codes::HookCodes; #[derive(Clone, Debug)] pub struct Hooks<T> { pub ping: Option<fn(MessageState<T>)>, pub pong: Option<fn(MessageState<T>)>, pub register: Option<fn(MessageS...
use message_state::MessageState; use hook_codes::HookCodes; #[derive(Clone, Debug)] pub struct Hooks<T> { pub ping: Option<fn(MessageState<T>)>, pub pong: Option<fn(MessageState<T>)>, pub register: Option<fn(MessageS...
}
pub fn add(mut self, hook: HookCodes, function: fn(MessageState<T>)) -> Self { match hook { HookCodes::Ping => self.ping = Some(function), HookCodes::Pong => self.pong = Some(function), HookCodes::Register => self.register = Some(function), HookCodes::RegisterAck ...
function_block-function_prefix_line
[ { "content": "pub fn pong(state: MessageState<State>) {\n\n let mut state_lock = state.state.lock().expect(\"Locking the mutex should be successful.\");\n\n match state_lock.peers.clone().get(&state.source) {\n\n Some(peer) => state_lock.peers.insert(state.source, (peer.0, 0, true)),\n\n Non...
Rust
vrp-core/src/solver/mutation/ruin/cluster_removal.rs
valerivp/vrp
27ee30e5f4c44e051e5cec1248e606305b52fc00
#[cfg(test)] #[path = "../../../../tests/unit/solver/mutation/ruin/cluster_removal_test.rs"] mod cluster_removal_test; use super::*; use crate::algorithms::dbscan::{create_clusters, Cluster, NeighborhoodFn}; use crate::algorithms::geometry::Point; use crate::construction::heuristics::InsertionContext; use crate::model...
#[cfg(test)] #[path = "../../../../tests/unit/solver/mutation/ruin/cluster_removal_test.rs
onment, 4, RuinLimits::default()) } } impl Ruin for ClusterRemoval { fn run(&self, _: &RefinementContext, mut insertion_ctx: InsertionContext) -> InsertionContext { let locked = insertion_ctx.solution.locked.clone(); let mut route_jobs = get_route_jobs(&insertion_ctx.solution); let max...
"] mod cluster_removal_test; use super::*; use crate::algorithms::dbscan::{create_clusters, Cluster, NeighborhoodFn}; use crate::algorithms::geometry::Point; use crate::construction::heuristics::InsertionContext; use crate::models::common::Timestamp; use crate::models::problem::Job; use crate::models::Problem; use cra...
random
[ { "content": "fn open_file(path: &str) -> BufReader<File> {\n\n println!(\"Reading '{}'\", path);\n\n BufReader::new(File::open(path).unwrap_or_else(|err| panic!(\"cannot open {} file: '{}'\", path, err.to_string())))\n\n}\n\n\n", "file_path": "examples/json-pragmatic/src/main.rs", "rank": 0, ...
Rust
grep-pcre2/src/matcher.rs
JesseH-/ripgrep
8892bf648cfec111e6e7ddd9f30e932b0371db68
use std::collections::HashMap; use grep_matcher::{Captures, Match, Matcher}; use pcre2::bytes::{CaptureLocations, Regex, RegexBuilder}; use error::Error; #[derive(Clone, Debug)] pub struct RegexMatcherBuilder { builder: RegexBuilder, case_smart: bool, word: bool, } impl RegexMatcherBuilder { pu...
use std::collections::HashMap; use grep_matcher::{Captures, Match, Matcher}; use pcre2::bytes::{CaptureLocations, Regex, RegexBuilder}; use error::Error; #[derive(Clone, Debug)] pub struct RegexMatcherBuilder { builder: RegexBuilder, case_smart: bool, word: bool, } impl RegexMatcherBuilder { pu...
self, haystack: &[u8], at: usize, ) -> Result<Option<Match>, Error> { Ok(self.regex .find_at(haystack, at) .map_err(Error::regex)? .map(|m| Match::new(m.start(), m.end()))) } fn new_captures(&self) -> Result<RegexCaptures, Error> { Ok(Rege...
self.word { let pattern = format!(r"(?<!\w)(?:{})(?!\w)", pattern); builder.build(&pattern) } else { builder.build(pattern) }; res.map_err(Error::regex).map(|regex| { let mut names = HashMap::new(); for (i, name) in ...
random
[ { "content": "fn matcher(pattern: &str) -> RegexMatcher {\n\n RegexMatcher::new(Regex::new(pattern).unwrap())\n\n}\n\n\n", "file_path": "grep-matcher/tests/test_matcher.rs", "rank": 0, "score": 334064.56055041763 }, { "content": "fn new_regex(pat: &str) -> Result<Regex, Error> {\n\n Re...
Rust
src/metrics.rs
netology-group/janus-conference
d7ae1def0cc8d697e70b108537635aa79320d4b9
use std::time::{Duration, Instant}; use crate::{message_handler::MethodKind, switchboard::Switchboard}; use http::StatusCode; use prometheus::{HistogramOpts, HistogramVec, IntCounterVec, IntGaugeVec, Opts, Registry}; use prometheus_static_metric::make_static_metric; make_static_metric! { pub struct RequestStats: ...
use std::time::{Duration, Instant}; use crate::{message_handler::MethodKind, switchboard::Switchboard}; use http::StatusCode; use prometheus::{HistogramOpts, HistogramVec, IntCounterVec, IntGaugeVec, Opts, Registry}; use prometheus_static_metric::make_static_metric; make_static_metric! { pub struct RequestStats: ...
let request_stats = IntCounterVec::new(Opts::new("request_stats", "Request stats"), &["status"])?; let response_stats = IntCounterVec::new(Opts::new("response_stats", "Response stats"), &["status"])?; let switchboard_stats = IntGaugeVec::new( Opts::new("swi...
let request_duration = HistogramVec::new( HistogramOpts::new("request_duration", "Request duration"), &["method"], )?;
assignment_statement
[ { "content": "pub fn relay_rtp(session: &Session, packet: &mut PluginRtpPacket) {\n\n (acquire_callbacks().relay_rtp)(session.as_ptr(), packet);\n\n}\n\n\n", "file_path": "src/janus_callbacks.rs", "rank": 0, "score": 180755.59645288196 }, { "content": "pub fn relay_rtcp(session: &Session,...
Rust
serenade/src/vmisknn/vmisknn_index_smallopt.rs
bolcom/serenade-experiments-sigmod
0a4c7f19d800d1c2784ea5536abb1a628cb12f7a
use std::collections::BinaryHeap; use std::error::Error; use dary_heap::OctonaryHeap; use hashbrown::hash_map::DefaultHashBuilder; use hashbrown::HashMap; use hashbrown::HashSet; use crate::vmisknn::{SessionScore, SessionTime}; use crate::vmisknn::similarity_hashed::SimilarityComputationHash; pub struct VMISSkNNInde...
use std::collections::BinaryHeap; use std::error::Error; use dary_heap::OctonaryHeap; use hashbrown::hash_map::DefaultHashBuilder; use hashbrown::HashMap; use hashbrown::HashSet; use crate::vmisknn::{SessionScore, SessionTime}; use crate::vmisknn::similarity_hashed::SimilarityComputationHash; pub struct VMISSkNNInde...
}
h_capacity(m); for (pos, item_id) in evolving_session.iter().enumerate() { if let Some(similar_sessions) = self.sessions_for_item.get(item_id) { let decay_factor = (pos + 1) as f64 / evolving_session.len() as f64; for session_id in similar_s...
function_block-function_prefixed
[ { "content": "pub fn read_training_data(training_data_path: &str) -> Vec<(TrainingSessionId, ItemId, Time)> {\n\n let mut line_iterator = create_buffered_line_reader(training_data_path).unwrap();\n\n line_iterator.next(); // skip header\n\n let training_data = line_iterator.par_bridge().filter_map(move...
Rust
src/buffer/primitive_buffer.rs
seventh-chord/gondola
4122966e5cf2cdd7947b2891c1906dfdf71406f2
use std::{mem, ptr}; use std::ops::Range; use std::marker::PhantomData; use gl; use gl::types::*; use super::*; pub struct PrimitiveBuffer<T: VertexData> { phantom: PhantomData<T>, pub(super) buffer: GLuint, target: BufferTarget, usage: BufferUsage, primitive_count: usize, allocated: usiz...
use std::{mem, ptr}; use std::ops::Range; use std::marker::PhantomData; use gl; use gl::types::*; use super::*; pub struct PrimitiveBuffer<T: VertexData> { phantom: PhantomData<T>, pub(super) buffer: GLuint, target: BufferTarget, usage: BufferUsage, primitive_count: usize, allocated: usiz...
pub fn with_data(target: BufferTarget, data: &[T]) -> PrimitiveBuffer<T> { if data.is_empty() { return PrimitiveBuffer::new(target, BufferUsage::StaticDraw); } let mut buffer = 0; let bytes = data.len() * mem::size_of::<T>(); unsafe { gl::GenB...
ptr::null(), usage as GLenum ); } PrimitiveBuffer { phantom: PhantomData, buffer, target, usage, allocated: initial_capacity, primitive_count: 0, } }
function_block-function_prefix_line
[ { "content": "/// This trait is used to mark types which can be used as indices in e.g. a element/index buffer.\n\n/// You should not implement this trait yourself.\n\n///\n\n/// This trait is implemented for `GLuint`, `GLushort` and `GLubyte`, which correspond to `u32`,\n\n/// `u16` and `u8`.\n\npub trait GlIn...
Rust
src/display.rs
icsga/Miditool
098ebea1d24463e16718526b469bfdfe2a81f6c7
use super::Avg; use super::MidiMessage; pub struct Colors { c_normal: &'static str, c_param: &'static str, c_value: &'static str, } pub const COLORS_BW: Colors = Colors{ c_normal: "", c_param: "", c_value: "" }; pub const COLORS_TC: Colors = Colors{ c_normal: "\x1b[30m", c_param: "\x1b[32m", c_value:"\x1b...
use super::Avg; use super::MidiMessage; pub struct Colors { c_normal: &'static str, c_param: &'static str, c_value: &'static str, } pub const COLORS_BW: Colors = Colors{ c_normal: "", c_param: "", c_value: "" }; pub const COLORS_TC: Colors = Colors{ c_normal: "\x1b[30m", c_param: "\x1b[32m", c_value:"\x1b...
pub fn show_message(&mut self, timestamp: u64, in_port: usize, message: &[u8]) { let m = MidiMessage::parse(message); match m { MidiMessage::NoteOn{channel, key, velocity} => { self.print_tpc(timestamp, in_port, channel + 1); print!("NoteOn {}key={} velo...
fn calc_bpm(&mut self, timestamp: u64) { if self.last_clock != 0 { let diff = (timestamp - self.last_clock) * 24; let bpm = 60000000.0 / diff as f64; let bpm = self.avg.add_value(bpm); let bpm = (bpm * 10.0).round() / 10.0; i...
function_block-full_function
[ { "content": "fn get_port<T: MidiIO>(midi_io: &T, port: usize) -> Result<T::Port, Box<dyn Error>> {\n\n let midi_ports = midi_io.ports();\n\n let port = midi_ports.get(port)\n\n .ok_or(\"Invalid port number\")?;\n\n Ok(port.clone())\n\n}\n\n\n", "file_path": "src/main.rs", ...
Rust
rspirv/binary/decoder.rs
fkaa/rspirv
cddf49f43133d7b91091c2c99134bb51fdb4f8d9
use spirv; use std::{mem, result}; use super::error::Error; use utils::num::u32_to_bytes; pub type Result<T> = result::Result<T, Error>; const WORD_NUM_BYTES: usize = 4; pub struct Decoder<'a> { bytes: &'a [u8], offset: usize, limit: Option<usize>, } impl<'a> Decoder<'a> { pu...
use spirv; use std::{mem, result}; use super::error::Error; use utils::num::u32_to_bytes; pub type Result<T> = result::Result<T, Error>; const WORD_NUM_BYTES: usize = 4; pub struct Decoder<'a> { bytes: &'a [u8], offset: usize, limit: Option<usize>, } impl<'a> Decoder<'a> { pu...
#[test] fn test_limit() { let mut v = vec![]; for _ in 0..12 { v.push(0xff); } let mut d = Decoder::new(&v); assert!(!d.has_limit()); assert!(!d.limit_reached()); d.set_limit(4); assert!(d.has_limit()); assert!(!d.limit_reac...
fn test_decoding_after_errors() { let b = vec![0x12, 0x34, 0x56, 0x78]; let mut d = Decoder::new(&b); assert_eq!(Ok(0x78563412), d.word()); assert_eq!(Err(Error::StreamExpected(4)), d.word()); assert_eq!(Err(Error::StreamExpected(4)), d.word()); assert_eq!(Err(Error::Stre...
function_block-full_function
[ { "content": "/// Splits the given u64 `value` into a vector of bytes in little-endian format.\n\npub fn u64_to_bytes(val: u64) -> Vec<u8> {\n\n (0..mem::size_of::<u64>())\n\n .map(|i| ((val >> (8 * i)) & 0xff) as u8)\n\n .collect()\n\n}\n\n\n", "file_path": "rspirv/utils/num.rs", "rank...
Rust
src/lib.rs
saethlin/miri-tools
ca938ead53d46c32caa2a9d02a15d6aab76e62c0
use std::collections::HashMap; use std::fmt; use std::fs; use std::io::Read; use std::path::Path; use color_eyre::Report; use flate2::read::GzDecoder; use once_cell::sync::Lazy; use serde::de::Visitor; use tar::Archive; pub mod db_dump; pub mod diagnose; use diagnose::diagnose; #[derive(Clone, Debug, serde::Seriali...
use std::collections::HashMap; use std::fmt; use std::fs; use std::io::Read; use std::path::Path; use color_eyre::Report; use flate2::read::GzDecoder; use once_cell::sync::Lazy; use serde::de::Visitor; use tar::Archive; pub mod db_dump; pub mod diagnose; use diagnose::diagnose; #[derive(Clone, Debug, serde::Seriali...
pub fn load_completed_crates() -> Result<Vec<Crate>, Report> { let mut crates = HashMap::new(); for entry in std::fs::read_dir("logs")? { let entry = entry?; let mut versions = Vec::new(); for ver in fs::read_dir(entry.path())? { let path = ver?.path(); let ver...
mponents.next(); let full_path = path.join(&components.as_path()); if let Some(parent) = full_path.parent() { fs::create_dir_all(parent)?; } entry.unpack(&full_path)?; } Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn diagnose(krate: &mut Crate) -> Result<()> {\n\n let path = format!(\"logs/{}/{}\", krate.name, krate.version);\n\n if let Ok(output) = fs::read_to_string(&path) {\n\n let output = ANSI_REGEX.replace_all(&output, \"\").to_string();\n\n // Strip ANSI escape codes from the ...
Rust
src/bin/memcached-client/main.rs
williammuji/muduo-rust
36b35337aa3975b28afdc5c92a305cc14e0c6c13
use muduo_rust::{CountdownLatch, Result}; use clap::Parser; use tracing_subscriber; use tracing::info; use tokio::net::TcpStream; use tokio_util::codec::{Framed, LinesCodec}; use futures::SinkExt; use tokio_stream::StreamExt; use std::time::Instant; use tokio::sync::broadcast; #[derive(Parser, Debug)] #[clap(author, v...
use muduo_rust::{CountdownLatch, Result}; use clap::Parser; use tracing_subscriber; use tracing::info; use tokio::net::TcpStream; use tokio_util::codec::{Framed, LinesCodec}; use futures::SinkExt; use tokio_stream::StreamExt; use std::time::Instant; use tokio::sync::broadcast; #[derive(Parser, Debug)] #[clap(author, v...
value.push('a'); } Client { name: format!("conn-{}", n), notify_send, op, sent: 0, acked: 0, requests, keys, value_len, value, connected, finished, } ...
, value_len: i32, connected: CountdownLatch, finished: CountdownLatch) -> Client { let mut value: String = String::with_capacity(value_len as usize); for _ in 0..value_len {
function_block-random_span
[ { "content": "struct GetHistogramFromKey {\n\n}\n\n\n\nimpl GetHistogram for GetHistogramFromKey {\n\n // REQUIRE: keys and pivots are sorted\n\n fn get_histogram(&self, keys: &Vec<i64>, pivots: &Vec<i64>) -> Vec<i64> {\n\n let mut result: Vec<i64> = vec![0; pivots.len()]; \n\n let mut j: us...
Rust
src/bin/flappy.rs
AlexViaColl/Icarus
48570d6ac0d7519c4c5e390cca57e94ed1e99389
use icarus::input::{InputState, KeyId}; use icarus::math::{Rect, Vec2}; use icarus::platform::{Config, Platform}; use icarus::vk_util::{self, RenderCommand, VkContext}; use std::mem; use std::time::Instant; const WIDTH: f32 = 1200.0; const HEIGHT: f32 = 675.0; const MAX_ENTITIES: usize = 200; fn main() { let mu...
use icarus::input::{InputState, KeyId}; use icarus::math::{Rect, Vec2}; use icarus::platform::{Config, Platform}; use icarus::vk_util::{self, RenderCommand, VkContext}; use std::mem; use std::time::Instant; const WIDTH: f32 = 1200.0; const HEIGHT: f32 = 675.0; const MAX_ENTITIES: usize = 200; fn main() { let mu...
#[derive(Default, Copy, Clone)] struct Sprite { material: Material, pos: Vec2, size: Vec2, depth: f32, rotation: u32, } impl Sprite { fn new<V: Into<Vec2>>(material: Material, pos: V, size: V, depth: f32) -> Self { Self::with_rot(material, pos, size, depth, 0) } fn with_rot<...
/ HEIGHT), 0.9, )); sprites.push(Sprite::new( Material::Base, ((i as f32) * BASE_WIDTH, HEIGHT - (BASE_HEIGHT / 2.0)), (BASE_WIDTH, BASE_HEIGHT), 0.8, )); } sprites.p...
random
[ { "content": "pub fn push_str(cmd: &mut Vec<RenderCommand>, s: &str, x: f32, y: f32, z: f32, pixel_size: f32) {\n\n push_str_color(cmd, s, (x, y), z, pixel_size, WHITE, false);\n\n}\n", "file_path": "src/vk_util.rs", "rank": 0, "score": 183955.65813849424 }, { "content": "pub fn push_char...
Rust
src/sys/pkg/lib/system-image/src/lib.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
mod cache_packages; mod errors; mod non_static_allowlist; mod path_hash_mapping; mod system_image; pub use crate::{ cache_packages::CachePackages, errors::{ AllowListError, CachePackagesInitError, PathHashMappingError, StaticPackagesInitError, }, non_static_allowlist::NonStaticAllowList, ...
mod cache_packages; mod errors; mod non_static_allowlist; mod path_hash_mapping; mod system_image; pub use crate::{ cache_packages::CachePackages, errors::{ AllowListError, CachePackagesInitError, PathHashMappingError, StaticPackagesInitError, }, non_static_allowlist::NonStaticAllowList, ...
#[fasync::run_singlethreaded(test)] async fn success() { let mock = MockBootArgumentsService::new(HashMap::from([( PKGFS_BOOT_ARG_KEY.to_string(), Some( "bin/pkgsvr+0000000000000000000000000000000000000000000000000000000000000000" .to_string(...
m(stream)).detach(); assert_matches!(get_system_image_hash(&proxy).await, Err(SystemImageHashError::BadHash(_))); }
function_block-function_prefixed
[]
Rust
backend/src/integrations/lifx/mod.rs
orriborri/homectl
f60ec502e9f61285e4a2658b2e07adb916cb29b3
pub mod lights; pub mod utils; use anyhow::{Context, Result}; use async_trait::async_trait; use homectl_types::{ device::Device, event::TxEventChannel, integration::{Integration, IntegrationActionPayload, IntegrationId}, }; use lights::{init_udp_socket, listen_udp_stream, poll_lights}; use serde::Deseriali...
pub mod lights; pub mod utils; use anyhow::{Context, Result}; use async_trait::async_trait; use homectl_types::{ device::Device, event::TxEventChannel, integration::{Integration, IntegrationActionPayload, IntegrationId}, }; use lights::{init_udp_socket, listen_udp_stream, poll_lights}; use serde::Deseriali...
let target = match lifx_msg.clone() { LifxMsg::Get(addr) => addr, LifxMsg::SetColor(state) => state.addr, LifxMsg::State(state) => state.addr, LifxMsg::SetPower(state) => state.addr, ...
ceiver; let socket = init_udp_socket(&config).await?; let socket = Arc::new(socket); listen_udp_stream(Arc::clone(&socket), integration_id, sender); tokio::spawn(async move { poll_lights(udp_sender_tx).await }); tokio::spawn(async move { loop { let...
random
[ { "content": "pub fn from_lifx_state(lifx_state: LifxState, integration_id: IntegrationId) -> Device {\n\n let hue = from_lifx_hue((f32::from(lifx_state.hue) / 65535.0) * 360.0);\n\n let sat = f32::from(lifx_state.sat) / 65535.0;\n\n let bri = f32::from(lifx_state.bri) / 65535.0;\n\n\n\n let power =...