file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
com.rs
//! Common utilities //! //! A standard vocabulary used throughout the code. use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync}; use crate::basic::sea::TableIndex; /// A fragment of source code. #[derive(Clone)] pub struct CodeFragment(sync::Arc<Vec<u8>>); impl CodeFragment { /// Creates a n...
else { Range { offset: self.offset, length: (other.end_offset() - self.offset()) as u32 } } } } impl fmt::Debug for Range { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}@{}", self.length, self.offset) ...
{ self }
conditional_block
physics_hooks.rs
use crate::dynamics::{RigidBodyHandle, RigidBodySet}; use crate::geometry::{ColliderHandle, ColliderSet, ContactManifold, SolverContact, SolverFlags}; use crate::math::{Real, Vector}; use na::ComplexField; /// Context given to custom collision filters to filter-out collisions. pub struct PairFilterContext<'a> { //...
/// This can be used to apply custom logic in order to decide whether two colliders /// should have their intersection computed by the narrow-phase. /// /// Note that using an intersection pair filter will replace the default intersection filtering /// which consists of preventing intersection compu...
///
random_line_split
physics_hooks.rs
use crate::dynamics::{RigidBodyHandle, RigidBodySet}; use crate::geometry::{ColliderHandle, ColliderSet, ContactManifold, SolverContact, SolverFlags}; use crate::math::{Real, Vector}; use na::ComplexField; /// Context given to custom collision filters to filter-out collisions. pub struct PairFilterContext<'a> { //...
self.solver_contacts.clear(); // NOTE: in some very rare cases `local_n1` will be // zero if the objects are exactly touching at one point. // So in this case we can't really conclude. // If the norm is non-zero, then w...
{ const CONTACT_CONFIGURATION_UNKNOWN: u32 = 0; const CONTACT_CURRENTLY_ALLOWED: u32 = 1; const CONTACT_CURRENTLY_FORBIDDEN: u32 = 2; let cang = ComplexField::cos(allowed_angle); // Test the allowed normal with the local-space contact normal that // points towards the e...
identifier_body
physics_hooks.rs
use crate::dynamics::{RigidBodyHandle, RigidBodySet}; use crate::geometry::{ColliderHandle, ColliderSet, ContactManifold, SolverContact, SolverFlags}; use crate::math::{Real, Vector}; use na::ComplexField; /// Context given to custom collision filters to filter-out collisions. pub struct PairFilterContext<'a> { //...
} CONTACT_CURRENTLY_ALLOWED => { // We allow all the contacts right now. The configuration becomes // uncertain again when the contact manifold no longer contains any contact. if self.solver_contacts.is_empty() { *self.user_dat...
{ // Discard all the contacts. self.solver_contacts.clear(); }
conditional_block
physics_hooks.rs
use crate::dynamics::{RigidBodyHandle, RigidBodySet}; use crate::geometry::{ColliderHandle, ColliderSet, ContactManifold, SolverContact, SolverFlags}; use crate::math::{Real, Vector}; use na::ComplexField; /// Context given to custom collision filters to filter-out collisions. pub struct PairFilterContext<'a> { //...
(&self, _: &PairFilterContext) -> bool { true } fn modify_solver_contacts(&self, _: &mut ContactModificationContext) {} }
filter_intersection_pair
identifier_name
main.rs
, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder}; pub mod api; pub mod db; pub mod error; #[cfg(test)] mod test; pub mod util; mod initialize; use db::{DatabaseCidr, DatabasePeer}; pub use error::ServerError; use initialize::InitializeOpts; use shared::{prompts, wg, CidrTree, Error, Interface, SERVER_CONFIG_DI...
Ok(()) } fn spawn_endpoint_refresher(interface: InterfaceName, network: NetworkOpt) -> Endpoints { let endpoints = Arc::new(RwLock::new(HashMap::new())); tokio::task::spawn({ let endpoints = endpoints.clone(); async move { let mut interval = tokio::time::interval(Duration::from...
{ println!("{} bringing down interface (if up).", "[*]".dimmed()); wg::down(interface, network.backend).ok(); let config = conf.config_path(interface); let data = conf.database_path(interface); std::fs::remove_file(&config) .with_path(&config) .map_err(|e|...
conditional_block
main.rs
, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder}; pub mod api; pub mod db; pub mod error; #[cfg(test)] mod test; pub mod util; mod initialize; use db::{DatabaseCidr, DatabasePeer}; pub use error::ServerError; use initialize::InitializeOpts; use shared::{prompts, wg, CidrTree, Error, Interface, SERVER_CONFIG_DI...
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> { let path = path.as_ref(); let file = File::open(path).with_path(path)?; if shared::chmod(&file, 0o600)? { println!( "{} updated permissions for {} to 0600.", "[!]".yellow(), ...
{ let mut invitation_file = File::create(&path).with_path(&path)?; shared::chmod(&invitation_file, 0o600)?; invitation_file .write_all(toml::to_string(self).unwrap().as_bytes()) .with_path(path)?; Ok(()) }
identifier_body
main.rs
/// Permanently uninstall a created network, rendering it unusable. Use with care. Uninstall { interface: Interface }, /// Serve the coordinating server for an existing network. Serve { interface: Interface, #[structopt(flatten)] network: NetworkOpt, }, /// Add a peer to...
#[tokio::test] async fn test_unparseable_public_key() -> Result<(), Error> { let server = test::Server::new()?;
random_line_split
main.rs
, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder}; pub mod api; pub mod db; pub mod error; #[cfg(test)] mod test; pub mod util; mod initialize; use db::{DatabaseCidr, DatabasePeer}; pub use error::ServerError; use initialize::InitializeOpts; use shared::{prompts, wg, CidrTree, Error, Interface, SERVER_CONFIG_DI...
(&self) -> bool { self.peer.is_admin && self.user_capable() } pub fn user_capable(&self) -> bool { !self.peer.is_disabled && self.peer.is_redeemed } pub fn redeemable(&self) -> bool { !self.peer.is_disabled &&!self.peer.is_redeemed } } #[derive(Deserialize, Serialize, Debug)...
admin_capable
identifier_name
population.rs
// Copyright (c) 2017 Ashley Jeffs // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, ...
for _ in 0..n_processes { let cvar_pair_clone = cvar_pair.clone(); let processed_stack_clone = processed_stack.clone(); let process_queue_clone = process_queue.clone(); scope.spawn(move || { let &(ref lock, ref cvar) = &*c...
let process_queue = Arc::new(Mutex::new(rx)); let processed_stack = Arc::new(Mutex::new(Vec::new()));
random_line_split
population.rs
// Copyright (c) 2017 Ashley Jeffs // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, ...
(init_pop: Vec<T>) -> Self { Population { units: init_pop, seed: 1, breed_factor: 0.5, survival_factor: 0.5, max_size: 100, } } //-------------------------------------------------------------------------- /// Sets the random seed ...
new
identifier_name
server.rs
// use std::{ // hash::Hash, // str, // io::Write, // net::{SocketAddr, IpAddr, Ipv4Addr}, // sync::Mutex, // time::{Instant} // }; // use actix_http::{ // body::Body, // http::{ // header::{CONTENT_TYPE, SERVER}, // HeaderValue,
// NewService, // Service, // }; // use actix_server::{ServerConfig}; // use actix_web::dev::Server use actix::prelude::*; // use bytes::{BytesMut, Bytes}; // use futures::{ // future::{ // ok, // join_all, // Future, // }, // Async, Poll, // }; // use serde_json::to_writer; // use actix_web::{ // App, // web, // middl...
// StatusCode, // }, // Error, Request, Response, // }; // use actix_service::{
random_line_split
server.rs
// use std::{ // hash::Hash, // str, // io::Write, // net::{SocketAddr, IpAddr, Ipv4Addr}, // sync::Mutex, // time::{Instant} // }; // use actix_http::{ // body::Body, // http::{ // header::{CONTENT_TYPE, SERVER}, // HeaderValue, // StatusCode, // }, // Error, Request, Response, // }; // use actix_service::{ // NewServ...
} if f { ss.remove(s); println!( "a websocket session removed from server : {} sockets opened", ss.len() ); } } } /// request to close all other connections #[derive(Message)] pub struct CloseAll; impl Handler<CloseAll> for...
{ // if ss[i] == msg.addr { // if v == msg.addr { s = i; f = true; break; // } }
conditional_block
server.rs
// use std::{ // hash::Hash, // str, // io::Write, // net::{SocketAddr, IpAddr, Ipv4Addr}, // sync::Mutex, // time::{Instant} // }; // use actix_http::{ // body::Body, // http::{ // header::{CONTENT_TYPE, SERVER}, // HeaderValue, // StatusCode, // }, // Error, Request, Response, // }; // use actix_service::{ // NewServ...
} /// websocket session disconnected #[derive(Message)] pub struct Disconnect { pub addr: Addr<WsSession>, // pub id : usize, } impl Handler<Disconnect> for WsServer { type Result = (); fn handle(&mut self, msg: Disconnect, _ctx: &mut Self::Context) -> Self::Result { println!("a websocket sess...
{ // println!("{:?} joined wsserver", msg.addr); // let mut s = &mut *self.sessions.get_mut().unwrap(); let s = &mut self.sessions; s.push(msg.addr); //.downgrade()); println!( "new web socket added to server : {} sockets opened", s.len() ); }
identifier_body
server.rs
// use std::{ // hash::Hash, // str, // io::Write, // net::{SocketAddr, IpAddr, Ipv4Addr}, // sync::Mutex, // time::{Instant} // }; // use actix_http::{ // body::Body, // http::{ // header::{CONTENT_TYPE, SERVER}, // HeaderValue, // StatusCode, // }, // Error, Request, Response, // }; // use actix_service::{ // NewServ...
(&mut self, msg: Disconnect, _ctx: &mut Self::Context) -> Self::Result { println!("a websocket session requested disconnect"); let mut s = 0; let mut f = false; // let mut ss = &mut *self.sessions.get_mut().unwrap(); let ss = &mut self.sessions; for i in 0..ss.len() { ...
handle
identifier_name
gimli.rs
_stash: $stash, } }}; } fn mmap(path: &Path) -> Option<Mmap> { let file = File::open(path).ok()?; let len = file.metadata().ok()?.len().try_into().ok()?; unsafe { Mmap::map(&file, len) } } cfg_if::cfg_if! { if #[cfg(windows)] { use core::mem::MaybeUninit; use s...
fn avma_to_svma(&self, addr: *const u8) -> Option<(usize, *const u8)> { self.libraries .iter() .enumerate() .filter_map(|(i, lib)| { // First up, test if this `lib` has any segment containing the // `addr` (handling relocation). If this chec...
{ // A very small, very simple LRU cache for debug info mappings. // // The hit rate should be very high, since the typical stack doesn't cross // between many shared libraries. // // The `addr2line::Context` structures are pretty expensive to create. Its // cost ...
identifier_body
gimli.rs
, _stash: $stash, } }}; } fn mmap(path: &Path) -> Option<Mmap> { let file = File::open(path).ok()?; let len = file.metadata().ok()?.len().try_into().ok()?; unsafe { Mmap::map(&file, len) } } cfg_if::cfg_if! { if #[cfg(windows)] { use core::mem::MaybeUninit; use ...
} struct Library { name: OsString, /// Segments of this library loaded into memory, and where they're loaded. segments: Vec<LibrarySegment>, /// The "bias" of this library, typically where it's loaded into memory. /// This value is added to each segment's stated address to get the actual /// vi...
/// Note that this is basically an LRU cache and we'll be shifting things /// around in here as we symbolize addresses. mappings: Vec<(usize, Mapping)>,
random_line_split
gimli.rs
if let Some(lib) = load_library(&me) { ret.push(lib); } if Module32NextW(snap, &mut me)!= TRUE { break; } } } CloseHandle(snap); } un...
mapping_for_lib
identifier_name
types.rs
use javascriptcore_sys::*; use std::convert::TryFrom;
macro_rules! retain_release { ($name:ident, $ffi_ref:ty, $retain_fn:tt, $drop_fn:tt) => { impl Drop for $name { fn drop(&mut self) { unsafe { $drop_fn(self.0) }; } } impl Clone for $name { fn clone(&self) -> $name { let x =...
use std::ffi::CString; use std::ops::Deref; use std::ptr::{null, null_mut};
random_line_split
types.rs
use javascriptcore_sys::*; use std::convert::TryFrom; use std::ffi::CString; use std::ops::Deref; use std::ptr::{null, null_mut}; macro_rules! retain_release { ($name:ident, $ffi_ref:ty, $retain_fn:tt, $drop_fn:tt) => { impl Drop for $name { fn drop(&mut self) { unsafe { $drop_f...
} impl fmt::Debug for Exception { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Exception") .field("stack", &self.stack()) .field("message", &self.message()) .finish() } } impl fmt::Display for Exception { fn fmt(&self, f: &mut fmt::Format...
{ let mut s = f.debug_struct("Object"); unsafe { let array = JSObjectCopyPropertyNames(*self.0, self.1); let size = JSPropertyNameArrayGetCount(array); for i in 0..size { let js_ref = JSPropertyNameArrayGetNameAtIndex(array, i); let pr...
identifier_body
types.rs
use javascriptcore_sys::*; use std::convert::TryFrom; use std::ffi::CString; use std::ops::Deref; use std::ptr::{null, null_mut}; macro_rules! retain_release { ($name:ident, $ffi_ref:ty, $retain_fn:tt, $drop_fn:tt) => { impl Drop for $name { fn drop(&mut self) { unsafe { $drop_f...
<'a>(&'a self, script: &'a String) -> Result<Value, Exception> { self.evaluate_script_sync(script) } pub fn add_function( &self, name: &str, callback: JsCallback, ) -> Result<(), Box<dyn std::error::Error>> { let name = String::new(name).unwrap(); let obj = s...
evaluate_script
identifier_name
tag.rs
//! A dictionary-based tagger. The raw format is tuples of the form `(word, lemma, part-of-speech)` //! where each word typically has multiple entries with different part-of-speech tags. use crate::types::*; use bimap::BiMap; use fs_err::File; use fst::{IntoStreamer, Map, Streamer}; use indexmap::IndexMap; use log::er...
( &self, word: &str, add_lower: bool, add_lower_if_empty: bool, ) -> Vec<WordData> { let mut tags = self.get_raw(&word); let lower = word.to_lowercase(); if (add_lower || (add_lower_if_empty && tags.is_empty())) && (word!= lower &&...
get_strict_tags
identifier_name
tag.rs
//! A dictionary-based tagger. The raw format is tuples of the form `(word, lemma, part-of-speech)` //! where each word typically has multiple entries with different part-of-speech tags. use crate::types::*; use bimap::BiMap; use fs_err::File; use fst::{IntoStreamer, Map, Streamer}; use indexmap::IndexMap; use log::er...
tags = next_tags .into_iter() .map(|mut x| { x.lemma = self.id_word( format!("{}{}", &word[..i], x.lemma.as_ref().to_lowercase()) .into...
{ let indices = word .char_indices() .take(std::cmp::max(n_chars - 4, 0) as usize) .skip(1) .map(|x| x.0); // the word always has at least one char if the above condition is satisfied // but s...
conditional_block
tag.rs
//! A dictionary-based tagger. The raw format is tuples of the form `(word, lemma, part-of-speech)` //! where each word typically has multiple entries with different part-of-speech tags. use crate::types::*; use bimap::BiMap; use fs_err::File; use fst::{IntoStreamer, Map, Streamer}; use indexmap::IndexMap; use log::er...
let reader = std::io::BufReader::new(file); for line in reader.lines() { let line = line?; if line.starts_with('#') { continue; } if disallowed.contains(&line) { continue; } ...
random_line_split
tag.rs
//! A dictionary-based tagger. The raw format is tuples of the form `(word, lemma, part-of-speech)` //! where each word typically has multiple entries with different part-of-speech tags. use crate::types::*; use bimap::BiMap; use fs_err::File; use fst::{IntoStreamer, Map, Streamer}; use indexmap::IndexMap; use log::er...
}
{ self.word_store .get_by_left(lemma) .and_then(|x| self.groups.get(x)) .map(|vec| vec.iter().map(|x| self.str_for_word_id(x)).collect()) .unwrap_or_else(Vec::new) }
identifier_body
rca.rs
// Optimization for RCA // Ordinarily, just a, b, c, and d are scanned separately and then combined by joins. // a: (each product, each city) // can be cut on drill 1 // b: (all products, each city) // c: (each product, all cities) // can be cut on drill 1 // d: (all products, all cities) // // Note that external cuts ...
( table: &TableSql, cuts: &[CutSql], drills: &[DrilldownSql], meas: &[MeasureSql], rca: &RcaSql, ) -> (String, String) { // append the correct rca drill to drilldowns // for a, both // for b, d2 // for c, d1 // for d, none let mut a_drills = drills.to_vec(); let mut b...
calculate
identifier_name
rca.rs
// Optimization for RCA // Ordinarily, just a, b, c, and d are scanned separately and then combined by joins. // a: (each product, each city) // can be cut on drill 1 // b: (all products, each city) // c: (each product, all cities) // can be cut on drill 1 // d: (all products, all cities) // // Note that external cuts ...
else { format!("groupArray({col}_{alias_postfix}) as {col}_{alias_postfix}_s", col=l.key_column, alias_postfix=alias_postfix) } }) }); let group_array_rca_drill_2 = join(group_array_rca_drill_2, ", "); let join_array_rca_drill_2 = rca.drill_2.iter() ...
{ format!("groupArray({key_col}_{alias_postfix}) as {key_col}_{alias_postfix}_s, groupArray({name_col}_{alias_postfix}) as {name_col}_{alias_postfix}_s", key_col=l.key_column, name_col=name_col, alias_postfix=alias_postfix) }
conditional_block
rca.rs
// Optimization for RCA // Ordinarily, just a, b, c, and d are scanned separately and then combined by joins. // a: (each product, each city) // can be cut on drill 1 // b: (all products, each city) // c: (each product, all cities) // can be cut on drill 1 // d: (all products, all cities) // // Note that external cuts ...
// // The optimization is to derive the c and d aggregates from a and b. Since cuts are allowed on the // first drill in the rca, both a and b have to be scanned (b cannot be cut on the first drill). // // In clickhouse there is no partition, so it's trickier to do what looks like two different group // by. // // The g...
// drill dim).
random_line_split
rca.rs
// Optimization for RCA // Ordinarily, just a, b, c, and d are scanned separately and then combined by joins. // a: (each product, each city) // can be cut on drill 1 // b: (all products, each city) // c: (each product, all cities) // can be cut on drill 1 // d: (all products, all cities) // // Note that external cuts ...
println!("c: {:?}", c_drills); println!("d: {:?}", d_drills); // prepend the rca sql to meas let all_meas = { let mut temp = vec![rca.mea.clone()]; temp.extend_from_slice(meas); temp }; // for cuts, // - a can be cut on d1 and ext // - b cannot be int cut, only ...
{ // append the correct rca drill to drilldowns // for a, both // for b, d2 // for c, d1 // for d, none let mut a_drills = drills.to_vec(); let mut b_drills = drills.to_vec(); let mut c_drills = drills.to_vec(); let d_drills = drills.to_vec(); a_drills.extend_from_slice(&rca...
identifier_body
mod.rs
use std::cell::RefCell; use std::collections::HashMap; use std::fs::{self, File}; use std::path::Path; use glium; use glium::backend::Facade; use image::{self, DynamicImage, GenericImage, Rgba}; use texture_packer::Rect; use texture_packer::SkylinePacker; use texture_packer::{TexturePacker, TexturePackerConfig}; use t...
fn texture_size(&self, texture_idx: usize) -> (u32, u32) { self.textures[texture_idx].dimensions() } fn get_frame(&self, tile_type: &str) -> &AtlasFrame { let tex_name = &self.config.locations[tile_type]; &self.config.frames[tex_name] } pub fn get_tile_texture_idx(&self, ...
{ self.texture_size(frame.texture_idx) }
identifier_body
mod.rs
use std::cell::RefCell; use std::collections::HashMap; use std::fs::{self, File}; use std::path::Path; use glium; use glium::backend::Facade; use image::{self, DynamicImage, GenericImage, Rgba}; use texture_packer::Rect; use texture_packer::SkylinePacker; use texture_packer::{TexturePacker, TexturePackerConfig}; use t...
(&self, tile_idx: usize, msecs: u64) -> (f32, f32) { let kind = self.get_tile_kind_indexed(tile_idx); self.get_texture_offset(kind, msecs) } pub fn get_texture(&self, idx: usize) -> &Texture2d { &self.textures[idx] } pub fn passes(&self) -> usize { self.textures.len() ...
get_texture_offset_indexed
identifier_name
mod.rs
use std::cell::RefCell; use std::collections::HashMap; use std::fs::{self, File}; use std::path::Path; use glium; use glium::backend::Facade; use image::{self, DynamicImage, GenericImage, Rgba}; use texture_packer::Rect; use texture_packer::SkylinePacker; use texture_packer::{TexturePacker, TexturePackerConfig}; use t...
pub fn new(texture_idx: usize, rect: Rect, tile_size: (u32, u32)) -> Self { AtlasFrame { tile_size: tile_size, texture_idx: texture_idx, rect: AtlasRect::from(rect), offsets: HashMap::new(), } } } pub type TilePacker<'a> = TexturePacker<'a, Dynami...
offsets: HashMap<String, AtlasTile>, } impl AtlasFrame {
random_line_split
unbond.rs
use crate::contract::{query_total_issued, slashing}; use crate::state::{ get_finished_amount, get_unbond_batches, read_config, read_current_batch, read_parameters, read_state, read_unbond_history, remove_unbond_wait_list, store_current_batch, store_state, store_unbond_history, store_unbond_wait_list, Unbond...
let max_peg_fee = amount * recovery_fee; let required_peg_fee = ((total_supply + current_batch.requested_with_fee) - state.total_bond_amount)?; let peg_fee = Uint128::min(max_peg_fee, required_peg_fee); amount_with_fee = (amount - peg_fee)?; } else { amount_with_f...
{ // Read params let params = read_parameters(&deps.storage).load()?; let epoch_period = params.epoch_period; let threshold = params.er_threshold; let recovery_fee = params.peg_recovery_fee; let mut current_batch = read_current_batch(&deps.storage).load()?; // Check slashing, update state,...
identifier_body
unbond.rs
use crate::contract::{query_total_issued, slashing}; use crate::state::{ get_finished_amount, get_unbond_batches, read_config, read_current_batch, read_parameters, read_state, read_unbond_history, remove_unbond_wait_list, store_current_batch, store_state, store_unbond_history, store_unbond_wait_list, Unbond...
<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, amount: Uint128, sender: HumanAddr, ) -> StdResult<HandleResponse> { // Read params let params = read_parameters(&deps.storage).load()?; let epoch_period = params.epoch_period; let threshold = params.er_threshold; ...
handle_unbond
identifier_name
unbond.rs
use crate::contract::{query_total_issued, slashing}; use crate::state::{ get_finished_amount, get_unbond_batches, read_config, read_current_batch, read_parameters, read_state, read_unbond_history, remove_unbond_wait_list, store_current_batch, store_state, store_unbond_history, store_unbond_wait_list, Unbond...
})?; // Send the money to the user let msgs = vec![BankMsg::Send { from_address: contract_address.clone(), to_address: sender_human, amount: coins(withdraw_amount.u128(), &*coin_denom), } .into()]; let res = HandleResponse { messages: msgs, log: vec![ ...
Ok(last_state)
random_line_split
main.rs
fuchsia_zircon::{self as zx, AsHandleRef}, futures::{prelude::*, StreamExt}, hyper, std::convert::TryFrom, std::str::FromStr as _, tracing::{debug, error, info, trace}, }; static MAX_REDIRECTS: u8 = 10; static DEFAULT_DEADLINE_DURATION: zx::Duration = zx::Duration::from_seconds(15); fn to_stat...
(mut self, loader_client: net_http::LoaderClientProxy) -> Result<(), zx::Status> { let client = fhyper::new_https_client_from_tcp_options(tcp_options()); loop { break match client.request(self.build_request()).await { Ok(hyper_response) => { let redirect =...
start
identifier_name
main.rs
fuchsia_zircon::{self as zx, AsHandleRef}, futures::{prelude::*, StreamExt}, hyper, std::convert::TryFrom, std::str::FromStr as _, tracing::{debug, error, info, trace}, }; static MAX_REDIRECTS: u8 = 10; static DEFAULT_DEADLINE_DURATION: zx::Duration = zx::Duration::from_seconds(15); fn to_stat...
Err(e) => { debug!("Not redirecting because: {}", e); break Ok(()); } }; trace!("Redirect allowed to {} {}", self.method, self.u...
{ let client = fhyper::new_https_client_from_tcp_options(tcp_options()); loop { break match client.request(self.build_request()).await { Ok(hyper_response) => { let redirect = redirect_info(&self.url, &self.method, &hyper_response); if ...
identifier_body
main.rs
fuchsia_zircon::{self as zx, AsHandleRef}, futures::{prelude::*, StreamExt}, hyper, std::convert::TryFrom, std::str::FromStr as _, tracing::{debug, error, info, trace}, }; static MAX_REDIRECTS: u8 = 10; static DEFAULT_DEADLINE_DURATION: zx::Duration = zx::Duration::from_seconds(15); fn to_sta...
} fn to_error_response(error: net_http::Error) -> net_http::Response { net_http::Response { error: Some(error), body: None, final_url: None, status_code: None, status_line: None, headers: None, redirect: None, ..net_http::Response::EMPTY } } struc...
random_line_split
spritecfg.rs
#![allow(dead_code)] extern crate asar; use std::path::{PathBuf, Path}; use std::io::prelude::*; use std::fs::{File, OpenOptions}; use nom::*; use asar::rom::RomBuf; use parse_aux::dys_prefix; use genus::Genus; use dys_tables::DysTables; use insert_err::{InsertResult, format_result, warnless_result, single_error}; #...
prop_bytes: [d[7], d[8]], source_path: path.with_file_name(s), name: name, name_set: Some(name_set), desc: desc, desc_set: Some(desc_set), .. SpriteCfg::new() }) } else { Err(CfgErr { explain: String::from("Old-style CFG too short") }) } } fn read_byte(s: &str) -> Resul...
{ let mut it = buf.split_whitespace().skip(1); let mut d = [0u8; 9]; for output_byte in &mut d { if let Some(s) = it.next() { *output_byte = try!(read_byte(s)); } else { return Err(CfgErr{ explain: String::from("Old-style CFG too short") }); } }; let (name, name_set) = default_name(path, gen, id); le...
identifier_body
spritecfg.rs
#![allow(dead_code)] extern crate asar; use std::path::{PathBuf, Path}; use std::io::prelude::*; use std::fs::{File, OpenOptions}; use nom::*; use asar::rom::RomBuf; use parse_aux::dys_prefix; use genus::Genus; use dys_tables::DysTables; use insert_err::{InsertResult, format_result, warnless_result, single_error}; #...
if init == 0 && self.needs_init() { return single_error("No init routine"); } if drop == 0 && self.needs_drop() { return single_error("Drop routine required by dys_opts, but not provided"); } if drop!= 0 &&!self.needs_drop() { return single_error("Sprite h...
{ return single_error("No main routine"); }
conditional_block
spritecfg.rs
#![allow(dead_code)] extern crate asar; use std::path::{PathBuf, Path}; use std::io::prelude::*; use std::fs::{File, OpenOptions}; use nom::*; use asar::rom::RomBuf; use parse_aux::dys_prefix; use genus::Genus; use dys_tables::DysTables; use insert_err::{InsertResult, format_result, warnless_result, single_error}; #...
(&self, ebit: bool) -> &String { if ebit && self.name_set.is_some() { self.name_set.as_ref().unwrap() } else { &self.name } } pub fn desc(&self, ebit: bool) -> &String { if ebit && self.desc_set.is_some() { self.desc_set.as_ref().unwrap() } else { &self.desc } } pub fn uses_ebit(&self) -> ...
name
identifier_name
spritecfg.rs
#![allow(dead_code)] extern crate asar; use std::path::{PathBuf, Path}; use std::io::prelude::*; use std::fs::{File, OpenOptions}; use nom::*; use asar::rom::RomBuf; use parse_aux::dys_prefix; use genus::Genus; use dys_tables::DysTables; use insert_err::{InsertResult, format_result, warnless_result, single_error}; #...
{ let mut tempasm = OpenOptions::new() .write(true) .truncate(true) .create(true) .open(temp) .unwrap(); tempasm.write_all(prelude.as_bytes()).unwrap(); let mut source_buf = Vec::<u8>::with_capacity(8 * 102...
random_line_split
jwt.rs
//! # A Firestore Auth Session token is a Javascript Web Token (JWT). This module contains JWT helper functions. use crate::credentials::Credentials; use crate::errors::FirebaseError; use biscuit::jwa::SignatureAlgorithm; use biscuit::{ClaimPresenceOptions, SingleOrMultiple, StringOrUri, ValidationOptions}; use chrono...
.get(&format!( "https://www.googleapis.com/service_accounts/v1/jwk/{}", account_mail )) .send() .await?; let jwk_set: JWKSetDTO = resp.json().await?; Ok(jwk_set) } /// Returns true if the access token (assumed to be a jwt) has expired /// /// An error is ret...
pub async fn download_google_jwks_async(account_mail: &str) -> Result<JWKSetDTO, Error> { let resp = reqwest::Client::new()
random_line_split
jwt.rs
//! # A Firestore Auth Session token is a Javascript Web Token (JWT). This module contains JWT helper functions. use crate::credentials::Credentials; use crate::errors::FirebaseError; use biscuit::jwa::SignatureAlgorithm; use biscuit::{ClaimPresenceOptions, SingleOrMultiple, StringOrUri, ValidationOptions}; use chrono...
{ #[serde(flatten)] pub(crate) headers: biscuit::jws::RegisteredHeader, #[serde(flatten)] pub(crate) ne: biscuit::jwk::RSAKeyParameters, } #[derive(Serialize, Deserialize)] pub struct JWKSetDTO { pub keys: Vec<JWSEntry>, } /// Download the Google JWK Set for a given service account. /// The resul...
JWSEntry
identifier_name
jwt.rs
//! # A Firestore Auth Session token is a Javascript Web Token (JWT). This module contains JWT helper functions. use crate::credentials::Credentials; use crate::errors::FirebaseError; use biscuit::jwa::SignatureAlgorithm; use biscuit::{ClaimPresenceOptions, SingleOrMultiple, StringOrUri, ValidationOptions}; use chrono...
} pub(crate) fn verify_access_token( credentials: &Credentials, access_token: &str, ) -> Result<TokenValidationResult, Error> { verify_access_token_with_claims(credentials, access_token) } pub fn verify_access_token_with_claims<T: PrivateClaims>( credentials: &Credentials, access_token: &str, ) -...
{ self.claims.get_scopes() }
identifier_body
jwt.rs
//! # A Firestore Auth Session token is a Javascript Web Token (JWT). This module contains JWT helper functions. use crate::credentials::Credentials; use crate::errors::FirebaseError; use biscuit::jwa::SignatureAlgorithm; use biscuit::{ClaimPresenceOptions, SingleOrMultiple, StringOrUri, ValidationOptions}; use chrono...
Ok(true) } /// Returns true if the jwt was updated and needs signing pub(crate) fn jwt_update_expiry_if(jwt: &mut AuthClaimsJWT, expire_in_minutes: i64) -> bool { let ref mut claims = jwt.payload_mut().unwrap().registered; let now = biscuit::Timestamp::from(Utc::now()); if let Some(issued_at) = clai...
{ let diff: Duration = Utc::now().signed_duration_since(expiry.deref().clone()); return Ok(diff.num_minutes() - tolerance_in_minutes > 0); }
conditional_block
spy.rs
use crate::{backend::Backend, error::error}; use cloudevents::{ event::{Data, ExtensionValue}, AttributesReader, Event, }; use drogue_cloud_service_api::{EXT_APPLICATION, EXT_DEVICE}; use itertools::Itertools; use patternfly_yew::*; use unicode_segmentation::UnicodeSegmentation; use wasm_bindgen::{closure::Clos...
let on_error = Closure::wrap(Box::new(move || { link.send_message(Msg::Failed); }) as Box<dyn FnMut()>); source.set_onerror(Some(&on_error.into_js_value().into())); // store result self.running = true; self.source = Some(source); } fn stop(&mut self...
// setup onerror let link = self.link.clone();
random_line_split
spy.rs
use crate::{backend::Backend, error::error}; use cloudevents::{ event::{Data, ExtensionValue}, AttributesReader, Event, }; use drogue_cloud_service_api::{EXT_APPLICATION, EXT_DEVICE}; use itertools::Itertools; use patternfly_yew::*; use unicode_segmentation::UnicodeSegmentation; use wasm_bindgen::{closure::Clos...
String, pub Html); impl TableRenderer for AttributeEntry { fn render(&self, index: ColumnIndex) -> Html { match index.index { 0 => html! {&self.0}, 1 => self.1.clone(), _ => html! {}, } } } fn render_details(event: &Event) -> Html { let mut attrs: Vec<A...
ibuteEntry(pub
identifier_name
service.rs
use std::io::Read; use std::sync::{Arc, Mutex}; use std::collections::HashMap; use futures::{self, Future, BoxFuture}; use curl::easy::{Easy, List}; use tokio_core::reactor::Handle; use tokio_curl::{Session, PerformError}; use serde_json::{from_value, from_str, Value}; pub type Fut<T> = BoxFuture<T, PerformError>;...
if task.is_none() { continue; } let task = task.unwrap(); timestamp = task.timestamp; cpus.push(task.cpus_user_time_secs + task.cpus_system_time_secs); mems.push(100.0 * task.mem_rss_bytes as f64 / ...
let mut timestamp: f64 = 0.0; for task in tasks {
random_line_split
service.rs
use std::io::Read; use std::sync::{Arc, Mutex}; use std::collections::HashMap; use futures::{self, Future, BoxFuture}; use curl::easy::{Easy, List}; use tokio_core::reactor::Handle; use tokio_curl::{Session, PerformError}; use serde_json::{from_value, from_str, Value}; pub type Fut<T> = BoxFuture<T, PerformError>;...
for task in tasks { if task.is_none() { continue; } let task = task.unwrap(); timestamp = task.timestamp; cpus.push(task.cpus_user_time_secs + task.cpus_system_time_secs); mems.push(100.0 * ...
{ let mut futs = Vec::new(); for (id, slave_id) in &app.tasks { let url = slaves.get::<String>(&slave_id).unwrap().to_string(); futs.push(self.get_task_statistic(url, id)); } let mut prev_timestamp = 0.0; let mut prev_cpu_time = 0.0; if let Some...
identifier_body
service.rs
use std::io::Read; use std::sync::{Arc, Mutex}; use std::collections::HashMap; use futures::{self, Future, BoxFuture}; use curl::easy::{Easy, List}; use tokio_core::reactor::Handle; use tokio_curl::{Session, PerformError}; use serde_json::{from_value, from_str, Value}; pub type Fut<T> = BoxFuture<T, PerformError>;...
{ handle: Handle, marathon_url: String, mesos_url: String, max_mem_usage: f64, max_cpu_usage: f64, multiplier: f64, max_instances: i64, } impl Service { pub fn new(handle: Handle, marathon_url: String, mesos_url: String, max_mem_usage: f64, max_cpu_usage: f64, ...
Service
identifier_name
service.rs
use std::io::Read; use std::sync::{Arc, Mutex}; use std::collections::HashMap; use futures::{self, Future, BoxFuture}; use curl::easy::{Easy, List}; use tokio_core::reactor::Handle; use tokio_curl::{Session, PerformError}; use serde_json::{from_value, from_str, Value}; pub type Fut<T> = BoxFuture<T, PerformError>;...
("AUTOSCALE_MEM_PERCENT", v) => { max_mem_usage = from_value(v.clone()).unwrap(); } ("AUTOSCALE_CPU_PERCENT", v) => { max_cpu_usage = from_value(v.clone()).unwrap(); } _ =...
{ max_instances = from_value(v.clone()).unwrap(); }
conditional_block
ctx.rs
//! The ØMQ context type. use crate::{auth::server::AuthServer, error::*}; use libzmq_sys as sys; use sys::errno; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use std::{ os::raw::{c_int, c_void}, ptr, str, sync::Arc, thread, }; lazy_static! { static ref GLOBAL_CONTEXT: Ctx ...
/// A value of `true` indicates that all new sockets are given a /// linger timeout of zero. /// pub fn no_linger(&self) -> bool { !self.raw.as_ref().get_bool(RawCtxOption::Blocky) } /// When set to `true`, all new sockets are given a linger timeout /// of zero. /// /// # Defaul...
self.raw.as_ref().get(RawCtxOption::SocketLimit) }
identifier_body
ctx.rs
//! The ØMQ context type. use crate::{auth::server::AuthServer, error::*}; use libzmq_sys as sys; use sys::errno; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use std::{ os::raw::{c_int, c_void}, ptr, str, sync::Arc, thread, }; lazy_static! { static ref GLOBAL_CONTEXT: Ctx ...
Self { ctx } } } /// A config for a [`Ctx`]. /// /// Usefull in configuration files. /// /// [`Ctx`]: struct.Ctx.html #[derive(Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct CtxConfig { io_threads: Option<i32>, max_msg_size: Option<i32>, max_sockets: Option<i32>, ...
panic!(msg_from_errno(unsafe { sys::zmq_errno() })); }
conditional_block
ctx.rs
//! The ØMQ context type. use crate::{auth::server::AuthServer, error::*}; use libzmq_sys as sys; use sys::errno; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use std::{ os::raw::{c_int, c_void}, ptr, str, sync::Arc, thread, }; lazy_static! { static ref GLOBAL_CONTEXT: Ctx ...
IOThreads, MaxSockets, MaxMsgSize, SocketLimit, IPV6, Blocky, } impl From<RawCtxOption> for c_int { fn from(r: RawCtxOption) -> c_int { match r { RawCtxOption::IOThreads => sys::ZMQ_IO_THREADS as c_int, RawCtxOption::MaxSockets => sys::ZMQ_MAX_SOCKETS as c_in...
} #[derive(Copy, Clone, Debug)] enum RawCtxOption {
random_line_split
ctx.rs
//! The ØMQ context type. use crate::{auth::server::AuthServer, error::*}; use libzmq_sys as sys; use sys::errno; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use std::{ os::raw::{c_int, c_void}, ptr, str, sync::Arc, thread, }; lazy_static! { static ref GLOBAL_CONTEXT: Ctx ...
&mut self, value: i32) -> &mut Self { self.inner.set_io_threads(Some(value)); self } /// See [`set_max_msg_size`]. /// /// [`set_max_msg_size`]: struct.Ctx.html#method.set_max_msg_size pub fn max_msg_size(&mut self, value: i32) -> &mut Self { self.inner.set_max_msg_size(Some...
o_threads(
identifier_name
main.rs
HashMap::new(); let mut offsets = Vec::new(); let mut num_bones = 0u32; for mesh in scene.get_meshes().iter() { for bone in mesh.get_bones().iter() { let name = bone.name.to_string(); match bone_map.get(&name) { Some(_) => continu...
// find the textures used by this model from the list of materials for mat in ai_scene.get_materials().iter() { let texture_src = mat.get_texture(ai::material::TextureType::Diffuse, 0 ); ma...
// Create the buffer for the bone transformations. We fill this // up each time we draw, so no need to do it here. let u_bone_transformations: gfx::BufferHandle<Mat4> = graphics.device.create_buffer(MAX_BONES, gfx::BufferUsage::Dynamic);
random_line_split
main.rs
::new(); let mut offsets = Vec::new(); let mut num_bones = 0u32; for mesh in scene.get_meshes().iter() { for bone in mesh.get_bones().iter() { let name = bone.name.to_string(); match bone_map.get(&name) { Some(_) => continue, ...
<'a> { pub vertices: Vec<Vertex>, pub indices: Vec<u32>, pub batches: Vec<ModelComponent>, pub scene: ai::Scene<'a>, pub bone_map: RefCell<BoneMap>, pub global_inverse: ai::Matrix4x4, pub bone_transform_buffer: gfx::BufferHandle<Mat4>, } #[inline(always)] fn lerp<S, T: Add<T,T> + Sub<T,T> +...
Model
identifier_name
lib.rs
use bitflags::bitflags; use std::{ fmt, fs::{File, OpenOptions}, io::{self, prelude::*, Result, SeekFrom}, iter, mem::{self, MaybeUninit}, ops::{Deref, DerefMut}, os::unix::{ fs::OpenOptionsExt, io::AsRawFd, }, ptr, slice, }; mod arch; mod kernel; macro_rules! trace...
/// breakpoint event, it returns an event handler that lets you /// handle events yourself. pub fn next_event(&mut self, flags: Flags) -> Result<EventHandler> { trace!(flags, self.file.write(&flags.bits().to_ne_bytes())?); Ok(EventHandler { inner: self }) } /// Convert this tracer to...
random_line_split
lib.rs
use bitflags::bitflags; use std::{ fmt, fs::{File, OpenOptions}, io::{self, prelude::*, Result, SeekFrom}, iter, mem::{self, MaybeUninit}, ops::{Deref, DerefMut}, os::unix::{ fs::OpenOptionsExt, io::AsRawFd, }, ptr, slice, }; mod arch; mod kernel; macro_rules! trace...
{ pub file: File, pub regs: Registers, pub mem: Memory, } impl Tracer { /// Attach to a tracer with the specified PID. This will stop it. pub fn attach(pid: Pid) -> Result<Self> { Ok(Self { file: OpenOptions::new() .read(true) .write(true) ...
Tracer
identifier_name
server.rs
use std::io::IoResult; use crypto::sha1::Sha1; use crypto::digest::Digest; use serialize::base64::{ToBase64, STANDARD}; use std::ascii::AsciiExt; use time; use std::io::{Listener, Acceptor}; use std::io::net::tcp::TcpListener; use std::io::net::tcp::TcpStream; use http::buffer::BufferedStream; use std::thread::Thread...
let mut sh = Sha1::new(); let mut out = [0u8; 20]; sh.input_str((String::from_str(sec_websocket_key) + WEBSOCKET_SALT).as_slice()); sh.result(out.as_mut_slice()); return out.to_base64(STANDARD); } // check if the http request is a web socket upgrade request, and return ...
{ // NOTE from RFC 6455 // // To prove that the handshake was received, the server has to take two // pieces of information and combine them to form a response. The first // piece of information comes from the |Sec-WebSocket-Key| header field // in the client handshake: ...
identifier_body
server.rs
use std::io::IoResult; use crypto::sha1::Sha1; use crypto::digest::Digest; use serialize::base64::{ToBase64, STANDARD}; use std::ascii::AsciiExt; use time; use std::io::{Listener, Acceptor}; use std::io::net::tcp::TcpListener; use std::io::net::tcp::TcpStream;
use http::server::{Server, Request, ResponseWriter}; use http::status::SwitchingProtocols; use http::headers::HeaderEnum; use http::headers::response::Header::ExtensionHeader; use http::headers::connection::Connection::Token; use http::method::Method::Get; pub use message::Payload::{Text, Binary, Empty}; pub use messa...
use http::buffer::BufferedStream; use std::thread::Thread; use std::sync::mpsc::{channel, Sender, Receiver};
random_line_split
server.rs
use std::io::IoResult; use crypto::sha1::Sha1; use crypto::digest::Digest; use serialize::base64::{ToBase64, STANDARD}; use std::ascii::AsciiExt; use time; use std::io::{Listener, Acceptor}; use std::io::net::tcp::TcpListener; use std::io::net::tcp::TcpStream; use http::buffer::BufferedStream; use std::thread::Thread...
(&self, r: Request, w: &mut ResponseWriter) -> bool { // TODO allow configuration of endpoint for websocket match (r.method.clone(), r.headers.upgrade.clone()){ // (&Get, &Some("websocket"), &Some(box [Token(box "Upgrade")])) => //\{ FIXME this doesn't work. but client must have the header "...
handle_possible_ws_request
identifier_name
x25519.rs
use core::ops::{Deref, DerefMut}; use super::common::*; use super::error::Error; use super::field25519::*; const POINT_BYTES: usize = 32; /// Non-uniform output of a scalar multiplication. /// This represents a point on the curve, and should not be used directly as a /// cipher key. #[derive(Clone, Debug, Eq, Partia...
sk_.copy_from_slice(sk); Ok(SecretKey::new(sk_)) } /// Perform the X25519 clamping magic pub fn clamped(&self) -> SecretKey { let mut clamped = self.clone(); clamped[0] &= 248; clamped[31] &= 63; clamped[31] |= 64; clamped } /// Recover the ...
{ return Err(Error::InvalidSecretKey); }
conditional_block
x25519.rs
use core::ops::{Deref, DerefMut}; use super::common::*; use super::error::Error; use super::field25519::*; const POINT_BYTES: usize = 32; /// Non-uniform output of a scalar multiplication. /// This represents a point on the curve, and should not be used directly as a /// cipher key. #[derive(Clone, Debug, Eq, Partia...
(dh: DHOutput) -> Self { PublicKey(dh.0) } } impl From<DHOutput> for SecretKey { fn from(dh: DHOutput) -> Self { SecretKey(dh.0) } } impl Drop for DHOutput { fn drop(&mut self) { Mem::wipe(self.0) } } /// A public key. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub...
from
identifier_name
x25519.rs
use core::ops::{Deref, DerefMut}; use super::common::*; use super::error::Error; use super::field25519::*; const POINT_BYTES: usize = 32; /// Non-uniform output of a scalar multiplication. /// This represents a point on the curve, and should not be used directly as a /// cipher key. #[derive(Clone, Debug, Eq, Partia...
let sk_1 = SecretKey::from_slice(&[ 1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]) .unwrap(); let output = PublicKey::base_point().unclamped_mul(&sk_1).unwrap(); assert_eq!(PublicKey::from(output), PublicKey::base_point()); let...
#[cfg(not(feature = "disable-signatures"))] pub use from_ed25519::*; #[test] fn test_x25519() {
random_line_split
physically_monotonic.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
( &self, ctx: &Context<Self::Domain>, id: &Id, _keys: &AvailableCollections, _plan: &GetPlan, ) -> Self::Domain { // A get operator yields physically monotonic output iff the corresponding // `Plan::Get` is on a local or global ID that is known to provide phys...
get
identifier_name
physically_monotonic.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
&self, _ctx: &Context<Self::Domain>, input: Self::Domain, _forms: &AvailableCollections, _input_key: &Option<Vec<MirScalarExpr>>, _input_mfp: &MapFilterProject, ) -> Self::Domain { // `Plan::ArrangeBy` is better thought of as `ensure_collections`, i.e., it ...
fn arrange_by(
random_line_split
web.rs
//! This is the initial MVP of the events service to get the BDD tests to work use db; use models::user::IOModel; use models::user::pg::PgModel as UserModel; use rouille; use rouille::input::post; use rouille::{Request, Response}; use services::user; use services::user::Service as UserService; use std::collections::Has...
#[test] fn test_form_to_password_grant() { assert_eq!( form_to_password_grant(&vec![ ("grant_type".into(), "password".into()), ("username".into(), "test-user".into()), ("password".into(), "test-password".into()), ]).unwrap(), user::PasswordGrantRequest { ...
{ let fields = form_to_map(fields); let username = fields.get("username").ok_or(WebError::MissingUsername)?; let password = fields.get("password").ok_or(WebError::MissingPassword)?; Ok(user::PasswordGrantRequest { username, password }) }
identifier_body
web.rs
//! This is the initial MVP of the events service to get the BDD tests to work use db; use models::user::IOModel; use models::user::pg::PgModel as UserModel; use rouille; use rouille::input::post; use rouille::{Request, Response}; use services::user; use services::user::Service as UserService; use std::collections::Has...
<'a> { pub status: &'a str, } /// this is the status endpoint fn status(user_model: &UserModel) -> Response { let status = user_model .find(&Uuid::new_v4()) .map(|_| Status { status: "up" }) .unwrap_or_else(|_| Status { status: "down" }); Response::json(&status) } #[derive(Deserializ...
Status
identifier_name
web.rs
//! This is the initial MVP of the events service to get the BDD tests to work use db; use models::user::IOModel; use models::user::pg::PgModel as UserModel; use rouille; use rouille::input::post; use rouille::{Request, Response}; use services::user; use services::user::Service as UserService; use std::collections::Has...
); assert_eq!( form_to_password_grant(&vec![("password".into(), "test-pass".into())]).unwrap_err(), WebError::MissingUsername ); } /// Converts the Form Fields into a `RefreshGrantRequest` fn form_to_refresh_grant(fields: &Fields) -> Result<user::RefreshGrantRequest, WebError> { let fi...
WebError::MissingPassword
random_line_split
chmod.rs
// // Copyright (c) 2018, The MesaLock Linux Project Contributors // All rights reserved. // // This work is licensed under the terms of the BSD 3-Clause License. // For a copy, see the LICENSE file. // // This file incorporates work covered by the following copyright and // permission notice: // // Copyright (c) 2...
.validator_os(validate_mode) .required(true)) //.conflicts_with("reference")) .arg(Arg::with_name("FILES") .index(2) .required(true) .mult...
random_line_split
chmod.rs
// // Copyright (c) 2018, The MesaLock Linux Project Contributors // All rights reserved. // // This work is licensed under the terms of the BSD 3-Clause License. // For a copy, see the LICENSE file. // // This file incorporates work covered by the following copyright and // permission notice: // // Copyright (c) 2...
(data: String) -> Self { Self { kind: MessageKind::Stdout, data, } } pub fn stderr(data: String) -> Self { Self { kind: MessageKind::Stderr, data, } } } struct Options<'a> { verbosity: Verbosity, preserve_root: bool, ...
stdout
identifier_name
chmod.rs
// // Copyright (c) 2018, The MesaLock Linux Project Contributors // All rights reserved. // // This work is licensed under the terms of the BSD 3-Clause License. // For a copy, see the LICENSE file. // // This file incorporates work covered by the following copyright and // permission notice: // // Copyright (c) 2...
} } } 0 } } } #[cfg(unix)] fn change_file( options: &Options, msgs: &mut [Option<Message>; 2], fperm: u32, mode: u32, file: &Path, ) -> i32 { if fperm == mode { if options.verbosity == Verbosity::Verbose { ...
{ let cmode_unwrapped = options.cmode.clone().unwrap(); for mode in cmode_unwrapped.split(',') { // cmode is guaranteed to be Some in this case let arr: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7']; let result = if mode.contains(arr) { ...
conditional_block
file.rs
use crate::reader::{LittleEndian, ReadBytesExt, Reader}; use std::fmt; use std::io::Read; use thiserror::Error; const ELF_MAGIC: [u8; 4] = [0x7f, b'E', b'L', b'F']; fn show_machine(value: u16) -> &'static str { match value { 0 => "No machine", 1 => "AT&T WE 32100", 2 => "SUN SPARC", ...
pub enum FileClass { // Invalid class None, // 32-bit objects ElfClass32, // 64 bit objects ElfClass64, // Unknown class Invalid(u8), } #[derive(Debug)] pub enum Encoding { // Invalid data encoding None, // 2's complement, little endian LittleEndian, // 2's complemen...
#[derive(Debug)]
random_line_split
file.rs
use crate::reader::{LittleEndian, ReadBytesExt, Reader}; use std::fmt; use std::io::Read; use thiserror::Error; const ELF_MAGIC: [u8; 4] = [0x7f, b'E', b'L', b'F']; fn show_machine(value: u16) -> &'static str { match value { 0 => "No machine", 1 => "AT&T WE 32100", 2 => "SUN SPARC", ...
{ // Invalid data encoding None, // 2's complement, little endian LittleEndian, // 2's complement big endian BigEndian, // Uknown data encoding Invalid(u8), } #[derive(Debug)] pub enum OsAbi { // UNIX System V ABI UnixVSystem, // HP-UX HpUx, // NetBDS NetBsd, ...
Encoding
identifier_name
mod.rs
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use deno_core::error::bad_resource_id; use deno_core::error::type_error; use deno_core::error::AnyError; use deno_core::op; use deno_core::OpState; use libz_sys::*; use std::borrow::Cow; use std::cell::RefCell; use std::future::Future; use std:...
(state: &mut OpState, handle: u32) -> Result<(), AnyError> { let resource = zlib(state, handle)?; let mut zlib = resource.inner.borrow_mut(); // If there is a pending write, defer the close until the write is done. zlib.close()?; Ok(()) } #[op] pub fn op_zlib_write_async( state: Rc<RefCell<OpState>>, h...
op_zlib_close
identifier_name
mod.rs
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use deno_core::error::bad_resource_id; use deno_core::error::type_error; use deno_core::error::AnyError; use deno_core::op; use deno_core::OpState; use libz_sys::*; use std::borrow::Cow; use std::cell::RefCell; use std::future::Future; use std:...
} self.err = match self.mode { Mode::Deflate | Mode::Gzip | Mode::DeflateRaw => self.strm.deflate_init( self.level, self.window_bits, self.mem_level, self.strategy, ), Mode::Inflate | Mode::Gunzip | Mode::InflateRaw | Mode::Unzip => { self.strm.inflate...
{}
conditional_block
mod.rs
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use deno_core::error::bad_resource_id; use deno_core::error::type_error; use deno_core::error::AnyError; use deno_core::op; use deno_core::OpState; use libz_sys::*; use std::borrow::Cow; use std::cell::RefCell; use std::future::Future; use std:...
} struct Zlib { inner: RefCell<ZlibInner>, } impl deno_core::Resource for Zlib { fn name(&self) -> Cow<str> { "zlib".into() } } #[op] pub fn op_zlib_new(state: &mut OpState, mode: i32) -> Result<u32, AnyError> { let mode = Mode::try_from(mode)?; let inner = ZlibInner { mode, ..Default::default...
{ self.err = self.strm.reset(self.mode); Ok(()) }
identifier_body
mod.rs
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use deno_core::error::bad_resource_id; use deno_core::error::type_error; use deno_core::error::AnyError; use deno_core::op; use deno_core::OpState; use libz_sys::*; use std::borrow::Cow; use std::cell::RefCell; use std::future::Future; use std:...
self.pending_close = false; check(self.init_done, "close before init")?; self.strm.end(self.mode); self.mode = Mode::None; Ok(true) } fn reset_stream(&mut self) -> Result<(), AnyError> { self.err = self.strm.reset(self.mode); Ok(()) } } struct Zlib { inner: RefCell<ZlibInner>, } ...
self.pending_close = true; return Ok(false); }
random_line_split
mod.rs
mod assignments; mod colors; mod directory_stack; mod flow; /// The various blocks pub mod flow_control; mod job; mod pipe_exec; mod shell_expand; mod signals; pub mod sys; /// Variables for the shell pub mod variables; use self::{ directory_stack::DirectoryStack, flow_control::{Block, Function, FunctionError,...
(&mut self) -> &mut BuiltinMap<'a> { &mut self.builtins } /// Access to the shell options #[must_use] pub const fn opts(&self) -> &Options { &self.opts } /// Mutable access to the shell options #[must_use] pub fn opts_mut(&mut self) -> &mut Options { &mut self.opts } /// Access to the var...
builtins_mut
identifier_name
mod.rs
mod assignments; mod colors; mod directory_stack; mod flow; /// The various blocks pub mod flow_control; mod job; mod pipe_exec; mod shell_expand; mod signals; pub mod sys; /// Variables for the shell pub mod variables; use self::{ directory_stack::DirectoryStack, flow_control::{Block, Function, FunctionError,...
/// Set the callback to call on each command pub fn set_on_command(&mut self, callback: Option<OnCommandCallback<'a>>) { self.on_command = callback; } /// Set the callback to call on each command pub fn on_command_mut(&mut self) -> &mut Option<OnCommandCallback<'a>> { &mut self.on_command...
{ &mut self.pre_command }
identifier_body
mod.rs
mod assignments; mod colors; mod directory_stack; mod flow; /// The various blocks pub mod flow_control; mod job; mod pipe_exec; mod shell_expand; mod signals; pub mod sys; /// Variables for the shell pub mod variables; use self::{ directory_stack::DirectoryStack, flow_control::{Block, Function, FunctionError,...
flow_control: Block, /// Contains the directory stack parameters. directory_stack: DirectoryStack, /// When a command is executed, the final result of that command is stored /// here. previous_status: Status, /// The job ID of the previous command sent to the background. prev...
/// started. builtins: BuiltinMap<'a>, /// Contains the aliases, strings, and array variable maps. variables: Variables, /// Contains the current state of flow control parameters.
random_line_split
lib.rs
//! The SGX root enclave //! //! ## Authors //! //! The Veracruz Development Team. //! //! ## Licensing and copyright notice //! //! See the `LICENSE_MIT.markdown` file in the Veracruz root directory for //! information on licensing and copyright. #![no_std] #[macro_use] extern crate sgx_tstd as std; use lazy_static:...
let mut dh_aek: sgx_key_128bit_t = sgx_key_128bit_t::default(); // Session Key, we won't use this let mut responder_identity = sgx_dh_session_enclave_identity_t::default(); let status = initiator.proc_msg3(&dh_msg3, &mut dh_aek, &mut responder_identity); if status.is_err() { return SgxRootEncl...
let dh_msg3_raw_len = mem::size_of::<sgx_dh_msg3_t>() as u32 + dh_msg3_raw.msg3_body.additional_prop_length; let dh_msg3 = unsafe { SgxDhMsg3::from_raw_dh_msg3_t(dh_msg3_raw, dh_msg3_raw_len) }; assert!(!dh_msg3.is_none()); let dh_msg3 = match dh_msg3 { Some(msg) => msg, None =...
identifier_body
lib.rs
//! The SGX root enclave //! //! ## Authors //! //! The Veracruz Development Team. //! //! ## Licensing and copyright notice //! //! See the `LICENSE_MIT.markdown` file in the Veracruz root directory for //! information on licensing and copyright. #![no_std] #[macro_use] extern crate sgx_tstd as std; use lazy_static:...
p_fwv_len: &mut usize) -> sgx_status_t { let version = env!("CARGO_PKG_VERSION"); *p_fwv_len = version.len(); sgx_status_t::SGX_SUCCESS } #[no_mangle] pub extern "C" fn get_firmware_version( p_firmware_version_buf: *mut u8, fv_buf_size: usize, ) -> sgx_status_t { let version = env!("CARGO_PKG_V...
et_firmware_version_len(
identifier_name
lib.rs
//! The SGX root enclave //! //! ## Authors //! //! The Veracruz Development Team. //! //! ## Licensing and copyright notice //! //! See the `LICENSE_MIT.markdown` file in the Veracruz root directory for //! information on licensing and copyright. #![no_std] #[macro_use] extern crate sgx_tstd as std; use lazy_static:...
} #[no_mangle] pub extern "C" fn sgx_get_collateral_report( p_pubkey_challenge: *const u8, pubkey_challenge_size: usize, p_target_info: *const sgx_target_info_t, report: *mut sgx_types::sgx_report_t, csr_buffer: *mut u8, csr_buf_size: usize, p_csr_size: *mut usize, ) -> sgx_status_t { l...
*private_key_guard = Some(pkcs8_bytes.as_ref().to_vec()); pkcs8_bytes.as_ref().to_vec() } }; return Ok(pkcs8_bytes);
random_line_split
main.rs
#![allow(clippy::needless_return)] #![feature(portable_simd)] use core_simd::Simd; use core::convert::TryInto; use srng::SRng; use simd_aes::SimdAes; const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([ 178, 201, 95, 240, 40, 41, 143, 216, 2, 209, 178, 114, 232, 4, 176, 188, ]); #[allow(non_snake_case)] fn ...
fn chosen_prefix(prefix: &[u8]) { let zero = Simd::splat(0); let mut message = prefix.to_vec(); let remainder = 16 - (message.len() % 16); message.extend((0..remainder).map(|_| b'A')); message.extend((0..16).map(|_| 0)); let hash = ComputeGlyphHash(&message); let pre_current = invert_last(...
{ let mut target_hash = Simd::<u64, 2>::from_array([message.len() as u64, 0]).to_ne_bytes(); target_hash ^= DEFAULT_SEED; let prefix = single_prefix(message.len(), target_hash); println!("Demonstrating prefix attack"); println!("message: {:x?}", message); println!("hash: {:x?}", ComputeGlyph...
identifier_body
main.rs
#![allow(clippy::needless_return)] #![feature(portable_simd)] use core_simd::Simd; use core::convert::TryInto; use srng::SRng; use simd_aes::SimdAes; const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([ 178, 201, 95, 240, 40, 41, 143, 216, 2, 209, 178, 114, 232, 4, 176, 188, ]); #[allow(non_snake_case)] fn ...
(prefix: Simd<u8, 16>, target: &[u8]) -> Vec<u8> { let mut image = prefix.to_array().to_vec(); image.extend_from_slice(target); image } fn prefix_collision_attack(message: &[u8]) { let mut target_hash = Simd::<u64, 2>::from_array([message.len() as u64, 0]).to_ne_bytes(); target_hash ^= DEFAULT_SEED...
concat
identifier_name
main.rs
#![allow(clippy::needless_return)] #![feature(portable_simd)] use core_simd::Simd; use core::convert::TryInto; use srng::SRng; use simd_aes::SimdAes; const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([ 178, 201, 95, 240, 40, 41, 143, 216, 2, 209, 178, 114, 232, 4, 176, 188, ]); #[allow(non_snake_case)] fn ...
b" known methods: https://m1el.github.io/refterm-hash", b" Best regards, -- Igor", ]; fn main() { padding_attack(); invert_attack(b"Qwerty123"); prefix_collision_attack(b"hello"); chosen_prefix(b"hello"); preimage_attack(b"hello"); const THREADS: u64 = 16; for msg in MESSAGE { ...
br#" two strings "A" and "B\x00" yield the same hash, because"#, b" the padding is constant, so zero byte in the end doens't", b" matter, and the first byte is `xor`ed with input length.", b" If you'd like to, you can read this blog post explaining", b" these attacks in detail and how to avoid them us...
random_line_split
main.rs
#![allow(clippy::needless_return)] #![feature(portable_simd)] use core_simd::Simd; use core::convert::TryInto; use srng::SRng; use simd_aes::SimdAes; const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([ 178, 201, 95, 240, 40, 41, 143, 216, 2, 209, 178, 114, 232, 4, 176, 188, ]); #[allow(non_snake_case)] fn ...
buffer[0] ^= len as u8; let recovered = &buffer[..len]; println!("recovered: {:x?}", recovered); println!("hash: {:x?}", ComputeGlyphHash(recovered)); println!(); } pub fn check_alphanum(bytes: Simd<u8, 16>) -> bool { // check if the characters are outside of '0'..'z' range if (bytes ...
{ println!("the plaintext mus be shorter than 16 bytes, cannot invert"); return; }
conditional_block
lib.rs
//! The crate serves as an bindings to the official (outdated) //! [dota2 webapi](https://dev.dota2.com/forum/dota-2/spectating/replays/webapi/60177-things-you-should-know-before-starting?t=58317) //! The crate has been made so you can call make calls directly and get a result back in a Struct. //! //! Read the full li...
} impl From<serde_json::Error> for Error { fn from(e: serde_json::Error) -> Error { Error::Json(e) } } /// The main `Dota2Api` of you library works by saving states of all the invoked URLs (you only call the one you need) /// language macro for easy implementation in various builder struct /// /// Th...
{ Error::Http(e) }
identifier_body
lib.rs
//! The crate serves as an bindings to the official (outdated) //! [dota2 webapi](https://dev.dota2.com/forum/dota-2/spectating/replays/webapi/60177-things-you-should-know-before-starting?t=58317) //! The crate has been made so you can call make calls directly and get a result back in a Struct. //! //! Read the full li...
self.$builder = $build::build(&*self.key); &mut self.$builder } }; } /// A `get!` macro to get our `get` functions macro_rules! get { ($func: ident, $return_type: ident, $builder: ident, $result: ident) => { pub fn $func(&mut self) -> Result<$return_type, Error> { ...
pub fn $func(&mut self) -> &mut $build {
random_line_split
lib.rs
//! The crate serves as an bindings to the official (outdated) //! [dota2 webapi](https://dev.dota2.com/forum/dota-2/spectating/replays/webapi/60177-things-you-should-know-before-starting?t=58317) //! The crate has been made so you can call make calls directly and get a result back in a Struct. //! //! Read the full li...
(&mut self, param_value: usize) -> &mut Self { self.url.push_str(&*format!("match_id={}&", param_value)); self } } builder!( GetTopLiveGameBuilder, "http://api.steampowered.com/IDOTA2Match_570/GetTopLiveGame/v1/?key={}&" ); impl GetTopLiveGameBuilder { language!(); /// Which partne...
match_id
identifier_name
lib.rs
//! The crate serves as an bindings to the official (outdated) //! [dota2 webapi](https://dev.dota2.com/forum/dota-2/spectating/replays/webapi/60177-things-you-should-know-before-starting?t=58317) //! The crate has been made so you can call make calls directly and get a result back in a Struct. //! //! Read the full li...
let _ = response.read_to_string(&mut temp); Ok(temp) } } //============================================================================== //IEconDOTA2_570 //============================================================================== builder!( GetHeroesBuilder, "http://api.steampowered....
{ return Err(Error::Forbidden( "Access is denied. Retrying will not help. Please check your API key.", )); }
conditional_block
lib.rs
//! Error handling layer for axum that supports extractors and async functions. //! //! This crate provides [`HandleErrorLayer`] which works similarly to //! [`axum::error_handling::HandleErrorLayer`] except that it supports //! extractors and async functions: //! //! ```rust //! use axum::{ //! Router, //! Box...
clippy::suboptimal_flops, clippy::lossy_float_literal, clippy::rest_pat_in_fully_bound_structs, clippy::fn_params_excessive_bools, clippy::exit, clippy::inefficient_to_string, clippy::linkedlist, clippy::macro_use_imports, clippy::option_option, clippy::verbose_file_reads, cl...
clippy::imprecise_flops,
random_line_split
lib.rs
//! Error handling layer for axum that supports extractors and async functions. //! //! This crate provides [`HandleErrorLayer`] which works similarly to //! [`axum::error_handling::HandleErrorLayer`] except that it supports //! extractors and async functions: //! //! ```rust //! use axum::{ //! Router, //! Box...
(&self) -> Self { Self { f: self.f.clone(), _extractor: PhantomData, } } } impl<F, E> fmt::Debug for HandleErrorLayer<F, E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HandleErrorLayer") .field("f", &format_args!("{}", ...
clone
identifier_name
manifest.rs
//! Reproducible package manifest data. pub use self::sources::Source; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use toml::de::Error as DeserializeError; use self::outputs::Outpu...
<T, U>(name: T, version: T, default_output_hash: T, refs: U) -> ManifestBuilder where T: AsRef<str>, U: IntoIterator<Item = OutputId>, { ManifestBuilder::new(name, version, default_output_hash, refs) } /// Computes the content-addressable ID of this manifest. /// /// # E...
build
identifier_name
manifest.rs
//! Reproducible package manifest data. pub use self::sources::Source; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use toml::de::Error as DeserializeError; use self::outputs::Outpu...
} /// Builder for creating new `Manifest`s. #[derive(Clone, Debug)] pub struct ManifestBuilder { package: Result<Package, ()>, env: BTreeMap<String, String>, sources: Sources, outputs: Result<Outputs, ()>, } impl ManifestBuilder { /// Creates a `Manifest` with the given name, version, default out...
{ toml::from_str(s) }
identifier_body
manifest.rs
//! Reproducible package manifest data. pub use self::sources::Source; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use toml::de::Error as DeserializeError; use self::outputs::Outpu...
name: Name, version: String, dependencies: BTreeSet<ManifestId>, build_dependencies: BTreeSet<ManifestId>, dev_dependencies: BTreeSet<ManifestId>, } /// A reproducible package manifest. #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] pub struct Manifest { package: Package, ...
struct Package {
random_line_split
manifest.rs
//! Reproducible package manifest data. pub use self::sources::Source; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use toml::de::Error as DeserializeError; use self::outputs::Outpu...
self } /// Adds a build dependency on `id`. /// /// # Laziness /// /// This kind of dependency is only downloaded when the package is being built from source. /// Otherwise, the dependency is ignored. Artifacts from build dependencies cannot be linked to /// at runtime. pub...
{ p.dependencies.insert(id); }
conditional_block