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
diverge/src/main.rs
Cisco-Talos/Barbervisor
b34cd716d965d100fcf61ae10f31eb15966dce78
use regex::Regex; use std::convert::TryInto; use std::fs::File; use std::io::{Read, BufReader, BufRead}; pub fn translate_phys(vaddr: u64, cr3: u64, data: &[u8]) -> usize { let mut curr_page = cr3; /* Calculate the components for each level of the page table from * the vaddr. */ let cr_offsets...
use regex::Regex; use std::convert::TryInto; use std::fs::File; use std::io::{Read, BufReader, BufRead}; pub fn translate_phys(vaddr: u64, cr3: u64, data: &[u8]) -> usize { let mut curr_page = cr3; /* Calculate the components for each level of the page table from * the vaddr. */ let cr_offsets...
&lines.next().unwrap().unwrap(); single_step += "\r\n"; } let mut vbox = windbg_to_vmregs(&single_step); let mut kernel = false; let mut data; let mut counter = 0; loop { let mut buffer = [0; std::mem::size_of::<VmRegs>()]; orig_trace...
.ok() .unwrap(), r11: u64::from_str_radix(m.name("r11").unwrap().as_str(), 16) .ok() .unwrap(), r12: u64::from_str_radix(m.name("r12").unwrap().as_str(), 16) .ok() .unwrap(), r13: u64::from_str_radix(m.name("r13").unwrap().as_str(), 1...
random
[ { "content": "/// Returns the virtual addresses and the virt to phys tranlations mapping from\n\n/// the data of a vbox core file\n\npub fn translate_phys(vaddr: u64, cr3: u64, data: &[u8]) -> usize {\n\n let cr3 = cr3 & 0xffff_ffff_ffff_f000;\n\n let mut curr_page = cr3;\n\n\n\n /* Calculate the compo...
Rust
storage/backup/backup-cli/src/backup_types/transaction/restore.rs
gegrid/diem
70b660ab70264c775f7f0ee5835c4138332803ec
use crate::{ backup_types::{ epoch_ending::restore::EpochHistory, transaction::manifest::{TransactionBackup, TransactionChunk}, }, metrics::{ restore::{TRANSACTION_REPLAY_VERSION, TRANSACTION_SAVE_VERSION}, verify::VERIFY_TRANSACTION_VERSION, }, storage::{BackupStor...
use crate::{ backup_types::{ epoch_ending::restore::EpochHistory, transaction::manifest::{TransactionBackup, TransactionChunk}, }, metrics::{ restore::{TRANSACTION_REPLAY_VERSION, TRANSACTION_SAVE_VERSION}, verify::VERIFY_TRANSACTION_VERSION, }, storage::{BackupStor...
ode.as_ref() { if first_to_replay > chunk.manifest.first_version { let last_to_save = min(last, first_to_replay - 1); let num_txns_to_save = (last_to_save - chunk.manifest.first_version + 1) as usize; restore_handler.save_transactions( ...
sactionRestoreOpt { #[structopt(long = "transaction-manifest")] pub manifest_handle: FileHandle, #[structopt( long = "replay-transactions-from-version", help = "Transactions with this version and above will be replayed so state and events are \ gonna pop up. Requires state at the ver...
random
[ { "content": "pub fn run(args: Args, xctx: XContext) -> crate::Result<()> {\n\n let engine = LintEngineConfig::new(xctx.core())\n\n .with_project_linters(&[&PlaygroundProject])\n\n .with_package_linters(&[&PlaygroundPackage])\n\n .with_file_path_linters(&[&PlaygroundFilePath])\n\n ...
Rust
server/src/auth/service.rs
lholznagel/eve_online
7f8cc4aa46b06c0edf64f89ff5853216cf5597b7
use crate::{error::Error, ProjectId}; use async_trait::*; use axum::extract::{FromRequest, Extension, RequestParts}; use caph_connector::{CharacterId, EveAuthClient, EveOAuthToken}; use sqlx::PgPool; use tracing::instrument; use serde::Deserialize; pub const EVE_DEFAULT_SCOPE: &[&str] = &[ "publicData", "esi-...
use crate::{error::Error, ProjectId}; use async_trait::*; use axum::extract::{FromRequest, Extension, RequestParts}; use caph_connector::{CharacterId, EveAuthClient, EveOAuthToken}; use sqlx::PgPool; use tracing::instrument; use serde::Deserialize; pub const EVE_DEFAULT_SCOPE: &[&str] = &[ "publicData", "esi-...
if result.is_some() { Ok(true) } else { Ok(false) } } #[instrument(err)] async fn save_login( &self, token: &str, state: &str, character: EveOAuthToken ) -> Result<(), Error> { ...
let result = sqlx::query!(" SELECT character_id FROM logins WHERE token = $1 ", token ) .fetch_optional(&self.pool) .await?;
assignment_statement
[ { "content": "/// Generates a secure token that can be used as a cookie token\n\n/// \n\n/// # Errors\n\n/// \n\n/// When either the ENV `SECRET_KEY` is not available or if generating\n\n/// the HMAC key fails.\n\n/// \n\n/// # Returns\n\n/// \n\n/// Base64 encoded key and a base64 encoded hashed version of the...
Rust
deadpool-bolt/src/lib.rs
lucis-fluxum/rust-bolt
2fb81c6695a073d3d743e788c2a1d97deea4bf87
#![warn(rust_2018_idioms)] use std::{convert::Infallible, io, net::SocketAddr}; use async_trait::async_trait; use deadpool::managed::RecycleResult; use tokio::{ io::BufStream, net::{lookup_host, ToSocketAddrs}, }; use tokio_util::compat::*; use bolt_client::{ error::{CommunicationError, ConnectionError, ...
#![warn(rust_2018_idioms)] use std::{convert::Infallible, io, net::SocketAddr}; use async_trait::async_trait; use deadpool::managed::RecycleResult; use tokio::{ io::BufStream, net::{lookup_host, ToSocketAddrs}, }; use tokio_util::compat::*; use bolt_client::{ error::{CommunicationError, ConnectionError, ...
} } #[async_trait] impl deadpool::managed::Manager for Manager { type Type = Client<Compat<BufStream<Stream>>>; type Error = ClientError; async fn create(&self) -> Result<Self::Type, Self::Error> { let mut client = Client::new( BufStream::new( Stream::connect(...
Ok(Self { addr: lookup_host(addr) .await? .next() .ok_or_else(|| io::Error::from(io::ErrorKind::AddrNotAvailable))?, domain, version_specifiers, metadata, })
call_expression
[ { "content": "fn format_versions(versions: &[u32]) -> String {\n\n versions\n\n .iter()\n\n .map(|&v| format_version(v))\n\n .collect::<Vec<String>>()\n\n .join(\", \")\n\n}\n", "file_path": "bolt-client/src/error.rs", "rank": 0, "score": 141220.45142544073 }, { ...
Rust
rd-agent/src/sideloader.rs
ignatenkobrain/resctl-demo
71bfc917567d7d3e6a76fbbdc5c183a7bcb950b8
use anyhow::{bail, Result}; use log::trace; use std::fs; use std::io; use std::io::prelude::*; use rd_agent_intf::{ SideloaderCmd, SideloaderReport, Slice, SliceKnobs, SvcStateReport, SIDELOADER_SVC_NAME, SIDELOAD_SVC_PREFIX, }; use rd_util::*; use super::Config; const SIDELOADER_CONFIG: &str = r#"{ "si...
use anyhow::{bail, Result}; use log::trace; use std::fs; use std::io; use std::io::prelude::*; use rd_agent_intf::{ SideloaderCmd, SideloaderReport, Slice, SliceKnobs, SvcStateReport, SIDELOADER_SVC_NAME, SIDELOAD_SVC_PREFIX, }; use rd_util::*; use super::Config; const SIDELOADER_CONFIG: &str = r#"{ "si...
pub fn apply(&mut self, cmd: &SideloaderCmd, slice_knobs: &SliceKnobs) -> Result<()> { self.update_cfg_file(cmd, slice_knobs)?; trace!("sideloader state {:?}", self.svc.unit.state); match self.svc.unit.state { systemd::UnitState::Running => Ok(()), _ => self.svc.sta...
fn update_cfg_file(&self, cmd: &SideloaderCmd, slice_knobs: &SliceKnobs) -> Result<()> { let cfg = sideloader_config(cmd.cpu_headroom * 100.0, slice_knobs); if let Ok(mut f) = fs::OpenOptions::new() .read(true) .open(&self.daemon_cfg_path) { let mut buf = Stri...
function_block-full_function
[ { "content": "pub fn sel_factory_iolat(io_type: &str, pct: &str) -> impl FnMut(&SelArg) -> Vec<f64> {\n\n let io_type = io_type.to_string();\n\n let pct = pct.to_string();\n\n move |arg: &SelArg| {\n\n let map = &arg.rep.iolat.map;\n\n if map.contains_key(&io_type)\n\n && map[&...
Rust
src/map.rs
Atul9/infer
e92ffc413132cb59d9537f9e5f9542f7c7368f00
use super::matchers; use super::Matcher; #[derive(Debug, Eq, PartialEq)] pub enum MatcherType { APP, ARCHIVE, AUDIO, DOC, FONT, IMAGE, VIDEO, CUSTOM, } pub fn setup(v: &mut Vec<(MatcherType, String, String, Matcher)>) { v.push(( MatcherType::APP, ...
use super::matchers; use super::Matcher; #[derive(Debug, Eq, PartialEq)] pub enum MatcherType { APP, ARCHIVE, AUDIO, DOC, FONT, IMAGE, VIDEO, CUSTOM, } pub fn setup(v: &mut Vec<(MatcherType, String, String, Matcher)>) { v.push(( MatcherType::APP, ...
v.push(( MatcherType::VIDEO, "video/x-msvideo".to_string(), "avi".to_string(), matchers::video::is_avi as Matcher, )); v.push(( MatcherType::VIDEO, "video/x-ms-wmv".to_string(), "wmv".to_string(), matchers::video::is_wmv as Matcher, )); ...
matchers::video::is_mp4 as Matcher, )); v.push(( MatcherType::VIDEO, "video/x-m4v".to_string(), "m4v".to_string(), matchers::video::is_m4v as Matcher, )); v.push(( MatcherType::VIDEO, "video/x-matroska".to_string(), "mkv".to_string(), ...
random
[ { "content": "// GetFtyp returns the major brand, minor version and compatible brands of the ISO-BMFF data\n\nfn get_ftyp(buf: &[u8]) -> Option<(String, String, Vec<String>)> {\n\n if buf.len() < 16 {\n\n return None;\n\n }\n\n\n\n let ftyp_length = BigEndian::read_u32(&buf[0..4]) as usize;\n\n\...
Rust
report/data_gen/src/colfind/theory_colfind_3d.rs
Byron/broccoli
b0dd6c7239da14713d0f6cda2761dbe49dafc900
use crate::inner_prelude::*; struct Res { num_pairs: usize, num_comparison: usize, } fn test1(grow: f64, inner: &mut [isize]) -> Res { let (num_pairs, num_comparison) = datanum::datanum_test_ret(|maker| { let mut bots = distribute(grow, inner, |a| a.to_isize_dnum(maker)); let mut tree = T...
use crate::inner_prelude::*; struct Res { num_pairs: usize, num_comparison: usize, }
fn test2(grow: f64, inner: &mut [isize]) -> Res { let (num_pairs, num_comparison) = datanum::datanum_test_ret(|maker| { let mut bb = distribute(grow, inner, |a| a.to_isize_dnum(maker)); let mut num_pairs = 0; broccoli::query::colfind::query_sweep_mut(axgeom::XAXIS, &mut bb, |_a, _b| { ...
fn test1(grow: f64, inner: &mut [isize]) -> Res { let (num_pairs, num_comparison) = datanum::datanum_test_ret(|maker| { let mut bots = distribute(grow, inner, |a| a.to_isize_dnum(maker)); let mut tree = TreeBuilder::new(&mut bots).build_seq(); let mut num_pairs = 0; tree.new_build...
function_block-full_function
[ { "content": "#[derive(Copy, Clone, Debug)]\n\nstruct NodeMass {\n\n center: Vec2<f32>,\n\n mass: f32,\n\n force: Vec2<f32>,\n\n}\n\n\n\nuse core::default::Default;\n\nimpl Default for NodeMass {\n\n fn default() -> NodeMass {\n\n NodeMass {\n\n center: vec2(Default::default(), Def...
Rust
buttplug/src/connector/transport/websocket/websocket_client.rs
blackspherefollower/buttplug-rs
1f9b2c7d24836dfccd01a959dc9b6f64e9a7d5cb
use crate::{ connector::{ transport::{ ButtplugConnectorTransport, ButtplugConnectorTransportSpecificError, ButtplugTransportIncomingMessage, }, ButtplugConnectorError, ButtplugConnectorResultFuture, }, core::messages::serializer::ButtplugSerializedMessage, util::async_manager, }; use ...
use crate::{ connector::{ transport::{ ButtplugConnectorTransport, ButtplugConnectorTransportSpecificError, ButtplugTransportIncomingMessage, }, ButtplugConnectorError, ButtplugConnectorResultFuture, }, core::messages::serializer::ButtplugSerializedMessage, util::async_manager, }; use ...
} Message::Ping(_) => {} Message::Pong(_) => {} Message::Close(_) => { info!("Websocket has requested close."); return; } }, Err(err) => { ...
if incoming_sender .send(ButtplugTransportIncomingMessage::Message( ButtplugSerializedMessage::Binary(v), )) .await .is_err() { error!("Websocket holder...
if_condition
[ { "content": "pub fn spawn<Fut>(_: Fut) -> Result<(), SpawnError>\n\nwhere\n\n Fut: Future<Output = ()> + Send + 'static,\n\n{\n\n unimplemented!(\"Dummy executor can't actually spawn!\")\n\n}\n\n\n", "file_path": "buttplug/src/util/async_manager/dummy.rs", "rank": 0, "score": 261572.71133111953 ...
Rust
src/util/auth.rs
afnan007a/Backpack
4100435272f4557bae815d1a4d943ff76410e24f
use actix_web::{http::StatusCode, web::Data, Error, FromRequest, HttpRequest}; use chrono::Utc; use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, Set}; use serde::{Deserialize, Serialize}; use ...
use actix_web::{http::StatusCode, web::Data, Error, FromRequest, HttpRequest}; use chrono::Utc; use jsonwebtoken::{decode, encode, DecodingKey, Encodi
, >, >; type Config = (); fn from_request(req: &actix_web::HttpRequest, _: &mut actix_web::dev::Payload) -> Self::Future { let req = req.clone(); Box::pin(async move { let (user_data, is_application) = match get_auth_data(req, ALLOW_UNVERIFIED).await { O...
ngKey, Header, Validation}; use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, Set}; use serde::{Deserialize, Serialize}; use crate::{ database::entity::{applications, users, verifications}, models::{MessageResponse, UserRole}, state::State, }; #[derive(Serialize, ...
random
[]
Rust
libplatune/management/src/search/search_engine.rs
aschey/Platune
ef84d44bbc380ce659159afcf037c7d71f812b78
use std::{collections::HashMap, str::FromStr}; use super::{ queries::{clean_query, combine_spellfix_results, get_search_query, replace_ampersand}, search_options::SearchOptions, search_result::SearchResult, }; use crate::{ db_error::DbError, entry_type::EntryType, search::{ queries::{ge...
use std::{collections::HashMap, str::FromStr}; use super::{ queries::{clean_query, combine_spellfix_results, get_search_query, replace_ampersand}, search_options::SearchOptions, search_result::SearchResult, }; use crate::{ db_error::DbError, entry_type::EntryType, search::{ queries::{ge...
async fn split_artist_filter(&self, query: &str) -> Result<(String, Vec<String>), DbError> { let artist_split = query.split("artist:").collect_vec(); match *artist_split.as_slice() { [] => Ok(("".to_owned(), vec![])), [query] => Ok((query.to_owned(), vec![])), ...
Result>, DbError> { let (adj_query, artist_filter) = self.split_artist_filter(query).await?; Ok(self .search_helper(&adj_query, &adj_query, options, artist_filter) .await?) }
function_block-function_prefixed
[ { "content": "fn replace_special_chars(query: &str) -> String {\n\n // Replace all special characters with whitespace because they cause sqlite to error\n\n let special_chars = Regex::new(r\"[^A-Za-z0-9&\\*\\s]\").unwrap();\n\n return special_chars.replace_all(query, \" \").trim().to_owned();\n\n}\n\n\...
Rust
src/commands/music/lastfm/nowplaying.rs
KamranMackey/Ellie
def8b988ce57ead580241428b5e1d6df74b1cdeb
use lastfm_rs::error::{ Error, LastFMErrorResponse::{InvalidParameters, OperationFailed} }; use serenity::{ client::Context, framework::standard::{macros::command, Args, CommandResult}, model::prelude::Message }; use tracing::error; use crate::utils::{get_profile_field, net_utils::*}; #[command]...
use lastfm_rs::error::{ Error, LastFMErrorResponse::{InvalidParameters, OperationFailed} }; use serenity::{ client::Context, framework::standard::{macros::command, Args, CommandResult
username); message .channel_id .send_message(context, |m| { m.embed(|embed| { embed.author(|author| author.name(header).url(url).icon_url(avatar)); embed.title(name); embed.url(track_url); embed.description(format!("**{}** ...
}, model::prelude::Message }; use tracing::error; use crate::utils::{get_profile_field, net_utils::*}; #[command] #[description("Retrieves the Last.fm now playing state of a given user.")] #[aliases("np")] #[usage("<user>, or leave blank")] async fn nowplaying(context: &Context, message: &Message, mut arguments:...
random
[ { "content": "use std::{\n\n error::Error,\n\n fmt::{Display, Formatter, Result},\n\n num::ParseIntError\n\n};\n\n\n\nuse tracing::error;\n\n\n\n#[derive(Debug)]\n\npub enum EllieError {\n\n Database(sqlx::Error),\n\n Parsing(ParseIntError),\n\n Serenity(serenity::Error),\n\n Custom(String)...
Rust
src/core/core.rs
another-s347/rusty-p4
b2c395e1b14e105762d7eb0879315ed8a7dca7d2
use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use std::fmt::Debug; use std::path::Path; use std::sync::{Arc, Mutex, RwLock}; use byteorder::BigEndian; use byteorder::ByteOrder; use bytes::Bytes; use failure::ResultExt; use futures::future::FutureExt; use futures::sink::SinkExt; use fu...
use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use std::fmt::Debug; use std::path::Path; use std::sync::{Arc, Mutex, RwLock}; use byteorder::BigEndian; use byteorder::ByteOrder; use bytes::Bytes; use failure::ResultExt; use futures::future::FutureExt; use futures::sink::SinkExt; use fu...
self, pipeconf:PipeconfID) -> Option<E> { Arc::make_mut(&mut self.pipeconf).remove(&pipeconf)?; Some(CommonEvents::PipeconfAdded(pipeconf).into_e()) } pub async fn update_pipeconf(&mut self, device:DeviceID, pipeconf:PipeconfID) -> Option<E> { let id = pipeconf; let pipeconf = ...
<E> { let id = pipeconf.get_id(); return if self.pipeconf.contains_key(&id) { None } else { Arc::make_mut(&mut self.pipeconf).insert(id, pipeconf); Some(CommonEvents::PipeconfAdded(id).into_e()) } } pub fn remove_pipeconf(&mut
random
[ { "content": "#[async_trait]\n\npub trait Context<E>: 'static + Send + Sync + Clone {\n\n type ContextState: Default + Clone;\n\n\n\n fn new(\n\n core_request_sender: futures::channel::mpsc::Sender<CoreRequest>,\n\n event_sender: futures::channel::mpsc::Sender<CoreEvent<E>>,\n\n conne...
Rust
src/lib.rs
bvssvni/dig
8e68943d2a06f995503a16411b5b2313d61e65ff
#![deny(missing_docs)] pub struct Container(pub f64); impl Container { pub fn put(&mut self, v: f64) { self.0 += v; } pub fn take(&mut self, v: f64) -> f64 { if self.0 <= v { let v = self.0; self.0 = 0.0; v } else { self.0 ...
#![deny(missing_docs)] pub struct Container(pub f64); impl Container { pub fn put(&mut self, v: f64) { self.0 += v; } pub fn take(&mut self, v: f64) -> f64 { if self.0 <= v { let v = self.0; self.0 = 0.0; v } else { self.0 ...
#[test] fn test_environment_chain() { let mut env = Environment::new(); let a = env.add_container(Container(1.0)); let b = env.add_container(Container(0.0)); let c = env.add_container(Container(0.0)); let ab = env.add_grabber(Grabber { source: a, ...
source: a, target: b, time: 1.0, volume: 2.0, }); assert_eq!(env.volume_of_container(a), 1.0); assert!(env.grab(ab).is_ok()); assert_eq!(env.volume_of_container(a), 0.0); assert_eq!(env.volume_of_container(b), 0.0); env.update(0.5); ...
function_block-function_prefix_line
[ { "content": "# dig\n\nA simple logistic environment primitive\n", "file_path": "README.md", "rank": 13, "score": 0.9013394748087158 } ]
Rust
raytracer/archyrt-core/src/loaders/ascn/mod.rs
garnold02alt/ArchyMario
8d8d1f1292ac65537f2408c45ee4e04ea3bd3084
pub mod amdl_textures; use crate::intersectables::triangle::Triangle; use crate::loaders::Loader; use crate::renderers::path_tracer::Material; use crate::utilities::math::{Vec2, Vec3, Matrix3x3}; use crate::{cameras::perspective::PerspectiveCamera, vector}; use anyhow::{anyhow, Result}; use asset::scene::{Scene, Poin...
pub mod amdl_textures; use crate::intersectables::triangle::Triangle; use crate::loaders::Loader; use crate::renderers::path_tracer::Material; use crate::utilities::math::{Vec2, Vec3, Matrix3x3}; use crate::{cameras::perspective::PerspectiveCamera, vector}; use anyhow::{anyhow, Result}; use asset::scene::{Scene, Poin...
pub fn get_prop_requests(&self) -> &Vec<PropRequest>{ &self.prop_requests } } impl Loader for ASCNLoader { type C = PerspectiveCamera; fn get_triangles(&self) -> &Vec<Triangle> { &self.triangles } fn get_camera(&self) -> &Self::C { &self.camera } }
::Diffuse, ); let triangle2 = Triangle::new( [point0, point3, point2], [uv0, uv3, uv2], AMDLTextureType::diffuse(face.texture.0), Material::Diffuse, ); triangles.push(triangle1...
random
[ { "content": "fn point(s: &Solid, i: usize) -> Point3<i16> {\n\n let point = s.geometry.points[i].position;\n\n Point3 {\n\n x: point.x as i16,\n\n y: point.y as i16,\n\n z: point.z as i16,\n\n }\n\n}\n", "file_path": "editor/packages/app/src/logic/elements/mod.rs", "rank":...
Rust
src/main.rs
acfoltzer/cargo-fund
b572a75e9e10984a987cc6635b1863a4cc9a9ae5
use crate::args::Opts; use anyhow::{anyhow, bail, Error}; use cargo_metadata::{Metadata, Package, PackageId}; use lazy_static::lazy_static; use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use structo...
use crate::args::Opts; use anyhow::{anyhow, bail, Error}; use cargo_metadata::{Metadata, Package, PackageId}; use lazy_static::lazy_static; use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use structo...
v>()?; let Opts::Fund(args) = Opts::from_args(); initialize_globals(&env, &args)?; let metadata = metadata::get(&args)?; let source_map = collect_sources(&metadata)?; let resolved = resolve_links(&source_map).await?; let num_found = resolved.len(); let inverted = invert_mapping(resolved); ...
function_block-function_prefixed
[ { "content": "pub fn get(args: &Args) -> Result<Metadata, Error> {\n\n let cargo = env::var_os(\"CARGO\").unwrap_or_else(|| OsString::from(\"cargo\"));\n\n\n\n let mut command = Command::new(cargo);\n\n command.arg(\"metadata\").arg(\"--format-version\").arg(\"1\");\n\n\n\n if args.quiet {\n\n ...
Rust
src/queryable/transaction.rs
tomhoule/mysql_async
433679f5abfaa2346addb2d7120edaf64ada701a
use futures_util::future::Either; use std::fmt; use crate::{ connection_like::{streamless::Streamless, ConnectionLike, ConnectionLikeWrapper}, error::*, io, queryable::Queryable, }; #[derive(Eq, PartialEq, Debug, Hash, Clone, Default)] pub struct TransactionOptions { consistent_snapshot: bool, ...
use futures_util::future::Either; use std::fmt; use crate::{ connection_like::{streamless::Streamless, ConnectionLike, ConnectionLikeWrapper}, error::*, io, queryable::Queryable, }; #[derive(Eq, PartialEq, Debug, Hash, Clone, Default)] pub struct TransactionOptions { consistent_snapshot: bool, ...
}
fn conn_like_mut(&mut self) -> &mut Self::ConnLike { match self.0 { Some(Either::Left(ref mut conn_like)) => conn_like, _ => unreachable!(), } }
function_block-function_prefix_line
[ { "content": "pub fn new<T, P>(\n\n conn_like: T,\n\n columns: Option<Arc<Vec<Column>>>,\n\n cached: Option<StmtCacheResult>,\n\n) -> QueryResult<T, P>\n\nwhere\n\n T: ConnectionLike + Sized + 'static,\n\n P: Protocol,\n\n P: Send + 'static,\n\n{\n\n QueryResult::new(conn_like, columns, cac...
Rust
tests/registering.rs
jean-airoldie/mio
162cdd3868742ed494ba03e7c843708eebd6849a
use std::io::{self, Write}; use std::thread::sleep; use std::time::Duration; use log::{debug, info, trace}; #[cfg(debug_assertions)] use mio::net::UdpSocket; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interests, Poll, Registry, Token}; mod util; use util::{any_local_address, init}; const SERVER: Tok...
use std::io::{self, Write}; use std::thread::sleep; use std::time::Duration; use log::{debug, info, trace}; #[cfg(debug_assertions)] use mio::net::UdpSocket; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interests, Poll, Registry, Token}; mod util; use util::{any_local_address, init}; const SERVER: Tok...
} } poll.poll(&mut events, Some(Duration::from_millis(100))) .unwrap(); assert!(events.iter().next().is_none()); } #[test] pub fn reregister_different_without_poll() { init(); let mut events = Events::with_capacity(1024); let mut poll = Poll::new().unwrap(); let l =...
if event.is_writable() { handler.handle_write(poll.registry(), event.token()); break; }
if_condition
[ { "content": "pub fn expect_no_events(poll: &mut Poll, events: &mut Events) {\n\n poll.poll(events, Some(Duration::from_millis(50)))\n\n .expect(\"unable to poll\");\n\n if !events.is_empty() {\n\n for event in events.iter() {\n\n error!(\"unexpected event: {:?}\", event);\n\n ...
Rust
src/year2017/day25.rs
CraZySacX/aoc
c96faf4c3fb0f39db0c2f5b573a307e5c779e421
use bytecount; use error::{Error, Result}; use regex::Regex; use std::collections::BTreeMap; use std::convert::TryFrom; use std::fmt; use std::io::BufRead; use utils::PrivateTryFromUsize; #[derive(Debug)] enum Move { Left, Right, } impl Default for Move { fn default() -> Self { Move::Le...
use bytecount; use error::{Error, Result}; use regex::Regex; use std::collections::BTreeMap; use std::convert::TryFrom; use std::fmt; use std::io::BufRead; use utils::PrivateTryFromUsize; #[derive(Debug)] enum Move { Left, Right, } impl Default for Move { fn default() -> Self { Move::Le...
} } impl fmt::Display for Move { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "{}", match *self { Move::Left => "left", Move::Right => "right", } ) } } #[derive(Debug, Default)] struct...
Ok(match val { "left" => Move::Left, "right" => Move::Right, _ => return Err(format!("Invalid move value: {}", val).into()), })
call_expression
[ { "content": "/// Generates the moves vector\n\nfn generate_moves(line: &str, moves: &mut Vec<Move>) -> Result<()> {\n\n let tokens: Vec<&str> = line.split(',').collect();\n\n let spin_re = Regex::new(r\"s(\\d{1,2})\")?;\n\n let exchange_re = Regex::new(r\"x(\\d{1,2})/(\\d{1,2})\")?;\n\n let partner...
Rust
aries_vcx/src/messages/connection/invite.rs
ryjones/aries-framework-rs
a4c434fe144029262c7d99f4da6f08e3749d1dd8
use std::convert::TryFrom; use futures::executor::block_on; use crate::error::prelude::*; use crate::handlers::out_of_band::OutOfBandInvitation; use crate::messages::a2a::{A2AMessage, MessageId}; use crate::messages::connection::did::Did; use crate::messages::connection::service::ServiceResolvable; #[derive(Debug, Cl...
use std::convert::TryFrom; use futures::executor::block_on; use crate::error::prelude::*; use crate::handlers::out_of_band::OutOfBandInvitation; use crate::messages::a2a::{A2AMessage, MessageId}; use crate::messages::connection::did::Did; use crate::messages::connection::service::ServiceResolvable; #[derive(Debug, Cl...
}
t_label(&_label()) .set_public_did(&_did()).unwrap(); assert_eq!(_public_invitation(), invitation); }
function_block-function_prefixed
[ { "content": "pub fn generate_public_invitation(public_did: &str, label: &str) -> VcxResult<String> {\n\n trace!(\"generate_public_invite >>> label: {}, public_did: {}\", public_did, label);\n\n let invitation = A2AMessage::ConnectionInvitationPublic(PublicInvitation::create()\n\n .set_public_did(p...
Rust
src/api/repos/releases.rs
Yatekii/octocrab
18be0fa3bb4f8b86d8a7c00481e81b518c1217a9
use super::*; pub struct ReleasesHandler<'octo, 'r> { parent: &'r RepoHandler<'octo>, } impl<'octo, 'r> ReleasesHandler<'octo, 'r> { pub(crate) fn new(parent: &'r RepoHandler<'octo>) -> Self { Self { parent } } ...
use super::*; pub struct ReleasesHandler<'octo, 'r> { parent: &'r RepoHandler<'octo>, } impl<'octo, 'r> ReleasesHandler<'octo, 'r> { pub(crate) fn new(parent: &'r RepoHandler<'octo>) -> Self { Self { parent } } ...
self.handler.parent.crab.get(url, Some(&self)).await } }
let url = format!( "/repos/{owner}/{repo}/releases", owner = self.handler.parent.owner, repo = self.handler.parent.repo );
assignment_statement
[ { "content": "/// Formats a GitHub preview from it's name into the full value for the\n\n/// `Accept` header.\n\n/// ```\n\n/// assert_eq!(octocrab::format_preview(\"machine-man\"), \"application/vnd.github.machine-man-preview\");\n\n/// ```\n\npub fn format_preview(preview: impl AsRef<str>) -> String {\n\n ...
Rust
crates/hmi/src/hmi_manager.rs
junelife/rust-anywhere
0e957cbf2e67bd37fe23719ad7f90533dbf2b3a7
use api::*; use lvgl::*; const LONG_PRESS_MS: u32 = 400; enum TimerState { Stopped, Running, Paused, } pub struct HmiManager { title: Option<Label>, gauge: Option<Gauge>, timestamp: Option<Label>, timer_state: TimerState, timer_elapsed: u32, last_ticks: u32, last_button_presse...
use api::*; use lvgl::*; const LONG_PRESS_MS: u32 = 400; enum TimerState { Stopped, Running, Paused, } pub struct HmiManager { title: Option<Label>, gauge: Option<Gauge>, timestamp: Option<Label>, timer_state: TimerState, timer_elapsed: u32, last_ticks: u32, last_button_presse...
mestamp.set_style(timestamp_style); timestamp.set_static_text(b"00:00.00\0"); timestamp.align_to_parent(Align::InBottomMid, 0, 0); self.timestamp = Some(timestamp); } Style::report_all_mod(); } pub unsafe fn update(&mut self) { let ticks = T...
ome(title); } static mut GAUGE_STYLE: Style = Style::new_empty(); let gauge_style = unsafe { &mut GAUGE_STYLE }; gauge_style.copy_from(Style::pretty()); (*gauge_style).text.font = Font::dejavu_20().into(); (*gauge_style).text.color = Color::WHITE.into(); if let ...
function_block-random_span
[ { "content": "fn get_hmi_manager() -> &'static mut HmiManager {\n\n static mut HMI_MANAGER: HmiManager = HmiManager::new_empty();\n\n unsafe { &mut HMI_MANAGER }\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn hmi_init() {\n\n let hmi = get_hmi_manager();\n\n hmi.init();\n\n}\n\n\n\n#[no_mangle]\n\n...
Rust
AoC17/rust/src/tests.rs
yury-fedorov/AoC18
23dcb580a978df7fa05220f6709f56707278f61f
use crate::common; use std::iter::FromIterator; fn day07( file : &str, answer1 : &str, answer2 : i32 ) { use crate::day07; let input = day07::parse( file ); let head = day07::task1( &input ); assert_eq!( answer1, head ); assert_eq!( answer2, day07::task2( &input, &head ) ); } #[test] fn test_day07...
use crate::common; use std::iter::FromIterator; fn day07( file : &str, answer1 : &str, answer2 : i32 ) { use crate::day07; let input = day07::parse( file ); let head = day07::task1( &input ); assert_eq!( answer1, head ); assert_eq!( answer2, day07::task2( &input, &head ) ); } #[test] fn test_day07...
; assert_eq!(141, answers.0); assert_eq!(171, answers.1); } fn day13( file : &str, answer1: i32, answer2 : i32 ) { use crate::day13; let map = day13::input( &common::input(file ) ); assert_eq!( answer1, day13::task1( &map ) ); if common::is_fast() && answer2 > 10000 { return } assert_eq!( a...
,{{}}}}") ); assert_eq!( 1, day09::task1("{<a>,<a>,<a>,<a>}") ); assert_eq!( 9, day09::task1("{{<ab>},{<ab>},{<ab>},{<ab>}}") ); assert_eq!( 9, day09::task1("{{<!!>},{<!!>},{<!!>},{<!!>}}" ) ); assert_eq!( 3, day09::task1("{{<a!>},{<a!>},{<a!>},{<ab>}}") ); assert_eq!(0, day09::task2( "<>" ) ); ...
random
[ { "content": "fn get_weight( tree : &HashMap<&str, &Data>, head : &str ) -> i32 {\n\n let ( _, w, leaves ) = tree.get( head ).unwrap();\n\n let mut result : i32 = *w;\n\n for l in leaves {\n\n result += get_weight( tree, l );\n\n }\n\n result\n\n}\n\n\n", "file_path": "AoC17/rust/src/day07.rs...
Rust
rafx-framework/src/graph/graph_image.rs
DavidVonDerau/rafx
5d42caed4bd7fcb5d32e3e26021669cf60071abd
use super::*; use rafx_api::{RafxExtents3D, RafxFormat, RafxResourceType, RafxSampleCount, RafxTextureBindType}; #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct RenderGraphImageUsageId(pub(super) usize); #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct VirtualImageId(pub(super) usize); #[d...
use super::*; use rafx_api::{RafxExtents3D, RafxFormat, RafxResourceType, RafxSampleCount, RafxTextureBindType}; #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct RenderGraphImageUsageId(pub(super) usize); #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct VirtualImageId(pub(super) usize); #[d...
pub fn set( &mut self, other: &RenderGraphImageSpecification, ) { *self = other.clone().into(); } } #[derive(Copy, Clone, Debug, PartialEq)] pub enum RenderGraphImageUsageType { Create, Read, ModifyRead, ModifyWrite, Output, } impl RenderGraphImageUs...
pub fn partial_merge( &mut self, other: &RenderGraphImageConstraint, ) -> bool { let mut complete_merge = true; if self.samples.is_some() && other.samples.is_some() && self.samples != other.samples { complete_merge = false; } else if other.samples.is_some() { ...
function_block-full_function
[ { "content": "fn recursive_modify_user_type<F: Fn(&mut UserType) -> bool>(\n\n user_types: &mut FnvHashMap<String, UserType>,\n\n type_name: &str,\n\n f: &F,\n\n) {\n\n let user_type = user_types.get_mut(type_name);\n\n let recurse = if let Some(user_type) = user_type {\n\n (f)(user_type)\...
Rust
src/car.rs
waimus/cornell-mcray
d69962181a3eb62b0ae97cbc33ee38c524c1384a
use std::collections::HashMap; use crate::physics::{IntoPhysx, PhysicsState, RigidDynamicHandle}; use kajiya::world_renderer::{AddMeshOptions, InstanceHandle, WorldRenderer}; use kajiya_simple::*; use physx::{prelude::*, traits::Class}; pub struct CarMeshes { body: kajiya::world_renderer::MeshHandle, left_whe...
use std::collections::HashMap; use crate::physics::{IntoPhysx, PhysicsState, RigidDynamicHandle}; use kajiya::world_renderer::{AddMeshOptions, InstanceHandle, WorldRenderer}; use kajiya_simple::*; use physx::{prelude::*, traits::Class}; pub struct CarMeshes { body: kajiya::world_renderer::MeshHandle, left_whe...
} pub struct Car { pub position: Vec3, pub rotation: Quat, gfx_meshes: HashMap<RigidDynamicHandle, InstanceHandle>, motors: Vec<*mut physx_sys::PxD6Joint>, steering: Vec<*mut physx_sys::PxD6Joint>, max_steering_angle: f32, suspension_height: f32, main_rb: RigidDynamicHandle, } impl C...
aked/car.mesh", AddMeshOptions::default())?; let left_wheel = world_renderer.add_baked_mesh("/baked/wheel_left.mesh", AddMeshOptions::default())?; let right_wheel = world_renderer.add_baked_mesh("/baked/wheel_right.mesh", AddMeshOptions::default())?; Ok(Self { ...
function_block-function_prefixed
[ { "content": "#[derive(Debug, StructOpt)]\n\n#[structopt(name = \"cornell-mcray\", about = \"Cornell McRay t'Racing\")]\n\nstruct Opt {\n\n #[structopt(long, default_value = \"1920\")]\n\n width: u32,\n\n\n\n #[structopt(long, default_value = \"1080\")]\n\n height: u32,\n\n\n\n #[structopt(long, ...
Rust
src/lib.rs
metanear/contract-rs
9698a405fcb358e20cf91b7f31271a90990ddacf
use borsh::{BorshDeserialize, BorshSerialize}; use near_sdk::collections::{Map, Vector}; use near_sdk::{env, ext_contract, near_bindgen, Promise, PromiseOrValue}; use serde::{Deserialize, Serialize}; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; type PublicKey = Vec<u8>; type AppI...
use borsh::{BorshDeserialize, BorshSerialize}; use near_sdk::collections::{Map, Vector}; use near_sdk::{env, ext_contract, near_bindgen, Promise, PromiseOrValue}; use serde::{Deserialize, Serialize}; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; type PublicKey = Vec<u8>; type AppI...
; env::storage_read(&app_key(&app_id, &key)).map(|bytes| String::from_utf8(bytes).unwrap()) } pub fn post_message(&mut self, app_id: AppId, message: Message) { verify_app_id(&app_id); self.verify_app_active(&app_id); let mut q = self.messages.get(&app_id).unwrap_or_else(|| { ...
ap<AppId, Vector<WrappedMessage>>, } #[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)] pub struct WrappedMessage { pub sender: AccountId, pub message: Message, pub time: u64, } fn verify_app_id(app_id: &AppId) { if app_id.len() < 2 || app_id.len() > 64 { env::panic(b"App ID l...
random
[ { "content": "# User contract for Meta NEAR\n\n\n\nContract implementing user-centric storage and inter-user messaging protocol for Meta NEAR.\n\n\n\n## Testing\n\nTo test run:\n\n```bash\n\ncargo test --package metanear-user -- --nocapture\n\n```\n\n\n\n## Build\n\n```bash\n\n./build.sh\n\n```\n\n\n\n## Deploy...
Rust
examples/basic.rs
khonsulabs/fabruic
04336dd430edc6bf54c89061a04fe30087ad93f1
use anyhow::{Error, Result}; use fabruic::{Endpoint, KeyPair}; use futures_util::{future, StreamExt, TryFutureExt}; const SERVER_NAME: &str = "test"; const SERVER_PORT: u16 = 34857; const CLIENTS: usize = 100; #[tokio::main] #[cfg_attr(test, test)] async fn main() -> Result<()> { let mut clients = Vec::with_capac...
use anyhow::{Error, Result}; use fabruic::{Endpoint, KeyPair}; use futures_util::{future, StreamExt, TryFutureExt}; const SERVER_NAME: &str = "test"; const SERVER_PORT: u16 = 34857; const CLIENTS: usize = 100; #[tokio::main] #[cfg_attr(test, test)]
async fn main() -> Result<()> { let mut clients = Vec::with_capacity(CLIENTS); let key_pair = KeyPair::new_self_signed(SERVER_NAME); let mut server = Endpoint::new_server(SERVER_PORT, key_pair.clone())?; let address = format!("quic://{}", server.local_address()?); for index in 0..CLIENTS { let add...
function_block-full_function
[ { "content": "#[test]\n\nfn validate() -> anyhow::Result<()> {\n\n\tuse crate::KeyPair;\n\n\n\n\tlet key_pair = KeyPair::new_self_signed(\"test\");\n\n\tlet certificate = key_pair.end_entity_certificate();\n\n\tassert_eq!(certificate, &Certificate::from_der(certificate.as_ref())?);\n\n\n\n\tOk(())\n\n}\n", ...
Rust
src/chunk.rs
jerry73204/concurrent-slice
a973d2ef923a641ab94638131fd82dfe77644166
use crate::{ chunks::{EvenChunks, Iter, SizedChunks, Windows}, common::*, }; use std::{ops::RangeBounds, slice::SliceIndex}; #[derive(Debug)] pub struct Chunk<'a, S, T> where S: AsRef<[T]> + Send + Sync + 'a, T: Send + Sync, { pub(super) owner: Arc<S>, pub(super) slice: NonNull<[T]>, pub(su...
use crate::{ chunks::{EvenChunks, Iter, SizedChunks, Windows}, common::*, }; use std::{ops::RangeBounds, slice::SliceIndex}; #[derive(Debug)] pub struct Chunk<'a, S, T> where S: AsRef<[T]> + Send + Sync + 'a, T: Send + Sync, { pub(super) owner: Arc<S>, pub(super) slice: NonNull<[T]>, pub(su...
pub fn to_range<R>(&self, range: R) -> Option<Self> where R: RangeBounds<usize> + SliceIndex<[T], Output = [T]>, { unsafe { let Self { owner, slice, .. } = self; let slice: &mut [T] = slice.clone().as_mut(); let new_slice: &mut [T] = slice.get_mut(range)...
s.into_iter(); let first = chunks.next().expect("the chunks must be non-empty"); let owner = first.owner.clone(); let chunks: Vec<_> = iter::once(first) .chain(chunks.inspect(|chunk| { assert_eq!( ...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn owning_iter_test() {\n\n let owner: Vec<_> = (0..3).collect();\n\n let owner = ChunkMut::new(owner);\n\n let mut iter = owner.into_iter_owned();\n\n assert_eq!(*iter.next().unwrap(), 0);\n\n assert_eq!(*iter.next().unwrap(), 1);\n\n assert_eq!(*iter.next().unwrap(),...
Rust
2020/aoc16/src/main.rs
ErikMcClure/aoc2021
4ee13f4a774f6d92fe0c3edefd6edd11e3c2ef39
use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; use std::collections::HashSet; use std::io::Read; fn get_rule(s: &str) -> ((i32, i32, i32, i32), String) { lazy_static! { static ref RULE: Regex = Regex::new(r"([a-z ]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)").unwr...
use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; use std::collections::HashSet; use std::io::Read; fn get_rule(s: &str) -> ((i32, i32, i32, i32), String) { lazy_static! { static ref RULE: Regex = Regex::new(r"([a-z ]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)").unwr...
let mut results: HashMap<usize, (i32, i32, i32, i32)> = HashMap::new(); while track.len() > 0 { let mut index = 99999999usize; for t in track.iter() { if t.1.len() == 1 { index = *t.1.iter().next().unwrap(); results.insert(index, *t.0); ...
let rulemap: HashMap<(i32, i32, i32, i32), String> = sections.next().unwrap().split('\n').map(get_rule).collect(); let mut ticket = sections.next().unwrap().split('\n').skip(1); let ticket: Vec<i32> = ticket .next() .unwrap() .split(',') .map(|x| x.parse().unwrap()) ...
random
[ { "content": "fn parse_rule(x: Result<String, std::io::Error>) -> (i32, Rule) {\n\n let mut x: &str = &x.unwrap();\n\n if x == \"8: 42\" {\n\n x = \"8: 42 | 42 8\";\n\n }\n\n if x == \"11: 42 31\" {\n\n x = \"11: 42 31 | 42 11 31\";\n\n }\n\n let mut parts = x.split(':');\n\n ...
Rust
src/spot/websocket.rs
crankykernel/rust-binance
726b47a4bc18caf7db7123e791386a3c242233d9
use std::collections::HashMap; use anyhow::Result; use futures_util::StreamExt; use serde::Deserialize; use serde_json::Value; use tokio::net::TcpStream; use tokio_tungstenite::tungstenite::error::Error; use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::{connect_async, tungstenite, MaybeTlsStream, ...
use std::collections::HashMap; use anyhow::Result; use futures_util::StreamExt; use serde::Deserialize; use serde_json::Value; use tokio::net::TcpStream; use tokio_tungstenite::tungstenite::error::Error; use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::{connect_async, tungstenite, MaybeTlsStream, ...
\ \"P\":\"0.00000000\",\ \"F\":\"0.00000000\",\ \"g\":-1,\ \"C\":\"\",\ \"x\":\"TRADE\",\ \"X\":\"FILLED\",\ \"r\":\"NONE\",\ \"i\":197554424,\ \"l\":\"30.00000000\",\ \"z\":\"30.00000000\",\ ...
X")] pub current_order_status: String, #[serde(rename = "r")] pub reject_reason: String, #[serde(rename = "i")] pub order_id: u64, #[serde(rename = "l", deserialize_with = "parse_f64_string")] pub last_executed_quantity: f64, #[serde(rename = "z", deserialize_with = "parse_f64_string")] ...
random
[]
Rust
tests/lib_test.rs
rekha-chitkara/john
0477efe104fad9279302afb42c46d9fb8c64d573
extern crate john; extern crate test; use john::{PushCommand, PeekCommand, PeekResult, ClearCommand}; const RIVER_SIZE: int = 100i; #[test] fn pushing_and_peeking_a_message() { ClearCommand::new().execute("a river"); PushCommand::new().execute("a river", "hello world"); let result = PeekCommand::new().e...
extern crate john; extern crate test; use john::{PushCommand, PeekCommand, PeekResult, ClearCommand}; const RIVER_SIZE: int = 100i; #[test] fn pushing_and_peeking_a_message() { ClearCommand::new().execute("a river"); PushCommand::new().execute("a river", "hello world"); let result = PeekCommand::new().e...
} b.iter(|| { clear.execute("an empty river") }) } #[bench] fn peeking_last_message_from_empty_river(b: &mut test::Bencher) { let clear = john::ClearCommand::new(); let peek = john::PeekCommand::new(); clear.execute("another empty river"); peek.execute("another empty river", None)...
Some(10)); match result { Some(_) => assert!(false), None => assert!(true) } } #[test] fn clearing_empty_river() { ClearCommand::new().execute("a river 5"); ClearCommand::new().execute("a river 5"); match PeekCommand::new().execute("a river 5", None) { Some(_) => assert!(...
random
[ { "content": "#[test]\n\nfn push_on_full_river_with_some_offset() {\n\n ClearCommand::new().execute(\"server_side_river_4\");\n\n PushCommand::new().execute(\"server_side_river_4\", \"a message\");\n\n PushCommand::new().execute(\"server_side_river_4\", \"a message 2\");\n\n PushCommand::new().execu...
Rust
bitworks/src/systems/belt_graphics.rs
payload/bitworks
e0d96d999b5f6223047f08653e27d3623a3f2673
use bevy::prelude::*; use bevy_prototype_lyon::plugin::ShapePlugin as LyonPlugin; use bevy_prototype_lyon::prelude::Geometry; use lyon_path::{builder::BorderRadii, traits::PathBuilder}; use crate::*; pub struct BeltGraphicsPlugin; impl Plugin for BeltGraphicsPlugin { fn build(&self, app: &mut AppBuilder) { ...
use bevy::prelude::*; use bevy_prototype_lyon::plugin::ShapePlugin as LyonPlugin; use bevy_prototype_lyon::prelude::Geometry; use lyon_path::{builder::BorderRadii, traits::PathBuilder}; use crate::*; pub struct BeltGraphicsPlugin; impl Plugin for BeltGraphicsPlugin { fn build(&self, app: &mut AppBuilder) { ...
struct ItemBubble; impl Geometry for ItemBubble { fn add_geometry(&self, b: &mut LyonBuilder) { b.add_rounded_rectangle( &lyon_geom::rect(-2.0, -2.0, 4.0, 4.0), &BorderRadii::new(1.0), lyon_path::Winding::Positive, ) } } #[derive(Clone, Default)] struct Bel...
if index >= draw_items.entities.len() { let entity = cmds .spawn_bundle(SpriteSheetBundle { texture_atlas: item_atlas.clone(), transform: Transform::from_translation(pos), visible: Visible { ...
function_block-function_prefix_line
[ { "content": "pub fn belt_input_system(mut belts: Query<(Entity, &mut Belt, &mut ItemInput)>) {\n\n // transfer items from ItemInput to belt and update ItemInput space\n\n for (_, mut belt, mut item_input) in belts.iter_mut() {\n\n for item in item_input.items.drain(0..).rev() {\n\n belt...
Rust
macros/src/derive_packet.rs
ported-pw/capsule
92ec1560abaac77147814f09cdeceb8d64bfeefd
/* * Copyright 2019 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicab...
/* * Copyright 2019 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicab...
4; #[inline] fn envelope(&self) -> &Self::Envelope { self.icmp().envelope() } #[inline] fn envelope_mut(&mut self) -> &mut Self::Envelope { self.icmp_mut().envelope_mut() } #[inline] fn off...
function_block-function_prefixed
[ { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn compute(pseudo_header_sum: u16, payload: &[u8]) -> u16 {\n\n let len = payload.len();\n\n let mut data = payload;\n\n let mut checksum = u32::from(pseudo_header_sum);\n\n\n\n // odd # of bytes, we add the last byte with padding separately\...
Rust
src/update/api.rs
Byron/git-tool
5f3da85b4f682a12a766dec3c57fc6a3f9f76391
use super::release::*; use crate::{core::Core, errors}; use serde::{Deserialize, Serialize}; use std::io; use std::path::PathBuf; #[async_trait::async_trait] pub trait Source<C: Core>: Default + Send + Sync { async fn get_releases(&self, core: &C) -> Result<Vec<Release>, errors::Error>; async fn get_binary<W: ...
use super::release::*; use crate::{core::Core, errors}; use serde::{Deserialize, Serialize}; use std::io; use std::path::PathBuf; #[async_trait::async_trait] pub trait Source<C: Core>: Default + Send + Sync { async fn get_releases(&self, core: &C) -> Result<Vec<Release>, errors::Error>; async fn get_binary<W: ...
} #[cfg(test)] mod tests { use super::*; #[test] fn test_serialize() { assert_eq!( serde_json::to_string(&UpdateState { target_application: Some(PathBuf::from("/bin/git-tool")), temporary_application: Some(PathBuf::from("/tmp/git-tool-update")), ...
pub fn for_phase(&self, phase: UpdatePhase) -> Self { UpdateState { target_application: self.target_application.clone(), temporary_application: self.temporary_application.clone(), phase, } }
function_block-full_function
[ { "content": "#[async_trait::async_trait]\n\npub trait Registry<C: Core>: Send + Sync {\n\n async fn get_entries(&self, core: &C) -> Result<Vec<String>, Error>;\n\n async fn get_entry(&self, core: &C, id: &str) -> Result<Entry, Error>;\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, Clone, Default)]\n...
Rust
src/main.rs
dertin/sql-to-liquibase-xml-rs
767433a80dcb7b4afb45b3778e175349f1c884de
extern crate chrono; extern crate regex; extern crate xml; use chrono::offset::Utc; use chrono::DateTime; use regex::Regex; use std::collections::HashMap; use std::fs::File; use std::time::SystemTime; use std::{fs, io::Write}; fn main() { let sql_raw = load_files_sql(); let str_find_insert: &str = "INSERT IN...
extern crate chrono; extern crate regex; extern crate xml; use chrono::offset::Utc; use chrono::DateTime; use regex::Regex; use std::collections::HashMap; use std::fs::File; use std::time::SystemTime; use std::{fs, io::Write}; fn main() { let sql_raw = load_files_sql(); let str_find_insert: &str = "INSERT IN...
; let field = str_field.replace('\"', "").replace('\'', ""); let str_field_trim = Box::leak(field.into_boxed_str()).trim(); let value = str_value .trim_start_matches('\'') .trim_end_matches('\'') .replace("\'\'", "\'"); map_fields_values.insert(str_...
match vec_item_set.get(1) { Some(value) => value.trim(), None => panic!("no values found: ".to_owned() + item_set), }
if_condition
[ { "content": "UPDATE table_name\n\nSET column1 = 'value1', column2 = NEWID(), column3 = ''\n\nWHERE condition = 'Active' AND condition2 = '12345'", "file_path": "sql/2_update.sql", "rank": 4, "score": 48840.06952672333 }, { "content": "INSERT INTO Customers (Id, CustomerName, ContactName, D...
Rust
src/lib.rs
jasonahills/opentelemetry-stackdriver
5bd57797f9ca1146d7842dfa6cb7ee7b58ffd1be
/* Copyright 2020 Vivint Smarthome Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
/* Copyright 2020 Vivint Smarthome Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
_span.set_span_id(hex::encode(span.context.span_id().to_be_bytes())); new_span.set_parent_span_id(hex::encode(span.parent_span_id.to_be_bytes())); new_span.set_start_time(system_time_to_timestamp(span.start_time)); new_span.set_end_time(system_time_to_timestamp(span.end_time)); ...
), ), project_name: project_name.into(), runtime: Mutex::new(Runtime::new().unwrap()), }) } } impl SpanExporter for StackDriverExporter { fn export(&self, batch: Vec<Arc<SpanData>>) -> ExportResult { use proto::{trace::Span, tracing::BatchWriteSpansRequest...
random
[ { "content": "fn main() {\n\n let out_dir = std::env::var(\"OUT_DIR\").unwrap();\n\n protoc_grpcio::compile_grpc_protos(\n\n &[\n\n \"google/devtools/cloudtrace/v2/tracing.proto\",\n\n \"google/devtools/cloudtrace/v2/trace.proto\",\n\n \"google/rpc/status.proto\",\n...
Rust
src/server/ip.rs
Roba1993/hap-rs
11c7d965442690a9816e27beed556d0e7bd0550d
use std::sync::Arc; use async_trait::async_trait; use futures::{ future::{self, BoxFuture, FutureExt}, lock::Mutex, }; use log::info; use crate::{ accessory::HapAccessory, config::Config, event::{Event, EventEmitter}, pointer, server::Server, storage::{accessory_list::AccessoryList, St...
use std::sync::Arc; use async_trait::async_trait; use futures::{ future::{self, BoxFuture, FutureExt}, lock::Mutex, }; use log::info; use crate::{ accessory::HapAccessory, config::Config, event::{Event, EventEmitter}, pointer, server::Server, storage::{accessory_list::AccessoryList, St...
} #[async_trait] impl Server for IpServer { fn run_handle(&self) -> BoxFuture<()> { let http_handle = self.http_server.run_handle(); let mdns_handle = self.mdns_responder.run_handle(); Box::pin(future::join(http_handle, mdns_handle).map(|_| ()).boxed()) } fn config_pointer(&self)...
d; } } }, _ => {}, } } .boxed() })); let event_emitter = Arc::new(Mutex::new(event_emitter)); let accessory_list = Arc::new(Mutex::new(AccessoryList::new(event_emi...
function_block-function_prefixed
[ { "content": "#[async_trait]\n\npub trait Storage: Send + Sync {\n\n /// Loads the `Config` from the `Storage`.\n\n async fn load_config(&self) -> Result<Config>;\n\n /// Saves the `Config` into the `Storage`.\n\n async fn save_config(&mut self, config: &Config) -> Result<()>;\n\n /// Deletes the...
Rust
little_raft/tests/raft_unstable.rs
suzaku/little-raft
e79dd88315fcbcbdd098c32dbb2730087d1ad9b0
use crossbeam_channel as channel; use crossbeam_channel::{unbounded, Receiver, Sender}; use little_raft::{ cluster::Cluster, message::Message, replica::Replica, state_machine::{StateMachine, StateMachineTransition, TransitionState}, }; use std::sync::{Arc, Mutex}; use std::{collections::BTreeMap, threa...
use crossbeam_channel as channel; use crossbeam_channel::{unbounded, Receiver, Sender}; use little_raft::{ cluster::Cluster, message::Message, replica::Replica, state_machine::{StateMachine, StateMachineTransition, TransitionState}, }; use std::sync::{Arc, Mutex}; use std::{collections::BTreeMap, threa...
fn create_state_machines( n: usize, applied_transitions_tx: Sender<(usize, usize)>, ) -> Vec<Arc<Mutex<Calculator>>> { let mut state_machines = Vec::new(); for i in 0..n { let state_machine = Arc::new(Mutex::new(Calculator { id: i, value: 0, pending_transiti...
fn create_peer_ids(n: usize) -> Vec<Vec<usize>> { let mut all_peer_ids = Vec::new(); for i in 0..n { let mut peer_ids = Vec::new(); for n in 0..n { if n != i { peer_ids.push(n); } } all_peer_ids.push(peer_ids); } all_peer_ids }
function_block-function_prefix_line
[ { "content": "fn halt_clusters(clusters: Vec<Arc<Mutex<ThreadCluster>>>) {\n\n thread::sleep(Duration::from_secs(1));\n\n for cluster in clusters.iter() {\n\n let mut c = cluster.lock().unwrap();\n\n c.halt = true;\n\n }\n\n thread::sleep(Duration::from_secs(2));\n\n}\n\n\n", "file...
Rust
src/foc_controller.rs
uLipe/rotom-rs
1d5b3d6db44ae0d9d64530977febcd69f6b4a97d
use std::f32; use std::f32::consts as math_consts; use modulator::foc_modulator as foc; use platform_traits::pwm_inverter as pwm; use platform_traits::current_sensor as cs; use platform_traits::rotor_position_sensor as encoder; use platform_traits::blocking_delay as delay; use foc_types::types as t; use pid_controller:...
use std::f32; use std::f32::consts as math_consts; use modulator::foc_modulator as foc; use platform_traits::pwm_inverter as pwm; use platform_traits::current_sensor as cs; use platform_traits::rotor_position_sensor as encoder; use platform_traits::blocking_delay as delay; use foc_types::types as t; use pid_controller:...
pub fn set_target_current(&mut self, current : t::Amperes) -> Result<(), FocResult> { if self.aligned != AlignedState::Aligned { Err(FocResult::FocNotAligned) } else { self.iq = current; Ok(()) } } pub fn get_rotor_position_ticks(&mut self) -> t...
pub fn initialize_foc(&mut self, initial_time : f32) -> Result<(), FocResult>{ let align_command_q = t::VoltageQ(self.supply_voltage.0 * 0.1); let align_command_d = t::VoltageD(0.0); let zeroq_voltage = t::VoltageQ(0.0); let zerod_voltage = t::VoltageD(0.0); let mut pha...
function_block-full_function
[ { "content": "#[inline(always)]\n\npub fn fast_sin(mut theta : f32) -> f32 {\n\n theta = angle_normalize(theta);\n\n let theta_y = B * theta + C * theta * match theta < 0.0 {\n\n true => -theta,\n\n false => theta \n\n };\n\n\n\n let result = P *( theta_y * (match theta_y < 0.0 {\n\n ...
Rust
examples/echo_client.rs
pferreir/rust-mumble-protocol
797ea4a4471f9e3d3221c46483ff414c0a70e236
use argparse::ArgumentParser; use argparse::Store; use argparse::StoreTrue; use bytes::Bytes; use futures::channel::oneshot; use futures::join; use futures::StreamExt; use futures::SinkExt; use mumble_protocol::control::msgs; use mumble_protocol::control::ClientControlCodec; use mumble_protocol::control::ControlPacket;...
use argparse::ArgumentParser; use argparse::Store; use argparse::StoreTrue; use bytes::Bytes; use futures::channel::oneshot; use futures::join; use futures::StreamExt; use futures::SinkExt; use mumble_protocol::control::msgs; use mumble_protocol::control::ClientControlCodec; use mumble_protocol::control::ControlPacket;...
async fn handle_udp( server_addr: SocketAddr, crypt_state: oneshot::Receiver<ClientCryptState>, ) { let udp_socket = UdpSocket::bind((Ipv6Addr::from(0u128), 0u16)) .await .expect("Failed to bind UDP socket"); let crypt_state = match crypt_state.await { Ok(crypt_state...
println!("TCP connected.."); let mut builder = native_tls::TlsConnector::builder(); builder.danger_accept_invalid_certs(accept_invalid_cert); let connector: TlsConnector = builder .build() .expect("Failed to create TLS connector") .into(); let tls_stream = connector ...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n // Prepare OUT_DIR/proto directory\n\n let out_dir = Path::new(&env::var(\"OUT_DIR\").unwrap()).join(\"proto\");\n\n fs::create_dir_all(&out_dir).expect(\"Failed to create $OUT_DIR/proto directory\");\n\n\n\n protobuf_codegen_pure::run(protobuf_codegen_pure::Args {\n\n ...
Rust
webapp/src/conversion/color_image.rs
easychen/vtracer
c8f4fc113338627f1b01f0b9d1ad470739949d62
use wasm_bindgen::prelude::*; use visioncortex::{PathSimplifyMode, PointI32}; use visioncortex::color_clusters::{IncrementalBuilder, Clusters, Runner, RunnerConfig}; use crate::canvas::*; use crate::svg::*; use serde::Deserialize; use super::util; #[derive(Debug, Deserialize)] pub struct ColorImageConverterParams { ...
use wasm_bindgen::prelude::*; use visioncortex::{PathSimplifyMode, PointI32}; use visioncortex::color_clusters::{IncrementalBuilder, Clusters, Runner, RunnerConfig}; use crate::canvas::*; use crate::svg::*; use serde::Deserialize; use super::util; #[derive(Debug, Deserialize)] pub struct ColorImageConverterParams { ...
pub fn tick(&mut self) -> bool { match &mut self.stage { Stage::New => { panic!("uninitialized"); }, Stage::Clustering(builder) => { self.canvas.log("Clustering tick"); if builder.tick() { self.stage = ...
good_min_area: self.params.filter_speckle, good_max_area: (width * height) as usize, is_same_color_a: self.params.color_precision, is_same_color_b: 1, deepen_diff: self.params.layer_difference, hollow_neighbours: 1, }, image); self.stage = Stag...
function_block-function_prefix_line
[ { "content": "pub fn path_simplify_mode(s: &str) -> PathSimplifyMode {\n\n\tmatch s {\n\n\t\t\"polygon\" => PathSimplifyMode::Polygon,\n\n\t\t\"spline\" => PathSimplifyMode::Spline,\n\n\t\t\"none\" => PathSimplifyMode::None,\n\n\t\t_ => panic!(\"unknown PathSimplifyMode {}\", s),\n\n\t}\n\n}", "file_path": ...
Rust
src/lib/preprocessor/preprocessor_tests.rs
YJDoc2/8086-Emulator
f72150f57871fa871629e741f86afa0df00fbb76
#[allow(unused_imports)] use super::preprocessor; #[test] fn test_data_directives() { let mut ctx = crate::util::preprocessor_util::Context::default(); let mut out = crate::util::preprocessor_util::Output::default(); let p = preprocessor::PreprocessorParser::new(); let o = p.parse(&mut ctx, &mut out, "...
#[allow(unused_imports)] use super::preprocessor; #[test] fn test_data_directives() { let mut ctx = crate::util::preprocessor_util::Context::default(); let mut out = crate::util::preprocessor_util::Output::default(); let p = preprocessor::PreprocessorParser::new(); let o = p.parse(&mut ctx, &mut out, "...
#[test] fn test_data_transfer_push_pop() { let mut ctx = crate::util::preprocessor_util::Context::default(); let mut out = crate::util::preprocessor_util::Output::default(); let p = crate::preprocessor::preprocessor::PreprocessorParser::new(); let o = p.parse(&mut ctx, &mut out, "l:DW [5,7] push CS pu...
l:DW 0 LEA AX , word l lea dx , word [SI,7]", ); assert!(o.is_ok()); assert_eq!(out.code.len(), 2); let o = p.parse(&mut ctx, &mut out, "LES"); assert!(o.is_err()); let o = p.parse(&mut ctx, &mut out, "LDS"); assert!(o.is_err()); }
function_block-function_prefix_line
[ { "content": "/// Function to set a particular flag\n\npub fn set_flag(reg: &mut u16, flag: Flags) {\n\n match flag {\n\n Flags::OVERFLOW => *reg = *reg | FLAG_OVERFLOW,\n\n Flags::DIRECTION => *reg = *reg | FLAG_DIRECTION,\n\n Flags::INTERRUPT => *reg = *reg | FLAG_INTERRUPT,\n\n ...
Rust
examples/quick-comparison.rs
malaire/reed-solomon-16
0e47ad71aeb60a68a27c2c486685d3163486bf36
use std::time::Instant; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use reed_solomon_16::engine::DefaultEngine; use reed_solomon_erasure::galois_16::ReedSolomon as ReedSolomon16; use reed_solomon_erasure::galois_8::ReedSolomon as ReedSolomon8; use reed_solomon_novelpoly::{CodeParams, WrappedShard}; con...
use std::time::Instant; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use reed_solomon_16::engine::DefaultEngine; use reed_solomon_erasure::galois_16::ReedSolomon as ReedSolomon16; use reed_solomon_erasure::galois_8::ReedSolomon as ReedSolomon8; use reed_solomon_novelpoly::{CodeParams, WrappedShard}; con...
fn test_reed_solomon_novelpoly(count: usize) { let start = Instant::now(); let r = CodeParams::derive_parameters(2 * count, count) .unwrap() .make_encoder(); let elapsed = start.elapsed(); print!("> reed-solomon-novelpoly {:9}", elapsed.as_micros()); let mut original =...
function_block-full_function
[ { "content": "fn use_high_rate(original_count: usize, recovery_count: usize) -> Result<bool, Error> {\n\n if original_count > GF_ORDER || recovery_count > GF_ORDER {\n\n return Err(Error::UnsupportedShardCount {\n\n original_count,\n\n recovery_count,\n\n });\n\n }\n\n\...
Rust
src/seqtable/read.rs
mjg54/seqOutBias
4b0d004cf7be18e35718dc2864341316fd78077c
extern crate bincode; use std::io::prelude::*; use std::io::SeekFrom; use std::io::Result; use std::io::Error; use std::io::ErrorKind; use byteorder::{LittleEndian, ReadBytesExt}; use bincode::rustc_serialize::{decode_from, decode}; use flate2::{Decompress,Flush}; use super::SeqTableParams; use super::write::SeqInf...
extern crate bincode; use std::io::prelude::*; use std::io::SeekFrom; use std::io::Result; use std::io::Error; use std::io::ErrorKind; use byteorder::{LittleEndian, ReadBytesExt}; use bincode::rustc_serialize::{decode_from, decode}; use flate2::{Decompress,Flush}; use super::SeqTableParams; use super::write::SeqInf...
pub fn vir_get(&mut self, position: i32) -> Result<(u32, u32)> { if position < 0 { Ok((0, 0)) } else { self.get(position as u32) } } pub fn get(&mut self, position: u32) -> Result<(u32, u32)> { let idx = (position / self.block_length) as usize; ...
fn read_block(&mut self, block_info: &SeqBlock) -> Result<Vec<(u32,u32)>> { let buf = &mut self.read_buffer[0..block_info.comp_size as usize]; let mut decompressor = Decompress::new(false); try!(self.reader.seek(SeekFrom::Start(block_info.offset))); try!(self.r...
function_block-full_function
[ { "content": "fn tabulate_bam<R: ioRead + Seek>(bamfilename: String, seqinfos: &Vec<SequenceInfo>, pair_range: &Option<(i32, i32)>, paired: bool, rlen: usize, minqual: u8, counts: &mut Vec<(u64, u64, u64, u64)>, table: &mut SeqTable<R>, regions: Option<&BedRanges>, exact_length: bool, tail_edge: bool) {\n\n ...
Rust
router/src/connection_pool.rs
re-gmbh/influxdb_iox
8717bfa74727bcac0adf762c81878bbdd63435b1
use std::sync::Arc; use cache_loader_async::cache_api::LoadingCache; use data_types::write_buffer::WriteBufferConnection; use observability_deps::tracing::debug; use write_buffer::{ config::WriteBufferConfigFactory, core::{WriteBufferError, WriteBufferWriting}, }; use crate::grpc_client::GrpcClient; type Key...
use std::sync::Arc; use cache_loader_async::cache_api::LoadingCache; use data_types::write_buffer::WriteBufferConnection; use observability_deps::tracing::debug; use write_buffer::{ config::WriteBufferConfigFactory, core::{WriteBufferError, WriteBufferWriting}, }; use crate::grpc_client::GrpcClient; type Key...
.await .map_err(|e| Arc::new(EWrapper(e)) as ConnectionError) } }); Self { grpc_clients, write_buffer_producers, } } #[cfg(test)] pub async fn new_testing() -> Self { use time::SystemProvider; let ti...
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl std::error::Error for EWrapper {} #[derive(Debug)] pub struct ConnectionPool { grpc_clients: LoadingCache<String, Arc<dyn GrpcClient>, ConnectionError>, write_buffer_producers: LoadingCache<Key...
random
[ { "content": "#[async_trait]\n\npub trait ServerType: std::fmt::Debug + Send + Sync + 'static {\n\n type RouteError: HttpApiErrorSource;\n\n\n\n /// Metric registry associated with the server.\n\n fn metric_registry(&self) -> Arc<Registry>;\n\n\n\n /// Trace collector associated with the server, if ...
Rust
src/lib.rs
seanbreckenridge/wca_userinfo
231bd654d9faa2044d09684331d5ed9ed7936804
use std::error::Error; use reqwest; use scraper::{Html, Selector}; use serde::Serialize; use simple_error::bail; pub type ParseResult<T> = Result<T, Box<dyn Error>>; static EXPECT_USER_INFO_TDS: usize = 5; static EXPECT_EVENT_TDS: usize = 10; static PERSON_INFORMATION_SELECTOR_STR: &str = "div.details table.table t...
use std::error::Error; use reqwest; use scraper::{Html, Selector}; use serde::Serialize; use simple_error::bail; pub type ParseResult<T> = Result<T, Box<dyn Error>>; static EXPECT_USER_INFO_TDS: usize = 5; static EXPECT_EVENT_TDS: usize = 10; static PERSON_INFORMATION_SELECTOR_STR: &str = "div.details table.table t...
#[derive(Serialize)] pub struct RecordGroup { pub time: Option<String>, pub national: Option<u32>, pub continent: Option<u32>, pub world: Option<u32>, } impl RecordGroup { pub fn from_str_values( time: &str, national: &str, continent: &str, world: &str, )...
fn parse_int(val: &str) -> ParseResult<Option<u32>> { if val.is_empty() { Ok(None) } else { match val.parse::<u32>() { Ok(int) => Ok(Some(int)), Err(_) => bail!("Could not parse integer: {}", val), } } }
function_block-full_function
[ { "content": "fn main() {\n\n let mut router = Router::new();\n\n router.get(\"/:wca_id\", controller, \"wca_id\");\n\n\n\n let port = get_port();\n\n\n\n let _server = Iron::new(router).http(format!(\"0.0.0.0:{}\", port)).unwrap();\n\n println!(\"Hosting wca_userinfo server on port: {}\", port);...
Rust
libs/rpmspec/src/lib.rs
wojciechkepka/pkger
20e377b92cbf82af0a46061decd6de6d2589a907
use pkgspec::SpecStruct; use std::fs; use std::io; use std::path::Path; #[derive(Clone, Debug, Default, PartialEq, SpecStruct)] pub struct RpmSpec { name: String, version: String, release: String, epoch: Option<String>, vendor: Option<String>, url: Option<Stri...
use pkgspec::SpecStruct; use std::fs; use std::io; use std::path::Path; #[derive(Clone, Debug, Default, PartialEq, SpecStruct)] pub struct RpmSpec { name: String, version: String, release: String, epoch: Option<String>, vendor: Option<String>, url: Option<Stri...
} impl RpmSpecBuilder { pub fn add_macro<N, O, B>(mut self, name: N, opts: Option<O>, body: B) -> Self where N: AsRef<str>, O: AsRef<str>, B: AsRef<str>, { let _macro = if let Some(opts) = opts { format!("{}({}) {}", name.as_ref(), opts.as_ref(), body.as_ref()) ...
pub fn render(&self) -> String { let summary = if let Some(summary) = &self.summary { summary.as_str() } else { "missing" }; let mut spec = format!( "Name: {}\nVersion: {}\nRelease: {}\nSummary: {}\n", self.name, ...
function_block-full_function
[ { "content": "/// Unpacks a given tar archive to the path specified by `output_dir`\n\npub fn unpack_tarball<T: io::Read, P: AsRef<Path>>(\n\n archive: &mut tar::Archive<T>,\n\n output_dir: P,\n\n) -> Result<()> {\n\n let output_dir = output_dir.as_ref();\n\n let span = info_span!(\"unpack-archive\"...
Rust
src/lexer.rs
default-username-852/human-resource-machine-compiler
60181585911efd7486bf90d96f51f3be089893e3
use lazy_static::lazy_static; use regex::Regex; use std::ops::Range; #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub enum Lexeme { Input, Output, LeftParentheses, RightParentheses, Plus, Equals, Loop, LeftCurlyBracket, RightCurlyBracket, Star, Comma, Semicolon, Numb...
use lazy_static::lazy_static; use regex::Regex; use std::ops::Range; #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub enum Lexeme { Input, Output, LeftParentheses, RightParentheses, Plus, Equals, Loop, LeftCurlyBracket, RightCurlyBracket, Star, Comma, Semicolon, Numb...
} #[derive(Debug)] pub enum Quantity { Finite(usize), Infinite, } #[derive(Debug)] pub enum DepthCriteria { Zero, OneOrMore, Any, } #[derive(Debug)] pub enum DepthType { Parentheses, CurlyBrackets, Both, } fn create_depth_table(tokens: &[Lexeme], deeper: Lexeme, shallower: Lexeme) -...
fn matches(&self, lexeme: &Lexeme, depth: i32) -> bool { self.0(lexeme) && match (self.1).0 { DepthCriteria::Zero => depth == 0, DepthCriteria::OneOrMore => depth >= 1, DepthCriteria::Any => true, } }
function_block-full_function
[ { "content": "type Syntax = (LexemePattern, Box<dyn Fn(Vec<Range<usize>>, &[Lexeme]) ->\n\n Result<AnyExpressionType, CompileError> + Send + Sync>);\n\n\n", "file_path": "src/parser.rs", "rank": 1, "score": 88352.38279423704 }, { "content": "fn create_label(num: &mut u8) -> String {\n\n ...
Rust
libtransact/src/families/smallbank/workload/mod.rs
peterschwarz/transact
a356d456aee65b1aa73a5cf397a72b504b27093e
/* * Copyright 2018 Intel Corporation * Copyright 2021 Cargill Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Un...
/* * Copyright 2018 Intel Corporation * Copyright 2021 Cargill Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Un...
.next_transaction() .expect("Unable to get txn pair"); let header = txn_pair.header(); assert!(header.dependencies().len() > 0); if header .dependencies() .iter() .any(|dep| !create_account_txn...
o_payload_builder() .map_err(|err| { InvalidStateError::with_message(format!( "Unable to convert execute action into sabre payload: {}", err )) })? .into_transaction_builder() .map_err(|err| { ...
random
[ { "content": "pub fn make_addresses(payload: &SmallbankTransactionPayload) -> Vec<String> {\n\n match payload.get_payload_type() {\n\n SBPayloadType::CREATE_ACCOUNT => vec![customer_id_address(\n\n payload.get_create_account().get_customer_id(),\n\n )],\n\n SBPayloadType::DEPO...
Rust
src/engine/youdao.rs
wfxr/clitrans
5a96846d7c56c786b74f02dd73986b1d70291995
use super::*; use itertools::Itertools; use regex::Regex; use scraper::{ElementRef, Html, Selector}; use structopt::lazy_static::lazy_static; #[derive(Clone)] pub struct Translator; impl Translate for Translator { fn translate(&self, query: &str) -> Result<Option<Translation>> { let uri = format_url!("htt...
use super::*; use itertools::Itertools; use regex::Regex; use scraper::{ElementRef, Html, Selector}; use structopt::lazy_static::lazy_static; #[derive(Clone)] pub struct Translator; impl Translate for Translator { fn translate(&self, query: &str) -> Result<Option<Translation>> { let uri = format_url!("htt...
fn parse_explanation_cn(detail: ElementRef) -> Vec<Explanation> { let mut exps = vec![]; let selector = Selector::parse("#phrsListTab > div.trans-container > ul > p").unwrap(); for record in detail.select(&selector) { let values = get_text(record, "span .search-js"); if values.is_empty() {...
map(|v| v.trim().to_owned()) .collect(); exps.push(Explanation { tag, items }); } } } exps }
function_block-function_prefix_line
[ { "content": "fn parse(url: &Uri, body: &str) -> Option<Translation> {\n\n let root = Html::parse_document(body);\n\n let content = get_element(\n\n &root,\n\n r#\"\n\n body\n\n .contentPadding\n\n .b_cards\n\n .b_cards\n\n .lf_area\n\n ...
Rust
src/linux/mod.rs
Rawnly/wallpaper.rs
feec35a5d914e2f3b563fb8ff6e56edbe8aa0c82
mod gnome; mod kde; mod lxde; mod xfce; use crate::{run, Mode, Result}; use enquote; use get_stdout; use std::{env, process::Command}; pub fn get() -> Result<String> { let desktop = env::var("XDG_CURRENT_DESKTOP").unwrap_or(Default::default()); if gnome::is_compliant(&desktop) { return gnome::get(); ...
mod gnome; mod kde; mod lxde; mod xfce; use crate::{run, Mode, Result}; use enquote; use get_stdout; use std::{env, process::Command}; pub fn get() -> Result<String> { let desktop = env::var("XDG_CURRENT_DESKTOP").unwrap_or(Default::default()); if gnome::is_compliant(&desktop) { return gnome::get(); ...
out[7..].into(); } Ok(stdout) }
lt<String> { let mut stdout = enquote::unquote(&get_stdout(command, args)?)?; if stdout.starts_with("file://") { stdout = std
function_block-random_span
[ { "content": "pub fn set(path: &str) -> Result<()> {\n\n run(\"pcmanfm\", &[\"-w\", path])\n\n}\n\n\n", "file_path": "src/linux/lxde.rs", "rank": 1, "score": 164161.58139132362 }, { "content": "/// Sets the wallpaper for KDE.\n\npub fn set(path: &str) -> Result<()> {\n\n eval(&format!(...
Rust
src/od/peekreader.rs
LuoZijun/coreutils
9b6f0b02e82b05cbe94d9b4c036e18bdb87b8042
use std::io; use std::io::{Read, Write}; use multifilereader::HasError; pub trait PeekRead { fn peek_read(&mut self, out: &mut [u8], peek_size: usize) -> io::Result<(usize, usize)>; } pub struct PeekReader<R> { inner: R, tem...
use std::io; use std::io::{Read, Write}; use multifilereader::HasError; pub trait PeekRead { fn peek_read(&mut self, out: &mut [u8], peek_size: usize) -> io::Result<(usize, usize)>; } pub struct PeekReader<R> { inner: R, tem...
} impl<R: HasError> HasError for PeekReader<R> { fn has_error(&self) -> bool { self.inner.has_error() } } #[cfg(test)] mod tests { use super::*; use std::io::{Cursor, Read}; #[test] fn test_read_normal() { let mut sut = PeekReader::new(Cursor::new(&b"abcdefgh"[..])); ...
self.write_to_tempbuffer(&out[real_size..bytes_in_buffer]); Ok((real_size, actual_peek_size)) } } } }
function_block-function_prefix_line
[ { "content": "fn write_tab_to_end<W: Write>(mut in_buf: &[u8], writer: &mut W) -> usize {\n\n loop {\n\n match in_buf\n\n .iter()\n\n .position(|c| *c == '\\n' as u8 || *c == '\\t' as u8)\n\n {\n\n Some(p) => {\n\n writer.write_all(&in_buf[..p]).u...
Rust
dao-utils/src/parts/mapping.rs
make-software/dao-contracts
aba3ed15d4c52ad411e6cd320f7daf1ef85715ac
use std::{ collections::{hash_map::DefaultHasher, BTreeMap}, hash::{Hash, Hasher}, marker::PhantomData, sync::Mutex, }; use casper_contract::{ contract_api::{runtime, storage}, unwrap_or_revert::UnwrapOrRevert, }; use casper_types::{ bytesrepr::{FromBytes, ToBytes}, CLTyped, Key, URef, ...
use std::{ collections::{hash_map::DefaultHasher, BTreeMap}, hash::{Hash, Hasher}, marker::PhantomData, sync::Mutex, }; use casper_contract::{ contract_api::{runtime, storage}, unwrap_or_revert::UnwrapOrRevert, }; use casper_types::{ bytesrepr::{FromBytes, ToBytes}, CLTyped, Key, URef, ...
pub fn get(&self, key: K, at: u32) -> Option<V> { self.mapping.get(&(key, at)) } pub fn get_or_none(&self, key: K, at: u32) -> Option<V> { self.mapping.get_or_none(&(key, at)) } pub fn get_or_revert(&self, key: K, at: u32) -> V { self.mapping.get_or_revert(&(key, at)) ...
pub fn replace(&self, key: K, at: u32, value: V) -> Result<(), Error> { let length = self.lengths.get(&key).unwrap_or(0); if at >= length { return Err(Error::MappingIndexDoesNotExist); } self.mapping.set(&(key, at), value); Ok(()) }
function_block-full_function
[ { "content": "/// Save value to the storage.\n\npub fn set_key<T: ToBytes + CLTyped>(name: &str, value: T) {\n\n match runtime::get_key(name) {\n\n Some(key) => {\n\n let key_ref = key.try_into().unwrap_or_revert();\n\n storage::write(key_ref, value);\n\n }\n\n None...
Rust
crates/trust/src/tcp.rs
rarescosma/eldiro
cb3c1db4da5be190f3e11351163de3b58c29362b
use std::io; pub enum State { Closed, SyncRcvd, Estab, } pub struct Connection { state: State, send: SendSequenceSpace, recv: RecvSequenceSpace, ip: etherparse::Ipv4Header, } struct SendSequenceSpace { una: u32, nxt: u32, wnd: u16, up: bool, ...
use std::io; pub enum State { Closed, SyncRcvd, Estab, } pub struct Connection { state: State, send: SendSequenceSpace, recv: RecvSequenceSpace, ip: etherparse::Ipv4Header, } struct SendSequenceSpace { una: u32, nxt: u32, wnd: u16, up: bool, ...
let mut syn_ack = etherparse::TcpHeader::new( tcph.destination_port(), tcph.source_port(), c.send.iss, c.send.wnd, ); syn_ack.acknowledgment_number = c.recv.nxt; syn_ack.syn = true; syn_ack.ack = true; c.ip.set_pa...
let mut c = Connection { state: State::SyncRcvd, send: SendSequenceSpace { iss, una: iss, nxt: iss + 1, wnd: 10, up: false, wl1: 0, wl2: 0, }, recv: RecvSequen...
assignment_statement
[ { "content": "fn take_while(accept: impl Fn(char) -> bool, s: &str) -> (&str, &str) {\n\n let take_end = s\n\n .char_indices()\n\n .find_map(|(idx, c)| if accept(c) { None } else { Some(idx) })\n\n .unwrap_or_else(|| s.len());\n\n (&s[take_end..], &s[..take_end])\n\n}\n\n\n", "fil...
Rust
src/converter.rs
Rodrigodd/audio-engine
c7ebfa7bef41662b94fb997e222760ead6ffd731
use super::SoundSource; use std::vec; #[cfg(test)] mod test { use crate::SoundSource; use super::SampleRateConverter; struct BufferSource { sample_rate: u32, channels: u16, buffer: Vec<i16>, i: usize, } impl SoundSource for BufferSource { fn channels(&sel...
use super::SoundSource; use std::vec; #[cfg(test)] mod test { use crate::SoundSource; use super::SampleRateConverter; struct BufferSource { sample_rate: u32, channels: u16, buffer: Vec<i16>, i: usize, } impl SoundSource for BufferSource { fn channels(&sel...
} len / self.inner.channels() as usize } else { unimplemented!("ChannelConventer only convert from 1 channel, or to 1 channel") } } } pub struct SampleRateConverter<T: SoundSource> { inner: T, output_sample_rate: u32, in_buffer: Box<[i...
if (i + 1) % self.inner.channels() as usize == 0 { buffer[i / self.inner.channels() as usize] = (sum / self.inner.channels() as i32) as i16; sum = 0; }
if_condition
[ { "content": "fn criterion_benchmark(c: &mut Criterion) {\n\n c.bench_function(\"ogg decoder\", |b| {\n\n b.iter(|| {\n\n let mut decoder =\n\n OggDecoder::new(Cursor::new(&include_bytes!(\"../examples/pipe.ogg\")[..]));\n\n while decoder.write_samples(&mut [0; 100...
Rust
src/bin/day07.rs
johannst/aoc2020
399293c7b1bf8a603d87321d50e27611c110cde0
use std::collections::{HashMap, HashSet, VecDeque}; use std::io; struct Node<'a> { col: &'a str, cnt: usize, } type Inner2Outer<'a> = HashMap<&'a str, HashSet<&'a str>>; type Outer2Inner<'a> = HashMap<&'a str, Vec<Node<'a>>>; fn parse_line<'a>(line: &'a str) -> io::Result<(&'a str, Vec<Node<'a>>)> { ...
use std::collections::{HashMap, HashSet, VecDeque}; use std::io; struct Node<'a> { col: &'a str, cnt: usize, } type Inner2Outer<'a> = HashMap<&'a str, HashSet<&'a str>>; type Outer2Inner<'a> = HashMap<&'a str, Vec<Node<'a>>>; fn parse_line<'a>(line: &'a str) -> io::Result<(&'a str,
hiny gold"); let mut inner_bags = 0; while let Some(bag) = queue.pop_front() { for node in &graph[bag] { inner_bags += node.cnt; for _ in 0..node.cnt { queue.push_back(node.col); } } } Ok(inner_bags) } fn main() -> io::Result<()> { ...
Vec<Node<'a>>)> { let outer_parser = regex::Regex::new(r"([a-z ]+) bags contain").unwrap(); let inner_parser = regex::Regex::new(r"(\d+) ([a-z ]+) bags?[,.]?").unwrap(); let outer = match outer_parser.captures(line) { Some(c) => c.get(1).expect("match outer_parser").as_str(), None => {...
random
[ { "content": "pub fn read_input_to_string(day: &str) -> String {\n\n let path = format!(\"{}/input/{}\", std::env!(\"CARGO_MANIFEST_DIR\"), day);\n\n match std::fs::read_to_string(&path) {\n\n Ok(input) => input,\n\n Err(e) => {\n\n println!(\"Failed to read input from '{}' with f...
Rust
profile/src/microphone/equalizer.rs
GoXLR-on-Linux/GoXLR-Utility
a3e46d3db524cbf54d4dcdd1d9549e87e587321d
use std::collections::HashMap; use std::os::raw::c_float; use std::str::FromStr; use xml::attribute::OwnedAttribute; #[derive(thiserror::Error, Debug)] #[allow(clippy::enum_variant_names)] pub enum ParseError { #[error("Expected int: {0}")] ExpectedInt(#[from] std::num::ParseIntError), #[error("Expected f...
use std::collections::HashMap; use std::os::raw::c_float; use std::str::FromStr; use xml::attribute::OwnedAttribute; #[derive(thiserror::Error, Debug)] #[allow(clippy::enum_variant_names)] pub enum ParseError { #[error("Expected int: {0}")] ExpectedInt(#[from] std::num::ParseIntError), #[error("Expected f...
pub fn parse_equaliser(&mut self, attributes: &[OwnedAttribute]) -> Result<(), ParseError> { for attr in attributes { if attr.name.local_name == "MIC_EQ_31.5HZ_GAIN" { self.eq_31h_gain = attr.value.parse::<c_float>()? as i8 } if attr.name.local_name == ...
0, eq_31h_freq: 31.5, eq_63h_freq: 63.0, eq_125h_freq: 125.0, eq_250h_freq: 250.0, eq_500h_freq: 500.0, eq_1k_freq: 1000.0, eq_2k_freq: 2000.0, eq_4k_freq: 4000.0, eq_8k_freq: 8000.0, eq_16k_freq: 160...
function_block-function_prefixed
[ { "content": "#[allow(clippy::comparison_chain)]\n\npub fn version_newer_or_equal_to(version: &VersionNumber, comparison: VersionNumber) -> bool {\n\n if version.0 > comparison.0 {\n\n return true;\n\n } else if version.0 < comparison.0 {\n\n return false;\n\n }\n\n\n\n if version.1 > ...
Rust
src/generate.rs
danpalmer/vector
b3554b16fa333727e21c8eaae87df4533e217c96
use crate::topology::config::{ component::ExampleError, GlobalOptions, SinkDescription, SourceDescription, TransformDescription, }; use indexmap::IndexMap; use serde::Serialize; use std::collections::BTreeMap; use structopt::StructOpt; use toml::Value; #[derive(StructOpt, Debug)] #[structopt(rename_all = "keba...
use crate::topology::config::{ component::ExampleError, GlobalOptions, SinkDescription, SourceDescription, TransformDescription, }; use indexmap::IndexMap; use serde::Serialize; use std::collections::BTreeMap; use structopt::StructOpt; use toml::Value; #[derive(StructOpt, Debug)] #[structopt(rename_all = "keba...
0 { Some(source_names.clone()) } else { None } }) .unwrap_or(vec!["TODO".to_owned()]), buffer: crate::buffers::BufferConfig::default...
function_block-function_prefixed
[ { "content": "// Splits the given input by a separator.\n\n// If the separator is `None`, then it will split on whitespace.\n\npub fn split(input: &str, separator: Option<String>) -> Vec<&str> {\n\n match separator {\n\n Some(separator) => input.split(&separator).collect(),\n\n None => input.sp...
Rust
memapi/src/flamegraph.rs
PLNech/filprofiler
812a750b7fe608adb25f4b9f09cce766b223e377
use std::{fs, io::Write, path::Path}; use inferno::flamegraph; use itertools::Itertools; pub fn filter_to_useful_callstacks<'i, K, I>( samples: I, total_samples: usize, ) -> impl Iterator<Item = (K, usize)> where K: Eq + std::hash::Hash + 'i, I: Iterator<Item = (K, &'i usize)>, { samples ....
use std::{fs, io::Write, path::Path}; use inferno::flamegraph; use itertools::Itertools; pub fn filter_to_useful_callstacks<'i, K, I>( samples: I, total_samples: usize, ) -> impl Iterator<Item = (K, usize)> where K: Eq + std::hash::Hash + 'i, I: Iterator<Item = (K, &'i usize)>, { samples ....
pub fn write_flamegraph<I: IntoIterator<Item = String>>( lines: I, path: &Path, reversed: bool, title: &str, subtitle: &str, count_name: &str, to_be_post_processed: bool, ) -> Result<(), Box<dyn std::error::Error>> { let flamegraph = get_flamegraph( lines, reversed, ...
pub fn write_lines<I: IntoIterator<Item = String>>(lines: I, path: &Path) -> std::io::Result<()> { let mut file = std::fs::File::create(path)?; for line in lines { file.write_all(line.as_bytes())?; file.write_all(b"\n")?; } file.flush()?; Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Create a new hashmap with an optional fixed seed.\n\npub fn new_hashmap<K, V>() -> HashMap<K, V, ARandomState> {\n\n match *HASH_SEED {\n\n Some(seed) => {\n\n HashMap::with_hasher(ARandomState::with_seeds(seed, seed + 1, seed + 2, seed + 3))\n\n }\n\n None =...
Rust
src/mlr003/operate/downlink.rs
Micropelt-EH4/micropelt
9b18c1a799e527e268ec82b195d7a537a6c48537
use std::fmt; use std::io::{Error, ErrorKind, Result}; use crate::{lorawan, PortPayload}; use super::super::set_value::SetValue; use super::super::utils::{close, Port}; const DOWNLINK_N_BYTES: usize = 6; #[derive(Clone, Debug)] pub struct Downlink { pub user_value: SetValue, pub room_temperature: f32, p...
use std::fmt; use std::io::{Error, ErrorKind, Result}; use crate::{lorawan, PortPayload}; use super::super::set_value::SetValue; use super::super::utils::{close, Port}; const DOWNLINK_N_BYTES: usize = 6; #[derive(Clone, Debug)] pub struct Downlink { pub user_value: SetValue, pub room_temperature: f32, p...
} fn safety_mode_to_bin(input: &SetValue) -> u8 { match input { SetValue::AmbientTemperature(_) => 0, SetValue::FlowTemperature(_) => 1, SetValue::ValvePosition(_) => 2, } } fn offset_comp_to_bin(input: i8) -> Result<u8> { let output = match input { -8 => 8, -7 => ...
match input { SetValue::ValvePosition(_) => 0, SetValue::FlowTemperature(_) => 1, SetValue::AmbientTemperature(_) => 2, }
if_condition
[ { "content": "pub fn bin_to_bool(input: u8) -> Result<bool> {\n\n match input {\n\n 0 => Ok(false),\n\n 1 => Ok(true),\n\n _ => Err(Error::new(\n\n ErrorKind::InvalidData,\n\n format!(\"A bit should only be 0 or 1, got {input}\"),\n\n )),\n\n }\n\n}\n\n\n"...
Rust
src/radio_mock.rs
bootstrap-prime/sx127x_lora
53fa9955863478bcb68039d56bba83808e4e4740
use crate::EmbeddedRadio; use crossbeam::channel; use embedded_hal::blocking::delay::DelayMs; #[derive(Debug)] pub enum LoraError<RX, TX> { Receiver(RX), Transmitter(TX), } type RadioBuffer = heapless::Vec<u8, 255>; pub struct MockLora { rx: channel::Receiver<RadioBuffer>, tx: Vec<channel::Sender<Rad...
use crate::EmbeddedRadio; use crossbeam::channel; use embedded_hal::blocking::delay::DelayMs; #[derive(Debug)] pub enum LoraError<RX, TX> { Receiver(RX), Transmitter(TX), } type RadioBuffer = heapless::Vec<u8, 255>; pub struct MockLora { rx: channel::Receiver<RadioBuffer>, tx: Vec<channel::Sender<Rad...
} impl EmbeddedRadio for MockLora { type Error = LoraError<channel::RecvError, channel::SendError<RadioBuffer>>; fn transmit_payload(&mut self, payload: &[u8]) -> Result<(), Self::Error> { let mut buffer: RadioBuffer = heapless::Vec::new(); for &payload_byte in payload.iter().take(255) { ...
s .iter() .map(|self_antenna| { let txs = radios_antennas_reference .iter() .filter(|e| e.0 != self_antenna.0) .map(|radio_ref| radio_ref.1 .0.clone()) .collect(); MockLora { ...
function_block-function_prefixed
[ { "content": "#[cortex_m_rt::entry]\n\nfn main() -> ! {\n\n let cp = cortex_m::Peripherals::take().unwrap();\n\n let p = pac::Peripherals::take().unwrap();\n\n\n\n let rcc = p.RCC.constrain();\n\n let clocks = rcc.cfgr.sysclk(MegaHertz(64)).pclk1(MegaHertz(32)).freeze();\n\n\n\n let gpioa = p.GPI...
Rust
cywad-webkit/src/lib.rs
estin/cywad
d715e08edd3ae8d4288d0010a958328e26a75dac
use std::io::Cursor; use std::sync::{Arc, Mutex}; use cairo::{Context, Format, ImageSurface}; use gtk::{ prelude::BuilderExtManual, prelude::Continue, Builder, ContainerExt, GtkWindowExt, Inhibit, WidgetExt, Window, WindowType, }; use webkit2gtk::{ CookieManagerExt, SettingsExt, TLSErrorsPolicy, WebContext...
use std::io::Cursor; use std::sync::{Arc, Mutex}; use cairo::{Context, Format, ImageSurface}; use gtk::{ prelude::BuilderExtManual, prelude::Continue, Builder, ContainerExt, GtkWindowExt, Inhibit, WidgetExt, Window, WindowType, }; use webkit2gtk::{ CookieManagerExt, SettingsExt, TLSErrorsPolicy, WebContext...
fn execute_step( execution_context: &Arc<Mutex<ExecutionContext>>, webview: &WebView, ) -> Result<ExecutionResult, Error> { let step = { let guard = execution_context.try_lock(); if guard.is_err() { warn!("Execution context locked by previous iteration...skip..."); ...
fn get_screenshot(webview: &WebView) -> Result<Vec<u8>, Error> { let vec = Vec::new(); let mut c = Cursor::new(vec); let allocation = webview.get_allocation(); let surface = ImageSurface::create(Format::ARgb32, allocation.width, allocation.height) .map_err(|_| anyhow!("Unable create surface"))?;...
function_block-function_prefix_line
[ { "content": "#[derive(Debug)]\n\nstruct MockServerInfo {\n\n url: String,\n\n}\n\n\n\nlazy_static! {\n\n static ref MOCK_SERVER_STATE: Mutex<MockServerState> = {\n\n Mutex::new(MockServerState {\n\n base_url: None,\n\n is_running: false,\n\n test_index: 0,\n\n ...
Rust
lib/src/common/mod.rs
trueagi-io/hyperon-experimental
50c2f136fb992880a2ecb104e279bbf9b31c53f1
pub mod plan; pub mod collections; mod arithmetics; pub use arithmetics::*; use crate::*; use std::cell::RefCell; use std::fmt::{Debug, Display}; use crate::metta::metta_atom; pub fn init_logger(is_test: bool) { let _ = env_logger::builder().is_test(is_test).try_init(); } pub struct Operation { pub name: &'...
pub mod plan; pub mod collections; mod arithmetics; pub use arithmetics::*; use crate::*; use std::cell::RefCell; use std::fmt::{Debug, Display}; use crate::metta::metta_atom; pub fn init_logger(is_test: bool) { let _ = env_logger::builder().is_test(is_test).try_init(); } pub struct Operation { pub name: &'...
}
f let (Some(refa), Some(refc)) = (opa.as_gnd::<&Operation>(), opc.as_gnd::<&Operation>()) { let ptra: *const Operation = *refa; let ptrc: *const Operation = *refc; assert_eq!(ptra, ptrc); } else { assert!(false); } }
function_block-function_prefixed
[ { "content": "fn check_type(args: &mut Vec<Atom>, op: fn(&Atom) -> bool) -> Result<Vec<Atom>, String> {\n\n let arg = args.get(0).ok_or_else(|| format!(\"Unary operation called without arguments\"))?; \n\n Ok(vec![Atom::value(op(arg))])\n\n}\n\n\n", "file_path": "lib/src/common/arithmetics.rs", "r...
Rust
server/src/fhir/definitions/coverage.rs
gematik/ref-eRp-FD-Server
94d6245829a08d03c8d872ba71c5d8cae0d9dccf
/* * Copyright (c) 2021 gematik GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
/* * Copyright (c) 2021 gematik GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
odeStream<S>) -> Result<(), EncodeError<S::Error>> where S: DataStorage, { let ident = self .value .as_ref() .map(|ident| (ident, self.alternative_id.as_ref())); stream .element()? .encode_opt("identifier", ident, encode_identi...
stream.end().await?; stream.end_substream().await?; } Ok(Extension { special_group, dmp_mark, insured_type, wop, }) } } #[async_trait(?Send)] impl Decode for Payor { async fn decode<S>(stream: &mut DecodeStream<S>) -> Resul...
random
[ { "content": "fn encode_for<S>(value: &Kvnr, stream: &mut EncodeStream<S>) -> Result<(), EncodeError<S::Error>>\n\nwhere\n\n S: DataStorage,\n\n{\n\n stream\n\n .element()?\n\n .encode(\"identifier\", value, encode_identifier)?\n\n .end()?;\n\n\n\n Ok(())\n\n}\n\n\n\npub const PROF...
Rust
tests/assert_eq.rs
spenserblack/rust-pretty-assertions
3f26a079e97276c335bd525942aa9eb9c3c47a5b
#[allow(unused_imports)] use pretty_assertions::{assert_eq, assert_ne}; extern crate difference; #[test] #[should_panic(expected = r#"assertion failed: `(left == right)` Diff < left / right > : Some( Foo { < lorem: "Hello World!...
#[allow(unused_imports)] use pretty_assertions::{assert_eq, assert_ne}; extern crate difference; #[test] #[should_panic(expected = r#"assertion failed: `(left == right)` Diff < left / right > : Some( Foo { < lorem: "Hello World!...
#[test] #[should_panic( expected = r#"assertion failed: `(left == right)`: custom panic message Diff < left / right > : Some( Foo { < lorem: "Hello World!", > lorem: "Hello Wr...
struct Foo { lorem: &'static str, ipsum: u32, dolor: Result<String, String>, } let x = Some(Foo { lorem: "Hello World!", ipsum: 42, dolor: Ok("hey".to_string()), }); let y = Some(Foo { lorem: "Hello Wrold!", ipsum: 42, dolor: Ok("h...
function_block-function_prefix_line
[]
Rust
sqlx-core/src/mysql/executor.rs
Istar-Eldritch/sqlx
f2ca42256badc2dc5d47c18c78aa1c9928ce63dd
use futures_core::future::BoxFuture; use crate::cursor::Cursor; use crate::describe::{Column, Describe}; use crate::executor::{Execute, Executor, RefExecutor}; use crate::mysql::protocol::{ self, ColumnDefinition, ComQuery, ComStmtExecute, ComStmtPrepare, ComStmtPrepareOk, FieldFlags, Status, }; use crate::mys...
use futures_core::future::BoxFuture; use crate::cursor::Cursor; use crate::describe::{Column, Describe}; use crate::executor::{Execute, Executor, RefExecutor}; use crate::mysql::protocol::{ self, ColumnDefinition, ComQuery, ComStmtExecute, ComStmtPrepare, ComStmtPrepareOk, FieldFlags, Status, }; use crate::mys...
fn fetch<'q, E>(&mut self, query: E) -> MySqlCursor<'_, 'q> where E: Execute<'q, Self::Database>, { MySqlCursor::from_connection(self, query) } #[doc(hidden)] fn describe<'e, 'q, E: 'e>( &'e mut self, query: E, ) -> BoxFuture<'e, crate::Result<MySql, Descri...
e>( &'c mut self, query: E, ) -> BoxFuture<'e, crate::Result<MySql, u64>> where E: Execute<'q, Self::Database>, { Box::pin(async move { let (query, arguments) = query.into_parts(); self.run(query, arguments).await?; self.affected_rows().aw...
function_block-function_prefixed
[ { "content": "fn parse_row_description(rd: RowDescription) -> (HashMap<Box<str>, usize>, Vec<TypeFormat>) {\n\n let mut columns = HashMap::new();\n\n let mut formats = Vec::new();\n\n\n\n columns.reserve(rd.fields.len());\n\n formats.reserve(rd.fields.len());\n\n\n\n for (index, field) in rd.fiel...
Rust
src/data_structure/wavelet_matrix.rs
noshi91/n91lib_rs
c9bd9cf36cbf4637884a049a4fe44f45b06ff71f
/* References [1] Claude, F., Navarro, G., & Ordónez, A. (2015). The wavelet matrix: An efficient wavelet tree for large alphabets. Information Systems, 47, 15-32. [2] Gagie, T., Puglisi, S. J., & Turpin, A. (2009, August). Range quantile queries: Another virtue of wavelet trees. In International Sym...
/* References [1] Claude, F., Navarro, G., & Ordónez, A. (2015). The wavelet matrix: An efficient wavelet tree for large alphabets. Information Systems, 47, 15-32. [2] Gagie, T., Puglisi, S. J., & Turpin, A. (2009, August). Range quantile queries: Another virtue of wavelet trees. In International Sym...
ret |= 1 << l; index = z + v.rank1(index); } } ret } pub fn rank(&self, value: usize, mut range: Range<usize>) -> usize { for (l, &(z, ref v)) in self.base_iter().rev() { if !access(value, l) { range.start = v.rank0(range.start); ...
().rev() { if !v.access(index) { index = v.rank0(index); } else {
function_block-random_span
[ { "content": "fn cascade_up_end<T: Ord>(data: &mut [T], mut index: usize) {\n\n while index != 1 {\n\n let parent = index / 2 - 1 | 1;\n\n if data[parent] >= data[index] {\n\n break;\n\n }\n\n data.swap(parent, index);\n\n index = parent;\n\n }\n\n}\n\n\n", ...
Rust
rust/app/src/handlers/legacy/signing.rs
Zondax/ledger-tezos
ac5b6fab1c5d093bb9f8edf3f8a1e3b30ab359be
/******************************************************************************* * (c) 2021 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/lic...
/******************************************************************************* * (c) 2021 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/lic...
v: u8 = curve.into(); let path = BIP32Path::<10>::new(path.iter().map(|n| 0x8000_0000 + n)) .unwrap() .serialize(); buffer[3] = crv; buffer[4] = path.len() as u8; buffer[5..5 + path.len()].copy_from_slice(path.as_slice()); path.len() } #[test] ...
ler for LegacySignWithHash { #[inline(never)] fn handle<'apdu>( flags: &mut u32, tx: &mut u32, buffer: ApduBufferRead<'apdu>, ) -> Result<(), Error> { use crate::handlers::baking::Baking; if let Some(upload) = Uploader::new(Baking).upload(&buffer)? { *tx ...
random
[ { "content": "pub fn handle_apdu(flags: &mut u32, tx: &mut u32, rx: u32, apdu_buffer: &mut [u8]) {\n\n crate::sys::zemu_log_stack(\"handle_apdu\\x00\");\n\n\n\n //construct reader\n\n let status_word = match ApduBufferRead::new(apdu_buffer, rx) {\n\n Ok(reader) => match apdu_dispatch(flags, tx, ...
Rust
bindings/python/src/lib.rs
sthagen/jsonschema-rs
5da86850abce159abb803663653c7bd1dd079c6a
#![warn( clippy::doc_markdown, clippy::redundant_closure, clippy::explicit_iter_loop, clippy::match_same_arms, clippy::needless_borrow, clippy::print_stdout, clippy::integer_arithmetic, clippy::cast_possible_truncation, clippy::map_unwrap_or, clippy::unseparated_literal_suffix, ...
#![warn( clippy::doc_markdown, clippy::redundant_closure, clippy::explicit_iter_loop, clippy::match_same_arms, clippy::needless_borrow, clippy::print_stdout, clippy::integer_arithmetic, clippy::cast_possible_truncation, clippy::map_unwrap_or, clippy::unseparated_literal_suffix, ...
fn make_options( draft: Option<u8>, with_meta_schemas: Option<bool>, ) -> PyResult<jsonschema::CompilationOptions> { let mut options = jsonschema::JSONSchema::options(); if let Some(raw_draft_version) = draft { options.with_draft(get_draft(raw_draft_version)?); } if with_meta_schemas =...
fn get_draft(draft: u8) -> PyResult<Draft> { match draft { DRAFT4 => Ok(jsonschema::Draft::Draft4), DRAFT6 => Ok(jsonschema::Draft::Draft6), DRAFT7 => Ok(jsonschema::Draft::Draft7), _ => Err(exceptions::PyValueError::new_err(format!( "Unknown draft: {}", draft...
function_block-full_function
[ { "content": "#[inline]\n\nfn is_enum_subclass(object_type: *mut pyo3::ffi::PyTypeObject) -> bool {\n\n unsafe { (*(object_type.cast::<ffi::PyTypeObject>())).ob_type == types::ENUM_TYPE }\n\n}\n\n\n", "file_path": "bindings/python/src/ser.rs", "rank": 1, "score": 228584.92748448713 }, { "...
Rust
crate-wasm/src/lib.rs
jweissman/rust-mandelbrot-set
c2428ddf013067f6830c6a5dd23e8c3d4ead8215
mod utils; use wasm_bindgen::prelude::*; use itertools_num::linspace; use num::complex::Complex64; use std::f64::consts; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; fn get_escape_time( x: f64, y: f64, max_iterations: u32, escape_rad...
mod utils; use wasm_bindgen::prelude::*; use itertools_num::linspace; use num::complex::Complex64; use std::f64::consts; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; fn get_escape_time( x: f64, y: f64, max_iterations: u32, escape_rad...
#[wasm_bindgen] pub fn get_tile(x: u32, y: u32, z: u32, max_iterations: u32, is_smoothed: bool, exponent: u32) -> Vec<u8> { let image_data = generate_image( x as f64, y as f64, (z as f64) - 2.0, max_iterations, is_smoothed, exponent, ); image_data.to_vec()...
enumerate(); let im_range = linspace(im_min, im_max, size as usize).enumerate(); let scaled_max_iterations = (max_iterations * 20) as usize; let black = [0, 0, 0]; let escape_radius = if is_smoothed { 3.0 } else { 2.0 }; for (x, im) in im_range { for (y, re) in re_range.clone() { ...
function_block-function_prefixed
[ { "content": "pub fn init() {\n\n set_panic_hook();\n\n}\n", "file_path": "crate-wasm/src/utils.rs", "rank": 2, "score": 50391.183241408624 }, { "content": "use cfg_if::cfg_if;\n\n\n\ncfg_if! {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `se...
Rust
src/bin/consensus.rs
tkerber/pistis-impl
9a8ab489759c9fcef360152d3483bce452b84fb5
use rand::distributions::Distribution; use rand::rngs::SmallRng; use rand::{thread_rng, Rng, SeedableRng}; use rand_distr::Exp; use rayon::prelude::*; use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::{create_dir_all, File}; use std::io::{stdout, Write}; const BASE_ITER: usize = 1_000; ...
use rand::distributions::Distribution; use rand::rngs::SmallRng; use rand::{thread_rng, Rng, SeedableRng}; use rand_distr::Exp; use rayon::prelude::*; use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::{create_dir_all, File}; use std::io::{stdout, Write}; const BASE_ITER: usize = 1_000; ...
15_000.0 * b, &mut rng(), ); print!("."); stdout().flush().unwrap(); (b, confs.iter().map(|c| exp.conf(*c)).collect::<Vec<_>>()) }) .collect::<Vec<_>>(); let mut fs = confs .i...
.sample(rng), ); } ConsensusParameters { honest_presample, adv_presample, } } fn honest_time<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { self.honest_presample [rng.next_u32() as usize & ((1 << PRESAMPLE_BITS)...
random
[ { "content": "fn bench_prove_all(c: &mut Criterion) {\n\n let mut fischlin = c.benchmark_group(\"prove Fischlin\");\n\n fischlin.bench_function(\"G1\", bench_prove::<G1Affine, Fischlin<G1Affine>>);\n\n fischlin.bench_function(\"G2\", bench_prove::<G2Affine, Fischlin<G2Affine>>);\n\n fischlin.finish(...
Rust
src/unwind.rs
nikodemus/foolang
f8d824a8d7ef5ef828911a8b4d0d6419ad29bf6e
use std::fmt; use crate::eval::EnvRef; use crate::objects::Object; use crate::source_location::SourceLocation; #[cfg(test)] use crate::source_location::Span; trait LineIndices { fn line_indices(&self) -> Vec<(usize, &str)>; } impl LineIndices for str { fn line_indices(&self) -> Vec<(usize, &str)> { ...
use std::fmt; use crate::eval::EnvRef; use crate::objects::Object; use crate::source_location::SourceLocation; #[cfg(test)] use crate::source_location::Span; trait LineIndices { fn line_indices(&self) -> Vec<(usize, &str)>; } impl LineIndices for str { fn line_indices(&self) -> Vec<(usize, &str)> { ...
fn start(&self) -> usize { if let Some(source_location) = &self.source_location { source_location.get_span().start } else { panic!("Expected Location with source location") } } fn end(&self) -> usize { if let Some(source_location) = &self.source_loc...
ontext(&self) -> String { match &self.context { None => "".to_string(), Some(ctx) => ctx.clone(), } }
function_block-function_prefixed
[ { "content": "pub fn unsafe_write_instance_variable(receiver: &Object, value: &Object, index: usize) -> Eval {\n\n let instance = receiver.instance()?;\n\n instance.instance_variables.borrow_mut()[index] = value.clone();\n\n Ok(value.clone())\n\n}\n\n\n", "file_path": "src/objects.rs", "rank": ...
Rust
src/midi/device.rs
Mossop/MidiCtrl
24a557ae5a535900fa9e6f6c12b01452d1deb534
use std::{ collections::{HashMap, HashSet}, error::Error, path::Path, sync::mpsc::Sender, }; use midi_control::MidiMessage; use midir::{MidiInput, MidiInputConnection, MidiOutput, MidiOutputConnection, MidiOutputPort}; use serde::Deserialize; use crate::{utils::iter_json, ControlMessage}; use super::...
use std::{ collections::{HashMap, HashSet}, error::Error, path::Path, sync::mpsc::Sender, }; use midi_control::MidiMessage; use midir::{MidiInput, MidiInputConnection, MidiOutput, MidiOutputConnection, MidiOutputPort}; use serde::Deserialize; use crate::{utils::iter_json, ControlMessage}; use super::...
} pub fn is_connected(&self) -> bool { self.connection.is_some() } fn handle_message<'a>( device_id: String, message: MidiMessage, sender: &Sender<ControlMessage>, controls: &'a Vec<Control>, ) -> Result<(), Box<dyn Error + 'a>> { match &message { ...
Ok(Device { connection, port: config.port.clone(), output, controls: config .controls .into_iter() .map(|control| (String::from(control.name()), control)) .collect(), })
call_expression
[ { "content": "fn open_incoming_stream(port: u16, sender: Sender<IncomingMessage>) -> Result<bool, String> {\n\n let stream = match open_stream(port)? {\n\n Some(stream) => stream,\n\n None => {\n\n log::warn!(\"Unable to connect for 10 seconds, giving up\");\n\n return Ok(...
Rust
solution/verifiable_confidential_ledger/src/main.rs
pro1515151515/WeDPR-Lab-Core
7320df2fb907ce3671e475e058286cc1c7798d47
use colored::*; use std; use wedpr_l_crypto_zkp_utils::point_to_bytes; use wedpr_s_verifiable_confidential_ledger::vcl; fn main() { print_highlight2( "#\n# Welcome to verifiable confidential ledger (VCL) demo!", "# 欢迎来到公开可验证密文账本demo演示!\n#", ); println!(); print_alert2( "Pleas...
use colored::*; use std; use wedpr_l_crypto_zkp_utils::point_to_bytes; use wedpr_s_verifiable_confidential_ledger::vcl; fn main() { print_highlight2( "#\n# Welcome to verifiable confidential ledger (VCL) demo!", "# 欢迎来到公开可验证密文账本demo演示!\n#", ); println!(); print_alert2( "Pleas...
fn print_highlight(message: &str) { println!("{}", message.green()); } fn print_highlight2(message1: &str, message2: &str) { println!("{}\n{}", message1.green(), message2.green()); } fn print_alert(message: &str) { println!("{}", message.yellow()); } fn print_alert2(message1: &str, message2: &str) { ...
print_alert("✗ Fail: c1_value * c2_value != c3_value"); } let meet_range_constraint = vcl::verify_range(&c1_credit, &range_proof_c1); if meet_range_constraint { print_highlight("✓ Pass: c1_value >= 0"); } else { print_alert("✗ Fail: c1_value < 0"); } pause_en(); print_highli...
function_block-function_prefix_line
[ { "content": "/// Verifies whether the value embedded in a confidential credit record belongs\n\n/// to (0, 2^RANGE_SIZE_IN_BITS - 1].\n\npub fn verify_range(c1: &ConfidentialCredit, proof: &[u8]) -> bool {\n\n wedpr_l_crypto_zkp_range_proof::verify_value_range(&c1.get_point(), proof)\n\n}\n\n\n\n#[cfg(test)...
Rust
cpu/src/clock.rs
gfedorkow/TX-2-Instruction-Simulator
c81badfe494acc6f86343d708fa4751b2711f9a8
use std::thread::sleep; use std::time::{Duration, Instant}; use tracing::{event, Level}; pub trait Clock { fn now(&self) -> Duration; fn consume(&mut self, inteval: &Duration); } #[derive(Debug)] pub struct BasicCloc...
use std::thread::sleep; use std::time::{Duration, Instant}; use tracing::{event, Level}; pub trait Clock { fn now(&self) -> Duration; fn consume(&mut self, inteval: &Duration); } #[derive(Debug)] pub struct BasicCloc...
or ); match self.sleep_owed.checked_sub(slept_for) { Some(remainder) => { self.sleep_owed = remainder; } None => { panic!("MinimalSleeper::really_sleep: overflow in sleep_owed"); ...
ep(&mut self) { match self.sleep_owed { SignedDuration { negative: false, magnitude, } => { let then = Instant::now(); event!(Level::DEBUG, "Sleeping for {:?}...", self.sleep_owed); sleep(magnitude); ...
function_block-random_span
[ { "content": "/// The `Inst` trait provides a way to extract the various fields\n\n/// within an instruction.\n\npub trait Inst {\n\n /// Obtain the value of the \"hold\" bit.\n\n fn is_held(&self) -> bool;\n\n\n\n /// Fetch the configuration field of the instruction. This is\n\n /// used as an ind...
Rust
lib/src/config/dictionaries.rs
djKooks/Viceroy
6462271f1c9176f79ac059cc87bfdde61d65ac62
use std::{collections::HashMap, fmt, path::PathBuf}; #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub struct DictionaryName(String); impl fmt::Display for DictionaryName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl DictionaryName { pub fn new(name: Str...
use std::{collections::HashMap, fmt, path::PathBuf}; #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub struct DictionaryName(String); impl fmt::Display for DictionaryName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl DictionaryName { pub fn new(name: Str...
toml.into_iter() .map(process_entry) .collect::<Result<_, _>>() .map(Self) } } fn parse_dict_as_json(name: &str, data: &str) -> Result<(), DictionaryConfigError> { let json: serde_json::Value = serde_json::from_str(data).map_err(|_| ...
l .remove("format") .ok_or(DictionaryConfigError::MissingFormat) .and_then(|format| match format { Value::String(format) => Ok(format.parse()?), _ => Err(DictionaryConfigEr...
function_block-function_prefixed
[]
Rust
northstar/src/runtime/mount.rs
alfonsoros88/northstar
b38d89a6498dcf4f2f5d6ee8d65a490f50c74836
use super::{ config::Config, device_mapper as dm, device_mapper, loopdev::{losetup, LoopControl}, state::{Container, Repository}, }; use bitflags::_core::str::Utf8Error; use floating_duration::TimeAsFloat; use log::{debug, info}; pub use nix::mount::MsFlags as MountFlags; use npk::{dm_verity::VerityHe...
use super::{ config::Config, device_mapper as dm, device_mapper, loopdev::{losetup, LoopControl}, state::{Container, Repository}, }; use bitflags::_core::str::Utf8Error; use floating_duration::TimeAsFloat; use log::{debug, info}; pub use nix::mount::MsFlags as MountFlags; use npk::{dm_verity::VerityHe...
} async fn verity_setup( &self, dev: &str, verity: &VerityHeader, name: &str, verity_hash: &str, size: u64, ) -> Result<PathBuf, Error> { debug!("Creating a read-only verity device (name: {})", &name); let start = time::Instant::now(); ...
Ok(PathBuf::from(format!( "{}{}", self.device_mapper_dev, dm_device.id() & 0xFF )))
call_expression
[ { "content": "/// Get the cgroup v1 controller hierarchy mount point\n\nfn mount_point(controller: &str) -> Result<PathBuf, Error> {\n\n let controller = controller.to_owned();\n\n MountIter::new()\n\n .map_err(Error::MountInfo)?\n\n .filter_map(Result::ok)\n\n .find(|m| m.fstype == \...
Rust
src/lib.rs
DefunctLizard/libretranslate-rs
ae3d9f37b18d32885ca5a690b9166e56d0383b6a
use serde_json::Value; #[derive(Debug, Clone, PartialEq, Hash)] pub struct Translation { pub url: String, pub source: Language, pub target: Language, pub input: String, pub output: String, } pub async fn translate<T: AsRef<str>>( source: Language, target: Language, input: T, key:...
use serde_json::Value; #[derive(Debug, Clone, PartialEq, Hash)] pub struct Translation { pub url: String, pub source: Language, pub target: Language, pub input: String, pub output: String, } pub async fn translate<T: AsRef<str>>( source: Language, target: Language, input: T, key:...
fn from_lang(&self, language: Language) -> Query { Query { url: "https://libretranslate.com/", text: self.as_ref(), source: language, target: Language::default(), } } } #[derive(Debug, Clone, PartialEq, Hash)] pub struct TranslationBuilder { ...
e.com/", text: self.as_ref(), source: Language::Detect, target: language, } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let lang = Language::English;\n\n let lang_parse = \"english\".parse::<Language>().unwrap();\n\n\n\n assert_eq!(lang, lang_parse);\n\n assert_eq!(\"en\", lang.as_code());\n\n assert_eq!(\"English\", lang.as_pretty());\n\n}\n", "file_path": "examples/language.rs",...
Rust
amethyst_assets/src/dyn_format.rs
Lknechtli/amethyst
2b7831ade1183e39d335e4eaf664c905ab90f183
use crate::SerializableFormat; use serde::{ de::{self, DeserializeSeed, Expected, SeqAccess, Visitor}, ser::{Serialize, SerializeTupleStruct, Serializer}, Deserialize, Deserializer, }; use std::{collections::BTreeMap, marker::PhantomData}; pub trait FormatRegisteredData: 'static { #[doc(hidden)]...
use crate::SerializableFormat; use serde::{ de::{self, DeserializeSeed, Expected, SeqAccess, Visitor}, ser::{Serialize, SerializeTupleStruct, Serializer}, Deserialize, Deserializer, }; use std::{collections::BTreeMap, marker::PhantomData}; pub trait FormatRegisteredData: 'static { #[doc(hidden)]...
; seq.next_element_seed(FnApply { deserialize_fn })? .ok_or_else(|| de::Error::invalid_length(1, &self)) } } impl<D: FormatRegisteredData> Serialize for dyn SerializableFormat<D> { fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> { let mut se...
match seq.next_element_seed(seq_lookup)? { Some(deserialize_fn) => deserialize_fn, None => { return Err(de::Error::custom("expected tagged Format")); } }
if_condition
[ { "content": "type FnState<T, E> = SendBoxFnOnce<'static, (), Box<dyn State<T, E>>>;\n\n\n\n/// Screen width used in predefined display configuration.\n\npub const SCREEN_WIDTH: u32 = 800;\n\n/// Screen height used in predefined display configuration.\n\npub const SCREEN_HEIGHT: u32 = 600;\n\n/// The ratio betw...
Rust
map_types/src/storage.rs
RobinMarchart/map
4cbd2166b088656ca6c767ef770922122bb2dc55
use std::{collections::HashMap, error::Error, fmt::Display}; use crate::{ChangeMessage, Position}; use futures::Future; use petgraph::graph::{DiGraph, NodeIndex}; use std::borrow::Borrow; #[derive(Debug, Clone)] pub struct NoSuchBranch { branch: (String, String), } impl From<(String, String)> for NoSuchBranch { ...
use std::{collections::HashMap, error::Error, fmt::Display}; use crate::{ChangeMessage, Position}; use futures::Future; use petgraph::graph::{DiGraph, NodeIndex}; use std::borrow::Borrow; #[derive(Debug, Clone)] pub struct NoSuchBranch { branch: (String, String), } impl From<(String, String)> for NoSuchBranch { ...
Err(e) => return Err(e), }, }; } } } else { return Err(StoreError::Branch(NoSuchBranch::from(b.clone()))); } } }
let branch_p = self.backend.set_branch(b, m.sha256); self.branches .get_mut(b) .expect("just tested") .copy_from_slice(m.sha256.borrow()); branch_p.await?; for p in self.change_handlers.iter().map(|h| h.1(m)...
random
[ { "content": "fn neighbours(&self)->Vec<Self>;\n\n}\n\n\n", "file_path": "map_types/src/position.rs", "rank": 1, "score": 128567.32976798512 }, { "content": "#[derive(Serialize, Deserialize, Debug, Clone)]\n\nstruct RenderEntity<P: Position<P>, B: Borders> {\n\n id: u64,\n\n ent_type: ...
Rust
bee-network/bee-autopeering/src/task.rs
charlesthompson3/bee
e4b6e2afb84bf2b3ded88d7ec73247de33cd8fcb
use crate::{ peer::{ lists::{ActivePeersList, ReplacementPeersList}, PeerStore, }, time::SECOND, }; use priority_queue::PriorityQueue; use tokio::{sync::oneshot, task::JoinHandle, time}; use std::{collections::HashMap, future::Future, time::Duration}; pub(crate) const MAX_SHUTDOWN_PRIOR...
use crate::{ peer::{ lists::{ActivePeersList, ReplacementPeersList}, PeerStore, }, time::SECOND, }; use priority_queue::PriorityQueue; use tokio::{sync::oneshot, task::JoinHandle, time}; use std::{collections::HashMap, future::Future, time::Duration}; pub(crate) const MAX_SHUTDOWN_PRIOR...
log::debug!("Flushing data to peer store..."); peer_store.delete_all()?; peer_store.store_all_active(&active_peers)?; peer_store.store_all_replacements(&replacements)?; log::info!("Done."); Ok(()) } }
if let Err(e) = time::timeout(SHUTDOWN_TIMEOUT, async { while let Some((task_name, _)) = shutdown_order.pop() { let task_handle = shutdown_handles.remove(&task_name).unwrap(); match task_handle.await { Ok(_) => { l...
if_condition
[ { "content": "fn topic_handler<N, E, T, P, F>(node: &mut N, topic: &'static str, f: F)\n\nwhere\n\n N: Node,\n\n E: Any + Clone + Send + Sync,\n\n T: Into<String> + Send,\n\n P: Into<Vec<u8>> + Send,\n\n F: 'static + Fn(&E) -> (T, P) + Send + Sync,\n\n{\n\n let bus = node.bus();\n\n let man...
Rust
src/request.rs
staktrace/rust_tinyget
24e9548efdea99df457dac08d28157e3c52d2c4f
use crate::connection::Connection; use crate::{Error, Response, ResponseLazy}; use std::collections::HashMap; pub type URL = String; #[derive(Clone, PartialEq, Debug)] pub struct Request { pub(crate) host: URL, resource: URL, headers: HashMap<String, String>, pub(crate) timeout: Option<u64>, max_r...
use crate::connection::Connection; use crate::{Error, Response, ResponseLazy}; use std::collections::HashMap; pub type URL = String; #[derive(Clone, PartialEq, Debug)] pub struct Request { pub(crate) host: URL, resource: URL, headers: HashMap<String, String>, pub(crate) timeout: Option<u64>, max_r...
#[cfg(not(feature = "https"))] pub fn send_lazy(self) -> Result<ResponseLazy, Error> { if self.https { Err(Error::HttpsFeatureNotEnabled) } else { Connection::new(self).send() } } pub(crate) fn as_bytes(&self) -> Vec<u...
pub fn send(self) -> Result<Response, Error> { if self.https { Err(Error::HttpsFeatureNotEnabled) } else { let response = Connection::new(self).send()?; Response::create(response) } }
function_block-full_function
[ { "content": "pub fn get_body(request: Result<tinyget::Response, tinyget::Error>) -> String {\n\n match request {\n\n Ok(response) => match response.as_str() {\n\n Ok(str) => String::from(str),\n\n Err(err) => {\n\n println!(\"\\n[ERROR]: {}\\n\", err);\n\n ...
Rust
src/utils.rs
jasongraalum/immeta
68957408ab1ab47bf0c9c545e8d94fc93d013cbb
use std::io::{self, Read, BufRead, ErrorKind}; use byteorder::{ReadBytesExt, LittleEndian, BigEndian}; use byteorder::ByteOrder as ByteOrderTrait; pub trait ReadExt: Read { fn read_exact_0(&mut self, mut buf: &mut [u8]) -> io::Result<usize> { let orig_len = buf.len() as u64; io::copy(&mut self.tak...
use std::io::{self, Read, BufRead, ErrorKind}; use byteorder::{ReadBytesExt, LittleEndian, BigEndian}; use byteorder::ByteOrder as ByteOrderTrait; pub trait ReadExt: Read { fn read_exact_0(&mut self, mut buf: &mut [u8]) -> io::Result<usize> { let orig_len = buf.len() as u64; io::copy(&mut self.tak...
fn skip_until(&mut self, delim: u8) -> io::Result<usize> { let mut read = 0; loop { let (done, used) = { let available = match self.fill_buf() { Ok(n) => n, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, ...
e.kind() == ErrorKind::Interrupted => continue, Err(e) => return Err(e) } as u64; let total = skipped + available; if total >= n { let extra = total - n; let to_skip = available - extra; skipped += to_skip; ...
function_block-function_prefixed
[ { "content": "/// Attempts to load metadata for an image contained in the provided input stream.\n\n///\n\n/// This method automatically determines the format of the contained image. Because it may\n\n/// need to read the stream from the beginning several times, a `Seek` bound is necessary\n\n/// on the input s...
Rust
cli/src/dev/mod.rs
tokenchain/serum-dex
4b7f03d4d7f6218003bbe31154b6684d86120ff1
extern crate crank as serum_crank; use anyhow::Result; use clap::Clap; use serum_common::client::rpc; use serum_context::Context; use serum_dex::instruction::NewOrderInstructionV1; use serum_dex::matching::{OrderType, Side}; use serum_registry::client::Client; use solana_sdk::pubkey::Pubkey; use solana_sdk::signatur...
extern crate crank as serum_crank; use anyhow::Result; use clap::Clap; use serum_common::client::rpc; use serum_context::Context; use serum_dex::instruction::NewOrderInstructionV1; use serum_dex::matching::{OrderType, Side}; use serum_registry::client::Client; use solana_sdk::pubkey::Pubkey; use solana_sdk::signatur...
fn allocate_account(ctx: &Context, program_id: Pubkey, size: usize) -> Result<()> { let rpc_client = ctx.rpc_client(); let wallet = ctx.wallet().unwrap(); let pk = rpc::create_account_rent_exempt(&rpc_client, &wallet, size, &program_id)?.pubkey(); println!("{}", serde_json::json!({"account": pk.to_str...
n!({ "wallet": g.wallet.to_string(), "srmMint": g.srm_mint.to_string(), "msrmMint": g.msrm_mint.to_string(), "god": g.god.to_string(), "godMsrm": g.god_msrm.to_string(), "godBalanceBefore": g.god_balance_before, "godMsrmBalanceBefore": ...
function_block-function_prefixed
[ { "content": "pub fn run(ctx: Context, cmd: Command) -> Result<()> {\n\n match cmd {\n\n Command::Crank(cmd) => serum_crank::start(\n\n Some(ctx.clone()),\n\n serum_crank::Opts {\n\n cluster: ctx.cluster,\n\n command: cmd,\n\n },\n\n ...
Rust
crates/libvmm/src/x86_64/svm/flags.rs
DeathWish5/RVM1.5
c340272c1e7efa5bb413533da5e2c9fa9b995eb6
use bit_field::BitField; use bitflags::bitflags; use crate::x86_64::msr::{Msr, MsrReadWrite}; bitflags! { pub struct VmCrFlags: u64 { const DPD = 1 << 0; const R_INIT = 1 << 1; const DIS_A20M = 1 << 2; con...
use bit_field::BitField; use bitflags::bitflags; use crate::x86_64::msr::{Msr, MsrReadWrite}; bitflags! { pub struct VmCrFlags: u64 { const DPD = 1 << 0; const R_INIT = 1 << 1; const DIS_A20M = 1 << 2; con...
ERROR_CODE; } info } } #[repr(u8)] #[derive(Debug)] pub enum VmcbTlbControl { DoNotFlush = 0, FlushAll = 0x01, FlushAsid = 0x03, FlushAsidNonGlobal = 0x07, }
const DR_X = 1 << 6; const DT = 1 << 7; const SEG = 1 << 8; const CR2 = 1 << 9; const LBR = 1 << 10; const AVIC = 1 << 11; const CET = 1 << 12; cons...
random
[ { "content": "pub fn current_cycle() -> u64 {\n\n unsafe { core::arch::x86_64::_rdtsc() }\n\n}\n\n\n", "file_path": "src/arch/x86_64/cpu.rs", "rank": 0, "score": 147615.53317540727 }, { "content": "pub fn current_time_nanos() -> u64 {\n\n current_cycle() * 1000 / frequency() as u64\n\n...
Rust
tools/wasm-strip/src/wasm.rs
neri/image-viewer
2f7ca68415f221b60912ca47b5a9191083bd4eec
use byteorder::*; use core::mem::transmute; use core::str; pub struct WasmMiniLoader { _phantom: (), } impl WasmMiniLoader { const MINIMAL_MOD_SIZE: usize = 8; const MAGIC: u32 = 0x6D736100; const VER_CURRENT: u32 = 0x0000_0001; #[inline] #[cfg(target_endian = "little")] ...
use byteorder::*; use core::mem::transmute; use core::str; pub struct WasmMiniLoader { _phantom: (), } impl WasmMiniLoader { const MINIMAL_MOD_SIZE: usize = 8; const MAGIC: u32 = 0x6D736100; const VER_CURRENT: u32 = 0x0000_0001; #[inline] #[cfg(target_endian = "little")] ...
} pub struct Leb128Stream<'a> { blob: &'a [u8], position: usize, } impl<'a> Leb128Stream<'a> { #[inline] pub const fn from_slice(slice: &'a [u8]) -> Self { Self { blob: slice, position: 0, } } #[inline] pub fn cloned(&self) -> Self { S...
drop(leb); Ok(positions .iter() .map(|(section_type, start, length)| WasmSection { section_type: *section_type, file_position: *start, stream: Leb128Stream::from_slice(&blob[magic + start..magic + start + length]), }) ...
function_block-function_prefix_line
[ { "content": "#[no_mangle]\n\npub fn encode() -> bool {\n\n let ib = image_buffer();\n\n let info = image_info();\n\n\n\n let qoi = Qoi {\n\n width: info.width as u32,\n\n height: info.height as u32,\n\n colors: match info.transparency {\n\n Transparency::Opaque => Color...
Rust
fenris-geometry/src/primitives/quad.rs
Andlon/fenris
297a9e9e09efb1f524cd439c8e88d6248aa500a6
use crate::{ AxisAlignedBoundingBox2d, BoundedGeometry, ConvexPolygon3d, Distance, GeneralPolygon, Triangle, Triangle2d, }; use itertools::izip; use nalgebra::{Point2, Point3, RealField, Scalar, U2}; #[derive(Debug, Copy, Clone, PartialEq)] pub struct Quad3d<T: Scalar> { vertices: [Point3<T>; 4], } impl<T: Sc...
use crate::{ AxisAlignedBoundingBox2d, BoundedGeometry, ConvexPolygon3d, Distance, GeneralPolygon, Triangle, Triangle2d, }; use itertools::izip; use nalgebra::{Point2, Point3, RealField, Scalar, U2}; #[derive(Debug, Copy, Clone, PartialEq)] pub struct Quad3d<T: Scalar> { vertices: [Point3<T>; 4], } impl<T: Sc...
} pub fn split_into_triangles(&self) -> (Triangle2d<T>, Triangle2d<T>) { let (conn1, conn2) = self.split_into_triangle_connectivities(); let mut vertices1 = [Point2::origin(); 3]; let mut vertices2 = [Point2::origin(); 3]; for (v, idx) in izip!(&mut vertices1, &conn1) { ...
if let Some(concave_corner_index) = self.concave_corner() { let i = concave_corner_index; let triangle1 = [(i + 2) % 4, (i + 3) % 4, (i + 0) % 4]; let triangle2 = [(i + 2) % 4, (i + 0) % 4, (i + 1) % 4]; (triangle1, triangle2) } else { let...
if_condition
[ { "content": "/// Attempt to create a quadrature rule for the reference triangle with the provided strength.\n\n///\n\n/// The returned quadrature rule is the smallest rule which provides sufficient accuracy.\n\n/// Note that it's possible for the strength of the returned rule to be higher than required, but\n\...
Rust
crates/vm/src/value/serialize.rs
Lutetium-Vanadium/anilang
e16e5afec2e7e7f33a86ce91c3ca03b5ab9c8db8
use super::Value; use crate::function::Function; use crate::types::Type; use crate::DeserializationContext; use serialize::{Deserialize, DeserializeCtx, Serialize}; use std::cell::RefCell; use std::io::{self, prelude::*}; use std::rc::Rc; impl Serialize for Value { fn serialize<W: Write>(&self, buf: &mut W) -> io:...
use super::Value; use crate::function::Function; use crate::types::Type; use crate::DeserializationContext; use serialize::{Deserialize, DeserializeCtx, Serialize}; use std::cell::RefCell; use std::io::{self, prelude::*}; use std::rc::Rc; impl Serialize for Value { fn serialize<W: Write>(&self, buf: &mut W) -> io:...
} impl DeserializeCtx<DeserializationContext> for Value { fn deserialize_with_context<R: BufRead>( data: &mut R, ctx: &mut DeserializationContext, ) -> io::Result<Value> { let tag = u16::deserialize(data)?; Ok(match Type::from(tag) { Type::Int => Value::Int(i64::de...
b) => { b.serialize(buf)?; Ok(3) } Value::Range(s, e) => { s.serialize(buf)?; e.serialize(buf)?; Ok(18) } Value::List(l) => Ok(2 + l.borrow().serialize(buf)?), Value::String(s) => ...
function_block-function_prefixed
[ { "content": "pub fn push(mut args: Vec<Value>) -> Result<Value> {\n\n if args.len() != 2 {\n\n return Err(ErrorKind::IncorrectArgCount {\n\n expected: 2,\n\n got: args.len(),\n\n });\n\n }\n\n\n\n let to_push = args.pop().unwrap();\n\n\n\n match &args[0] {\n\n ...
Rust
src/arch/src/aarch64/gic/gicv3/mod.rs
psalaberria002/firecracker
86340cb109d7eb1174bb080ef0bcb0aadc80b0f9
mod regs; use std::{boxed::Box, result}; use kvm_ioctls::DeviceFd; use crate::aarch64::gic::{Error, GICDevice, GicState}; type Result<T> = result::Result<T, Error>; pub(crate) struct GICv3 { fd: DeviceFd, properties: [u64; 4], vcpu_count: u64, } impl GICv3 { const SZ_6...
mod regs; use std::{boxed::Box, result}; use kvm_ioctls::DeviceFd; use crate::aarch64::gic::{Error, GICDevice, GicState}; type Result<T> = result::Result<T, Error>; pub(crate) struct GICv3 { fd: DeviceFd, properties: [u64; 4], vcpu_count: u64, } impl GICv3 { const SZ_6...
} fn save_pending_tables(fd: &DeviceFd) -> Result<()> { let init_gic_attr = kvm_bindings::kvm_device_attr { group: kvm_bindings::KVM_DEV_ARM_VGIC_GRP_CTRL, attr: u64::from(kvm_bindings::KVM_DEV_ARM_VGIC_SAVE_PENDING_TABLES), addr: 0, flags: 0, }; fd.set_device_attr(&init_gi...
fn init_device_attributes(gic_device: &dyn GICDevice) -> Result<()> { /* Setting up the distributor attribute. We are placing the GIC below 1GB so we need to substract the size of the distributor. */ Self::set_device_attribute( &gic_device.device_fd(), kvm_bindin...
function_block-full_function
[ { "content": "/// Restore the state of the GIC device.\n\npub fn restore_state(fd: &DeviceFd, mpidrs: &[u64], state: &GicState) -> Result<()> {\n\n dist_regs::set_dist_regs(fd, &state.dist)?;\n\n\n\n if mpidrs.len() != state.gic_vcpu_states.len() {\n\n return Err(Error::InconsistentVcpuCount);\n\n ...
Rust
src/lib.rs
gurkeclub/wvr-shadertoy
918bcc0e4fcf0b2b838526993c778efd3a3eee76
#[macro_use] extern crate serde_derive; use anyhow::Result; use wvr_data::config::filter::FilterConfig; use wvr_data::config::project::ProjectConfig; use wvr_data::config::project::ViewConfig; use wvr_data::config::rendering::RenderStageConfig; use wvr_data::types::BufferPrecision; use std::collections::HashMap; use ...
#[macro_use] extern crate serde_derive; use anyhow::Result; use wvr_data::config::filter::FilterConfig; use wvr_data::config::project::ProjectConfig; use wvr_data::config::project::ViewConfig; use wvr_data::config::rendering::RenderStageConfig; use wvr_data::types::BufferPrecision; use std::collections::HashMap; use ...
fs::create_dir(&fragment_shader_directory).unwrap(); } if let Ok(mut file) = fs::File::create(fragment_shader_directory.join("main.glsl")) { file.write_all(&shader_code.into_bytes()).unwrap(); } } let project_config = ProjectConfig { bpm: 89.0, view: ViewCon...
function_block-function_prefix_line
[ { "content": "#[derive(Debug, Serialize, Deserialize)]\n\n#[serde(tag = \"ctype\")]\n\npub enum InputConfig {\n\n #[serde(rename = \"buffer\")]\n\n Buffer { channel: i64 },\n\n #[serde(rename = \"webcam\")]\n\n Webcam { channel: i64 },\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub stru...
Rust
src/lib.rs
ProjectKML/fast_obj_rs
6fb0f69e7217cf8fe1741f1d9cc14593ccd8e4b4
use std::{ ffi::{CString, NulError}, os::raw::c_char, path::Path, slice, str }; use libc::{c_void, strlen}; use crate::ObjLoadError::InvalidPath; mod ffi; #[derive(Debug)] pub enum ObjLoadError { InvalidPath, ParsingFailed } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Index { pu...
use std::{ ffi::{CString, NulError}, os::raw::c_char, path::Path, slice, str }; use libc::{c_void, strlen}; use crate::ObjLoadError::InvalidPath; mod ffi; #[derive(Debug)] pub enum ObjLoadError { InvalidPath, ParsingFailed } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Index { pu...
} pub fn positions(&self) -> &[f32] { unsafe { slice::from_raw_parts((*self.mesh).positions, (*self.mesh).position_count as usize) } } pub fn texcoords(&self) -> &[f32] { unsafe { slice::from_raw_parts((*self.mesh).texcoords, (*self.mesh).texcoord_count as usize) } } pub fn n...
if mesh == std::ptr::null_mut() { Err(ObjLoadError::ParsingFailed) } else { Ok(Self { mesh }) }
if_condition
[ { "content": "#[cfg(not(feature = \"generate_bindings\"))]\n\nfn generate_bindings(_: &str) {}\n", "file_path": "build.rs", "rank": 0, "score": 35572.14391007289 }, { "content": "#[cfg(feature = \"generate_bindings\")]\n\nfn generate_bindings(output_file: &str) {\n\n let bindings = bindge...
Rust
src/extended_gcd.rs
stallmanifold/modpow
b53c1af7e53a3216125aa4c70824dea2689f76b8
use num::{Integer, Zero, One, BigInt, PrimInt}; use num::bigint::Sign; #[derive(Clone)] pub struct Gcd<T> where T: Clone { pub coef_x: T, pub coef_y: T, pub g: T, pub gcd_xy: T, } pub trait ExtendedGcd<T> where T: Clone { ...
use num::{Integer, Zero, One, BigInt, PrimInt}; use num::bigint::Sign; #[derive(Clone)] pub struct
coef_y: BigInt::from(206), }, TestCase { x: <BigInt as Num>::from_str_radix("294248851906335666255475965306356\ 33692994051181214434796327203075", 10).unwrap(), y: <Bi...
Gcd<T> where T: Clone { pub coef_x: T, pub coef_y: T, pub g: T, pub gcd_xy: T, } pub trait ExtendedGcd<T> where T: Clone { fn extended_gcd(&self, y: ...
random
[]
Rust
src/hosts.rs
Icelk/kvarn-reference
be33686e9de30ea0dc03fd1cd6ed0e384d658e33
use comprash::ClientCachePreference; use internals::mime; use kvarn::prelude::*; struct UnsafeSyncFuture<F>(F); impl<F> UnsafeSyncFuture<F> { fn new(future: F) -> UnsafeSyncFuture<Pin<Box<F>>> { UnsafeSyncFuture(Box::pin(future)) } } unsafe impl<F> Send for UnsafeSyncFuture<F> {} unsafe impl<F> Sync fo...
use comprash::ClientCachePreference; use internals::mime; use kvarn::prelude::*; struct UnsafeSyncFuture<F>(F); impl<F> UnsafeSyncFuture<F> { fn new(future: F) -> UnsafeSyncFuture<Pin<Box<F>>> { UnsafeSyncFuture(Box::pin(future)) } } unsafe impl<F> Send for UnsafeSyncFuture<F> {} unsafe impl<F> Sync fo...
pub fn kvarn_extensions() -> Extensions { let mut extensions = kvarn_extensions::new(); kvarn_extensions::force_cache( &mut extensions, &[ (".png", ClientCachePreference::Changing), (".woff2", ClientCachePreference::Full), (".woff", ClientCachePreference::Ful...
tensions); host.disable_client_cache().disable_server_cache(); let se_handle = kvarn_search::mount_search(&mut host.extensions, "/search", kvarn_search::Options::default()).await; se_handle.index(&host).await; host }
function_block-function_prefixed
[ { "content": "# Kvarn reference binary\n\n\n\nThis is a reference implementation of the Kvarn server library.\n\nIt's for my personal use for my domains [icelk.dev](https://icelk.dev/) and [kvarn.org](https://kvarn.org/)\n\nand will therefore not work with most configurations.\n\n\n\nFor now, I suggest forking ...
Rust
src_core_extensions/const_default_trait.rs
rodrimati1992/core_extensions
9797a7e1d4a50ceacd11ae75ac590ffd42accfbf
use crate::const_default; use std_::{ cell::{Cell,RefCell,UnsafeCell}, cmp::Reverse, marker::PhantomData, mem::ManuallyDrop, num::Wrapping, sync::atomic::{AtomicUsize,AtomicIsize,AtomicBool}, }; #[allow(unused_imports)] use std_::sync::atomic; #[cfg_attr(feature = "docsrs", doc(cfg(feature ...
use crate::const_default; use std_::{ cell::{Cell,RefCell,UnsafeCell}, cmp::Reverse, marker::PhantomData, mem::ManuallyDrop, num::Wrapping, sync::atomic::{AtomicUsize,AtomicIsize,AtomicBool}, }; #[allow(unused_imports)] use std_::sync::atomic; #[cfg_attr(feature = "docsrs", doc(cfg(feature ...
#[test] fn for_rust_1_22(){ assert_eq!(const_def_assert!([NonCopy;2]), [NonCopy,NonCopy]); assert_eq!(const_def_assert!(()), ()); assert_eq!(const_def_assert!((NonCopy,)), (NonCopy,)); assert_eq!(const_def_assert!((NonCopy,NonCopy)), (NonCopy,NonCopy)); assert_...
fn always_available(){ assert_eq!(const_def_assert!([u8;6]), [0;6]); assert_eq!(const_def_assert!([u8;16]), [0;16]); assert_eq!(const_def_assert!([u8;32]), [0;32]); assert_eq!(const_def_assert!(()), ()); assert_eq!(const_def_assert!((u8,)), (0,)); assert_eq!(cons...
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\npub fn remove_whitespace(s: &str) -> String {\n\n s.chars().filter(|c| !c.is_whitespace()).collect()\n\n}\n\n\n\n\n", "file_path": "tests/misc_tests/utils_tests.rs", "rank": 1, "score": 284716.39133231086 }, { "content": "/// Extension trait for string...
Rust
src/main.rs
fossabot/k-iter
379bd0b8f970f9b1f92c8efe5a2859f487765e00
#[macro_use] extern crate clap; extern crate ctrlc; extern crate rusoto_core; extern crate rusoto_kinesis; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time; use clap::{App, Arg}; use rusoto_core::Region; use rusoto_kinesis::{GetRecordsError, GetRecordsInput, GetShardI...
#[macro_use] extern crate clap; extern crate ctrlc; extern crate rusoto_core; extern crate rusoto_kinesis; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time; use clap::{App, Arg}; use rusoto_core::Region; use rusoto_kinesis::{GetRecordsError, GetRecordsInput, GetShardI...
) .arg( Arg::with_name("iterator-type") .short("t") .long("iterator-type") .possible_values(&IteratorType::variants()) .default_value("LATEST") .value_name("TYPE") .help("Sets iterator type."), ...
d_iterator_type: String, region: Region, ) -> Self { let c = KinesisClient::simple(region); let input = GetShardIteratorInput { shard_id, shard_iterator_type, stream_name, ..Default::default() }; KinesisIterator { cl...
random
[ { "content": "# k-iter: Kinesis Subscriber for CLI\n\n\n\n[![Build Status](https://travis-ci.org/ROki1988/k-iter.svg?branch=master)](https://travis-ci.org/ROki1988/k-iter) [![Build status](https://ci.appveyor.com/api/projects/status/omrdwsvjciq68xf9?svg=true)](https://ci.appveyor.com/project/ROki1988/k-iter)[![...
Rust
libafl_frida/src/lib.rs
marcograss/LibAFL
730df64712893aa5e0e32b0ffac3c886766c44c9
pub mod asan_rt; pub mod helper; #[derive(Clone, Copy, Debug)] #[allow(clippy::struct_excessive_bools)] pub struct FridaOptions { enable_asan: bool, enable_asan_leak_detection: bool, enable_asan_continue_after_error: bool, enable_asan_allocation_backtraces: bool, enable_coverage: bool, enable_d...
pub mod asan_rt; pub mod helper; #[derive(Clone, Copy, Debug)] #[allow(clippy::struct_excessive_bools)] pub struct FridaOptions { enable_asan: bool, enable_asan_leak_detection: bool, enable_asan_continue_after_error: bool, enable_asan_allocation_backtraces: bool, enable_coverage: bool, enable_d...
#[inline] pub fn asan_enabled(self) -> bool { self.enable_asan } #[inline] pub fn coverage_enabled(self) -> bool { self.enable_coverage } #[inline] pub fn drcov_enabled(self) -> bool { self.enable_drcov } #[inline] pub fn asan_...
pub fn parse_env_options() -> Self { let mut options = Self::default(); if let Ok(env_options) = std::env::var("LIBAFL_FRIDA_OPTIONS") { for option in env_options.trim().to_lowercase().split(':') { let (name, mut value) = option.split_at(option.find('=')....
function_block-full_function
[]
Rust
rust/src/error.rs
sampersand/knight
faf4fe8694a9402525e67ee7f01c39f543e72693
use std::io; use std::fmt::{self, Display, Formatter}; use crate::rcstring::InvalidChar; use std::error::Error; #[derive(Debug)] pub enum ParseError { NothingToParse, UnknownTokenStart { chr: char, line: usize }, UnterminatedQuote { line: usize }, MissingFunctionArgument { func: c...
use std::io; use std::fmt::{self, Display, Formatter}; use crate::rcstring::InvalidChar; use std::error::Error; #[derive(Debug)] pub enum ParseError { NothingToParse, UnknownTokenStart { chr: char, line: usize }, UnterminatedQuote { line: usize }, MissingFunctionArgument { func: c...
}
fn source(&self) -> Option<&(dyn Error + 'static)> { match self { Self::Parse(err) => Some(err), Self::Io(err) => Some(err), Self::InvalidString(err) => Some(err), Self::Custom(err) => Some(err.as_ref()), _ => None } }
function_block-full_function
[ { "content": "pub fn modulo(args: &[Value], env: &mut Environment<'_, '_, '_>) -> Result<Value, RuntimeError> {\n\n\tmatch args[0].run(env)? {\n\n\t\tValue::Number(lhs) =>\n\n\t\t\tlhs.checked_rem(args[1].run(env)?.to_number()?)\n\n\t\t\t\t.map(Value::from)\n\n\t\t\t\t.ok_or(RuntimeError::DivisionByZero { modul...
Rust
src/pages/post.rs
csotello/RustProject
bb7319acc06aaa4ca63eb816235c35d023030801
use crate::routes::Routes; use crate::utils::*; use db::*; use yew::events::ChangeData; use yew::prelude::*; use yew::services::reader::{File, FileData, ReaderService, ReaderTask}; use yew_router::agent::RouteRequest::ChangeRoute; use yew_router::prelude::RouteAgent; extern crate base64; pub enum Msg { SetDescripti...
use crate::routes::Routes; use crate::utils::*; use db::*; use yew::events::ChangeData; use yew::prelude::*; use yew::services::reader::{File, FileData, ReaderService, ReaderTask}; use yew_router::agent::RouteRequest::ChangeRoute; use ye
link: ComponentLink<Self>, description: String, file: String, task: Vec<ReaderTask>, error: bool, props: Props, } impl Component for Post { type Message = Msg; type Properties = Props; fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self { Self ...
w_router::prelude::RouteAgent; extern crate base64; pub enum Msg { SetDescription(String), SetFile(FileData), LoadFile(File), ResetFile, Submit, None, } #[derive(Properties, Clone)] pub struct Props { pub db: Data, pub callback: Callback<(String, String, String)>, pub user: Option<U...
random
[ { "content": "use db::*;\n\n\n\n#[test]\n\n/// Test post related functions\n", "file_path": "tests/db.rs", "rank": 0, "score": 25534.44157602948 }, { "content": " assert_eq!(item.description, \"updated\".to_string());\n\n db.create_rating(id, \"you\".to_string(), 2, \"great\".to_string...
Rust
gensokyo-vulkan/src/image/view.rs
Usami-Renko/hakurei
cccc69fe71d6efd75089d1c03c9c49fefde8e2ca
use ash::vk; use ash::version::DeviceV1_0; use crate::core::GsDevice; use crate::image::target::{ GsImage, ImageSpecificCI }; use crate::image::format::GsImageFormat; use crate::error::{ VkResult, VkError }; use crate::types::format::Format; use crate::types::vkuint; use std::ptr; pub struct GsImageView { pu...
use ash::vk; use ash::version::DeviceV1_0; use crate::core::GsDevice; use crate::image::target::{ GsImage, ImageSpecificCI }; use crate::image::format::GsImageFormat; use crate::error::{ VkResult, VkError }; use crate::types::format::Format; use crate::types::vkuint; use std::ptr; pub struct GsImageView { pu...
let handle = unsafe { device.logic.handle.create_image_view(&image_view_ci, None) .or(Err(VkError::create("Image View")))? }; let view = GsImageView { handle }; Ok(view) } pub(crate) fn build_for_swapchain(&self, device: &GsDevice, image: &GsImage,...
let image_view_ci = vk::ImageViewCreateInfo { s_type : vk::StructureType::IMAGE_VIEW_CREATE_INFO, p_next : ptr::null(), flags : vk::ImageViewCreateFlags::empty(), image : image.handle, view_type : self.view_type, for...
assignment_statement
[]
Rust
src/trivial_pc_as/constraints/data_structures.rs
arkworks-rs/accumulation
4a680af486a061927e2e46f3d7bf8830a96752b7
use crate::trivial_pc_as::{InputInstance, SingleProof}; use crate::ConstraintF; use ark_ec::AffineCurve; use ark_ff::{Field, PrimeField}; use ark_nonnative_field::NonNativeFieldVar; use ark_r1cs_std::alloc::{AllocVar, AllocationMode}; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::groups::CurveVar; use ark_r1c...
use crate::trivial_pc_as::{InputInstance, SingleProof}; use crate::ConstraintF; use ark_ec::AffineCurve; use ark_ff::{Field, PrimeField}; use ark_nonnative_field::NonNativeFieldVar; use ark_r1cs_std::alloc::{AllocVar, AllocationMode}; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::groups::CurveVar; use ark_r1c...
eval: NonNativeFieldVar<G::ScalarField, ConstraintF<G>>, #[doc(hidden)] pub _affine: PhantomData<G>, } impl<G, C> AllocVar<InputInstance<G>, ConstraintF<G>> for InputInstanceVar<G, C> where G: AffineCurve, C: CurveVar<G::Projective, ConstraintF<G>>, { fn new_variable<T: Borrow<InputInstance<G>>>( ...
Error>, mode: AllocationMode, ) -> Result<Self, SynthesisError> { let ns = cs.into(); f().and_then(|vk| { let vk = FpVar::<CF>::new_variable( ns.clone(), || { Ok(Absorbable::<CF>::to_sponge_field_elements(vk.borrow()) ...
random
[ { "content": "#[derive(Copy, Clone)]\n\nstruct DummyCircuit<F: PrimeField> {\n\n pub a: Option<F>,\n\n pub b: Option<F>,\n\n pub num_input_variables: usize,\n\n pub num_witness_variables: usize,\n\n pub num_constraints: usize,\n\n}\n\n\n\nimpl<F: PrimeField> ConstraintSynthesizer<F> for DummyCirc...
Rust
main/src/ifd.rs
gopakumarce/guru
67a5e286bf5772edd7415714605817c51cdc1d0c
use super::*; use crate::ipv4::add_route; use crate::ipv4::del_route; use apis_interface::{CurvesApi, InterfaceErr, InterfaceSyncHandler}; use dpdk::DpdkHw; use fwd::intf::Interface; use fwd::intf::ModifyInterfaceMsg; use fwd::ZERO_IP; use interface::IfNode; use l2_eth_decap::EthDecap; use l2_eth_encap::EthEncap; use m...
use super::*; use crate::ipv4::add_route; use crate::ipv4::del_route; use apis_interface::{CurvesApi, InterfaceErr, InterfaceSyncHandler}; use dpdk::DpdkHw; use fwd::intf::Interface; use fwd::intf::ModifyInterfaceMsg; use fwd::ZERO_IP; use interface::IfNode; use l2_eth_decap::EthDecap; use l2_eth_encap::EthEncap; use m...
fn handle_add_class( &self, ifname: String, name: String, parent: String, qlimit: i32, is_leaf: bool, curves: CurvesApi, ) -> thrift::Result<()> { let mut r2 = self.r2.lock().unwrap(); let intf; if let Some(i) = r2.ifd.interfaces....
let mut r2 = self.r2.lock().unwrap(); if cur_addr != ZERO_IP { del_route( &mut r2, cur_addr, cur_masklen, Ipv4Addr::new(0, 0, 0, 0), ifindex, ); } add_route(&mut r2, addr, masklen, Ipv4Addr::n...
function_block-function_prefix_line
[ { "content": "fn interface_add(ifname: String, ifindex: i32, mac: String) {\n\n let (i_prot, o_prot) = match api_client(common::API_SVR, common::INTF_APIS) {\n\n Ok((i, o)) => (i, o),\n\n Err(why) => {\n\n println!(\"Client connection failed: {}\", why);\n\n return;\n\n ...