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/connectivity/bluetooth/profiles/bt-avrcp/src/packets/notification.rs
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
use std::{u32, u64}; use super::*; pub_decodable_enum! { NotificationEventId<u8, Error> { EventPlaybackStatusChanged => 0x01, EventTrackChanged => 0x02, EventTrackReachedEnd => 0x03, EventTrackReachedStart => 0x04, ...
use std::{u32, u64}; use super::*; pub_decodable_enum! { NotificationEventId<u8, Error> { EventPlaybackStatusChanged => 0x01, EventTrackChanged => 0x02, EventTrackReachedEnd => 0x03, EventTrackReachedStart => 0x04, ...
-> Self { Self { identifier } } pub fn unknown() -> Self { Self::new(0x0) } pub fn none() -> Self { Self::new(u64::MAX) } pub fn identifier(&self) -> u64 { self.identifier } } impl VendorDependent for TrackChangedNotificationResponse { fn pdu_id(&self)...
kStatus { self.playback_status } } impl VendorDependent for PlaybackStatusChangedNotificationResponse { fn pdu_id(&self) -> PduId { PduId::RegisterNotification } } impl Decodable for PlaybackStatusChangedNotificationResponse { fn decode(buf: &[u8]) -> PacketResult<Self> { if bu...
random
[]
Rust
src/lib.rs
david-sawatzke/swm050-rs
058b264da47b82461d2415f8b32723f5f0e48fa3
#![doc = "Peripheral access API for SWM050 microcontrollers (generated using svd2rust v0.16.1)\n\nYou can find an overview of the API [here].\n\n[here]: https://docs.rs/svd2rust/0.16.1/svd2rust/#peripheral-api"] #![deny(missing_docs)] #![deny(warnings)] #![allow(non_camel_case_types)] #![no_std] extern crate bare_metal...
#![doc = "Peripheral access API for SWM050 microcontrollers (generated using svd2rust v0.16.1)\n\nYou can find an overview of the API [here].\n\n[here]: https://docs.rs/svd2rust/0.16.1/svd2rust/#peripheral-api"] #![deny(missing_docs)] #![deny(warnings)] #![allow(non_camel_case_types)] #![no_std] extern crate bare_metal...
}) } #[doc = r"Unchecked version of `Peripherals::take`"] pub unsafe fn steal() -> Self { DEVICE_PERIPHERALS = true; Peripherals { SYS: SYS { _marker: PhantomData, }, PORT: PORT { _marker: PhantomData, }...
if unsafe { DEVICE_PERIPHERALS } { None } else { Some(unsafe { Peripherals::steal() }) }
if_condition
[ { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "src/generic.rs", "rank": 0, "score": 72900.83226561888 }, { "content": "#[doc = \"T...
Rust
day11/src/main.rs
thomas9911/aoc-2021
a226244802b69cef33ebed33a44a7537805d0d64
use derive_more::{Deref, DerefMut, From}; use std::convert::TryFrom; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; fn fetch_file_path() -> &'static str { if Path::new("src/input.txt").exists() { "src/input.txt" } else { "day11/src/input.txt" } } #[derive(Debug,...
use derive_more::{Deref, DerefMut, From}; use std::convert::TryFrom; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; fn fetch_file_path() -> &'static str { if Path::new("src/input.txt").exists() { "src/input.txt" } else { "day11/src/input.txt" } } #[derive(Debug,...
fn cells_update(&mut self) { let mut new_grid = self.clone(); for (i, line) in self.data.iter().enumerate() { for (j, cell) in line.iter().enumerate() { if let Octopus::Charging(x) = cell { if x > &MAX_CELL_AMOUNT { new_grid....
f) { self.iter_mut().for_each(|x| { x.iter_mut().for_each(|y| match y { Octopus::Charging(z) => *z += 1, Octopus::Charged => (), }) }) }
function_block-function_prefixed
[ { "content": "fn parse_hex(ch: char) -> Option<&'static [u8]> {\n\n Some(match ch {\n\n '0' => &[0, 0, 0, 0],\n\n '1' => &[0, 0, 0, 1],\n\n '2' => &[0, 0, 1, 0],\n\n '3' => &[0, 0, 1, 1],\n\n '4' => &[0, 1, 0, 0],\n\n '5' => &[0, 1, 0, 1],\n\n '6' => &[0, 1, 1...
Rust
git-object/src/immutable/commit.rs
PoignardAzur/gitoxide
e6acd193f5140f264b8fad6decd924b19a1fee3f
use std::borrow::Cow; use nom::{ branch::alt, bytes::{complete::is_not, complete::tag}, combinator::{all_consuming, opt}, multi::many0, IResult, }; use smallvec::SmallVec; use crate::{ immutable::{object::decode, parse, parse::NL, Signature}, BStr, ByteSlice, }; #[derive(PartialEq, Eq, De...
use std::borrow::Cow; use nom::{ branch::alt, bytes::{complete::is_not, complete::tag}, combinator::{all_consuming, opt}, multi::many0, IResult, }; use smallvec::SmallVec; use crate::{ immutable::{object::decode, parse, parse::NL, Signature}, BStr, ByteSlice, }; #[derive(PartialEq, Eq, De...
} pub mod iter { use crate::{ bstr::ByteSlice, immutable::{commit::parse_message, object::decode, parse, parse::NL, Signature}, }; use bstr::BStr; use git_hash::{oid, ObjectId}; use nom::{ branch::alt, bytes::complete::is_not, combinator::{all_consuming, opt...
fn size_of_commit() { assert_eq!( std::mem::size_of::<Commit<'_>>(), 216, "the size of an immutable commit shouldn't change unnoticed" ); }
function_block-full_function
[ { "content": "pub fn hex_to_id(hex: &[u8]) -> git_hash::ObjectId {\n\n git_hash::ObjectId::from_hex(hex).expect(\"40 bytes hex\")\n\n}\n\n\n\npub struct RefInfo {\n\n id: git_hash::ObjectId,\n\n parent_ids: Vec<git_hash::ObjectId>,\n\n pos: GraphPosition,\n\n root_tree_id: git_hash::ObjectId,\n\n...
Rust
src/main.rs
wooga/jenkins-metrics
dc1572e2206e8120cd5826989a3da59b32526f24
use chrono::{DateTime, Utc}; use humantime::format_duration as f_duration; use log::*; use prettytable::{cell, format, row, Table}; use chrono::Duration as CDuration; use jenkins_metrics::cli::Options; use jenkins_metrics::report::Report; use jenkins_metrics::ReportSample; use serde_json::from_reader; use std::cmp::O...
use chrono::{DateTime, Utc}; use humantime::format_duration as f_duration; use log::*; use prettytable::{cell, format, row, Table}; use chrono::Duration as CDuration; use jenkins_metrics::cli::Options; use jenkins_metrics::report::Report; use jenkins_metrics::ReportSample; use serde_json::from_reader; use std::cmp::O...
2}", statistical::mean(&executor_utilization)), f_duration(Duration::from_secs_f64( statistical::mean(&queuing_durations).floor() )), f_duration(Duration::from_secs_f64( statistical::median(&queuing_durations).floor() )), f_duration(Duration::from_secs_f64...
function_block-function_prefixed
[ { "content": " def date = new Date()\n", "file_path": "scripts/jenkins_metrics.groovy", "rank": 2, "score": 65940.5006439964 }, { "content": " def timings = build.getAction(jenkins.metrics.impl.TimeInQueueAction.class)\n\n if(timings) {\n\n report = [:]\n\n ...
Rust
src/measurement_ops.rs
oxarbitrage/RustQIP
56757b5a3eb2474542aa8a47ff839470d98d4f91
use crate::rayon_helper::*; use crate::utils::extract_bits; use crate::{Complex, Precision}; use num::Zero; use std::cmp::{max, min}; pub fn prob_magnitude<P: Precision>(input: &[Complex<P>]) -> P { iter!(input).map(Complex::<P>::norm_sqr).sum() } pub fn measure_prob<P: Precision>( n: u64, measured: u64, ...
use crate::rayon_helper::*; use crate::utils::extract_bits; use crate::{Complex, Precision}; use num::Zero; use std::cmp::{max, min}; pub fn prob_magnitude<P: Precision>(input: &[Complex<P>]) -> P { iter!(input).map(Complex::<P>::norm_sqr).sum() } pub fn measure_prob<P: Precision>( n: u64, measured: u64, ...
P>, } pub fn measure<P: Precision>( n: u64, indices: &[u64], input: &[Complex<P>], output: &mut [Complex<P>], offsets: Option<(u64, u64)>, measured: Option<MeasuredCondition<P>>, ) -> (u64, P) { let input_offset = offsets.map(|(i, _)| i); let m = if let Some(measured) = &measured { ...
+ input_offset; break; } } let indices: Vec<_> = indices.iter().map(|indx| n - 1 - indx).collect(); extract_bits(measured_indx, &indices) } #[derive(Debug)] pub struct MeasuredCondition<P: Precision> { pub measured: u64, pub prob: Option<
random
[ { "content": "/// Helper function for Boxing static functions and applying using the given UnitaryBuilder.\n\npub fn apply_function<F: 'static + Fn(u64) -> (u64, f64) + Send + Sync>(\n\n b: &mut dyn UnitaryBuilder,\n\n r_in: Register,\n\n r_out: Register,\n\n f: F,\n\n) -> Result<(Register, Register...
Rust
src/typeck/subtyping.rs
ThePuzzlemaker/sysf-rs
b4acd1b5cf8978bf3ebbaecba6153852f6b6b126
use crate::ast::core::Ty; use crate::ctx::TyCtxt; use crate::trace; #[cfg(feature = "trace")] use tracing::instrument; #[cfg_attr(feature = "trace", instrument(level = "trace", skip(ctx)))] pub fn subtype(ctx: &mut TyCtxt, ty1: &Ty, ty2: &Ty) -> Option<()> { trace!("subtype/enter"); match (ty1, ty2) { ...
use crate::ast::core::Ty; use crate::ctx::TyCtxt; use crate::trace; #[cfg(feature = "trace")] use tracing::instrument; #[cfg_attr(feature = "trace", instrument(level = "trace", skip(ctx)))] pub fn subtype(ctx: &mut TyCtxt, ty1: &Ty, ty2: &Ty) -> Option<()> { trace!("subtype/enter"); match (ty1, ty2) { ...
ctx.solve_evar(*beta, Ty::ExstVar(evar)); } Ty::Arrow(a1, a2) => { let alpha2 = ctx.fresh_evar(); let alpha1 = ctx.fresh_evar(); ctx.insert_unsolved_before_evar(evar, alpha2)?; ctx.insert_unsolved_before_evar(evar, alpha1)?; ...
if !ctx.contains_evar(*beta) { trace!("inst_right/leave: InstRReach: no beta in ctx"); return None; }
if_condition
[ { "content": "#[cfg_attr(feature = \"trace\", instrument(level = \"trace\", skip(ctx)))]\n\npub fn check(ctx: &mut TyCtxt, term: &Term, ty: &Ty) -> Option<()> {\n\n trace!(\"check/enter\");\n\n\n\n match (term, ty) {\n\n // 1I; BoolI (not in paper)\n\n (_, Ty::Unit | Ty::Bool) => (),\n\n ...
Rust
src/base/mod.rs
youngspe/rc-vec
1ab385b5da9326cf4a165d2530f9e0892e8c293d
pub mod vec_ref; use header_slice::HeaderVec; use vec_ref::{HeaderVecParts, VecMut, VecRef}; pub trait Counter: Default + Clone {} pub struct BaseRcVec<V: VecType, T> { parts: HeaderVecParts<V::Counter, T>, } pub unsafe trait VecType { type Counter: Counter; fn incr(counter: &Self::Counter); fn decr...
pub mod vec_ref; use header_slice::HeaderVec; use vec_ref::{HeaderVecParts, VecMut, VecRef}; pub trait Counter: Default + Clone {} pub struct BaseRcVec<V: VecType, T> { parts: HeaderVecParts<V::Counter, T>, } pub unsafe trait VecType { type Counter: Counter; fn incr(counter: &Self::Counter); fn decr...
pub fn try_into_vec(mut self) -> Result<HeaderVec<V::Counter, T>, Self> { if !self.try_make_unique() { return Err(self); } Ok(unsafe { self.parts.into_vec() }) } } impl<V: VecType, T> Drop for BaseRcVec<V, T> { fn drop(&mut self) { unsafe { V::decr...
pub fn try_make_vec_mut(&mut self) -> Option<VecMut<V::Counter, T>> { if !self.try_make_unique() { return None; } Some(unsafe { self.unsafe_vec_mut() }) }
function_block-full_function
[ { "content": "#[test]\n\npub fn from_self_iter() {\n\n base_str_iter_test::<RcString>();\n\n}\n\n\n", "file_path": "src/test/string/from_iter.rs", "rank": 1, "score": 76477.36442486948 }, { "content": "#[test]\n\npub fn add_self() {\n\n let s = rc_str!(\"foo\") + rc_str!(\"bar\");\n\n ...
Rust
src/lib.rs
bhgomes/streamers
d987b46760c301bc9d28841f39e89fde6b4415fe
#![cfg_attr(docsrs, feature(doc_cfg), forbid(broken_intra_doc_links))] #![feature(generic_associated_types)] #![allow(incomplete_features)] #![forbid(missing_docs)] #![no_std] use { core::{ future::{ready, Future, Ready}, marker::PhantomData, pin::Pin, task::{Context, Poll}, }...
#![cfg_attr(docsrs, feature(doc_cfg), forbid(broken_intra_doc_links))] #![feature(generic_associated_types)] #![allow(incomplete_features)] #![forbid(missing_docs)] #![no_std] use { core::{ future::{ready, Future, Ready}, marker::PhantomData, pin::Pin, task::{Context, Poll}, }...
} } impl<T, E, V> FromStream<Result<T, E>> for Result<V, E> where V: FromStream<T>, { type Future<S> where S: IntoStream<Item = Result<T, E>>, = ResultFromStreamFuture<T, E, V, S>; #[inline] fn from_stream<S>(stream: S) -> Self::Future<S> where ...
if self.error.is_err() { (0, Some(0)) } else { let (_, upper) = self.stream.size_hint(); (0, upper) }
if_condition
[]
Rust
zebra-state/src/on_disk.rs
fakecoinbase/ZcashFoundationslashzebra
5b3c6e4c6cc9fc125f53a3f798833a66648fefc9
use super::{Request, Response}; use crate::Config; use futures::prelude::*; use std::sync::Arc; use std::{ error, future::Future, pin::Pin, task::{Context, Poll}, }; use tower::{buffer::Buffer, Service}; use zebra_chain::serialization::{ZcashDeserialize, ZcashSerialize}; use zebra_chain::{ block::{...
use super::{Request, Response}; use crate::Config; use futures::prelude::*; use std::sync::Arc; use std::{ error, future::Future, pin::Pin, task::{Context, Poll}, }; use tower::{buffer::Buffer, Service}; use zebra_chain::serialization::{ZcashDeserialize, ZcashSerialize}; use zebra_chain::{ block::{...
} Request::GetDepth { hash } => { let storage = self.clone(); async move { if !storage.contains(&hash)? { return Ok(Response::Depth(None)); } let block = storage ...
storage = self.clone(); async move { storage .get(hash)? .map(|block| Response::Block { block }) .ok_or_else(|| "block could not be found".into()) } .boxed() } ...
random
[ { "content": "type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;\n\n\n\n/// Signaling mechanism for batchable services that allows explicit flushing.\n\npub enum BatchControl<R> {\n\n /// A new batch item.\n\n Item(R),\n\n /// The current batch should be flushed.\n\n Flush,\n\n}\n\n...
Rust
src/image/images.rs
pierreprinetti/rust-openstack
267de802f66d207aff02bda28b5d8676d931924c
use std::rc::Rc; use chrono::{DateTime, FixedOffset}; use fallible_iterator::{FallibleIterator, IntoFallibleIterator}; use super::super::common::{ImageRef, IntoVerified, Refresh, ResourceIterator, ResourceQuery}; use super::super::session::Session; use super::super::utils::Query; use super::super::{Error, Result, S...
use std::rc::Rc; use chrono::{DateTime, FixedOffset}; use fallible_iterator::{FallibleIterator, IntoFallibleIterator}; use super::super::common::{ImageRef, IntoVerified, Refresh, ResourceIterator, ResourceQuery}; use super::super::session::Session; use super::super::utils::Query; use super::super::{Error, Result, S...
pub fn all(self) -> Result<Vec<Image>> { self.into_iter().collect() } pub fn one(mut self) -> Result<Image> { debug!("Fetching one image with {:?}", self.query); if self.can_paginate { self.query.push("limit"...
t", self.sort.join(",")); } debug!("Fetching images with {:?}", self.query); ResourceIterator::new(self) }
function_block-function_prefixed
[ { "content": "/// Create a new container.\n\n///\n\n/// Returns `true` if the container was created, `false` if it existed.\n\npub fn create_container<C>(session: &Session, container: C) -> Result<bool>\n\nwhere\n\n C: AsRef<str>,\n\n{\n\n let c_id = container.as_ref();\n\n debug!(\"Creating container ...
Rust
distant-lua/src/session/api.rs
chipsenkbeil/distant
c6c07c5c2ce6ef5c1499c08ce077a14c2c558716
use crate::{ runtime, session::proc::{Output, RemoteProcess as LuaRemoteProcess}, }; use distant_core::{ DirEntry, Error as Failure, Metadata, RemoteLspProcess, RemoteProcess, SessionChannel, SessionChannelExt, SystemInfo, }; use mlua::prelude::*; use once_cell::sync::Lazy; use paste::paste; use serde::...
use crate::{ runtime, session::proc::{Output, RemoteProcess as LuaRemoteProcess}, }; use distant_core::{ DirEntry, Error as Failure, Metadata, RemoteLspProcess, RemoteProcess, SessionChannel, SessionChannelExt, SystemInfo, }; use mlua::prelude::*; use once_cell::sync::Lazy; use paste::paste; use serde::...
String>, #[serde(default)] detached: bool }, |channel, tenant, params| { channel.spawn(tenant, params.cmd, params.args, params.detached).await } ); make_api!( spawn_wait, Output, { cmd: String, #[serde(default)] args: Vec<String>, #[serde(default)] detached: bool }, |channel, tenant, pa...
make_api!( read_file, Vec<u8>, { path: PathBuf }, |channel, tenant, params| { channel.read_file(tenant, params.path).await } ); make_api!( read_file_text, String, { path: PathBuf }, |channel, tenant, params| { channel.read_file_text(tenant, params.path).await } ); make_api!( remov...
random
[ { "content": "/// Spawns a task on the global runtime for a future that returns a `LuaResult<T>`\n\npub fn spawn<F, T>(f: F) -> impl Future<Output = LuaResult<T>>\n\nwhere\n\n F: Future<Output = Result<T, LuaError>> + Send + 'static,\n\n T: Send + 'static,\n\n{\n\n futures::future::ready(get_runtime())...
Rust
src/handler/topic.rs
fakeshadow/pixel-social
7e2fff3acae5b9d8fa6ae711642de2dd83f037cd
use std::future::Future; use chrono::Utc; use tokio_postgres::types::{ToSql, Type}; use crate::handler::{ cache::MyRedisPool, cache::TOPIC_U8, cache_update::{CacheFailedMessage, CacheServiceAddr}, db::{GetStatement, MyPostgresPool, ParseRowStream}, }; use crate::model::{ errors::ResError, topi...
use std::future::Future; use chrono::Utc; use tokio_postgres::types::{ToSql, Type}; use crate::handler::{ cache::MyRedisPool, cache::TOPIC_U8, cache_update::{CacheFailedMessage, CacheServiceAddr}, db::{GetStatement, MyPostgresPool, ParseRowStream}, }; use crate::model::{ errors::ResError, topi...
!("category:{}:topics_time", cid); self.get_cache_with_uids_from_zrevrange(key.as_str(), page, crate::handler::cache::TOPIC_U8) .await } pub(crate) fn get_topics( &self, ids: Vec<u32>, ) -> impl Future<Output = Result<(Vec<Topic>, Vec<u32>), ResError>> + '_ { sel...
ql + Sync)); index += 1; } if let Some(s) = &t.thumbnail { query.push_str(" thumbnail=$"); query.push_str(index.to_string().as_str()); query.push_str(","); params.push(s as &(dyn ToSql + Sync)); index += 1; } if let ...
random
[]
Rust
timescale-api/src/main.rs
dianasaur323/timescale-ui-hack
687b5a81ec3808e444eb2855494e21c2648f8851
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; extern crate dotenv; extern crate postgres; extern crate rocket_cors; use postgres::{Connection, TlsMode}; use std::env; use serde::{Serialize, Deserialize}; use rocket::http::Method; use rocket_cors::{ AllowedHeaders, AllowedOrigi...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; extern crate dotenv; extern crate postgres; extern crate rocket_cors; use postgres::{Connection, TlsMode}; use std::env; use serde::{Serialize, Deserialize}; use rocket::http::Method; use rocket_cors::{ AllowedHeaders, AllowedOrigi...
fn main() { rocket::ignite() .attach(make_cors()) .mount("/", routes![index]) .mount("/hypertable", routes![hypertable]) .launch(); }
allowed_origins, allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(), allowed_headers: AllowedHeaders::some(&[ "Authorization", "Accept", "Access-Control-Allow-Origin", ]), allow_credentials: true, ..Default::default() ...
function_block-function_prefix_line
[ { "content": "# timescale-ui-hack\n\nHacked up Timescale UI demo\n\n\n\nSet database URL: echo DATABASE_URL=postgres://postgres:password@localhost/rust-web-with-rocket > .env\n", "file_path": "README.md", "rank": 8, "score": 2.561161859373789 } ]
Rust
src/mac/srp/simple.rs
unseddd/cryptopals
d390dafbdfd91e3613abb9f99902ab3f9251a594
use alloc::vec::Vec; use core::ops::Mul; use num::bigint::BigUint; use num::Zero; use rand::{thread_rng, Rng}; use isha2::Sha2; use crate::dh; use crate::mac::hmac_sha256; use super::{Error, SecureRemotePassword}; use super::{FAILED_LOGIN, SUCCESSFUL_LOGIN}; pub const DICTIONARY: [&'static [u8; 10]; 10] = [ b"l...
use alloc::vec::Vec; use core::ops::Mul; use num::bigint::BigUint; use num::Zero; use rand::{thread_rng, Rng}; use isha2::Sha2; use crate::dh; use crate::mac::hmac_sha256; use super::{Error, SecureRemotePassword}; use super::{FAILED_LOGIN, SUCCESSFUL_LOGIN}; pub const DICTIONARY: [&'static [u8; 10]; 10] = [ b"l...
fn generate_password_exponent(&mut self, password: &[u8]) -> Result<(), Error> { let mut input = self.salt.to_be_bytes().to_vec(); input.extend_from_slice(&password); let xh = isha2::sha256::Sha256::digest(&input).map_err(|e| Error::Sha256(e))?; le...
nt, challenge: &[u8; isha2::sha256::DIGEST_LEN], ) -> Result<&'static str, Error> { if email != self.email { return Err(Error::InvalidEmail); } if self.validate_challenge(&client_public_key, &challenge)? { Ok(SUCCESSFUL_LOGIN) } else { Err...
function_block-function_prefixed
[ { "content": "/// XOR fixed-length byte slices\n\n///\n\n/// errors: returns Error on unequal lengths\n\npub fn xor_equals(left: &mut [u8], right: &[u8]) -> Result<(), Error> {\n\n if left.len() != right.len() {\n\n return Err(Error::XORLength);\n\n }\n\n for (i, j) in left.iter_mut().zip(right....
Rust
src/app.rs
Ealhad/sorting-visualization
8b0c6118158dc1104839dd53f0da85d318b5c6b8
use graphics; use graphics::types::Color; use opengl_graphics::GlGraphics; use piston::input::*; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use algorithms::Algorithm; use array::Array; use state::*; const BACKGROUND_COLOR: Color = graphics::color::BLACK; const VALUE_COLOR: Color = graphics::color::WH...
use graphics; use graphics::types::Color; use opengl_graphics::GlGraphics; use piston::input::*; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use algorithms::Algorithm; use array::Array; use state::*; const BACKGROUND_COLOR: Color = graphics::color::BLACK; const VALUE_COLOR: Color = graphics::color::WH...
pub fn render(&mut self, gl: &mut GlGraphics, args: RenderArgs) { let window_w = f64::from(args.width); let window_h = f64::from(args.height); gl.draw(args.viewport(), |ctx, gl| { graphics::clear(BACKGROUND_COLOR, gl); let anim = self.0.animation(); let len = anim.a...
ay_accesses: Vec::with_capacity(1024), }), pause_notifier: Condvar::new(), }); let algorithm_state = state.clone(); thread::Builder::new() .name("algorithm".to_string()) .spawn(move || { let array = Array::new(algorithm_state); array.wait(500); algorithm.sor...
function_block-function_prefixed
[]
Rust
src/lib.rs
JackThomson2/fastdivide
0ab67f3e1657faf7f0cd8708156951715637b302
/*! # Yes, but what is it really ? Division is a very costly operation for your CPU (probably between 10 and 40 cycles). You may have noticed that when the divisor is known at compile time, your compiler transforms the operations into a cryptic combination of a multiplication and bitshift. Fastdivide is about doing ...
/*! # Yes, but what is it really ? Division is a very costly operation for your CPU (probably between 10 and 40 cycles). You may have noticed that when the divisor is known at compile time, your compiler transforms the operations into a cryptic combination of a multiplication and bitshift. Fastdivide is about doing ...
const fn fast_path(divisor: u64) -> Option<DividerU64> { if is_power_of_2(divisor) { return None; } if divisor == 0 { unsafe { core::hint::unreachable_unchecked() } } let floor_log_2_d: u8 = 63u8 - (divisor.leading_zeros() as u8); let u = 1...
t fn power_of_2_division(divisor: u64) -> Option<DividerU64> { let floor_log_2_d: u8 = 63u8 - (divisor.leading_zeros() as u8); if is_power_of_2(divisor) { return Some(DividerU64::BitShift(floor_log_2_d)); } None }
function_block-function_prefixed
[ { "content": "fn divide(item: u64, divider: usize) -> u64 {\n\n let divider = unsafe { CONST_ARRAY.get_unchecked(divider) };\n\n divider.divide(item)\n\n}\n\n\n", "file_path": "src/bench.rs", "rank": 1, "score": 68251.01793907073 }, { "content": "#[bench]\n\nfn bench_const_fast_divide(...
Rust
lib/collection/tests/collection_restore_test.rs
kgrech/qdrant
ab58a41a1128bd2d124c454850d22749d516ba7c
use std::sync::Arc; use tempdir::TempDir; use collection::collection_builder::collection_loader::load_collection; use collection::collection_manager::simple_collection_searcher::SimpleCollectionSearcher; use collection::collection_manager::simple_collection_updater::SimpleCollectionUpdater; use collection::operations...
use std::sync::Arc; use tempdir::TempDir; use collection::collection_builder::collection_loader::load_collection; use collection::collection_manager::simple_collection_searcher::SimpleCollectionSearcher; use collection::collection_manager::simple_collection_updater::SimpleCollectionUpdater; use collection::operations...
&r#"[{ "k": { "type": "keyword", "value": "v1" } }, { "k": "v2"}]"#, ) .unwrap(), }), ); collection .update_by(insert_points, true, updater.clone()) .await .unwrap(); } let collection = load_collection(collectio...
_fixture; mod common; #[tokio::test] async fn test_collection_reloading() { let collection_dir = TempDir::new("collection").unwrap(); { let _collection = simple_collection_fixture(collection_dir.path()).await; } let updater = Arc::new(SimpleCollectionUpdater::new()); for _i in 0..5 { ...
random
[ { "content": "use std::fs::create_dir_all;\n\nuse std::path::Path;\n\nuse std::sync::Arc;\n\n\n\nuse crossbeam_channel::unbounded;\n\nuse parking_lot::{Mutex, RwLock};\n\nuse tokio::runtime;\n\n\n\nuse segment::segment_constructor::simple_segment_constructor::build_simple_segment;\n\nuse segment::types::HnswCon...
Rust
src/actions.rs
nidble/pluto-rs
18f18952004dcd300d1dc81b3064bd88e8f85e10
use chrono::{DateTime, Utc}; use log::{log, Level}; use rweb::{get, post, Rejection, Reply}; use serde::Deserialize; use serde_json::json; use std::convert::Infallible; use crate::api; use crate::http_error::{decorate_error, HttpError}; use crate::model; use crate::util; #[derive(Debug, Deserialize)] #[serde(rename_a...
use chrono::{DateTime, Utc}; use log::{log, Level}; use rweb::{get, post, Rejection, Reply}; use serde::Deserialize; use serde_json::json; use std::convert::Infallible; use crate::api; use crate::http_error::{decorate_error, HttpError}; use crate::model; use crate::util; #[derive(Debug, Deserialize)] #[serde(rename_a...
("/api/v1/exchanges") .reply(&action) .await; let mut db_repo = db_repo.lock().unwrap(); db_repo.checkpoint(); let mut api = api.lock().unwrap(); api.checkpoint(); } }
om: f64, } #[get("/healthz")] pub async fn status(#[data] repo: impl model::Repository) -> Result<impl Reply, Rejection> { repo.ping().await.map_err(decorate_error(1001))?; Ok(rweb::reply::reply()) } #[post("/api/v1/exchanges")] pub async fn new_exchange( #[data] repo: impl model::Repository, #[data]...
random
[ { "content": "pub fn init_routes<R, A>(\n\n repo: R,\n\n api_service: A,\n\n) -> anyhow::Result<impl Filter<Extract = (impl Reply,), Error = Infallible> + Clone>\n\nwhere\n\n R: Repository,\n\n A: Api,\n\n{\n\n let health_check = status(repo.clone());\n\n let exchanges = new_exchange(repo, api...
Rust
crates/building_blocks_mesh/src/quad.rs
superdump/building-blocks
410244a3a499b9d7f893c07f94cdd5089313c0ba
use super::{PosNormMesh, PosNormTexMesh}; use building_blocks_core::{ axis::{Axis3Permutation, SignedAxis3}, prelude::*, }; pub struct QuadGroup<M> { pub quads: Vec<(Quad, M)>, pub face: OrientedCubeFace, } impl<M> QuadGroup<M> { pub fn new(face: OrientedCubeFace) -> Self { Self { ...
use super::{PosNormMesh, PosNormTexMesh}; use building_blocks_core::{ axis::{Axis3Permutation, SignedAxis3}, prelude::*, }; pub struct QuadGroup<M> { pub quads: Vec<(Quad, M)>, pub face: OrientedCubeFace, } impl<M> QuadGroup<M> { pub fn new(face: OrientedCubeFace) -> Self { Self { ...
, minu_maxv.into(), maxu_maxv.into(), ] } pub fn quad_mesh_positions(&self, quad: &Quad) -> [[f32; 3]; 4] { let [c0, c1, c2, c3] = self.quad_corners(quad); [c0.0, c1.0, c2.0, c3.0] } pub fn quad_mesh_normals(&self) -> [[f32; 3]; 4] { [self.mesh_...
SignedAxis3) -> Self { Self::new( normal.sign, Axis3Permutation::even_with_normal_axis(normal.axis), ) } pub fn quad_corners(&self, quad: &Quad) -> [Point3f; 4] { let w_vec = self.u * quad.width; ...
random
[ { "content": "pub fn plane(n: Point3f, thickness: f32) -> impl Fn(&Point3i) -> f32 {\n\n move |p| {\n\n let pf: Point3f = (*p).into();\n\n\n\n let d = pf.dot(&n);\n\n\n\n d * d - thickness\n\n }\n\n}\n\n\n", "file_path": "crates/building_blocks_procgen/src/signed_distance_fields.r...
Rust
src/lib.rs
hwiechers/peggler
6c9c02ac2ba7e4029af0cb615700cde1f3588f8f
#[derive(Debug, Eq, PartialEq)] pub struct ParseError; pub type ParseResult<'a, T> = Result<(T, &'a str), ParseError>; pub type Parser<T> = Fn(&str) -> ParseResult<T>; pub fn optional<'a, T>(result: ParseResult<'a, T>, input: &'a str) -> ParseResult<'a, Option<T>> { match result { Ok((value, remaining))...
#[derive(Debug, Eq, PartialEq)] pub struct ParseError; pub type ParseResult<'a, T> = Result<(T, &'a str), ParseError>; pub type Parser<T> = Fn(&str) -> ParseResult<T>; pub fn optional<'a, T>(result: ParseResult<'a, T>, input: &'a str) -> ParseResult<'a, Option<T>> { match result { Ok((value, remaining))...
mod rule_definition; mod sequences; mod choices; mod subexpressions; mod string_expressions; mod optional; mod one_or_more; mod zero_or_more; mod and; mod not; }
if input.starts_with("c") { Ok((3, &input[1..])) } else { Err(ParseError) } }
function_block-function_prefix_line
[]
Rust
src/errors.rs
genofire/tss-sapi
6a1ae1009b67ea3f960f81515a81fbac8f23d618
pub mod tcti { error_chain! { errors { GenFail { description("general failure") display("general failure") } IoError { description("I/O failure") display("I/O failure") } NotWrapped(e:...
pub mod tcti { error_chain! { errors { GenFail { description("general failure") display("general failure") } IoError { description("I/O failure") display("I/O failure") } NotWrapped(e:...
d or is not correct for the use") } Initialize { description("TPM not initialized") display("TPM not initialized") } Insufficient { description("the TPM was unable to unmarshal a value\ because there were...
display("the authorization HMAC check failed and DA counter incremented") } BadAuth { description("authorization failure without DA implications") display("authorization failure without DA implications") } Disabled { ...
random
[ { "content": " pub trait ErrorCodes {\n\n fn is_format_one(self) -> bool;\n\n fn get_code_fmt1(self) -> Self;\n\n fn get_code_ver1(self) -> Self;\n\n }\n\n\n\n impl ErrorCodes for TSS2_RC {\n\n fn is_format_one(self) -> bool {\n\n is_bit_set(self, TPM_RC_FORMAT_ON...
Rust
transition_functions/src/blocks/block_processing.rs
pikaciu22x/framework
5dff45eaa5ad5f8c3bfcb6353d341609318dac46
use helper_functions::beacon_state_accessors::*; use helper_functions::beacon_state_mutators::*; use helper_functions::crypto::{bls_verify, hash, hash_tree_root, signed_root}; use helper_functions::math::*; use helper_functions::misc::{compute_domain, compute_epoch_at_slot}; use helper_functions::predicates::{ is_a...
use helper_functions::beacon_state_accessors::*; use helper_functions::beacon_state_mutators::*; use helper_functions::crypto::{bls_verify, hash, hash_tree_root, signed_root}; use helper_functions::math::*; use helper_functions::misc::{compute_domain, compute_epoch_at_slot}; use helper_functions::predicates::{ is_a...
fn process_attestation<T: Config>(state: &mut BeaconState<T>, attestation: &Attestation<T>) { let data = &attestation.data; let attestation_slot = data.slot; assert!(data.index < get_committee_count_at_slot(state, attestation_slot).unwrap()); assert!( data.target.epoch == get_previous_epoch(st...
&(header.signature.clone()).try_into().unwrap(), domain ) .unwrap()); } slash_validator(state, proposer_slashing.proposer_index, None).unwrap(); } fn process_attester_slashing<T: Config>( state: &mut BeaconState<T>, attester_slashing: &AttesterSlashing<T>, ) { ...
random
[ { "content": "pub fn process_slots<T: Config>(state: &mut BeaconState<T>, slot: Slot) {\n\n // assert!(state.slot <= slot);\n\n while state.slot < slot {\n\n process_slot(state);\n\n //# Process epoch on the start slot of the next epoch\n\n if (state.slot + 1) % T::SlotsPerEpoch::U64 ...
Rust
htsget-search/src/htsget/bam_search.rs
metaclips/htsget-mvp
3c172638ac58ff31dd730e73de2f52aa0b0febdd
use std::{fs::File, path::Path}; use bam::bai::index::reference_sequence::bin::Chunk; use noodles_bam::{self as bam, bai}; use noodles_bgzf::VirtualPosition; use noodles_sam::{self as sam}; use crate::{ htsget::{Format, HtsGetError, Query, Response, Result, Url}, storage::{BytesRange, GetOptions, Storage, UrlOp...
use std::{fs::File, path::Path}; use bam::bai::index::reference_sequence::bin::Chunk; use noodles_bam::{self as bam, bai}; use noodles_bgzf::VirtualPosition; use noodles_sam::{self as sam}; use crate::{ htsget::{Format, HtsGetError, Query, Response, Result, Url}, storage::{BytesRange, GetOptions, Storage, UrlOp...
fn get_keys_from_id(&self, id: &str) -> (String, String) { let bam_key = format!("{}.bam", id); let bai_key = format!("{}.bai", bam_key); (bam_key, bai_key) } fn get_byte_ranges_for_all_reads( &self, bam_key: &str, bai_index: &bai::Index, ) -> Result<Vec<BytesRange>> { ...
let byte_ranges = match query.reference_name.as_ref() { None => self.get_byte_ranges_for_all_reads(bam_key.as_str(), &bai_index)?, Some(reference_name) if reference_name.as_str() == "*" => { self.get_byte_ranges_for_unmapped_reads(bam_key.as_str(), &bai_index)? } Some(reference_name) => ...
function_block-function_prefix_line
[ { "content": "/// An Storage represents some kind of object based storage (either locally or in the cloud)\n\n/// that can be used to retrieve files for alignments, variants or its respective indexes.\n\npub trait Storage {\n\n // TODO Consider another type of interface based on IO streaming\n\n // so we don'...
Rust
src/lzp2.rs
mgrabmueller/campross
5944c3cf8f30330c25b13bcb80bb87b7e7650b6f
use std::io::{Read, Write, Bytes}; use std::io; use huff::adaptive as nested; use error::Error; const WINDOW_BITS: usize = 12; const LENGTH_BITS: usize = 8; const MIN_MATCH_LEN: usize = 1; const MAX_MATCH_LEN: usize = ((1 << LENGTH_BITS) - 1) + MIN_MATCH_LEN; const LOOK_AHEAD_BYTES: usize = MAX_MATCH_LEN; const...
use std::io::{Read, Write, Bytes}; use std::io; use huff::adaptive as nested; use error::Error; const WINDOW_BITS: usize = 12; const LENGTH_BITS: usize = 8; const MIN_MATCH_LEN: usize = 1; const MAX_MATCH_LEN: usize = ((1 << LENGTH_BITS) - 1) + MIN_MATCH_LEN; const LOOK_AHEAD_BYTES: usize = MAX_MATCH_LEN; const...
pub fn to_inner(self) -> W { self.inner.into_inner() } } impl<W: Write> Write for Writer<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut written = 0; while written < buf.len() { while written < buf.len() && self.look_ahead_bytes < LOOK_AHEAD_BY...
fn process(&mut self) -> io::Result<()> { let search_pos = self.position; let hsh = self.hash_context(); let match_pos = self.hashtab[hsh]; let ofs = if match_pos < self.position { self.position - match_pos } else { self.p...
function_block-full_function
[ { "content": "pub fn compress<R: Read, W: Write>(mut input: R, output: W) -> Result<W, Error> {\n\n let mut cw = Writer::new(output);\n\n try!(io::copy(&mut input, &mut cw));\n\n try!(cw.flush());\n\n Ok(cw.to_inner())\n\n}\n\n\n", "file_path": "src/lzp1.rs", "rank": 0, "score": 183887.7...
Rust
splashsurf_lib/src/sph_interpolation.rs
w1th0utnam3/splashsurf
b206e1521794a552c0436fbb84d332e718a4bf5d
use crate::kernel::SymmetricKernel3d; use crate::profile; use crate::Real; use crate::{kernel, ThreadSafe}; use nalgebra::{SVector, Unit, Vector3}; use rayon::prelude::*; use rstar::primitives::GeomWithData; use rstar::RTree; use std::ops::AddAssign; pub struct SphInterpolator<R: Real> { compact_support_radius: ...
use crate::kernel::SymmetricKernel3d; use crate::profile; use crate::Real; use crate::{kernel, ThreadSafe}; use nalgebra::{SVector, Unit, Vector3}; use rayon::prelude::*; use rstar::primitives::GeomWithData; use rstar::RTree; use std::ops::AddAssign; pub struct SphInterpolator<R: Real> { compact_support_radius: ...
values } #[allow(non_snake_case)] fn interpolate_quantity_inplace<T: InterpolationQuantity<R>>( &self, particle_quantity: &[T], interpolation_points: &[Vector3<R>], interpolated_values: &mut Vec<T>, first_order_correction: bool, ) { profile!("in...
.unscale(r) * kernel.evaluate_gradient_norm(r); density_grad += kernel_grad * vol_j; } Unit::new_normalize(density_grad) }) .collect_into_vec(normals); } pub fn interpolate_normals( &self, interpo...
random
[ { "content": "#[inline(never)]\n\npub fn compute_particle_densities<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n particle_neighbor_lists: &[Vec<usize>],\n\n compact_support_radius: R,\n\n particle_rest_mass: R,\n\n enable_multi_threading: bool,\n\n) -> Vec<R> {\n\n let mut de...
Rust
serenade/examples/weighted_intersection_random_data.rs
bolcom/serenade-experiments-sigmod
0a4c7f19d800d1c2784ea5536abb1a628cb12f7a
#![allow(warnings)] extern crate hashbrown; extern crate num_format; extern crate rand; use hashbrown::HashSet; use num_format::{Locale, ToFormattedString}; use rand::rngs::ThreadRng; use rand::Rng; use std::collections::BinaryHeap; use std::time::{Duration, Instant}; const NUM_ITEMS_IN_EVOLVING_SESSION: usize = 10;...
#![allow(warnings)] extern crate hashbrown; extern crate num_format; extern crate rand; use hashbrown::HashSet; use num_format::{Locale, ToFormattedString}; use rand::rngs::ThreadRng; use rand::Rng; use std::collections::BinaryHeap; use std::time::{Duration, Instant}; const NUM_ITEMS_IN_EVOLVING_SESSION: usize = 10;...
fn eytzinger_search(array_e: &Vec<usize>, key: &usize) -> Result<usize, usize> { let mut k = 1; let n = array_e.len() - 1; while k <= n { k = 2 * k + (array_e[k] < *key) as usize; } k >>= (!k).trailing_zeros() + 1; if array_e[k] == *key { Ok(k) } else { Err(k) ...
r( array: &Vec<usize>, array_e: &mut Vec<usize>, permutation: &mut Vec<usize>, mut ind_arr: usize, mut ind_eyt: usize, n: usize, ) -> (usize) { if (ind_eyt <= n) { ind_arr = eytzinger(array, array_e, permutation, ind_arr, 2 * ind_eyt, n); array_e[ind_eyt] = array[ind_arr]; ...
function_block-function_prefixed
[ { "content": "fn print_timing(duration: &mut [Duration], n_iterations: &usize, name: &str) {\n\n duration.sort();\n\n let mut duration_total = Duration::new(0, 0);\n\n let mut duration_max = Duration::new(0, 0);\n\n let mut n_iterations_p90: usize;\n\n let mut duration_p90: Duration;\n\n if *n...
Rust
src/server.rs
zedseven/listing-file-server
c0f412ffb0a71489fcc411c9fe21bd01948d1682
use std::{ cmp::Reverse, fs::read_dir, path::{Path, PathBuf}, }; use rocket::{ async_trait, error, figment, fs::{NamedFile, Options}, http::{ext::IntoOwned, uri::Segments, Method}, response::Redirect, route::{Handler, Outcome, Route}, warn_, Data, Request, }; use rocket_dyn_templates::Template; #[derive...
use std::{ cmp::Reverse, fs::read_dir, path::{Path, PathBuf}, }; use rocket::{ async_trait, error, figment, fs::{NamedFile, Options}, http::{ext::IntoOwned, uri::Segments, Method}, response::Redirect, route::{Handler, Outcome, Route}, warn_, Data, Request, }; use rocket_dyn_templates::Template; #[derive...
#[track_caller] pub fn new<P>(path: P, options: Options, template_renderer: R) -> Self where P: AsRef<Path>, R: 'static + Fn(String, Vec<String>) -> Template + Send + Sync + Clone, { use rocket::yansi::Paint; let path = path.as_ref(); if !path.is_dir() { let path = path.display(); error...
pub fn from<P>(path: P, template_renderer: R) -> Self where P: AsRef<Path>, R: 'static + Fn(String, Vec<String>) -> Template + Send + Sync + Clone, { ListingFileServer::new(path, Options::None, template_renderer) }
function_block-full_function
[ { "content": "# listing-file-server\n\n[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://choosealicense.com/licenses/mit/)\n\n\n\nA feature-equivalent copy of [`rocket::fs::FileServer`](https://api.rocket.rs/v0.5-rc/rocket/fs/struct.FileServer.html)\n\nthat provides directory listings...
Rust
src/components/nav.rs
Kazakuri/anilist-toolbox
258ce381fee43ebced986cd64ef1e081c2186268
use yew::prelude::*; use yew_router::prelude::*; use yewtil::store::{Bridgeable, ReadOnly, StoreWrapper}; use crate::agents::anilist; use crate::agents::anilist::AniList; use crate::routes::AppRoute; pub struct Nav { viewer: Option<anilist::Viewer>, _anilist: Box<dyn Bridge<StoreWrapper<AniList>>>, client_id: ...
use yew::prelude::*; use yew_router::prelude::*; use yewtil::store::{Bridgeable, ReadOnly, StoreWrapper}; use crate::agents::anilist; use crate::agents::anilist::AniList; use crate::routes::AppRoute; pub struct Nav { viewer: Option<anilist::Viewer>, _anilist: Box<dyn Bridge<StoreWrapper<AniList>>>, client_id: ...
}
fn view(&self) -> Html { html! { <nav class="flex items-center justify-between flex-wrap bg-white dark:bg-gray-900 py-2 lg:px-12 shadow border-solid border-t-2 border-blue-700"> <div class="flex justify-between lg:w-auto w-full lg:border-b-0 pl-6 pr-2 border-solid border-b-2 border-gray-300 pb-5 lg:pb...
function_block-full_function
[ { "content": "fn item(f: &mut Formatter, started: &mut bool, name: &str, value: u32) -> Result {\n\n if value > 0 {\n\n if *started {\n\n f.write_str(\" \")?;\n\n }\n\n\n\n write!(f, \"{}{}\", value, name)?;\n\n *started = true;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\nimpl Display for Duration {\n\...
Rust
src/lib.rs
loehde/axum-msgpack
c42c47023d882c892cee12d4fe1cab9e1f39a4c9
#![forbid(unsafe_code)] use std::ops::{Deref, DerefMut}; use axum::{ async_trait, body::Full, extract::{FromRequest, RequestParts}, response::{IntoResponse, Response}, BoxError, }; use axum::{ body::{self, Bytes}, http::{header::HeaderValue, StatusCode}, }; use hyper::header; use rejection...
#![forbid(unsafe_code)] use std::ops::{Deref, DerefMut}; use axum::{ async_trait, body::Full, extract::{FromRequest, RequestParts}, response::{IntoResponse, Response}, BoxError, }; use axum::{ body::{self, Bytes}, http::{header::HeaderValue, StatusCode}, }; use hyper::header; use rejection...
} impl<T> Deref for MsgPackRaw<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for MsgPackRaw<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<T> From<T> for MsgPackRaw<T> { fn from(inner: T) -> Self { Sel...
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { if message_pack_content_type(req)? { let bytes = Bytes::from_request(req).await?; let value = rmp_serde::from_read_ref(&bytes).map_err(InvalidMsgPackBody::from_err)?; Ok(MsgPackRaw(value)) ...
function_block-function_prefix_line
[ { "content": "use std::{error::Error as StdError, fmt};\n\n\n\nuse axum::BoxError;\n\n\n\n#[derive(Debug)]\n\npub struct Error {\n\n inner: BoxError,\n\n}\n\n\n\nimpl Error {\n\n pub(crate) fn new(error: impl Into<BoxError>) -> Self {\n\n Self {\n\n inner: error.into(),\n\n }\n\n ...
Rust
src/lib.rs
bvssvni/higher_order_core
56bcb975c11b02933606c1697ecc380d1e40a4ae
#![deny(missing_docs)] use std::sync::Arc; pub type Func<T, U> = Arc<dyn Fn(T) -> U + Send + Sync>; #[derive(Copy, Clone)] pub struct Arg<T>(pub T); pub trait Ho<T>: Sized { type Fun: Clone; } pub trait Call<T>: Ho<Arg<T>> { fn call(f: &Self::Fun, val: T) -> Self; } impl<T, U> Call<T> for U wher...
#![deny(missing_docs)] use std::sync::Arc; pub type Func<T, U> = Arc<dyn Fn(T) -> U + Send + Sync>; #[derive(Copy, Clone)] pub struct Arg<T>(pub T); pub trait Ho<T>: Sized { type Fun: Clone; } pub trait Call<T>: Ho<Arg<T>> { fn call(f: &Self::Fun, val: T) -> Self; } impl<T, U> Call
r()).collect() } } pub trait HMap<Out> { type Fun; fn hmap(self, f: &Self::Fun) -> Out; } impl<T, U> HMap<U> for T where U: Call<T> { type Fun = U::Fun; fn hmap(self, f: &Self::Fun) -> U { <U as Call<T>>::call(f, self) } } impl<T, U> HMap<[U; 2]> for [T; 2] where T: HMap<U> ...
<T> for U where U: Ho<Arg<T>, Fun = Func<T, Self>> { fn call(f: &Self::Fun, val: T) -> Self {f(val)} } impl<T: Clone> Ho<()> for T {type Fun = T;} pub type Fun<T, U> = <U as Ho<T>>::Fun; impl<T> Ho<Arg<T>> for f64 {type Fun = Func<T, f64>;} impl<T> Ho<Arg<T>> for f32 {type Fun = Func<T, f32>;} impl<T> Ho<Arg<T>>...
random
[ { "content": "### Design\n\n\n\nHere is an example of how to declare a new higher order data structure:\n\n\n\n```rust\n\nuse higher_order_core::{Ho, Call, Arg, Fun, Func};\n\nuse std::sync::Arc;\n\n\n\n/// Higher order 3D point.\n\n#[derive(Clone)]\n\npub struct Point<T = ()> where f64: Ho<T> {\n\n /// Func...
Rust
TDT4195/comp_graphics/src/shader.rs
jorgstei/Datateknologi
6fea7bf2c557cd93981c6996c7f4cca02f343d9e
use gl; use std::{ ptr, str, ffi::CString, path::Path, }; pub struct Shader { pub program_id: u32, } pub struct ShaderBuilder { program_id: u32, shaders: Vec::<u32>, } #[allow(dead_code)] pub enum ShaderType { Vertex, Fragment, TessellationControl, TessellationEvaluation, ...
use gl; use std::{ ptr, str, ffi::CString, path::Path, }; pub struct Shader { pub program_id: u32, } pub struct ShaderBuilder { program_id: u32, shaders: Vec::<u32>, } #[allow(dead_code)] pub enum ShaderType { Vertex, Fragment, TessellationControl, TessellationEvaluation, ...
} impl ShaderType { fn from_ext(ext: &std::ffi::OsStr) -> Result<ShaderType, String> { match ext.to_str().expect("Failed to read extension") { "vert" => { Ok(ShaderType::Vertex) }, "frag" => { Ok(ShaderType::Fragment) }, "tcs" => { Ok(ShaderType::TessellationControl) }...
fn into(self) -> gl::types::GLenum { match self { ShaderType::Vertex => { gl::VERTEX_SHADER }, ShaderType::Fragment => { gl::FRAGMENT_SHADER }, ShaderType::TessellationControl => { gl::TESS_CONTROL_SHADER }, S...
function_block-full_function
[ { "content": "// need to specify type of parameters (in brackets) and type of return val (after ->)\n\n// Disgusting syntax: You return shit by not adding a ; to the end of the line.\n\nfn multiply(n1: i32, n2:i32) -> i32{\n\n n1 + n2;\n\n n1 * n2\n\n}\n\n\n\n\n\n\n", "file_path": "TDT4195/Rust_testin...
Rust
src/view/default.rs
DusterTheFirst/mission-control
d86a80324cf60b17780c899f551c3d5d3e1b69f4
use std::borrow::Cow; use iced::{ button, pick_list, window::Mode, Align, Button, Column, Container, Element, HorizontalAlignment, Length, PickList, Row, Text, }; use interlink::{phy::InterlinkMethod, proto::VehicleIdentification}; use crate::{ element::{ ground_station_status::ground_station_stat...
use std::borrow::Cow; use iced::{ button, pick_list, window::Mode, Align, Button, Column, Container, Element, HorizontalAlignment, Length, PickList, Row, Text, }; use interlink::{phy::InterlinkMethod, proto::VehicleIdentification}; use crate::{ element::{ ground_station_status::ground_station_stat...
izontal_alignment(HorizontalAlignment::Center), ) .push(PickList::new( time_base_picker, Cow::Borrowed(TimeBase::ALL), time_base.into(), Message::ChangeTimeBase, )) .push( Text::new(format!("W...
(10) .push(top_row( &mut app.instruments.temperature, &app.time, app.time_base, app.interlink, app.vehicle.as_ref(), )) .push( Row::new() .width(Length::Fill) .height(Length::FillPortion(4)) ...
random
[ { "content": "pub fn view(app: &mut InstrumentCluster) -> Element<Message> {\n\n Column::new()\n\n .width(Length::Fill)\n\n .height(Length::Fill)\n\n .spacing(10)\n\n .push(\n\n Row::new()\n\n .width(Length::Fill)\n\n .height(Length::Fill)\...
Rust
src/line_reader.rs
flub/rpgp
0c17c48336d00b2be95a8e404f1a437181c345be
use std::io; use std::io::prelude::*; #[derive(Debug)] pub struct LineReader<R> { inner: R, } impl<R: Read + Seek> LineReader<R> { pub fn new(input: R) -> Self { LineReader { inner: input } } pub fn into_inner(self) -> R { self.inner } } impl<R: Read + Seek> Seek for LineRea...
use std::io; use std::io::prelude::*; #[derive(Debug)] pub struct LineReader<R> { inner: R, } impl<R: Read + Seek> LineReader<R> { pub fn new(input: R) -> Self { LineReader { inner: input } } pub fn into_inner(self) -> R { self.inner } } impl<R: Read + Seek> Seek for LineRea...
} if offset > 0 { return Ok(offset); } n = self.inner.read(into)?; } Ok(n) } } #[cfg(test)] mod tests { use super::*; use std::io::Cursor; use std::io::Read; fn read_exact(data: &[u8], size: usize) -> V...
if b != b'\r' && b != b'\n' { if i != offset { into[offset] = b; } offset += 1; }
if_condition
[ { "content": "#[cfg(not(feature = \"rinbuf\"))]\n\n#[inline(always)]\n\npub fn new_buf_reader<R>(capacity: usize, inner: R) -> BufReader<R> {\n\n BufReader::with_capacity(capacity, inner)\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 283107.40941857826 }, { "content": "/// ...
Rust
src/neural_network/mutator.rs
elsid/gannai
b659b2695d515eced0b1fec7df62715bccaf95bf
use std::collections::btree_map; use std::collections::BTreeSet; use super::common::{Node, Weight}; use super::graph::{Graph, NodeArcs}; use super::id_generator::IdGenerator; use super::network::{Connection, Network, NetworkBuf}; pub use super::graph::Arc; #[derive(Clone, Debug, PartialEq)] pub struct Mutator { ...
use std::collections::btree_map; use std::collections::BTreeSet; use super::common::{Node, Weight}; use super::graph::{Graph, NodeArcs}; use super::id_generator::IdGenerator; use super::network::{Connection, Network, NetworkBuf}; pub use super::graph::Arc; #[derive(Clone, Debug, PartialEq)] pub struct Mutator { ...
pub fn union(&self, other: &Mutator) -> Self { Mutator { inputs: self.inputs.union(&other.inputs).cloned().collect(), outputs: self.outputs.union(&other.outputs).cloned().collect(), graph: self.graph.union(&other.graph), } } pub fn rm_useless(&mut self)...
e); } for (&src, &src_node) in network.nodes.iter() { for (dst, &weight) in network.weights.row(src).iter().enumerate() { if weight > 0.0 { graph.add_arc(src_node, network.nodes[&dst], weight); } } } let inputs =...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn test_connected_component_by_outgoing_for_dst_with_arc_from_src_return_dst() {\n\n let mut graph = Graph::new();\n\n let src = Node(1);\n\n let dst = Node(2);\n\n graph.add_node(src);\n\n graph.add_node(dst);\n\n graph.add_arc(src, dst, 1.0);\n\n let mut visited =...
Rust
src/time/duration.rs
solid-rs/itron-rs
fcb0ed838e7542abab37db941dffa3eb63ab8c3d
use crate::abi; use core::{convert::TryFrom, time::Duration as StdDuration}; use super::Timeout; #[cfg_attr( feature = "nightly", doc = "[`duration!`] can be used to construct a `Duration` in a concise syntax." )] #[cfg_attr( not(feature = "nightly"), doc = "If `nightly` feature is enabled...
use crate::abi; use core::{convert::TryFrom, time::Duration as StdDuration}; use super::Timeout; #[cfg_attr( feature = "nightly", doc = "[`duration!`] can be used to construct a `Duration` in a concise syntax." )] #[cfg_attr( not(feature = "nightly"), doc = "If `nightly` feature is enabled...
#[inline] pub fn from_nanos(nanos: u128) -> Option<Self> { u64::try_from(nanos / 1_000) .ok() .and_then(Self::from_micros) } } impl TryFrom<StdDuration> for Duration { type Error = super::TryFromDurationError; #[inline] fn...
4) -> Option<Self> { match () { () => { if micros > abi::TMAX_RELTIM as u64 { None } else { Some(unsafe { Self::from_raw(micros as u32) }) } } } }
function_block-function_prefixed
[ { "content": "#[inline]\n\n#[doc(alias = \"ena_ter\")]\n\npub fn enable_termination() -> Result<(), Error<EnableTerminationError>> {\n\n match () {\n\n #[cfg(not(feature = \"none\"))]\n\n () => unsafe {\n\n Error::err_if_negative(abi::ena_ter())?;\n\n Ok(())\n\n },\...
Rust
vulkano/src/instance/extensions.rs
realitix/vulkano
401bc3bcbe152a9c984cf08cf08d251567024d0e
use std::collections::HashSet; use std::error; use std::ffi::{CStr, CString}; use std::fmt; use std::iter::FromIterator; use std::ptr; use std::str; use Error; use OomError; use VulkanObject; use check_errors; use instance::PhysicalDevice; use instance::loader; use instance::loader::LoadingError; use vk; macro_rule...
use std::collections::HashSet; use std::error; use std::ffi::{CStr, CString}; use std::fmt; use std::iter::FromIterator; use std::ptr; use std::str; use Error; use OomError; use VulkanObject; use check_errors; use instance::PhysicalDevice; use instance::loader; use instance::loader::LoadingError; use vk; macro_rule...
} #[inline] fn cause(&self) -> Option<&error::Error> { match *self { SupportedExtensionsError::LoadingError(ref err) => Some(err), SupportedExtensionsError::OomError(ref err) => Some(err), } } } impl fmt::Display for SupportedExtensionsError { #[inline] ...
match *self { SupportedExtensionsError::LoadingError(_) => "failed to load the Vulkan shared library", SupportedExtensionsError::OomError(_) => "not enough memory available", }
if_condition
[ { "content": "pub fn reflect<R>(name: &str, mut spirv: R) -> Result<String, Error>\n\n where R: Read\n\n{\n\n let mut data = Vec::new();\n\n spirv.read_to_end(&mut data)?;\n\n\n\n // now parsing the document\n\n let doc = parse::parse_spirv(&data)?;\n\n\n\n let mut output = String::new();\n\n ...
Rust
src/diagnostics/archivist/tests/v2/src/lib.rs
dahliaOS/fuchsia-pi4
5b534fccefd918b5f03205393c1fe5fddf8031d0
use diagnostics_hierarchy::{assert_data_tree, testing::AnyProperty}; use diagnostics_reader::{ArchiveReader, Data, Inspect, Logs, Severity}; use fidl_fuchsia_diagnostics::ArchiveAccessorMarker; use futures::StreamExt; use std::{collections::HashSet, iter::FromIterator}; mod test_topology; const STUB_INSPECT_COMPONE...
use diagnostics_hierarchy::{assert_data_tree, testing::AnyProperty}; use diagnostics_reader::{ArchiveReader, Data, Inspect, Logs, Severity}; use fidl_fuchsia_diagnostics::ArchiveAccessorMarker; use futures::StreamExt; use std::{collections::HashSet, iter::FromIterator}; mod test_topology; const STUB_INSPECT_COMPONE...
#[fuchsia::test] async fn read_v2_components_single_selector() { let mut builder = test_topology::create(test_topology::Options::default()) .await .expect("create base topology"); test_topology::add_component(&mut builder, "child_a", STUB_INSPECT_COMPONENT_URL) .await .expect("...
wrap(); let data = ArchiveReader::new() .with_archive(accessor) .add_selector("child:root") .retry_if_empty(true) .with_minimum_schema_count(1) .snapshot::<Inspect>() .await .expect("got inspect data"); assert_data_tree!(data[0].payload.as_ref().unwrap(),...
function_block-function_prefixed
[]
Rust
src/cache/memory_cache.rs
Cryptonomic/ImageProxy
4c4d0d15e9a56c8c8080d18fd3e3a0d5815d8a73
use log::{error, warn}; use prometheus::IntGaugeVec; use std::collections::VecDeque; use std::hash::Hash; use std::{ collections::HashMap, sync::{ atomic::{AtomicI64, AtomicU64, Ordering}, Arc, RwLock, }, }; use super::{ByteSizeable, Cache}; pub struct MemoryBoundedLruCache<K, V> { ite...
use log::{error, warn}; use prometheus::IntGaugeVec; use std::collections::VecDeque; use std::hash::Hash; use std::{ collections::HashMap, sync::{ atomic::{AtomicI64, AtomicU64, Ordering}, Arc, RwLock, }, }; use super::{ByteSizeable, Cache}; pub struct MemoryBoundedLruCache<K, V> { ite...
), } } fn gather_metrics(&self, metric: &IntGaugeVec) { metric .with_label_values(&["memorycache", "items"]) .set(self.len() as i64); metric .with_label_values(&["memorycache", "mem_total_bytes"]) .set(self.max_size_in_bytes as i64); ...
k(mut item_map), Ok(mut lru)) => { item_map.clear(); lru.clear(); self.evictions.store(0, Ordering::SeqCst); self.current_size.store(0, Ordering::SeqCst); } _ => error!("Item cache is poisoned, a write error was possibly encountered...
function_block-random_span
[ { "content": "/// Factory method for cache\n\npub fn get_cache<K, V>(config: &CacheConfig) -> Option<Box<dyn Cache<K, V> + Send + Sync>>\n\nwhere\n\n K: 'static + Hash + Eq + Clone + Send + Sync,\n\n V: 'static + ByteSizeable + Send + Sync,\n\n{\n\n match config.cache_type {\n\n CacheType::Memor...
Rust
src/srp.rs
Gellardo/cryptopals
a7f45a91c9c178f8139e8cc8a31440ad7f826012
use crate::dh::{begin_dh_nist, gen_random}; use crate::sha1::MySha1; use crate::srp::Messages::{Register, SRP1, SRP2, SRP3, SRP4}; use crate::u32_be_bytes; use num_bigint::BigUint; use std::ops::{Add, Rem}; use std::sync::mpsc::{Receiver, Sender}; #[derive(Debug)] pub enum Messages<'a> { Register { id: &'a [u8], p...
use crate::dh::{begin_dh_nist, gen_random}; use crate::sha1::MySha1; use crate::srp::Messages::{Register, SRP1, SRP2, SRP3, SRP4}; use crate::u32_be_bytes; use num_bigint::BigUint; use std::ops::{Add, Rem}; use std::sync::mpsc::{Receiver, Sender}; #[derive(Debug)] pub enum Messages<'a> { Register { id: &'a [u8], p...
pub fn client(tx: Sender<Messages>, rx: Receiver<Messages>) { client_ext(tx, rx, &|a, g, n| g.modpow(a, n), &get_hmac) } pub fn get_hmac(salt: &[u8], shared_k: &[u32]) -> [u32; 5] { MySha1::hmac(&u32_be_bytes(&shared_k), &salt.to_vec()) }
d_k); tx.send(SRP3 { hmac: hmac1 }).unwrap(); match rx.recv().unwrap() { SRP4 { auth } => { if auth { println!("c: success") } else { println!("c: auth fail"); panic!("the authentication failed") } } _ =>...
function_block-function_prefixed
[ { "content": "/// Same as a == b with a logline why the comparison failed\n\npub fn compare(a: &Vec<u8>, b: &Vec<u8>) -> bool {\n\n for i in 0..a.len() {\n\n if a.get(i) != b.get(i) {\n\n println!(\"mismatch @{}: {:?} != {:?}\", i, a.get(i), b.get(i));\n\n return false;\n\n ...
Rust
cloudflow/src/process.rs
youduda/cloudflow
eaa6926315ad792aa23c4e7dec0be519823a1fc8
use crate::os::OsBase; use crate::util::*; use abi_stable::StableAbi; pub use cglue::slice::CSliceMut; use cglue::trait_group::c_void; use filer::branch; use filer::prelude::v1::{Error, ErrorKind, ErrorOrigin, Result, *}; use memflow::prelude::v1::*; use once_cell::sync::OnceCell; pub extern "C" fn on_node(node: &Nod...
use crate::os::OsBase; use crate::util::*; use abi_stable::StableAbi; pub use cglue::slice::CSliceMut; use cglue::trait_group::c_void; use filer::branch; use filer::prelude::v1::{Error, ErrorKind, ErrorOrigin, Result, *}; use memflow::prelude::v1::*; use once_cell::sync::OnceCell; pub extern "C" fn on_node(node: &Nod...
extern "C" fn map_into_phys_maps( proc: &LazyProcessArc, ctx: &CArc<c_void>, ) -> COption<LeafArcBox<'static>> { if proc .proc() .and_then(|proc| as_ref!(proc.get_orig() impl VirtualTranslate)) .is_some() { let file = FnFile::new(proc.clone(), |proc| { let pro...
function_block-full_function
[ { "content": "pub fn split_path(path: &str) -> (&str, Option<&str>) {\n\n path.split_once(\"/\")\n\n .map(|(a, b)| (a, Some(b)))\n\n .unwrap_or((path, None))\n\n}\n\n\n", "file_path": "filer/src/branch.rs", "rank": 0, "score": 191720.84502424294 }, { "content": "fn map_check...
Rust
src/commands/decompress.rs
Crypto-Spartan/ouch
dd3a57fbfa73bceb0ce6e41715afb9f8d954f1cf
use std::{ io::{self, BufReader, Read, Write}, ops::ControlFlow, path::{Path, PathBuf}, }; use fs_err as fs; use crate::{ commands::warn_user_about_loading_zip_in_memory, extension::{ split_first_compression_format, CompressionFormat::{self, *}, Extension, }, info, ...
use std::{ io::{self, BufReader, Read, Write}, ops::ControlFlow, path::{Path, PathBuf}, }; use fs_err as fs; use crate::{ commands::warn_user_about_loading_zip_in_memory, extension::{ split_first_compression_format, CompressionFormat::{self, *}, Extension, }, info, ...
nice_directory_display(temp_dir_path), nice_directory_display(output_file_path) ); } Ok(ControlFlow::Continue(files)) }
function_block-function_prefix_line
[ { "content": "#[cfg(unix)]\n\nfn __unix_set_permissions(file_path: &Path, file: &ZipFile) -> crate::Result<()> {\n\n use std::{fs::Permissions, os::unix::fs::PermissionsExt};\n\n\n\n if let Some(mode) = file.unix_mode() {\n\n fs::set_permissions(file_path, Permissions::from_mode(mode))?;\n\n }\n...
Rust
schedular/src/lib.rs
YassinEldeeb/Deadliner
e49fc625484ad466db6346f68b9efda89b7f490f
mod macros; mod notify; mod server; mod startup_launch; mod system_tray; use std::{ env, fs, sync::{Arc, Mutex}, }; use chrono::{Local, NaiveDateTime}; use deadliner_gui::{generate_deadline_over_wallpaper, new_path, update_wallpaper, SanitizedConf}; pub use macros::*; pub use notify::*; pub use server::*; pub...
mod macros; mod notify; mod server; mod startup_launch; mod system_tray; use std::{ env, fs, sync::{Arc, Mutex}, }; use chrono::{Local, NaiveDateTime}; use deadliner_gui::{generate_deadline_over_wallpaper, new_path, update_wallpaper, SanitizedConf}; pub use macros::*; pub use notify::*; pub use server::*; pub...
notify_deadline_over(); } fn get_minutes_left(conf: &SanitizedConf) -> i64 { let today = Local::now().naive_local(); let deadline = NaiveDateTime::parse_from_str(&conf.deadline_str, "%Y-%m-%d %I:%M %p").unwrap(); let diff = deadline.signed_duration_since(today); let minutes = diff.num_minutes();...
match file_path { Ok(file_path) => { wallpaper::set_mode(conf.bg_mode.into()).unwrap(); wallpaper::set_from_path(&file_path).unwrap(); } _ => {} }
if_condition
[ { "content": "pub fn run_server(exit: Arc<Mutex<bool>>) {\n\n let port: u16 = fs::read_to_string(new_path(\"port.txt\"))\n\n .unwrap()\n\n .trim()\n\n .parse()\n\n .unwrap();\n\n let addr = format!(\"127.0.0.1:{}\", port);\n\n\n\n let listener = TcpListener::bind(&addr).unwr...
Rust
src/commands/utility/leaderboard.rs
Shexaa/bot
392e4b0491c7d084b2e85b3551ce93c73926b20e
use crate::prelude::*; use serenity::{ framework::standard::{macros::command, Args, CommandResult}, model::prelude::*, prelude::*, }; #[command] #[only_in(guilds)] #[min_args(0)] #[max_args(1)] #[description("Retrieves the leaderboard (of a channel/user).")] #[usage("leaderboard <optional: channel|user>")]...
use crate::prelude::*; use serenity::{ framework::standard::{macros::command, Args, CommandResult}, model::prelude::*, prelude::*, }; #[command] #[only_in(guilds)] #[min_args(0)] #[max_args(1)] #[description("Retrieves the leaderboard (of a channel/user).")] #[usage("leaderboard <optional: channel|user>")]...
_else(|| anyhow!("Guild ID not found."))?; let rows = get_user_scores(guild_id).await?; let mut result = String::new(); let mut user_found = false; let mut processed = 0; for x in rows.iter() { if processed >= 10 && user_found { break; }; let id = x.user_id.parse...
}; if processed < 10 { result += &format!("{}. {} - {}\n", processed + 1, member.display_name(), x.points)[..]; if member.user == msg.author { user_found = true; }; } else if member.user == msg.author { result += "...\n"; ...
random
[ { "content": "pub use crate::data::{cache::*, db::*};\n\npub use crate::db::{connect, leaderboard::*, log::*, money::*, prefix::*, reactionroles::*};\n\npub use crate::utils::parse::*;\n\npub use crate::{error_return, error_return_ok, none_return, none_return_ok};\n\npub use anyhow::{anyhow, Result};\n\npub use...
Rust
rust/operator/src/lib.rs
stackabletech/operator-skeleton
bf12dc77c98f19ae8c4fc49b25f42126a87c4874
mod error; use crate::error::Error; use stackable_productname_crd::commands::{Restart, Start, Stop}; use async_trait::async_trait; use k8s_openapi::api::core::v1::{ConfigMap, EnvVar, Pod}; use kube::api::{ListParams, ResourceExt}; use kube::Api; use kube::CustomResourceExt; use product_config::types::PropertyNameKind;...
mod error; use crate::error::Error; use stackable_productname_crd::commands::{Restart, Start, Stop}; use async_trait::async_trait; use k8s_openapi::api::core::v1::{ConfigMap, EnvVar, Pod}; use kube::api::{ListParams, ResourceExt}; use kube::Api; use kube::CustomResourceExt; use product_config::types::PropertyNameKind;...
) .await?; trace!( "{}: Found [{}] pods", context.log_name(), existing_pods.len() ); let productname_spec: ProductnameClusterSpec = context.resource.spec.clone(); let mut eligible_nodes = HashMap::new(); eligible_nodes.insert( ...
build_common_labels_for_all_managed_resources( APP_NAME, &context.resource.name(), )
call_expression
[ { "content": "fn main() -> Result<(), stackable_operator::error::Error> {\n\n built::write_built_file().expect(\"Failed to acquire build-time information\");\n\n\n\n ProductnameCluster::write_yaml_schema(\"../../deploy/crd/productnamecluster.crd.yaml\")?;\n\n Restart::write_yaml_schema(\"../../deploy/c...
Rust
src/evaluate/attributes.rs
Blinningjr/rust-debug
e665a7a7365d6b077296d4554151d67334417d6f
use gimli::{ AttributeValue::{ AddressClass, Data1, Data2, Data4, Data8, DebugStrRef, Encoding, Sdata, Udata, }, DebuggingInformationEntry, DwAddr, DwAte, Reader, Unit, }; use anyhow::{anyhow, Result}; use log::error; pub fn name_attribute<R: Reader<Offset = usize>>( dwarf: &gimli::Dwarf<R>, ...
use gimli::{ AttributeValue::{ AddressClass, Data1, Data2, Data4, Data8, DebugStrRef, Encoding, Sdata, Udata, }, DebuggingInformationEntry, DwAddr, DwAte, Reader, Unit, }; use anyhow::{anyhow, Result}; use log::error; pub fn name_attribute<R: Reader<Offset = usize>>( dwarf: &gimli::Dwarf<R>, ...
ome((unit.header.offset(), offset))); } Some(gimli::AttributeValue::DebugInfoRef(di_offset)) => { let offset = gimli::UnitSectionOffset::DebugInfoOffset(di_offset); let mut iter = dwarf.debug_info.units(); while let Ok(Some(header)) = iter.next() { let...
("Unimplemented for {:?}", unknown)); } None => return Ok(None), }; } pub fn byte_size_attribute<R: Reader<Offset = usize>>( die: &DebuggingInformationEntry<R>, ) -> Result<Option<u64>> { return match die.attr_value(gimli::DW_AT_byte_size)? { Some(Udata(val)) => Ok(Some(val)), ...
random
[ { "content": "/// Find a compilation unit(gimli-rs Unit) using a address.\n\n///\n\n/// Description:\n\n///\n\n/// * `dwarf` - A reference to gimli-rs Dwarf struct.\n\n/// * `pc` - A 32 bit machine code address, which is most commonly the current program counter value.\n\n///\n\n/// This function will check if ...
Rust
backend/server/src/api/auth.rs
hgzimmerman/BucketQuestions
02b7b0312424ccdaf26b36d7d6dc509c92cd91e4
use crate::{ error::{DependentConnectionError, Error}, get_google_login_link, state::{HttpsClient, State}, }; use askama::Template; use authorization::{JwtPayload, Secret}; use db::{ user::db_types::{NewUser, User}, BoxedRepository, }; use futures::{future::Future, stream::Stream}; use hyper::{body:...
use crate::{ error::{DependentConnectionError, Error}, get_google_login_link, state::{HttpsClient, State}, }; use askama::Template; use authorization::{JwtPayload, Secret}; use db::{ user::db_types::{NewUser, User}, BoxedRepository, }; use futures::{future::Future, stream::Stream}; use hyper::{body:...
}) } fn create_jwt(user: User, secret: Secret) -> Result<String, Rejection> { let lifetime = chrono::Duration::weeks(30); let payload: JwtPayload<User> = JwtPayload::new(user, lifetime); payload .encode_jwt_string(&secret) .map_err(warp::reject::custom) } fn login_template_render(...
if let DieselError::NotFound = error { let new_user = NewUser { google_user_id: google_jwt_payload.sub, google_name: google_jwt_payload.name, }; conn.create_user(new_user) .map_err(|_| Error::DatabaseError("Could...
if_condition
[ { "content": "/// A filter that is responsible for configuring everything that can be served.\n\n///\n\n/// # Notes\n\n/// It is responsible for:\n\n/// * Routes the API\n\n/// * Handles file requests and redirections\n\n/// * Initializes warp logging\n\n/// * converts errors\n\n/// * Handles CORS\n\npub fn rou...
Rust
madato/src/yaml.rs
inosion/markdown-tools
c28c8680ee3cc70c64e057b2b287828d09549a40
use super::mk_table; use linked_hash_map::LinkedHashMap; use std::fs::File; use std::io::prelude::*; use types::*; #[allow(unused_imports)] use utils::StripMargin; #[test] fn can_yaml_to_md() { let yml_data = " |- data1: somevalue | data2: someother value here | col3: 100 | col4: gar gar ...
use super::mk_table; use linked_hash_map::LinkedHashMap; use std::fs::File; use std::io::prelude::*; use types::*; #[allow(unused_imports)] use utils::StripMargin; #[test] fn can_yaml_to_md() { let yml_data = " |- data1: somevalue | data2: someother value here | col3: 100 | col4: gar gar ...
fn load_yaml(yaml: &str) -> Table<String, String> { let deserialized_map: Table<String, String> = serde_yaml::from_str(&yaml).unwrap(); deserialized_map } fn _load_json(json: &str) -> Table<String, String> { let deserialized_map: Table<String, String> = serde_json::from_str(&json).unwrap(); deseriali...
t() }; let tbl_md = mk_md_table_from_yaml(&yml_data, &Some(render_options)); println!("::expected\n{}\n\nreceived:{}", expected, tbl_md); assert!(tbl_md == expected); }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn can_mk_table_with_value_regex() {\n\n let tbl_md = mk_table(\n\n &vec![\n\n linkedhashmap![s!(\"foo\") => s!(\"ggg\"), s!(\"bar\") => s!(\"fred\"), s!(\"nop\") => s!(\"no\")],\n\n linkedhashmap![s!(\"foo\") => s!(\"ggg\"), s!(\"bar\") => s!(\"abc\"), s...
Rust
nrf52840-dk/examples/nrf52840-dk-psila.rs
blueluna/nrf52840-dk-experiments
bbe34a24b9002f9f446e949d7b8013d2e8dae484
#![no_main] #![no_std] use nrf52840_dk as _; use rtic::app; use nrf52840_hal::{clocks, gpio}; use nrf52840_pac as pac; use bbqueue::{self, BBBuffer}; use embedded_hal::digital::v2::OutputPin; use nrf52_cryptocell::CryptoCellBackend; use psila_data::{ cluster_library::{AttributeDataType, ClusterLibraryStatus}...
#![no_main] #![no_std] use nrf52840_dk as _; use rtic::app; use nrf52840_hal::{clocks, gpio}; use nrf52840_pac as pac; use bbqueue::{self, BBBuffer}; use embedded_hal::digital::v2::OutputPin; use nrf52_cryptocell::CryptoCellBackend; use psila_data::{ cluster_library::{AttributeDataType, ClusterLibraryStatus}...
let _ = cx.spawn.radio_rx(); } } extern "C" { fn QDEC(); } };
if let Ok(grant) = queue.read() { let packet_length = grant[0] as usize; let data = &grant[1..=packet_length]; let _ = radio.queue_transmission(data); grant.release(packet_length + 1); }
if_condition
[ { "content": "fn clear(slice: &mut [u8]) {\n\n for v in slice.iter_mut() {\n\n *v = 0;\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum EncryptDecrypt {\n\n /// Encryp operation\n\n Encrypt = 0,\n\n /// Decryp operation\n\n Decrypt = 1,\n\n}\n\n\n\n/// Block cipher key t...
Rust
src/main.rs
TheClonerx/grip
2e8121b51d4ccccb9b610d74e7852b46eeb63bdc
#![deny(rust_2018_idioms)] use futures_util::StreamExt; use std::io::Write; mod console; mod package; const ARG_FILE: &str = "file"; const ARG_LIST_TOKENS: &str = "list-tokens"; const ARG_PRINT_LLVM_IR: &str = "print-llvm-ir"; const ARG_BUILD: &str = "build"; const ARG_BUILD_SOURCES_DIR: &str = "sources-dir"; const ...
#![deny(rust_2018_idioms)] use futures_util::StreamExt; use std::io::Write; mod console; mod package; const ARG_FILE: &str = "file"; const ARG_LIST_TOKENS: &str = "list-tokens"; const ARG_PRINT_LLVM_IR: &str = "print-llvm-ir"; const ARG_BUILD: &str = "build"; const ARG_BUILD_SOURCES_DIR: &str = "sources-dir"; const ...
} let mut output_file_path = std::path::PathBuf::from(source_file_path.parent().unwrap()); output_file_path.push(source_file_path.file_stem().unwrap()); output_file_path.set_extension(package::PATH_OUTPUT_FILE_EXTENSION); write_or_print_output(llvm_module, &output_file_path, &matches); } else { ...
} let source_file_contents = source_file_contents_result.unwrap(); let build_result = package::build_single_file(&llvm_context, &llvm_module, &source_file_contents, &matches); if let Err(diagnostics) = build_result { for diagnostic in diagnostics { console::print_diagnostic( ...
random
[ { "content": "pub fn fetch_source_file_contents(source_file_path: &std::path::PathBuf) -> Result<String, String> {\n\n if !source_file_path.is_file() {\n\n return Err(String::from(\n\n \"path does not exist, is not a file, or is inaccessible\",\n\n ));\n\n }\n\n\n\n let source_file_contents = std:...
Rust
colour_math_gtk/src/hue_wheel.rs
pwil3058/rs_colour_math_obsolete
ac3fcab63c44975e8de901aa93da7f5c5cffde7e
use std::{ cell::{Cell, RefCell}, collections::HashMap, rc::Rc, }; use pw_gix::{ cairo, gdk, gtk::{self, prelude::*}, gtkx::menu_ng::{ManagedMenu, ManagedMenuBuilder, MenuItemSpec}, sav_state::MaskedCondns, wrapper::*, }; use colour_math::ScalarAttribute; use colour_math_cairo::*; ...
use std::{ cell::{Cell, RefCell}, collections::HashMap, rc::Rc, }; use pw_gix::{ cairo, gdk, gtk::{self, prelude::*}, gtkx::menu_ng::{ManagedMenu, ManagedMenuBuilder, MenuItemSpec}, sav_state::MaskedCondns, wrapper::*, }; use colour_math::ScalarAttribute; use colour_math_cairo::*; ...
}
dk::EventMask::LEAVE_NOTIFY_MASK | gdk::EventMask::BUTTON_RELEASE_MASK, ) .build(); let popup_menu = ManagedMenuBuilder::new().build(); let gtk_hue_wheel = Rc::new(GtkHueWheel { vbox: gtk::Box::new(gtk::Orientation::Vertical, 0), draw...
function_block-function_prefixed
[ { "content": "type ChangeCallback = Box<dyn Fn(RGB)>;\n\n\n\n#[derive(PWO, Wrapper)]\n\npub struct ColourManipulatorGUI {\n\n vbox: gtk::Box,\n\n colour_manipulator: RefCell<ColourManipulator>,\n\n drawing_area: gtk::DrawingArea,\n\n incr_value_btn: gtk::Button,\n\n decr_value_btn: gtk::Button,\n...
Rust
src/write.rs
njaard/sonnerie
8417f80aa4ff4c2d604edde934e9b7df4395040a
use byteorder::{BigEndian, ByteOrder, WriteBytesExt}; use crossbeam::channel; use parking_lot::{Condvar, Mutex}; use std::io::Write; use std::sync::Arc; pub(crate) const SEGMENT_SIZE_GOAL: usize = 1024 * 1024; const SEGMENT_SIZE_EXTRA: usize = 1024 * 1024 + 1024 * 32; pub(crate) struct Writer<W: Write + Send + 'stati...
use byteorder::{BigEndian, ByteOrder, WriteBytesExt}; use crossbeam::channel; use parking_lot::{Condvar, Mutex}; use std::io::Write; use std::sync::Arc; pub(crate) const SEGMENT_SIZE_GOAL: usize = 1024 * 1024; const SEGMENT_SIZE_EXTRA: usize = 1024 * 1024 + 1024 * 32; pub(crate) struct Writer<W: Write + Send + 'stati...
pub(crate) fn store_current_segment(&mut self) -> std::io::Result<()> { let header = Header { first_key: self.first_segment_key.as_bytes().to_owned(), last_key: self.last_segment_key.as_bytes().to_owned(), }; let payload = std::mem::replace( &mut self.current_segment_data, Vec::with_capacity(SEG...
self.current_timestamp.copy_from_slice(&data[0..8]); if self.current_record_size.is_none() { let mut buf = unsigned_varint::encode::u32_buffer(); let o = unsigned_varint::encode::u32(data.len() as u32 - 8, &mut buf); self.current_key_data.write_all(o).unwrap(); } self.current_key_data.write_all(dat...
function_block-function_prefix_line
[ { "content": "fn write_many<W: std::io::Write + Send>(w: &mut Writer<W>, key: &str, range: std::ops::Range<u32>) {\n\n\tfor n in range {\n\n\t\tlet mut buf = [0u8; 12];\n\n\t\tbyteorder::BigEndian::write_u64(&mut buf[..], n as u64);\n\n\t\tbyteorder::BigEndian::write_u32(&mut buf[8..12], n);\n\n\t\tw.add_record...
Rust
src/error/expected/mod.rs
Byron/rust-dangerous
9021f78213d5d6622a514a1f9085d515a654e260
mod length; mod valid; mod value; pub use self::length::ExpectedLength; pub use self::valid::ExpectedValid; pub use self::value::ExpectedValue; #[cfg(feature = "alloc")] use alloc::boxed::Box; use crate::display::ErrorDisplay; use crate::fmt; use crate::input::{Bytes, Input, MaybeString}; use super::{ Context, ...
mod length; mod valid; mod value; pub use self::length::ExpectedLength; pub use self::valid::ExpectedValid; pub use self::value::ExpectedValue; #[cfg(feature = "alloc")] use alloc::boxed::Box; use crate::display::ErrorDisplay; use crate::fmt; use crate::input::{Bytes, Input, MaybeString}; use super::{ Context, ...
Self { kind, input, stack: S::from_root(context), } } } impl<'i, S> Details<'i> for Expected<'i, S> where S: ContextStack, { fn input(&self) -> MaybeString<'i> { self.input.clone() } fn span(&self) -> Bytes<'i> { match &self.kind...
let (input, context) = match &kind { ExpectedKind::Valid(err) => (err.input(), err.context()), ExpectedKind::Value(err) => (err.input(), err.context()), ExpectedKind::Length(err) => (err.input(), err.context()), };
assignment_statement
[ { "content": "#[inline(always)]\n\npub fn input<'i, I>(input: I) -> I::Input\n\nwhere\n\n I: IntoInput<'i>,\n\n{\n\n input.into_input()\n\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n// Bound\n\n\n\n/// Indication of whether [`Input`] will change in futher p...
Rust
Day 06 - Signals and Noise/src/main.rs
kAworu/adventofcode-2016
1c93f92c45b3a27e357b959ecf19c3992595525b
mod signals_and_noise { use ::std::collections::HashMap; use ::std::ops::{Deref, DerefMut}; use ::std::str::FromStr; #[derive(Debug)] struct CharFreq(HashMap<char, u32>); impl CharFreq { fn new() -> CharFreq { CharFreq(HashMap::new()) } ...
mod signals_and_noise { use ::std::collections::HashMap; use ::std::ops::{Deref, DerefMut}; use ::std::str::FromStr; #[derive(Debug)] struct CharFreq(HashMap<char, u32>); impl CharFreq { fn new() -> CharFreq { CharFreq(HashMap::new()) } ...
#[test] fn part1_example() { let messages = "\ eedadn drvtee eandsr raavrd atevrs tsrnev sdttsa rasrtv nssdts ntnada svetve tesnvt vntsnd vrdear dvrsen enarar"; let ec: ErrorCorrector = messages.parse().unwrap(); assert_eq!(ec.src_message(), "easter".to_string()); } #[test] fn part2_example() { let m...
fn main() { let mut input = String::new(); let stdin = std::io::stdin(); stdin.lock().read_to_string(&mut input).expect("no input given"); let mut ec: ErrorCorrector = ErrorCorrector::new(); for message in input.lines() { ec.register(message); } println!("The error-corrected v...
function_block-full_function
[ { "content": "// simple input parsing helper\n\nfn parse_instructions(input: String) -> Vec<Instruction> {\n\n input.lines().map(|line| line.parse().unwrap()).collect()\n\n}\n\n\n", "file_path": "Day 10 - Balance Bots/src/main.rs", "rank": 0, "score": 119323.6263418468 }, { "content": "fn...
Rust
rust/rsnano/src/ffi/stats.rs
simpago/rsnano-node
6a59b6005b14eca1a00c362e314d1e0f6234f714
use std::{ ffi::{c_void, CStr}, ops::Deref, sync::Arc, }; use num::FromPrimitive; use crate::stats::{stat_type_as_str, FileWriter, JsonWriter, Stat, StatConfig, StatLogSink}; use super::FfiPropertyTreeWriter; #[repr(C)] pub struct StatConfigDto { pub sampling_enabled: bool, pub capacity: usize, ...
use std::{ ffi::{c_void, CStr}, ops::Deref, sync::Arc, }; use num::FromPrimitive; use crate::stats::{stat_type_as_str, FileWriter, JsonWriter, Stat, StatConfig, StatLogSink}; use super::FfiPropertyTreeWriter; #[repr(C)] pub struct StatConfigDto { pub sampling_enabled: bool, pub capacity: usize, ...
#[no_mangle] pub unsafe extern "C" fn rsn_stat_count( handle: *mut StatHandle, stat_type: u8, detail: u8, dir: u8, ) -> u64 { let stat_type = FromPrimitive::from_u8(stat_type).unwrap(); let detail = FromPrimitive::from_u8(detail).unwrap(); let dir = FromPrimitive::from_u8(dir).unwrap(); ...
pub unsafe extern "C" fn rsn_stat_disable_sampling( handle: *mut StatHandle, stat_type: u8, detail: u8, dir: u8, ) { let stat_type = FromPrimitive::from_u8(stat_type).unwrap(); let detail = FromPrimitive::from_u8(detail).unwrap(); let dir = FromPrimitive::from_u8(dir).unwrap(); (*handle)...
function_block-full_function
[]
Rust
src/main.rs
brianm/dice
8c75ab748b0e9aa24c2211f2faeb3b572d3eb1d9
use anyhow::{bail, Result}; use pest; use pest::Parser; use proptest::prelude::*; use rand; use rand::Rng; use std::fmt; use structopt::StructOpt; use rayon::prelude::*; #[macro_use] extern crate pest_derive; fn main() -> Result<()> { let args = Cli::from_args(); if args.expression.len() == 0 { ...
use anyhow::{bail, Result}; use pest; use pest::Parser; use proptest::prelude::*; use rand; use rand::Rng; use std::fmt; use structopt::StructOpt; use rayon::prelude::*; #[macro_use] extern crate pest_derive; fn main() -> Result<()> { let args = Cli::from_args(); if args.expression.len() == 0 { ...
} impl RollSpec { fn roll(&self) -> Roll { let mut rolls: Vec<i64> = (0..self.num) .into_par_iter() .map(|_| roll_die(self.size as u64) as i64) .collect(); rolls.par_sort(); let range = if self.keep_high != 0 { self.num - s...
suffix.push_str(&format!(" keep highest {}", self.keep_high)); } else if self.drop_low > 0 { suffix.push_str(&format!(" drop lowest {}", self.drop_low)); } else if self.drop_high > 0 { suffix.push_str(&format!(" drop highest {}", self.drop_high)); } else if self.keep_low ...
function_block-function_prefix_line
[ { "content": "# dice\n\n\n\nRolls dice using a small expression language:\n\n\n\nThe simplest expression is just a number, indicating to roll\n\na die with that many sides, ie: `dice 20` or `dice d20` to roll a 20 sided die.\n\n\n\nIf you want to roll multiple dice you can specify how many with a prefix,\n\nfor...
Rust
kernel/kernel_main/src/drivers/traits/block.rs
FranchuFranchu/rust-0bsd-riscv-kernel
e31789c49540d2c1637ebcff72361c5505c52843
use alloc::boxed::Box; use core::{any::Any, future::Future}; pub use kernel_syscall_abi::filesystem::GenericBlockDeviceError; use crate::{ arc_inject::WeakInjectRwLock, unsafe_buffer::{UnsafeSlice, UnsafeSliceMut}, }; #[derive(Debug)] pub enum BlockRequestFutureBuffer { WriteFrom(UnsafeSlice<u8>), Re...
use alloc::boxed::Box; use core::{any::Any, future::Future}; pub use kernel_syscall_abi::filesystem::GenericBlockDeviceError; use crate::{ arc_inject::WeakInjectRwLock, unsafe_buffer::{UnsafeSlice, UnsafeSliceMut}, }; #[derive(Debug)] pub enum BlockRequestFutureBuffer { WriteFrom(UnsafeSlice<u8>), Re...
async fn write(&self, sector: u64, buffer: &[u8]) -> Result<(), ()> { let f = RwLock::read(self).create_request( sector, BlockRequestFutureBuffer::WriteFrom(unsafe { UnsafeSlice::new(buffer) }), ); f.await; Ok(()) } } #[async_trait] impl<R: lock_api::Raw...
t( sector, BlockRequestFutureBuffer::ReadInto(unsafe { UnsafeSliceMut::new(buffer) }), ); f.await; Ok(()) }
function_block-function_prefixed
[ { "content": "pub trait WrappedVirtioDeviceType: Send + Sync + 'static {\n\n type RequestMeta: Unpin;\n\n type RequestBuildingData;\n\n\n\n type Trait;\n\n\n\n fn create_request(&mut self, data: Self::RequestBuildingData) -> RequestFuture<Self>\n\n where\n\n Self: Sized;\n\n fn device(&...
Rust
src/ser.rs
NobodyXu/ssh_mux_format
8e73aabf8278127f179eaa3c77d548a92fe41180
use serde::{ser, Serialize}; use std::convert::TryInto; use crate::{Error, Result, SerBacker}; #[derive(Clone, Debug)] pub struct Serializer<T: SerBacker = Vec<u8>> { pub(crate) output: T, } impl Default for Serializer { fn default() -> Self { Self::new() } } impl<T: SerBacker> Serializer<T> { ...
use serde::{ser, Serialize}; use std::convert::TryInto; use crate::{Error, Result, SerBacker}; #[derive(Clone, Debug)] pub struct Serializer<T: SerBacker = Vec<u8>> { pub(crate) output: T, } impl Default for Serializer { fn default() -> Self { Self::new() } } impl<T: SerBacker> Serializer<T> { ...
fn serialize_tuple_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant> { self.serialize_unit_variant(name, variant_index, variant)?; self.serialize_tuple(len) } fn se...
fn serialize_newtype_variant<T>( self, name: &'static str, variant_index: u32, variant: &'static str, value: &T, ) -> Result<()> where T: ?Sized + Serialize, { self.serialize_unit_variant(name, variant_index, variant)?; value.serialize(self) ...
function_block-full_function
[ { "content": "/// Return a deserialized value and trailing bytes.\n\n///\n\n/// # Example\n\n///\n\n/// Simple Usage:\n\n///\n\n/// ```ignore\n\n/// let serialized = to_bytes(value).unwrap();\n\n/// // Ignore the size\n\n/// let (new_value, _trailing_bytes) = from_bytes::<T>(&serialized[4..]).unwrap();\n\n///\n...
Rust
ascii-hangman/src/main.rs
getreu/ascii-hangman
66b523d687074d3dc766e00a07c8eb722cdafb2b
#![cfg(not(target_arch = "wasm32"))] use ascii_hangman_backend::game::State; use ascii_hangman_backend::Backend; use ascii_hangman_backend::HangmanBackend; use ascii_hangman_backend::{AUTHOR, CONF_TEMPLATE, TITLE, VERSION}; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::Write; us...
#![cfg(not(target_arch = "wasm32"))] use ascii_hangman_backend::game::State; use ascii_hangman_backend::Backend; use ascii_hangman_backend::HangmanBackend; use ascii_hangman_backend::{AUTHOR, CONF_TEMPLATE, TITLE, VERSION}; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::Write; us...
}
fn render(&self) { queue!(stdout(), Clear(ClearType::All), MoveTo(0, 0)).unwrap(); #[cfg(not(windows))] queue!(stdout(), ResetColor).unwrap(); #[cfg(windows)] queue!(stdout(), SetForegroundColor(Color::Grey),).unwrap(); queue!( stdout(), ...
function_block-full_function
[ { "content": "/// API to interact with all game logic. This is used by the desktop frontend\n\n/// in `main.rs` or by the web-app frontend in `lib.rs`.\n\npub trait HangmanBackend {\n\n /// Initialize the application with config data and start the first game.\n\n fn new(config: &str) -> Result<Self, Confi...
Rust
src/lz77.rs
mgrabmueller/campross
5944c3cf8f30330c25b13bcb80bb87b7e7650b6f
use std::io::{Read, Write}; use std::io; use error::Error; const WINDOW_BITS: usize = 12; const LENGTH_BITS: usize = 4; const MIN_MATCH_LEN: usize = 4; const MAX_MATCH_LEN: usize = ((1 << LENGTH_BITS) - 1) + MIN_MATCH_LEN - 1; const LOOK_AHEAD_BYTES: usize = MAX_MATCH_LEN + 1; const WINDOW_SIZE: usize = 1 << WIN...
use std::io::{Read, Write}; use std::io; use error::Error; const WINDOW_BITS: usize = 12; const LENGTH_BITS: usize = 4; const MIN_MATCH_LEN: usize = 4; const MAX_MATCH_LEN: usize = ((1 << LENGTH_BITS) - 1) + MIN_MATCH_LEN - 1; const LOOK_AHEAD_BYTES: usize = MAX_MATCH_LEN + 1; const WINDOW_SIZE: usize = 1 << WIN...
fn process(&mut self, output: &mut [u8]) -> io::Result<usize> { let mut written = 0; while written < output.len() { if let Some(m1) = try!(self.getc()) { let mbm2 = try!(self.getc()); let mblit = try!(self.getc()); match (mbm2, mblit)...
fn copy_out(&mut self, output: &mut [u8], written: &mut usize) { while *written < output.len() && self.returned != self.position { output[*written] = self.window[self.returned]; *written += 1; self.returned = mod_window(self.returned + 1); } }
function_block-full_function
[ { "content": "pub fn compress<R: Read, W: Write>(mut input: R, output: W) -> Result<W, Error> {\n\n let mut cw = Writer::new(output);\n\n try!(io::copy(&mut input, &mut cw));\n\n try!(cw.flush());\n\n Ok(cw.to_inner())\n\n}\n\n\n", "file_path": "src/lzp1.rs", "rank": 0, "score": 263145.9...
Rust
src/image_processing.rs
BlackHoleFox/repost-me-not
e80c47a4836d4f5550ac6ddae9d43554b5d19440
use crate::Error; use image::io::Reader; use img_hash::{HashAlg, HasherConfig}; use std::io::Cursor; type HashStorage = [u8; 64]; pub type ImageHash = img_hash::ImageHash<HashStorage>; const DIFFERENCE_THRESHOLD: u32 = 8; pub fn process_image(image: Vec<u8>) -> Result<ImageHash, Error> { let hasher = HasherConf...
use crate::Error; use image::io::Reader; use img_hash::{HashAlg, HasherConfig}; use std::io::Cursor; type HashStorage = [u8; 64]; pub type ImageHash = img_hash::ImageHash<HashStorage>; const DIFFERENCE_THRESHOLD: u32 = 8; pub fn process_image(image: Vec<u8>) -> Result<ImageHash, Error> { let hasher = HasherConf...
)?; ( process_image(entries[0].clone()).unwrap(), process_image(entries[1].clone()).unwrap(), ) }; assert!( similar_enough(&h1, h2.as_bytes()), "did not detect a duplicate in directo...
or seeking can't fail") .decode() .map_err(Error::UnsupportedImageFormat)?; tracing::trace!( "It took {}ms to decode the image", start.elapsed().as_millis() ); let start = std::time::Instant::now(); let hash = hasher.hash_image(&image); tracing::trace!( "It t...
random
[ { "content": "fn save_image(\n\n context: &bot::Context,\n\n image: Vec<u8>,\n\n msg: &Message,\n\n) -> Result<PreviouslySeen, Error> {\n\n let hash = image_processing::process_image(image)?;\n\n tracing::debug!(\"Image hash was {:0x?}\", hash.as_bytes());\n\n\n\n let now = std::time::SystemTi...
Rust
sdk/src/batches/store/mod.rs
leebradley/grid
2001cec0ff1951f953ee345f4d030ce42a68aac3
#[cfg(feature = "diesel")] pub(in crate) mod diesel; mod error; use chrono::NaiveDateTime; use crate::hex; use crate::paging::Paging; #[cfg(feature = "diesel")] pub use self::diesel::DieselBatchStore; pub use error::BatchStoreError; #[derive(Clone, Debug, PartialEq)] pub struct Batch { pub header_signature: S...
#[cfg(feature = "diesel")] pub(in crate) mod diesel; mod error; use chrono::NaiveDateTime; use crate::hex; use crate::paging::Paging; #[cfg(feature = "diesel")] pub use self::diesel::DieselBatchStore; pub use error::BatchStoreError; #[derive(Clone, Debug, PartialEq)] pub struct Batch { pub header_signature: S...
} #[derive(Clone, Debug, PartialEq)] pub struct BatchSubmitInfo { pub header_signature: String, pub serialized_batch: String, pub service_id: Option<String>, } #[derive(Clone, Debug, PartialEq)] pub struct Transaction { pub header_signature: String, pub batch_id: String, pub family_name: Stri...
ignature.to_string(), batch_id: self.header_signature.clone(), family_name: family_name.to_string(), family_version: family_version.to_string(), signer_public_key: self.signer_public_key.clone(), }); }
function_block-function_prefixed
[ { "content": "/// Parses a hex string into a byte array\n\n///\n\n/// # Arguments\n\n///\n\n/// * `hex`: the hex string to convert\n\npub fn parse_hex(hex: &str) -> Result<Vec<u8>, HexError> {\n\n if hex.len() % 2 != 0 {\n\n return Err(HexError {\n\n context: format!(\"{} is not valid hex:...
Rust
src/article.rs
tragle/blarf
8fccac32da8e7d3b421f80b6399b627b8f1f8148
use pulldown_cmark::{html, Parser}; pub struct Article { pub markdown: String, pub slug: String, pub title: String, } impl Article { pub fn new(markdown: String, slug: String) -> Article { match...
use pulldown_cmark::{html, Parser}; pub struct Article { pub markdown: String, pub slug: String, pub title: String, } impl Article { pub fn new(markdown: String, slug: String) -> Article { match...
fn as_html(&self) -> String { let parser = Parser::new(&self.markdown); let mut html_buf = String::new(); html::push_html(&mut html_buf, parser); html_buf } fn get_slugs(i: usize, articles: &[Article]) -> (Option<&str>, Option<&str>) { let first = 0; let la...
pub fn get_title(markdown: &str) -> Option<&str> { let pattern = "# "; let lines: Vec<&str> = markdown.split('\n').collect(); for line in lines { if line.starts_with(&pattern) { let (_, title) = &line.split_at(pattern.len()); return Some(title.trim());...
function_block-full_function
[ { "content": "fn write_articles(articles: &[Article], email: Option<&str>, css: &str) -> std::io::Result<()> {\n\n let first = 0;\n\n let last = articles.len() - 1;\n\n\n\n for i in first..=last {\n\n let article = &articles[i];\n\n let footer = Article::render_footer(i, &articles, email)...
Rust
src/thread_pool.rs
luan-cestari/ferrous-threads
ef799c2a0c22ed09735ca78eaa2f13373d4cff2d
use std::boxed::FnBox; use std::thread::{self, spawn}; use std::sync::mpsc::{channel, Sender, SendError, Receiver, TryRecvError, RecvError}; use std::error::Error; use std::fmt; trait Runner { fn run(self: Box<Self>); } impl <F: FnBox()> Runner for F { fn run(self: Box<F>) { self.call_box(()) } ...
use std::boxed::FnBox; use std::thread::{self, spawn}; use std::sync::mpsc::{channel, Sender, SendError, Receiver, TryRecvError, RecvError}; use std::error::Error; use std::fmt; trait Runner { fn run(self: Box<Self>); } impl <F: FnBox()> Runner for F { fn run(self: Box<F>) { self.call_box(()) } ...
); assert!(thr1.is_ok()); let thr1 = thr1.ok().unwrap(); assert!(thr2.is_ok()); let thr2 = thr2.ok().unwrap(); let res = thr1.start(f1); assert!(res.is_ok()); let res = thr2.start(f2); assert!(res.is_ok()); let res = thr1.join(); assert!...
(); sentinel.done(); }); } impl ThreadPool { pub fn new(init_threads: usize, max_threads: usize) -> ThreadPool { let (sn, rc) = channel(); let mut thrs = Vec::new(); for _i in 0..init_threads { spawn_thread(sn.clone()); let thr = rc.recv().ex...
random
[ { "content": "fn send_prime_to_workers(p: usize, sn_sieves: &Vec<Sender<Option<usize>>>) {\n\n for sn in sn_sieves.iter() {\n\n assert!(sn.send(Some(p)).is_ok());\n\n }\n\n}\n\n\n", "file_path": "examples/sieve_of_eratosthenes.rs", "rank": 5, "score": 78150.10181862851 }, { "con...
Rust
src/tpi/mod.rs
pombredanne/pdb
1be293bf852b27e59b694567ea68f1bc38fa757f
use std::fmt; use std::result; use crate::common::*; use crate::msf::Stream; use crate::FallibleIterator; pub(crate) mod constants; mod data; mod header; mod primitive; use self::data::parse_type_data; use self::header::*; use self::primitive::type_data_for_primitive; pub use self::data::*; pub use self::primitiv...
use std::fmt; use std::result; use crate::common::*; use crate::msf::Stream; use crate::FallibleIterator; pub(crate) mod constants; mod data; mod header; mod primitive; use self::data::parse_type_data; use self::header::*; use self::primitive::type_data_for_primitive; pub use self::data::*; pub use self::primitiv...
} #[derive(Debug)] pub struct TypeFinder<'t> { buffer: ParseBuffer<'t>, minimum_type_index: TypeIndex, maximum_type_index: TypeIndex, positions: Vec<u32>, shift: u8, } impl<'t> TypeFinder<'t> { fn new(type_info: &'t TypeInformation<'_>, shift: u8) -> Self { let count = type_info.heade...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Type{{ kind: 0x{:4x} [{} bytes] }}", self.raw_kind(), self.1.len() ) }
function_block-full_function
[ { "content": "fn header_matches(actual: &[u8], expected: &[u8]) -> bool {\n\n actual.len() >= expected.len() && &actual[0..expected.len()] == expected\n\n}\n\n\n", "file_path": "src/msf/mod.rs", "rank": 0, "score": 197703.4753333742 }, { "content": "fn parse_symbol_data(kind: u16, data: &...
Rust
src/lib.rs
rrybarczyk/bgpdump-rs
87f784661f4160fccd8973b7c542902728f126fe
#![deny(missing_docs)] use byteorder::{BigEndian, ReadBytesExt}; use std::io::{Error, ErrorKind, Read}; pub mod records { pub mod bgp; pub mod bgp4plus; pub mod bgp4mp; pub mod isis; pub mod ospf; pub mod rip; pub mod tabledump; } pub use records:...
#![deny(missing_docs)] use byteorder::{BigEndian, ReadBytesExt}; use std::io::{Error, ErrorKind, Read}; pub mod records { pub mod bgp; pub mod bgp4plus; pub mod bgp4mp; pub mod isis; pub mod ospf; pub mod rip; pub mod tabledump; } pub use records:...
} pub struct Reader<T> where T: Read, { pub stream: T, } #[derive(Debug)] pub struct Header { pub timestamp: u32, pub extended: u32, pub record_type: u16, pub sub_type: u16, pub length: u32, } #[derive(Debug)] #[allow(missing_docs)] #[allow(non_camel_cas...
pub fn size(&self) -> u32 { match self { AFI::IPV4 => 4, AFI::IPV6 => 16, } }
function_block-full_function
[ { "content": "///\n\n/// # Summary\n\n/// Used to parse ISIS MRT records.\n\n///\n\n/// # Panics\n\n/// This function does not panic.\n\n///\n\n/// # Errors\n\n/// Any IO error will be returned while reading from the stream.\n\n/// If an ill-formatted stream or header is provided behavior will be undefined.\n\n...
Rust
2020/20_jurassic_jigsaw_part_2.rs
garciparedes/advent-of-code
77fcd55546b114f9017146b3079d4a333dd87091
use std::io::prelude::*; use std::io; use std::cmp; use std::collections::{ HashSet, HashMap, }; const PATTERN: &'static str = " # # ## ## ### # # # # # # "; fn main() -> io::Result<()> { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer)?; ...
use std::io::prelude::*; use std::io; use std::cmp; use std::collections::{ HashSet, HashMap, }; const PATTERN: &'static str = " # # ## ## ### # # # # # # "; fn main() -> io::Result<()> { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer)?; ...
fn compose_board<'a>(structure: &Vec<Vec<&Tile>>, first_tile: &Tile) -> Option<Vec<Vec<Tile>>> { let mut board: Vec<Vec<Tile>> = Vec::new(); for i in 0..structure.len() { let mut row = Vec::new(); for j in 0..structure[0].len() { if i == 0 && j == 0 { row.push(first...
fn orient_tiles(structure: &Vec<Vec<&Tile>>) -> Vec<Vec<Tile>> { let mut first_tile = structure[0][0].clone(); if let Some(ans) = compose_board(&structure, &first_tile) { return ans; } for _ in 0..2 { first_tile = first_tile.swap(); for _ in 0..4 { first_tile = first_...
function_block-full_function
[ { "content": "fn build_adjacency<'a>(buffer: &'a str) -> HashMap<&'a str, HashSet<(&'a str, usize)>> {\n\n let mut adjacency = HashMap::new();\n\n\n\n for row in buffer.trim().split(\"\\n\") {\n\n let mut kv = row.split(\"contain\");\n\n let origin = kv.next().unwrap().split(\" bag\").next()...
Rust
src/lib.rs
cuddlefishie/inline-gdscript
32f7f243e56bd1628265ed86db23d1cca7a0ceb2
pub use inline_gdscript_macros::gdscript; use gdnative_core::{ core_types::{FromVariant, OwnedToVariant, ToVariant, Variant}, libc::c_char, }; pub struct Context(Variant); impl Context { fn new_with_source(src: &str) -> Self { let api = gdnati...
pub use inline_gdscript_macros::gdscript; use gdnative_core::{ core_types::{FromVariant, OwnedToVariant, ToVariant, Variant}, libc::c_char, }; pub struct Context(Variant); impl Context { fn new_with_source(src: &str) -> Self { let api = gdnati...
for line in source.lines() { new_src.push_str(&indent); new_src.push_str(line); new_src.push('\n'); } let mut ctx = Context::new_with_source(&format!( "extends Reference; func run():{}\n{}", new_src, extra_source )); set_v...
ce: &'static str, extra_source: &'static str, indent: usize, set_variables: F, ) -> Self { let mut new_src = String::new(); let indent: String = " ".repeat(indent);
function_block-random_span
[ { "content": "#[proc_macro]\n\npub fn gdscript(toks: TokenStream1) -> TokenStream1 {\n\n TokenStream1::from(match gdscript_impl(TokenStream::from(toks)) {\n\n Ok(tokens) => tokens,\n\n Err(tokens) => tokens,\n\n })\n\n}\n", "file_path": "inline-gdscript-macros/src/lib.rs", "rank": 1,...
Rust
src/datastream.rs
bdunderscore/vrc-calendar-updater
81dc688b915692617d437568417e8db0d3a403de
use crate::render_prims::*; use anyhow::{bail, Result, Context}; use std::convert::{TryFrom, TryInto}; use tracing::{debug, info, trace}; const DATA_COL_WIDTH: i32 = 64; const HEADER_HEIGHT: u32 = 128; #[derive(Copy, Clone, Debug, Default)] pub struct ByteColor { b: u8, g: u8, r: u8, a: u8, } tra...
use crate::render_prims::*; use anyhow::{bail, Result, Context}; use std::convert::{TryFrom, TryInto}; use tracing::{debug, info, trace}; const DATA_COL_WIDTH: i32 = 64; const HEADER_HEIGHT: u32 = 128; #[derive(Copy, Clone, Debug, Default)] pub struct ByteColor { b: u8, g: u8, r: u8, a: u8, } tra...
: u8 = convert_part(r)?; let g: u8 = convert_part(g)?; let b: u8 = convert_part(b)?; Ok(Self { r, g, b, a: 0xFF }) } fn to_array(self) -> [u8; 4] { let ByteColor { r, g, b, a } = self; let le_bytes = [b, g, r, a]; let int_val = u32::from_le_bytes(le_bytes); ...
e: u32) -> Result<Self> { if value >= (1 << 18) { bail!(format!("Value {} is too large to be represented", value)); } let r = (value >> 12) & 0x3F; let g = (value >> 6) & 0x3F; let b = value & 0x3F; let r
function_block-random_span
[ { "content": "fn debug_color(surf: &mut cairo::Context) {\n\n let mut c = COUNTER.fetch_add(1, Ordering::Relaxed);\n\n let r = (1 + c % 4) as f64 / 4.0;\n\n c >>= 2;\n\n let g = (1 + c % 4) as f64 / 4.0;\n\n c >>= 2;\n\n let b = (1 + c % 4) as f64 / 4.0;\n\n\n\n surf.set_source_rgb(r, g, b)...
Rust
src/core/testutil.rs
sbosnick/caledon
acadef3df65193850f2a716305514ccccb8f212d
use std::convert::TryFrom; use super::{ ConversionError, Fd, FromOpcodeError, Interface, Message, MessageList, ObjectId, Protocol, ProtocolFamily, ProtocolFamilyMessageList, ProtocolMessageList, }; pub struct DestroyRequest {} impl Message for DestroyRequest { const OPCODE: u16 = 0; type Signature =...
use std::convert::TryFrom; use super::{ ConversionError, Fd, FromOpcodeError, Interface, Message, MessageList, ObjectId, Protocol, ProtocolFamily, ProtocolFamilyMessageList, ProtocolMessageList, }; pub struct DestroyRequest {} impl Message for DestroyRequest { const OPCODE: u16 = 0; type Signature =...
sts::{Conjoin, Destroy}; match self { BuildTimeWaylandTests(FdPasser(Destroy(msg))) => handler.handle(msg), BuildTimeWaylandTests(FdPasser(Conjoin(msg))) => handler.handle(msg), } } } impl ProtocolFamilyMessageList for FamilyEvents { type ProtocolFamily = Protocols; ...
has_fd(opcode: super::OpCode) -> bool { match opcode { 0 => false, 1 => true, _ => panic!("Unknown opcode"), } } } impl From<PreFdEvent> for Events { fn from(p: PreFdEvent) -> Self { Events::PreFd(p) } } impl TryFrom<Events> for PreFdEvent { ty...
random
[ { "content": "#[derive(Debug, Snafu)]\n\nenum ClientErrorImpl<E: error::Error + 'static> {\n\n #[snafu(display(\"Error with the underlying communication channel during the {}\", phase))]\n\n Transport { source: E, phase: ClientPhase },\n\n\n\n #[snafu(display(\"Fatal protocol error during the {}: {}\",...
Rust
src/dev/pca9536.rs
Rahix/port-expander
ce2091d1d75521cb9b4e6c57854f94ffe72423e8
use crate::I2cExt; pub struct Pca9536<M>(M); impl<I2C> Pca9536<shared_bus::NullMutex<Driver<I2C>>> where I2C: crate::I2cBus, { pub fn new(i2c: I2C) -> Self { Self::with_mutex(i2c) } } impl<I2C, M> Pca9536<M> where I2C: crate::I2cBus, M: shared_bus::BusMutex<Bus = Driver<I2C>>, { pub ...
use crate::I2cExt; pub struct Pca9536<M>(M); impl<I2C> Pca9536<shared_bus::NullMutex<Driver<I2C>>> where I2C: crate::I2cBus, { pub fn new(i2c: I2C) -> Self { Self::with_mutex(i2c) } } impl<I2C, M> Pca9536<M> where I2C: crate::I2cBus, M: shared_bus::BusMutex<Bus = Driver<I2C>>, { pub ...
}
mock_i2c::Transaction::write(super::ADDRESS, vec![0x01, 0xfd]), mock_i2c::Transaction::write(super::ADDRESS, vec![0x01, 0xff]), mock_i2c::Transaction::write(super::ADDRESS, vec![0x01, 0xfd]), mock_i2c::Transaction::write_read(super::ADDRESS, vec![0x00], vec![0x01]), ...
function_block-function_prefix_line
[ { "content": "/// Set multiple pins at the same time.\n\n///\n\n/// The usual method of setting multiple pins\n\n///\n\n/// ```no_run\n\n/// # let i2c = embedded_hal_mock::i2c::Mock::new(&[]);\n\n/// # let mut pcf = port_expander::Pcf8574::new(i2c, false, false, false);\n\n/// # let p = pcf.split();\n\n/// # le...
Rust
src/graph/dominators.rs
mrbbot/montera
79018b243f7824441fabe7215805fe32d9f8b48a
use crate::graph::{Graph, NodeId, NodeMap, NodeOrder, Order}; fn intersect( post_order: &NodeOrder, doms: &NodeMap<Option<NodeId>>, mut finger1: NodeId, mut finger2: NodeId, ) -> NodeId { while finger1 != finger2 { while post_order.cmp(finger1, /* < */ finger2).is_lt() { finge...
use crate::graph::{Graph, NodeId, NodeMap, NodeOrder, Order}; fn intersect( post_order: &NodeOrder, doms: &NodeMap<Option<NodeId>>, mut finger1: NodeId, mut finger2: NodeId, ) -> NodeId { while finger1 != finger2 { while post_order.cmp(finger1, /* < */ finger2).is_lt() { finge...
t expected_idom = hashmap! { n1 => n1, n2 => n1, n3 => n2, n4 => n3, n5 => n3, n6 => n3, n7 => n2, n8 => n7, }; assert_eq!(idom, expected_idom.into()); } #[test] fn immediate_dominators_cyclic() ...
let mut new_idom = *self[b] .predecessors .iter() .find(|&&p| idom[p].is_some()) .unwrap(); for &p in &self[b].predecessors { if p != new_idom && idom[p].is_some() { ...
random
[ { "content": "/// Performs the rendering phase of WebAssembly generation, lowering all pseudo-instructions to real\n\n/// WebAssembly instructions using program wide information. See [`Renderer`] for more details.\n\npub fn render_module(\n\n classes: Arc<HashMap<Arc<String>, Class>>,\n\n virtual_table: R...
Rust
src/plot/gnuplot_backend/iteration_times.rs
jmwill86/criterion.rs
1d75c14d4e0554c0db9e64f30573b5d2b08d488b
use std::process::Child; use criterion_plot::prelude::*; use super::*; use crate::report::{BenchmarkId, ComparisonData, MeasurementData, ReportContext}; use crate::measurement::ValueFormatter; fn iteration_times_figure( formatter: &dyn ValueFormatter, measurements: &MeasurementData<'_>, size: Option<Siz...
use std::process::Child; use criterion_plot::prelude::*; use super::*; use crate::report::{BenchmarkId, ComparisonData, MeasurementData, ReportContext}; use crate::measurement::ValueFormatter; fn iteration_times_figure( formatter: &dyn ValueFormatter, measurements: &MeasurementData<'_>, size: Option<Siz...
y: scaled_base_y.as_ref(), }, |c| { c.set(DARK_RED) .set(Label("Base")) .set(PointSize(0.5)) .set(PointType::FilledCircle) }, ) .plot( Points { x: 1..(...
w(&all_data).max(); let unit = formatter.scale_values(typical_value, &mut all_data); let (scaled_current_y, scaled_base_y) = all_data.split_at(current_data.len()); let scaled_current_y = Sample::new(scaled_current_y); let scaled_base_y = Sample::new(scaled_base_y); let mut figure = Figure::new(); ...
random
[ { "content": "fn debug_script(path: &Path, figure: &Figure) {\n\n if crate::debug_enabled() {\n\n let mut script_path = path.to_path_buf();\n\n script_path.set_extension(\"gnuplot\");\n\n info!(\"Writing gnuplot script to {:?}\", script_path);\n\n let result = figure.save(script_p...
Rust
cyrel-sync/src/main.rs
alyrow/cyrel
e28fa84045db07020b731a54d3f7e5f5198ce693
use std::collections::HashSet; use std::env; use anyhow::{anyhow, Context}; use celcat::{ entities::{Student, StudentId}, fetch::Celcat, fetchable::{ calendar::{CalView, CalendarData, CalendarDataRequest, Course}, event::{Element, Event, EventRequest, RawElement}, resources::{Resour...
use std::collections::HashSet; use std::env; use anyhow::{anyhow, Context}; use celcat::{ entities::{Student, StudentId}, fetch::Celcat, fetchable::{ calendar::{CalView, CalendarData, CalendarDataRequest, Course}, event::{Element, Event, EventRequest, RawElement}, resources::{Resour...
async fn update_event(state: &State, course: Course) -> anyhow::Result<()> { let event: Event = match state .celcat .fetch(EventRequest { event_id: course.id.clone(), }) .await { Ok(event) => event, Err(err) => { error!( "...
async fn event_updater(state: &'static State, mut rx: mpsc::Receiver<Message>) { let mut already_updated = HashSet::<String>::new(); while let Some((c, s)) = rx.recv().await { let updated = already_updated.insert(c.id.0.clone()); tokio::spawn(async move { if !updated { ...
function_block-full_function
[ { "content": "SELECT id, firstname, lastname, email, password\n\nFROM users\n\nWHERE email = $1\n\n \"#,\n\n email\n\n )\n\n .fetch_one(pool)\n\n .await?;\n\n\n\n Ok(User {\n\n id: user.id,\n\n firstname: user.firstname,\n\n lastname...
Rust
front-end/src/lib.rs
christianfosli/visnake-wasm
91544e75282d4fb70c4938cf9e6bf5e7f0b37822
use futures::stream::StreamExt; use gloo_dialogs::alert; use gloo_timers::callback::Interval; use gloo_utils::{document, window}; use js_sys::Error; use std::fmt; use std::sync::{Arc, RwLock}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::spawn_local; use web_sys::HtmlElement; mod...
use futures::stream::StreamExt; use gloo_dialogs::alert; use gloo_timers::callback::Interval; use gloo_utils::{document, window}; use js_sys::Error; use std::fmt; use std::sync::{Arc, RwLock}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::spawn_local; use web_sys::HtmlElement; mod...
log::debug!("Refreshing highscore tables"); highscores::fetch_and_set(highscore_api).await?; Ok(()) }
match highscores::check_and_submit(highscore_api, apple_count).await { Ok(()) => {} Err(e) => { log::error!("{e:?}"); alert(&format!("An error occured: {e}")); } }
if_condition
[ { "content": "pub fn snake(doc: &Document, snake: &Snake) -> Result<(), JsValue> {\n\n let context = get_canvas_context(doc)?;\n\n context.set_fill_style(&JsValue::from_str(\"#abba00\"));\n\n context.fill_rect(\n\n snake.head().x,\n\n snake.head().y,\n\n snake::LINE_THICKNESS,\n\n ...
Rust
src/render.rs
AATruttse/DNDDice
13bf4723bc0f35b152b1060d9d769374b6591358
use itertools::Itertools; use crate::dices::IntValue; use crate::errors::errorln; use crate::init::OPT; use crate::output::{output, outputln}; use crate::statlists::StatList; use crate::strings::{ADVDISADV_ERROR_MSG, ADVDISADV_ADV_CODE, ADVDISADV_DISADV_CODE}; pub fn render_roll( is_several_rolls: bool, ...
use itertools::Itertools; use crate::dices::IntValue; use crate::errors::errorln; use crate::init::OPT; use crate::output::{output, outputln}; use crate::statlists::StatList; use crate::strings::{ADVDISADV_ERROR_MSG, ADVDISADV_ADV_CODE, ADVDISADV_DISADV_CODE}; pub fn render_roll( is_several_rolls: bool, ...
ool, is_ordered: bool, i: usize, stat : &Vec<IntValue>, statlist: &StatList) { if !OPT.numbers_only && is_shownumber { let num_str = format!("{}: ", i); output(&num_str); } if is_ordered && !OPT.numbers_only { for i in 0..statlist.len() { let stat_str = f...
e = match drop_str.len() + crop_str.len() + reroll_str.len() { 0 => "", _ => " " }; let add_str: String = match add { x if x > 0 => format!("{}+{}{}", add_space, add_space, x), x if x < 0 => format!("{}-{}{}", add_space, add_space,-x), _ ...
random
[ { "content": "#[inline(always)]\n\npub fn n_d_reroll_drop_crop_plus(n: usize, d: usize, reroll: &[usize], plus: IntValue, drop: usize, crop: usize) -> Result<IntValue, DiceError> {\n\n if n == 0 {\n\n return Err(DiceError::Dices0);\n\n }\n\n\n\n if d == 0 {\n\n return Err(DiceError::Sides...
Rust
src/widget_generators.rs
DanieleBonaldo/rec
2665f303fa5547e9237d937a886353e6e4442baf
use crate::styles::*; use std::path::Path; use fltk::{prelude::*, enums, enums::{FrameType, Event, LabelType, Align}, group, button, input, text}; use super::THEME; #[derive(Clone, Debug, Copy)] pub enum Mess { Prev, Next, Chrono, Search, Children, } pub fn create_button(...
use crate::styles::*; use std::path::Path; use fltk::{prelude::*, enums, enums::{FrameType, Event, LabelType, Align}, group, button, input, text}; use super::THEME; #[derive(Clone, Debug, Copy)] pub enum Mess { Prev, Next, Chrono, Search, Children, } pub fn create_button(...
} pub fn create_text_widget(text: &str) -> text::TextDisplay { let mut buf = text::TextBuffer::default(); buf.set_text(text); let mut txt = text::TextDisplay::default(); txt.set_buffer(buf); txt.wrap_mode(text::WrapMode::AtBounds,200); to_default_style(&mut txt, &THEME); to_text_style(&mu...
pub fn update_frame(&mut self) { let image = fltk::image::RgbImage::new(&self.buffer, self.size[0] * self.mult, self.size[1] * self.mult, fltk::enums::ColorDepth::Rgb8); if let Ok(mut image) = image { image.scale(self.size[0],self.size[1],true,true); self.frame.set_image_scaled(S...
function_block-full_function
[ { "content": "pub fn to_button_style(widget: &mut impl WidgetExt, st: &Theme) {\n\n widget.set_color(enums::Color::from_hex(0x000050));\n\n widget.set_selection_color(enums::Color::from_hex(0x000030));\n\n widget.set_label_color(enums::Color::from_hex(st.get().label));\n\n widget.clear_visible_focus...
Rust
src/states/image_pull.rs
rickrain/krustlet-cri
749bc7740b4e9a9597aab744a4171248771289cd
use async_trait::async_trait; use k8s_cri::v1alpha2 as cri; use log::{debug, error, info}; use std::convert::TryFrom; use tokio::net::UnixStream; use tonic::transport::{Channel, Endpoint, Uri}; use tower::service_fn; use super::{error::Error, starting::Starting, PodState}; use kubelet::state::prelude::*; #[derive(Def...
use async_trait::async_trait; use k8s_cri::v1alpha2 as cri; use log::{debug, error, info}; use std::convert::TryFrom; use tokio::net::UnixStream; use tonic::transport::{Channel, Endpoint, Uri}; use tower::service_fn; use super::{error::Error, starting::Starting, PodState}; use kubelet::state::prelude::*; #[derive(Def...
async fn pull_image( image_client: &mut cri::image_service_client::ImageServiceClient<Channel>, image: &str, sandbox_config: &cri::PodSandboxConfig, ) -> anyhow::Result<()> { info!("Pulling image: {}", &image); let request = tonic::Request::new(cri::PullImageRequest { image: Some(cri::Imag...
e_present( image_client: &mut cri::image_service_client::ImageServiceClient<Channel>, image: &str, ) -> anyhow::Result<bool> { let request = tonic::Request::new(cri::ImageStatusRequest { image: Some(cri::ImageSpec { image: image.to_string(), }), verbose: false, }); ...
function_block-function_prefixed
[ { "content": "use kubelet::state::prelude::*;\n\n\n\nuse super::PodState;\n\n\n\n#[derive(Default, Debug)]\n\n/// The Pod failed to run.\n\npub struct Error {\n\n pub message: String,\n\n}\n\n\n\n#[async_trait::async_trait]\n\nimpl State<PodState> for Error {\n\n async fn next(\n\n self: Box<Self>,...
Rust
nonebot_rs/src/matcher/api.rs
abrahum/nonebot-rs
8c090098a10f574637fcad16fd74357e875bd43e
use super::Matcher; use crate::api_resp; use crate::event::SelfId; use colored::*; use tracing::{event, Level}; macro_rules! no_resp_api { ($fn_name: ident, $param: ident: $param_type: ty) => { pub async fn $fn_name(&self, $param: $param_type) { if let Some(bot) = &self.bot { bo...
use super::Matcher; use crate::api_resp; use crate::event::SelfId; use colored::*; use tracing::{event, Level}; macro_rules! no_resp_api { ($fn_name: ident, $param: ident: $param_type: ty) => { pub async fn $fn_name(&self, $param: $param_type) { if let Some(bot) = &self.bot { bo...
esp_api!( get_stranger_info, api_resp::StrangerInfo, user_id: String, no_cache: bool ); resp_api!(get_friend_list, Vec<api_resp::FriendListItem>); resp_api!( get_group_info, api_resp::GroupInfo, group_id: String, no_cache: bool ); resp_...
"Calling api {} {}", stringify!($fn_name).blue(), "with unbuilt matcher!".red() ); } } }; } macro_rules! resp_api { ($fn_name: ident, $resp_data_type: ty) => { pub async fn $fn_name(&self) -> Option<$resp_d...
random
[ { "content": "pub fn r6s() -> Vec<Matcher<MessageEvent>> {\n\n let mut headers = HeaderMap::new();\n\n headers.insert(\"Host\", \"www.r6s.cn\".parse().unwrap());\n\n headers.insert(\"referer\", \"https://www.r6s.cn\".parse().unwrap());\n\n headers.insert(\"user-agent\", \"Mozilla/5.0 (Windows NT 10....
Rust
src/todo.rs
kamyuentse/pomotodo-rs
848c89b0c6b149acecb6f67d69169ac520ecf731
use uuid::Uuid; use chrono::prelude::*; #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum RepeatType { None, EachDay, EachWeek, EachTwoWeek, EachMonth, EachYear, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Todo { ...
use uuid::Uuid; use chrono::prelude::*; #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum RepeatType { None, EachDay, EachWeek, EachTwoWeek, EachMonth, EachYear, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Todo { ...
type Err = ::std::io::Error; #[cfg_attr(rustfmt, rustfmt_skip)] fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "none" => Ok(RepeatType::None), "each_day" => Ok(RepeatType::EachDay), "each_week" => Ok(RepeatType::EachWeek), ...
completed: None, completed_at: None, repeat_type: None, remind_time: None, estimated_pomo_count: None, costed_pomo_count: None, sub_todos: None, } } } impl Default for TodoParameter { fn default() -> TodoParameter { ...
random
[ { "content": "#[test]\n\nfn test_session() {\n\n let sess = Session::with_token(\"Your token here\").unwrap();\n\n\n\n let mut pomo = sess.create_pomo(&Pomo { ..Default::default() }).unwrap();\n\n let patched_pomo = sess.update_pomo(&pomo.uuid.unwrap(), \"Test pomo patch\".to_string())\n\n .unwr...
Rust
src/day_23.rs
apljungquist/aocoracle
8b09acf8d40330a2eed8fc12a2d70c8d5a1971e8
use std::fs; use hashbrown::HashMap; type Tile = u64; type Room = u64; type Amphipod = u64; const NUM_ROOM: usize = 4; type Rooms = [Room; NUM_ROOM]; type Hallway = u64; type Paths = HashMap<(Room, Tile), Vec<Tile>>; const EXISTENCE_MASK: u64 = 0b100; const VALUE_MASK: u64 = 0b011; const MASK_WIDTH: u64 = 3; fn _...
use std::fs; use hashbrown::HashMap; type Tile = u64; type Room = u64; type Amphipod = u64; const NUM_ROOM: usize = 4; type Rooms = [Room; NUM_ROOM]; type Hallway = u64; type Paths = HashMap<(Room, Tile), Vec<Tile>>; const EXISTENCE_MASK: u64 = 0b100; const VALUE_MASK: u64 = 0b011; const MASK_WIDTH: u64 = 3; fn _...
fn _from_file<F, T>(func: F, stem: &str) -> T where F: Fn(&str) -> T, { func(&fs::read_to_string(format!("inputs/23/{}.txt", stem)).unwrap()) } #[cfg(test)] mod tests { use super::*; #[test] fn part_1_works_on_example() { assert_eq!(_from_file(part_1, "example"), 12521); } #[tes...
2]); rooms[2] = _push(tmp.0, 0); rooms[2] = _push(rooms[2], 1); rooms[2] = _push(rooms[2], tmp.1); tmp = _pop(rooms[3]); rooms[3] = _push(tmp.0, 2); rooms[3] = _push(rooms[3], 0); rooms[3] = _push(rooms[3], tmp.1); _part_x(rooms) }
function_block-function_prefixed
[ { "content": "fn _room_is_accessible(paths: &Paths, hallway: Hallway, src: Tile, dst: Room) -> bool {\n\n for step in paths.get(&(dst, src)).unwrap() {\n\n if src == *step {\n\n continue;\n\n }\n\n if _contains(hallway, *step) {\n\n return false;\n\n }\n\n ...
Rust
src/main.rs
maekawatoshiki/rcaml
c9824653d7acd5de76731428b52d63e41f51c3e9
extern crate rcaml; use rcaml::parser; extern crate clap; use clap::{App, Arg}; extern crate ansi_term; use self::ansi_term::{Colour, Style}; extern crate nom; use std::fs::OpenOptions; use std::io::prelude::*; const VERSION_STR: &'static str = env!("CARGO_PKG_VERSION"); pub fn run(e: &str) { use rcaml::codeg...
extern crate rcaml; use rcaml::parser; extern crate clap; use clap::{App, Arg}; extern crate ansi_term; use self::ansi_term::{Colour, Style}; extern crate nom; use std::fs::OpenOptions; use std::io::prelude::*; const VERSION_STR: &'static str = env!("CARGO_PKG_VERSION"); pub fn run(e: &str) { use rcaml::codeg...
g( Arg::with_name("version") .short("v") .long("version") .help("Show version info"), ) .arg(Arg::with_name("FILE") .help("Input file") .index(1)) .get_matches(); if app.is_present("...
function_block-function_prefixed
[ { "content": "pub fn f(node: &NodeKind, tyenv: &mut HashMap<usize, Type>, idgen: &mut id::IdGen) -> NodeKind {\n\n let _infered_ty = g(node, &HashMap::new(), tyenv, idgen);\n\n // TODO: infered_ty == Unit\n\n deref_term(node, tyenv)\n\n}\n", "file_path": "src/typing.rs", "rank": 0, "score":...
Rust
crates/apps/plugin-host/plugin-host-lib/src/commands/main/mod.rs
yamadapc/augmented-audio
2f662cd8aa1a0ba46445f8f41c8483ae2dc552d3
use std::ops::Deref; use std::path::Path; use std::path::PathBuf; use std::process::exit; use std::sync::mpsc::channel; use std::thread; use std::time::Duration; use notify::{watcher, RecommendedWatcher, RecursiveMode, Watcher}; use tao::event::{Event, WindowEvent}; use tao::event_loop::ControlFlow; #[cfg(target_os = ...
use std::ops::Deref; use std::path::Path; use std::path::PathBuf; use std::process::exit; use std::sync::mpsc::channel; use std::thread; use std::time::Duration; use notify::{watcher, RecommendedWatcher, RecursiveMode, Watcher}; use tao::event::{Event, WindowEvent}; use tao::event_loop::ControlFlow; #[cfg(target_os = ...
fn get_audio_options(run_options: &RunOptions) -> (AudioProcessorSettings, AudioThreadOptions) { let mut audio_settings = AudioThread::default_settings().unwrap(); audio_settings.set_sample_rate( run_options .sample_rate() .map(|s| s as f32) .unwrap_or_else(|| audio...
editor"); let (width, height) = editor.size(); let window = tao::window::WindowBuilder::new() .with_inner_size(tao::dpi::Size::Logical(tao::dpi::LogicalSize::new( width as f64, height as f64, ))) .build(&event_loop) .expect("Failed to create editor window...
function_block-function_prefixed
[ { "content": "pub fn get_raw_window_handle(parent: *mut c_void) -> RawWindowHandle {\n\n let parent_id = parent as id;\n\n let parent_window = unsafe { msg_send![parent_id, window] };\n\n RawWindowHandle::MacOS(MacOSHandle {\n\n ns_window: parent_window,\n\n ns_view: parent,\n\n .....
Rust
src/commands.rs
ludumipsum/turbobunny-example
2b3006e103c1a5f61ea2ec687372711dbe5890b1
use serde_derive::{Deserialize, Serialize}; use std::path::PathBuf; const CMD_NOTFOUND_URL: &str = "/404"; const GOOGLE_SEARCH_URL: &str = "https://www.google.com/search"; const LI_BUILDKITE_BASE: &str = "https://buildkite.com/ludumipsum"; const LI_GITHUB_BASE: &str = "https://www.github.com/ludumipsum"; const LI_MA...
use serde_derive::{Deserialize, Serialize}; use std::path::PathBuf; const CMD_NOTFOUND_URL: &str = "/404"; const GOOGLE_SEARCH_URL: &str = "https://www.google.com/search"; const LI_BUILDKITE_BASE: &str = "https://buildkite.com/ludumipsum"; const LI_GITHUB_BASE: &str = "https://www.github.com/ludumipsum"; const LI_MA...
pub fn match_query<T: AsRef<str>>( &self, query: T, ) -> Option<(&BunnyCommand, String)> { for command in &self.commands { for matcher in &command.matchers { let query_str = query.as_ref(); if query_str == *matcher {...
pub fn new<T: AsRef<str>>(fqdn: T, resources_path: &PathBuf) -> Self { Self { commands: gen_cmd_list(), fallback: Some(gen_google_cmd()), fqdn: fqdn.as_ref().to_string(), resources_path: resources_path.clone(), } }
function_block-full_function
[ { "content": "TurboBunny\n\n==========\n\n\n\nTurbobunny is a bunny1/bunnylol clone. It's a quicklinking tool that's meant to\n\nstand in for your browser's default search engine and provide some convenient\n\naliases for stuff you do a lot. Ideally it should feel kinda like having a nice\n\nset of shell rcscri...
Rust
crates/ra_syntax/src/validation.rs
phansch/rust-analyzer
22949dab267bf7b8b3da73fe7745a12daca21a52
use std::u32; use arrayvec::ArrayString; use crate::{ algo::visit::{visitor_ctx, VisitorCtx}, ast::{self, AstNode}, SourceFileNode, string_lexing::{self, CharComponentKind}, yellow::{ SyntaxError, SyntaxErrorKind::*, }, }; pub(crate) fn validate(file: &SourceFileNode) -> Vec<S...
use std::u32; use arrayvec::ArrayString; use crate::{ algo::visit::{visitor_ctx, VisitorCtx}, ast::{self, AstNode}, SourceFileNode, string_lexing::{self, CharComponentKind}, yellow::{ SyntaxError, SyntaxErrorKind::*, }, }; pub(crate) fn validate(file: &SourceFileNode) -> Vec<S...
character close and backslash */ } _ => assert_valid_char(&(byte as char).to_string()), } } } #[test] fn test_unicode_codepoints() { let valid = ["Ƒ", "バ", "メ", "﷽"]; for c in &valid { assert_valid_char(c); } } #[test] fn...
Err(_) => { errors.push(SyntaxError::new(MalformedUnicodeEscape, range)); } } } CodePoint => { if text == "\t" || text == "\r" { errors.push(SyntaxError::new(UnescapedCodepo...
random
[ { "content": "fn find_reparsable_node(node: SyntaxNodeRef, range: TextRange) -> Option<(SyntaxNodeRef, fn(&mut Parser))> {\n\n let node = algo::find_covering_node(node, range);\n\n return algo::ancestors(node)\n\n .filter_map(|node| reparser(node).map(|r| (node, r)))\n\n .next();\n\n\n\n ...
Rust
src/config/cmd.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::path::PathBuf; use clap::Parser; use serde_json::Value; use super::{load_builder_from_paths, load_source_from_paths, process_paths, ConfigBuilder}; use crate::cli::handle_config_errors; use crate::config; #[derive(Parser, Debug, Clone)] #[clap(rename_all = "kebab-case")] pub struct Opts { #[clap(sh...
use std::path::PathBuf; use clap::Parser; use serde_json::Value; use super::{load_builder_from_paths, load_source_from_paths, process_paths, ConfigBuilder}; use crate::cli::handle_config_errors; use crate::config; #[derive(Parser, Debug, Clone)] #[clap(rename_all = "kebab-case")] pub struct Opts { #[clap(sh...
.unwrap() .as_ref(), ) .unwrap(); assert_eq!( json["sources"]["in"]["format"], json!(format!("${{{}}}", env_var)) ); assert_eq!( json["sinks"]["out"]["inputs"], json!(vec![format!("${{{}}}", env_var_in_arr)...
serialize_to_json( toml::from_str(config_source.as_ref()).unwrap(), &ConfigBuilder::from_toml(interpolated_config_source.as_ref()), true, false, )
call_expression
[ { "content": "pub fn open_fixture(path: impl AsRef<Path>) -> crate::Result<serde_json::Value> {\n\n let test_file = match File::open(path) {\n\n Ok(file) => file,\n\n Err(e) => return Err(e.into()),\n\n };\n\n let value: serde_json::Value = serde_json::from_reader(test_file)?;\n\n Ok(v...
Rust
crates/vm/src/types/mod.rs
Lutetium-Vanadium/anilang
e16e5afec2e7e7f33a86ce91c3ca03b5ab9c8db8
use enumflags2::BitFlags; #[cfg(test)] mod tests; #[derive(Debug, PartialEq, Eq)] pub enum Cast { Implicit(Type), Explicit, } #[derive(Copy, Clone, Debug, PartialEq, Eq, BitFlags)] #[rustfmt::skip] #[repr(u16)] pub enum Type { Int = 0b000000001, Float = 0b000000010, String = 0b00000010...
use enumflags2::BitFlags; #[cfg(test)] mod tests; #[derive(Debug, PartialEq, Eq)] pub enum Cast { Implicit(Type), Explicit, } #[derive(Copy, Clone, Debug, PartialEq, Eq, BitFlags)] #[rustfmt::skip] #[repr(u16)] pub enum Type { Int = 0b000000001, Float = 0b000000010, String = 0b00000010...
fn implicit_cast(&self, to_type: Type) -> Value { match to_type { Type::Float if self.type_() == Type::Int => { Value::Float(self.into()) } _ => unreachable!( "Unexpected explicit cast from {:?} to {:?}, for possible explicit casts c...
Float(_) => Type::Float, Value::String(_) => Type::String, Value::List(_) => Type::List, Value::Object(_) => Type::Object, Value::Range(..) => Type::Range, Value::Function(_) => Type::Function, Value::Null => Type::Null, } }
function_block-function_prefixed
[ { "content": "pub fn b(b: bool) -> Value {\n\n Value::Bool(b)\n\n}\n\n\n", "file_path": "crates/vm/src/test_helpers.rs", "rank": 1, "score": 226853.7265668929 }, { "content": "pub fn run(mut show_ast: bool, mut show_bytecode: bool) {\n\n let repl = shelp::Repl::<AnilangLangInterface>::...
Rust
rs/canister_sandbox/sandbox_launcher/src/lib.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use std::{ collections::HashMap, os::unix::{net::UnixStream, prelude::FromRawFd}, sync::{Arc, Condvar, Mutex}, thread, }; use ic_canister_sandbox_common::{ child_process_initialization, controller_launcher_client_stub::{self, ControllerLauncherClientStub}, controller_launcher_service::Contr...
use std::{ collections::HashMap, os::unix::{net::UnixStream, prelude::FromRawFd}, sync::{Arc, Condvar, Mutex}, thread, }; use ic_canister_sandbox_common::{ child_process_initialization, controller_launcher_client_stub::{self, ControllerLauncherClientStub}, controller_launcher_service::Contr...
panic!("Launcher detected sandbox exit"); } }, } }); Self { pid_to_canister_id, has_children, } } } impl LauncherService for LauncherServer { fn launch_sandbox( &self, Launch...
if let Some(canister_id) = canister_id { controller .sandbox_exited(SandboxExitedRequest { canister_id }) .sync() .unwrap(); }
if_condition
[]
Rust
crates/read_ctags/src/language.rs
maco/unused
f543c1bd3ed6af12b4a41f4c186741093e2b50b7
use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::path::Path; use std::str::FromStr; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] #[allow(missing_docs)] pub enum Language { CSS, Elixir, Elm, HTML, JSON, JavaScript, Markdown, Pytho...
use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::path::Path; use std::str::FromStr; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] #[allow(missing_docs)] pub enum Language { CSS, Elixir, Elm, HTML, JSON, JavaScript, Markdown, Pytho...
} #[cfg(test)] mod tests { use super::*; use totems::assert_ok; #[test] fn calculates_common_files() { assert_eq!(Language::from_path("../foo/bar.rb"), Some(Language::Ruby)); assert_eq!(Language::from_path("/tmp/foo.md"), Some(Language::Markdown)); assert_eq!(Language::from_pa...
S), "ex" => Ok(Language::Elixir), "exs" => Ok(Language::Elixir), "elm" => Ok(Language::Elm), "html" => Ok(Language::HTML), "json" => Ok(Language::JSON), "js" => Ok(Language::JavaScript), "jsx" => Ok(Language::JavaScript), "m...
function_block-function_prefixed
[ { "content": "fn tag_value<'a>(tag_name: &'a str) -> impl Fn(&'a str) -> IResult<&'a str, String> {\n\n move |input| {\n\n let non_commented_value = preceded(terminated(tag(tag_name), tag(\"\\t\")), to_tab);\n\n map(\n\n tuple((non_commented_value, metadata_comment)),\n\n ...
Rust
src/request.rs
Kinto/kinto-http.rs
66832119505606de832fbe1679044758a1b3fd1c
use std::str; use std::io::Read; use serde_json; use serde_json::Value; use hyper::method::Method; use hyper::header::{Headers, ContentType, IfMatch, IfNoneMatch}; use hyper::status::StatusCode; use KintoConfig; use error::KintoError; use response::ResponseWrapper; #[derive(Debug, Clone)] pub struct RequestPreparer ...
use std::str; use std::io::Read; use serde_json; use serde_json::Value; use hyper::method::Method; use hyper::header::{Headers, ContentType, IfMatch, IfNoneMatch}; use hyper::status::StatusCode; use KintoConfig; use error::KintoError; use response::ResponseWrapper; #[derive(Debug, Clone)] pub struct RequestPreparer ...
}; let next_page_url = try!(str::from_utf8(page_header.as_slice())); let mut temp_request = self.clone(); temp_request.preparer().path = next_page_url.replace(base_response.config.server_url.as_str(), ""); t...
uestPreparer { config: config, method: Method::Get, path: path, headers: Headers::new(), query: String::new(), body: None, } } } pub trait KintoRequest: Clone { fn preparer(&mut self) -> &mut RequestPreparer; fn if_match(...
random
[ { "content": "/// Split a path (e.g. \"/buckets/food/collections/foo\") into a resource name `HashMap`.\n\npub fn extract_ids_from_path(path: &str) -> HashMap<String, Option<String>> {\n\n\n\n // XXX: Remove version from path if exists. We shouldn't hardcode version\n\n let path = path.replace(\"/v1\", \"...
Rust
emutk-vax/src/cpu/instrs/impls/util.rs
moonheart08/emutk
755de1feeeb10f640810399e57b9d2f6cb96eae3
use crate::cpu::VAXCPU; use crate::cpu::instrs::operands::*; use crate::bus::VAXBus; use crate::Error; use crate::VAXNum; pub fn parse_read_operand <B: VAXBus, T: VAXNum> (cpu: &mut VAXCPU<B>) -> Result<UnresolvedOperand<T>, Error> { let pc = cpu.regfile.get_pc(); let op_head: [u8;2] = cpu.read_val...
use crate::cpu::VAXCPU; use crate::cpu::instrs::operands::*; use crate::bus::VAXBus; use crate::Error; use crate::VAXNum; pub fn parse_read_operand <B: VAXBus, T: VAXNum> (cpu: &mut VAXCPU<B>) -> Result<UnresolvedOperand<T>, Error> { let pc = cpu.regfile.get_pc(); let op_head: [u8;2] = cpu.read_val...
} #[inline] pub fn read_data<T: VAXNum, B: VAXBus>(cpu: &mut VAXCPU<B>) -> Result<T, Error> { let pc = cpu.regfile.get_pc(); let result = cpu.read_val::<T>(pc); cpu.regfile.set_pc(pc + T::BYTE_LEN as u32); result } #[inline] pub fn jump_with_byte_displacement<B: VAXBus>(cpu: &mut VAXCPU<B>, disp: u8)...
if cpu.regfile.get_psl().get_cur_mod() == 0 { Ok(()) } else { Err(Error::new_privileged_instruction_fault()) }
if_condition
[ { "content": "pub fn instr_branch_low_bit_true\n\n <T: VAXBus>\n\n (cpu: &mut VAXCPU<T>, cycle_count: &mut Cycles)\n\n -> Result<(), Error>\n\n{\n\n instr_branch_low_bit(cpu, cycle_count, true)\n\n}\n\n\n", "file_path": "emutk-vax/src/cpu/instrs/impls/control.rs", "rank": 18, "score": 14...
Rust
days/09/src/main.rs
JustinKuli/adventofcode2021
fb97be3395170e4a69355dcd02223811544f0b5f
#![allow(unused_variables)] use std::error::Error; use std::collections::HashMap; use std::collections::HashSet; fn main() { let data = read_data(String::from("data.txt")) .expect("Failed to get data"); let ans1 = part_one(data.clone()).expect("Failed to get answer 1"); println!("Part one answer:...
#![allow(unused_variables)] use std::error::Error; use std::collections::HashMap; use std::collections::HashSet; fn main() { let data = read_data(String::from("data.txt")) .expect("Failed to get data"); let ans1 = part_one(data.clone()).expect("Failed to get answer 1"); println!("Part one answer:...
fn get_neighbors(data: Vec<String>, i: i32, j: i32) -> Vec<i32> { let mut v = Vec::new(); match lookup(data.clone(), i-1, j) { Some(n) => v.push(n), None => {} } match lookup(data.clone(), i+1, j) { Some(n) => v.push(n), None => {} } match lookup(data.clone()...
None => return 0 } let neighbors = get_neighbors(data.clone(), i, j); for n in neighbors { if l >= n { return 0 } } return l+1; }
function_block-function_prefix_line
[ { "content": "fn part_one(mut p1_pos: i32, mut p2_pos: i32) -> Result<String, Box<dyn Error>> {\n\n let mut p1_score = 0;\n\n let mut p2_score = 0;\n\n let mut next_roll = 1;\n\n let mut roll_count = 0;\n\n\n\n loop {\n\n if next_roll == 0 {\n\n next_roll = 100;\n\n }\n\n...
Rust
lib_foundry_win32/src/lib.rs
moss-oliver/tremor
e49b2a10b07e2217f29166a905f96556b5a1cc15
extern crate lib_foundry_common; use lib_foundry_common::Platform; use lib_foundry_common::PlatformEvent; use lib_foundry_common::Window; use lib_foundry_common::KeyboardKey; use lib_foundry_common::PlatformError; use lib_foundry_common::PlatformType; extern crate winapi; extern crate user32; extern crate gdi32; exte...
extern crate lib_foundry_common; use lib_foundry_common::Platform; use lib_foundry_common::PlatformEvent; use lib_foundry_common::Window; use lib_foundry_common::KeyboardKey; use lib_foundry_common::PlatformError; use lib_foundry_common::PlatformType; extern crate winapi; extern crate user32; extern crate gdi32; exte...
dKey::G}, 72 => {keyboard = KeyboardKey::H}, 73 => {keyboard = KeyboardKey::I}, 74 => {keyboard = KeyboardKey::J}, 75 => {keyboard = KeyboardKey::K}, 76 => {keyboard = KeyboardKey::L}, 77 => {keyboard = KeyboardKey::M}, 78 => {keyboard ...
ode>> { let hwnd : *mut winapi::HWND__; unsafe { hwnd = user32::CreateWindowExW(0, window_class.lpszClassName, window_name.to_wide_null().as_ptr() as *mut _, WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, w, h, ...
random
[ { "content": "#[cfg(windows)]\n\npub fn draw_bmp(window: &Win32Window, width:u32, height:u32, bmp: *const u8) {\n\n win32_draw_bmp(window, width, height, bmp);\n\n}\n\n\n", "file_path": "lib_foundry_platform/src/lib.rs", "rank": 0, "score": 181770.27813054537 }, { "content": "#[cfg(window...
Rust
biscuit-auth/src/datalog/symbol.rs
biscuit-auth/biscuit-rust
40eae24704eeafd4414585ba7f9d122940f195f1
use std::collections::HashSet; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; pub type SymbolIndex = u64; use super::{Check, Fact, Predicate, Rule, Term, World}; #[derive(Clone, Debug, PartialEq, Default)] pub struct SymbolTable { symbols: Vec<String>, } const DEFAULT_SYMBOLS: [&str; 28] =...
use std::collections::HashSet; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; pub type SymbolIndex = u64; use super::{Check, Fact, Predicate, Rule, Term, World}; #[derive(Clone, Debug, PartialEq, Default)] pub struct SymbolTable { symbols: Vec<String>, } const DEFAULT_SYMBOLS: [&str; 28] =...
pub fn strings(&self) -> Vec<String> { self.symbols.clone() } pub fn current_offset(&self) -> usize { self.symbols.len() } pub fn split_at(&mut self, offset: usize) -> SymbolTable { let mut table = SymbolTable::new(); table.symbols = self.symbols.split_off(offset)...
pub fn get(&self, s: &str) -> Option<SymbolIndex> { if let Some(index) = DEFAULT_SYMBOLS.iter().position(|sym| *sym == s) { return Some(index as u64); } self.symbols .iter() .position(|sym| sym.as_str() == s) .map(|i| (OFFSET + i) as SymbolIndex) ...
function_block-full_function
[ { "content": "pub fn fact<I: AsRef<Term>>(name: SymbolIndex, terms: &[I]) -> Fact {\n\n Fact {\n\n predicate: Predicate {\n\n name,\n\n terms: terms.iter().map(|id| id.as_ref().clone()).collect(),\n\n },\n\n }\n\n}\n\n\n", "file_path": "biscuit-auth/src/datalog/mod....
Rust
server/src/config.rs
yuyang0/rrqlite
29de5ac75aa0391571bf0ed05f65e5ce060cd175
use clap::Parser; use core_exception::{ErrorCode, Result}; use core_store::config::StoreConfig; use serde::{Deserialize, Serialize}; macro_rules! load_field_from_env { ($field:expr, $field_type: ty, $env:expr) => { if let Some(env_var) = std::env::var_os($env) { $field = env_var ...
use clap::Parser; use core_exception::{ErrorCode, Result}; use core_store::config::StoreConfig; use serde::{Deserialize, Serialize}; macro_rules! load_field_from_env { ($field:expr, $field_type: ty, $env:expr) => { if let Some(env_var) = std::env::var_os($env) { $field = env_var ...
let cfg = toml::from_str::<Config>(txt.as_str()) .map_err(|e| ErrorCode::ConfigError(format!("{:?}", e)))?; cfg.check()?; Ok(cfg) } pub fn check(&self) -> Result<()> { Ok(()) } pub fn load_from_env(cfg: &mut Config) { load_field_from_...
let txt = std::fs::read_to_string(file) .map_err(|e| ErrorCode::ConfigError(format!("File: {}, err: {:?}", file, e)))?;
assignment_statement
[ { "content": "pub fn get_default_raft_advertise_host() -> String {\n\n match hostname::get() {\n\n Ok(h) => match h.into_string() {\n\n Ok(h) => h,\n\n _ => \"UnknownHost\".to_string(),\n\n },\n\n _ => \"UnknownHost\".to_string(),\n\n }\n\n}\n\n\n", "file_pat...
Rust
crates/symbolicator/src/services/cacher.rs
pombredanne/symbolicator
ac4b9165b1539286d06c0ed3599b7145a3ada505
use std::collections::BTreeMap; use std::fmt; use std::io; use std::path::{Path, PathBuf}; use std::sync::Arc; use futures::channel::oneshot; use futures::future::{self, FutureExt, Shared, TryFutureExt}; use parking_lot::Mutex; use sentry::{Hub, SentryFutureExt}; use symbolic::common::ByteView; use tempfile::NamedTemp...
use std::collections::BTreeMap; use std::fmt; use std::io; use std::path::{Path, PathBuf}; use std::sync::Arc; use futures::channel::oneshot; use futures::future::{self, FutureExt, Shared, TryFutureExt}; use parking_lot::Mutex; use sentry::{Hub, SentryFutureExt}; use symbolic::common::ByteView; use tempfile::NamedTemp...
fn compute(&self, request: T, key: CacheKey) -> BoxedFuture<Result<T::Item, T::Error>> { let cache_path = get_scope_path(self.config.cache_dir(), &key.scope, &key.cache_key); if let Some(ref path) = cache_path { if let Some(item) = tryf!...
h); let item = request.load(key.scope.clone(), status, byteview, CachePath::Cached(path)); Ok(Some(item)) }
function_block-function_prefixed
[ { "content": "pub fn get_scope_path(cache_dir: Option<&Path>, scope: &Scope, cache_key: &str) -> Option<PathBuf> {\n\n Some(\n\n cache_dir?\n\n .join(safe_path_segment(scope.as_ref()))\n\n .join(safe_path_segment(cache_key)),\n\n )\n\n}\n\n\n", "file_path": "crates/symboli...
Rust
src/array.rs
Clueliss/owned_chunks
ef69c74540c3496dc53a21b11dd638f8b960ef68
use std::{ cmp::min, mem::{self, MaybeUninit}, ops::Range, ptr, }; pub struct ArrayChunks<T, const N: usize, const CHUNK_SZ: usize> { array: [MaybeUninit<T>; N], chunk_size: usize, alive: Range<usize>, } pub struct ArrayChunk<T, const CHUNK_SZ: usize> { array: [May...
use std::{ cmp::min, mem::{self, MaybeUninit}, ops::Range, ptr, }; pub struct ArrayChunks<T, const N: usize, const CHUNK_SZ: usize> { array: [MaybeUninit<T>; N], chunk_size: usize, alive: Range<usize>, } pub struct ArrayChunk<T, const CHUNK_SZ: usize> { array: [May...
} impl<T, const CHUNK_SZ: usize> Iterator for ArrayChunk<T, CHUNK_SZ> { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.alive .next() .map(|ix| unsafe { self.array.get_unchecked(ix).assume_init_read() }) } } #[cfg(test)] ...
fn next(&mut self) -> Option<Self::Item> { if self.alive.is_empty() { None } else { let chunk_start = self.alive.start; let chunk_end = min(chunk_start + self.chunk_size, self.alive.end); self.alive.start = chunk_end; let chunk_len = chunk_end ...
function_block-full_function
[ { "content": "/// A variant of [`OwnedChunks`] with const chunk size; this primarily exists to allow storage size\n\n/// optimizations for types where storage size depends on a constant, like [`arrays`](prim@array). For further\n\n/// information see the docs of [`array::ArrayChunks#Implementation details`].\n\...
Rust
src/seating_system.rs
ktsimpso/adventofcode2020
ec7bd2df39279f0448e7d39416d1b743d642e8fc
use crate::lib::{default_sub_command, file_to_lines, parse_lines, Command}; use anyhow::Error; use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}; use nom::{branch::alt, character::complete, combinator::map, multi::many1}; use simple_error::SimpleError; use strum::VariantNames; use strum_macros::{EnumString,...
use crate::lib::{default_sub_command, file_to_lines, parse_lines, Command}; use anyhow::Error; use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}; use nom::{branch::alt, character::complete, combinator::map, multi::many1}; use simple_error::SimpleError; use strum::VariantNames; use strum_macros::{EnumString,...
println!("{:#?}", result); }) .map(|_| ()) } fn process_seat_layout(seating_system_arguments: &SeatingSystemArgs) -> Result<usize, Error> { file_to_lines(&seating_system_arguments.file) .and_then(|lines| parse_lines(lines, parse_row_of_seats)) .map(|seating_arrangement|...
tem_arguments = match arguments.subcommand_name() { Some("part1") => SeatingSystemArgs { file: "day11/input.txt".to_string(), tolerance: 4, adjacency_definition: AdjacencyDefinition::DirectlyNextTo, }, Some("part2") => SeatingSystemArgs { file: "da...
function_block-random_span
[ { "content": "fn parse_directions(line: &String) -> Result<Direction, Error> {\n\n map_res(\n\n tuple((complete::alpha1, parse_isize)),\n\n |(direction, value)| match direction {\n\n \"N\" => Ok(Direction::North(value)),\n\n \"E\" => Ok(Direction::East(value)),\n\n ...
Rust
src/log.rs
toolness/rust-nycdb-csv-fun
c9dac1ac100cb566e1438289f6e25938ac277fde
use std::fs::{File, metadata, OpenOptions}; use std::path::Path; use std::error::Error; use update_type::UpdateType; #[derive(Serialize, Deserialize)] pub struct Revision { pub id: u64, pub byte_offset: u64, pub rows: u64 } #[derive(Clone)] pub struct CsvLog { pub basename: String, pub filename: ...
use std::fs::{File, metadata, OpenOptions}; use std::path::Path; use std::error::Error; use update_type::UpdateType; #[derive(Serialize, Deserialize)] pub struct Revision { pub id: u64, pub byte_offset: u64, pub rows: u64 } #[derive(Clone)] pub struct CsvLog { pub basename: String, pub filename: ...
} pub struct LogRevisionWriter { info: CsvLog, rev: Revision, logfile_writer: csv::Writer<File> } impl LogRevisionWriter { fn new(info: CsvLog) -> Result<Self, Box<Error>> { let byte_offset = metadata(&info.filename)?.len(); let logfile = OpenOptions::new() .write(true).ap...
writer.write_record(logfile_reader.headers()?)?; pos.set_byte(rev.byte_offset); logfile_reader.seek(pos).unwrap(); for result in logfile_reader.records() { let record = result?; writer.write_record(&record)?; rows += 1; ...
function_block-function_prefix_line
[ { "content": "fn process_csv_and_update_log(csvlog: &mut CsvLog, filename: &str) -> Result<(), Box<Error>> {\n\n let start_time = SystemTime::now();\n\n let pkmap_filename = format!(\"{}.pkmap.dat\", csvlog.basename);\n\n let pkmap_path = Path::new(&pkmap_filename);\n\n let mut pk_map = PkHashMap::n...
Rust
yarte_parser/src/error.rs
dskleingeld/yarte
f3cd2db21fc4c64f74ef08f988357a282defee96
use std::{ collections::BTreeMap, fmt::{self, Display, Write}, path::PathBuf, }; use annotate_snippets::{ display_list::{DisplayList, FormatOptions}, snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, }; use derive_more::Display; use yarte_helpers::config::Config; use crate:...
use std::{ collections::BTreeMap, fmt::{self, Display, Write}, path::PathBuf, }; use annotate_snippets::{ display_list::{DisplayList, FormatOptions}, snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, }; use derive_more::Display; use yarte_helpers::config::Config; use crate:...
pub fn emitter<I, T>(sources: &BTreeMap<PathBuf, String>, config: &Config, errors: I) -> ! where I: Iterator<Item = ErrorMessage<T>>, T: Display, { let mut prefix = config.get_dir().clone(); prefix.pop(); let mut errors: Vec<ErrorMessage<T>> = errors.collect(); errors.sort_unstable_by(|a, b| a....
function_block-full_function
[ { "content": "pub fn get_source(path: &Path) -> String {\n\n match fs::read_to_string(path) {\n\n Ok(mut source) => match source\n\n .as_bytes()\n\n .iter()\n\n .rposition(|x| !x.is_ascii_whitespace())\n\n {\n\n Some(j) => {\n\n source....