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
block.rs
//! Implementations of cryptographic attacks against block ciphers. use utils::data::Data; use utils::metrics; use victims::block::{EcbOrCbc, EcbWithSuffix, EcbWithAffixes, EcbUserProfile, CbcCookie}; /// Determine whether a block cipher is using ECB or CBC mode. /// /// Given a black box which encrypts (padded) user...
test_block.push(byte as u8); let output = ecb_affixes_box.encrypt(&Data::from_bytes(test_block)); if &output.bytes()[output_start..output_start + block_size] == block { suffix.push(byte as u8); continue 'outer; } } } Data::...
let output_start = prefix_len + extra_padding; for byte in 0..256 { let mut test_block = vec![0; block_size - (prefix_len % block_size)]; test_block.extend_from_slice(partial_block);
random_line_split
block.rs
//! Implementations of cryptographic attacks against block ciphers. use utils::data::Data; use utils::metrics; use victims::block::{EcbOrCbc, EcbWithSuffix, EcbWithAffixes, EcbUserProfile, CbcCookie}; /// Determine whether a block cipher is using ECB or CBC mode. /// /// Given a black box which encrypts (padded) user...
let output = ecb_suffix_box.encrypt(&Data::from_bytes(test_bytes)); assert!(metrics::has_repeated_blocks(&output, block_size)); // Keep track of the suffix bytes that we have decrypted so far. let mut suffix = Vec::new(); // Decrypt the suffix one byte at a time. 'outer: loop { // Pad...
{ // Determine the block size by repeatedly encrypting larger chunks of data until the output // jumps in length. let block_size; let base_len = ecb_suffix_box.encrypt(&Data::new()).len(); let mut cnt = 1; loop { let bytes = vec![0; cnt]; let input = Data::from_bytes(bytes); ...
identifier_body
block.rs
//! Implementations of cryptographic attacks against block ciphers. use utils::data::Data; use utils::metrics; use victims::block::{EcbOrCbc, EcbWithSuffix, EcbWithAffixes, EcbUserProfile, CbcCookie}; /// Determine whether a block cipher is using ECB or CBC mode. /// /// Given a black box which encrypts (padded) user...
} } Data::from_bytes(suffix) } /// Find the length of an unknown prefix which is appended to ECB-encrypted messages. fn find_ecb_prefix_len(ecb_affixes_box: &EcbWithAffixes, block_size: usize) -> usize { // Find the block in which the prefix ends, by finding the first block which is different up...
{ suffix.push(byte as u8); continue 'outer; }
conditional_block
lib.rs
//! # sunvox-sys //! //! FFI bindings to the Sunvox library (http://warmplace.ru/soft/sunvox). // --- Crate attributes --- // #![allow(non_camel_case_types)] // --- ==== --- // // --- External crates --- // extern crate libc; // --- ==== --- // // --- Use --- // use libc::{c_void, c_int, c_uint, c_char, c_uchar, ...
{ /// The note column. /// /// - 0: Nothing. /// - 1 to 127 inclusive: A normal note. /// - 128+: See the `NOTECMD` constants. pub note: c_uchar, /// The velocity column (note velocity). /// /// - 0: Empty (default). /// - 1 to 129 inclusive: The specified velocity + 1. pu...
sunvox_note
identifier_name
lib.rs
//! # sunvox-sys //! //! FFI bindings to the Sunvox library (http://warmplace.ru/soft/sunvox). // --- Crate attributes --- // #![allow(non_camel_case_types)] // --- ==== --- // // --- External crates --- // extern crate libc; // --- ==== --- // // --- Use --- // use libc::{c_void, c_int, c_uint, c_char, c_uchar, ...
/// A single note cell in a pattern. #[repr(C)] #[derive(Clone, Debug)] pub struct sunvox_note { /// The note column. /// /// - 0: Nothing. /// - 1 to 127 inclusive: A normal note. /// - 128+: See the `NOTECMD` constants. pub note: c_uchar, /// The velocity column (note velocity). ///...
random_line_split
ctap.rs
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Client to Authenticator Protocol CTAPv2 over USB HID //! //! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-...
fn enable(&'a self) { // Set up the default control endpoint self.client_ctrl.enable(); // Setup buffers for IN and OUT data transfer. self.controller() .endpoint_set_out_buffer(ENDPOINT_NUM, &self.buffers[OUT_BUFFER].buf); self.controller() .endpoint_s...
} impl<'a, U: hil::usb::UsbController<'a>> hil::usb::Client<'a> for CtapHid<'a, U> {
random_line_split
ctap.rs
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Client to Authenticator Protocol CTAPv2 over USB HID //! //! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-...
} else { // Make sure to put the RX buffer back. self.recv_buffer.replace(buf); hil::usb::OutResult::Ok } }) } TransferType::Bulk | TransferTyp...
{ // We can't receive data. Record that we have data to send later // and apply back pressure to USB self.saved_endpoint.set(endpoint); self.recv_buffer.replace(buf); ...
conditional_block
ctap.rs
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Client to Authenticator Protocol CTAPv2 over USB HID //! //! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-...
} fn receive_cancel(&'a self) -> Result<&'static mut [u8; 64], ErrorCode> { self.saved_endpoint.take(); match self.recv_buffer.take() { Some(buf) => Ok(buf), None => Err(ErrorCode::BUSY), } } } impl<'a, U: hil::usb::UsbController<'a>> hil::usb::Client<'a> f...
{ self.recv_buffer.replace(recv); if self.saved_endpoint.is_some() { // We have saved data from before, let's pass it. if self.can_receive() { self.recv_buffer.take().map(|buf| { self.client.map(move |client| { client.p...
identifier_body
ctap.rs
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Client to Authenticator Protocol CTAPv2 over USB HID //! //! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-...
(&'a self, endpoint: usize) { self.client_ctrl.ctrl_status(endpoint) } /// Handle the completion of a Control transfer fn ctrl_status_complete(&'a self, endpoint: usize) { if self.send_buffer.is_some() { self.controller().endpoint_resume_in(ENDPOINT_NUM); } self...
ctrl_status
identifier_name
block.rs
use ::slice::Slice; use ::errors::RubbleResult; use ::util::coding; use ::status::Status; use ::comparator::SliceComparator; use std::mem; use std::str; pub struct OwnedBlock { data: Vec<u8>, restart_offset: usize, } pub struct SliceBlock<'a> { data: Slice<'a>, restart_offset: usize, } pub trait Bloc...
impl<'a> SliceBlock<'a> { fn get_size(&self) -> usize { self.data.len() } } struct DecodedEntry<'a> { new_slice: Slice<'a>, shared: u32, non_shared: u32, value_length: u32, } /// Helper routine: decode the next block entry starting at "p", /// storing the number of shared key bytes, non_shared key...
random_line_split
block.rs
use ::slice::Slice; use ::errors::RubbleResult; use ::util::coding; use ::status::Status; use ::comparator::SliceComparator; use std::mem; use std::str; pub struct OwnedBlock { data: Vec<u8>, restart_offset: usize, } pub struct SliceBlock<'a> { data: Slice<'a>, restart_offset: usize, } pub trait Bloc...
fn get_restart_point(&self, index: usize) -> usize { assert!(index < self.num_restarts); let offset = self.restarts + index * mem::size_of::<u32>(); coding::decode_fixed32(&self.data[offset..]) as usize } pub fn seek_to_restart_point(&mut self, index: usize) { self...
{ self.value_offset + self.value_len }
identifier_body
block.rs
use ::slice::Slice; use ::errors::RubbleResult; use ::util::coding; use ::status::Status; use ::comparator::SliceComparator; use std::mem; use std::str; pub struct OwnedBlock { data: Vec<u8>, restart_offset: usize, } pub struct SliceBlock<'a> { data: Slice<'a>, restart_offset: usize, } pub trait Bloc...
(&self, a: Slice, b: Slice) -> i32 { self.comparator.compare(a, b) } /// Return the offset in data_ just past the end of the current entry. fn next_entry_offset(&self) -> usize { self.value_offset + self.value_len } fn get_restart_point(&self, index: usize) -> usize { ...
compare
identifier_name
generator.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Implementation of Generator thread and Generator trait. //! //! Generator thread accept a set of serializable arguments. use { crate::common_operat...
() { let mut command_count = ActiveCommands::new(); assert_eq!(command_count.count(), 0); let mut command_count_copy = command_count.clone(); command_count.increment(); let thd = thread::spawn(move || { sleep(time::Duration::from_secs(1)); // First repay...
active_command_block_test
identifier_name
generator.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Implementation of Generator thread and Generator trait. //! //! Generator thread accept a set of serializable arguments. use { crate::common_operat...
command_count: Arc<(Mutex<u64>, Condvar)>, } impl ActiveCommands { pub fn new() -> ActiveCommands { ActiveCommands { command_count: Arc::new((Mutex::new(0), Condvar::new())) } } /// Decrements number of active commands. Waits on the condition variable if /// command_count is zero. Returns ...
random_line_split
generator.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Implementation of Generator thread and Generator trait. //! //! Generator thread accept a set of serializable arguments. use { crate::common_operat...
/// Based on the input args this returns a generator that can generate requested /// IO load.For now we only allow sequential io. fn pick_generator_type(args: &GeneratorArgs, target_id: u64) -> Box<dyn Generator> { if!args.sequential { panic!("Only sequential io generator is implemented at the moment"); ...
{ let mut operations: Vec<OperationType> = vec![]; if args.operations.write { operations.push(OperationType::Write); } else { assert!(false); } return operations; }
identifier_body
generator.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Implementation of Generator thread and Generator trait. //! //! Generator thread accept a set of serializable arguments. use { crate::common_operat...
else { assert!(false); } return operations; } /// Based on the input args this returns a generator that can generate requested /// IO load.For now we only allow sequential io. fn pick_generator_type(args: &GeneratorArgs, target_id: u64) -> Box<dyn Generator> { if!args.sequential { panic!("...
{ operations.push(OperationType::Write); }
conditional_block
main.rs
#![feature(try_from)] extern crate itertools; extern crate ketos; extern crate minutiae; extern crate pcg; extern crate rand; extern crate uuid; use std::fmt::{self, Debug, Formatter}; use std::rc::Rc; use ketos::{Context, GlobalScope, Scope, Value}; use ketos::compile::compile; use ketos::bytecode::Code; use ketos:...
context, cell_action_executor, self_action_executor, entity_action_executor ) { Ok(()) => (), Err(err) => println!("Error while retrieving action buffers from context: {}", err), ...
} match process_action_buffers(
random_line_split
main.rs
#![feature(try_from)] extern crate itertools; extern crate ketos; extern crate minutiae; extern crate pcg; extern crate rand; extern crate uuid; use std::fmt::{self, Debug, Formatter}; use std::rc::Rc; use ketos::{Context, GlobalScope, Scope, Value}; use ketos::compile::compile; use ketos::bytecode::Code; use ketos:...
(context: &Context, universe_index: usize) { let scope: &GlobalScope = context.scope(); scope.add_named_value("__CELL_ACTIONS", Value::Unit); scope.add_named_value("__SELF_ACTIONS", Value::Unit); scope.add_named_value("__ENTITY_ACTIONS", Value::Unit); scope.add_named_value("UNIVERSE_INDEX", Value::I...
reset_action_buffers
identifier_name
main.rs
#![feature(try_from)] extern crate itertools; extern crate ketos; extern crate minutiae; extern crate pcg; extern crate rand; extern crate uuid; use std::fmt::{self, Debug, Formatter}; use std::rc::Rc; use ketos::{Context, GlobalScope, Scope, Value}; use ketos::compile::compile; use ketos::bytecode::Code; use ketos:...
} #[cfg(feature = "wasm")] fn init( universe: U, engine: OurSerialEngine ) { use minutiae::emscripten::{EmscriptenDriver, CanvasRenderer}; let driver = EmscriptenDriver; driver.init(universe, engine, &mut [ Box::new(MinDelay::from_tps(59.99)), Box::new(CanvasRenderer::new(UNIVERS...
{ match cell.state.contents { CellContents::Anthill => [222, 233, 244, 255], CellContents::Empty => [12, 12, 12, 255], CellContents::Food(_) => [200, 30, 40, 255], // TODO: Different colors for different food amounts CellContents::Filled(_) => [230, 230, 230, 255]...
conditional_block
main.rs
#![feature(try_from)] extern crate itertools; extern crate ketos; extern crate minutiae; extern crate pcg; extern crate rand; extern crate uuid; use std::fmt::{self, Debug, Formatter}; use std::rc::Rc; use ketos::{Context, GlobalScope, Scope, Value}; use ketos::compile::compile; use ketos::bytecode::Code; use ketos:...
} #[derive(Clone)] struct MES(ketos::Value); impl Default for MES { fn default() -> Self { MES(ketos::Value::Unit) } } impl MutEntityState for MES {} enum CA { } impl CellAction<CS> for CA {} #[derive(Debug)] enum EA { } type U = Universe2D<CS, ES, MES>; fn map_value_to_self_action(val: &Valu...
{ ES::Ant(ant) }
identifier_body
lower.rs
//! Methods for lower the HIR to types. pub(crate) use self::diagnostics::LowerDiagnostic; use crate::resolve::{HasResolver, TypeNs}; use crate::ty::{Substitution, TyKind}; use crate::{ arena::map::ArenaMap, code_model::StructKind, diagnostics::DiagnosticSink, name_resolution::Namespace, primitive_...
CallableDef::Struct(s) => fn_sig_for_struct_constructor(db, s), } } pub(crate) fn fn_sig_for_fn(db: &dyn HirDatabase, def: Function) -> FnSig { let data = def.data(db.upcast()); let resolver = def.id.resolver(db.upcast()); let params = data .params() .iter() .map(|tr| Ty::f...
random_line_split
lower.rs
//! Methods for lower the HIR to types. pub(crate) use self::diagnostics::LowerDiagnostic; use crate::resolve::{HasResolver, TypeNs}; use crate::ty::{Substitution, TyKind}; use crate::{ arena::map::ArenaMap, code_model::StructKind, diagnostics::DiagnosticSink, name_resolution::Namespace, primitive_...
pub(crate) fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: Struct) -> FnSig { let data = def.data(db.upcast()); let resolver = def.id.resolver(db.upcast()); let params = data .fields .iter() .map(|(_, field)| Ty::from_hir(db, &resolver, data.type_ref_map(), field.type_ref)...
{ let data = def.data(db.upcast()); let resolver = def.id.resolver(db.upcast()); let params = data .params() .iter() .map(|tr| Ty::from_hir(db, &resolver, data.type_ref_map(), *tr).0) .collect::<Vec<_>>(); let ret = Ty::from_hir(db, &resolver, data.type_ref_map(), *data.r...
identifier_body
lower.rs
//! Methods for lower the HIR to types. pub(crate) use self::diagnostics::LowerDiagnostic; use crate::resolve::{HasResolver, TypeNs}; use crate::ty::{Substitution, TyKind}; use crate::{ arena::map::ArenaMap, code_model::StructKind, diagnostics::DiagnosticSink, name_resolution::Namespace, primitive_...
else { type_for_struct(db, def) } } fn type_for_struct(_db: &dyn HirDatabase, def: Struct) -> Ty { TyKind::Struct(def).intern() } fn type_for_type_alias(_db: &dyn HirDatabase, def: TypeAlias) -> Ty { TyKind::TypeAlias(def).intern() } pub mod diagnostics { use crate::diagnostics::{PrivateAcce...
{ TyKind::FnDef(def.into(), Substitution::empty()).intern() }
conditional_block
lower.rs
//! Methods for lower the HIR to types. pub(crate) use self::diagnostics::LowerDiagnostic; use crate::resolve::{HasResolver, TypeNs}; use crate::ty::{Substitution, TyKind}; use crate::{ arena::map::ArenaMap, code_model::StructKind, diagnostics::DiagnosticSink, name_resolution::Namespace, primitive_...
(self) -> bool { matches!(self, CallableDef::Struct(_)) } } impl HasVisibility for CallableDef { fn visibility(&self, db: &dyn HirDatabase) -> Visibility { match self { CallableDef::Struct(strukt) => strukt.visibility(db), CallableDef::Function(function) => function.visi...
is_struct
identifier_name
movegen.rs
Drop; use std::iter::ExactSizeIterator; use std::mem; #[derive(Copy, Clone, PartialEq, PartialOrd)]
square: Square, bitboard: BitBoard, promotion: bool, } impl SquareAndBitBoard { pub fn new(sq: Square, bb: BitBoard, promotion: bool) -> SquareAndBitBoard { SquareAndBitBoard { square: sq, bitboard: bb, promotion: promotion, } } } pub type MoveLi...
pub struct SquareAndBitBoard {
random_line_split
movegen.rs
; use std::iter::ExactSizeIterator; use std::mem; #[derive(Copy, Clone, PartialEq, PartialOrd)] pub struct SquareAndBitBoard { square: Square, bitboard: BitBoard, promotion: bool, } impl SquareAndBitBoard { pub fn new(sq: Square, bb: BitBoard, promotion: bool) -> SquareAndBitBoard { SquareAndB...
() { movegen_perft_test("8/8/8/8/8/p7/8/k1K5 b - - 0 1".to_owned(), 6, 2217); } #[test] fn movegen_perft_23() { movegen_perft_test("8/k1P5/8/1K6/8/8/8/8 w - - 0 1".to_owned(), 7, 567584); } #[test] fn movegen_perft_24() { movegen_perft_test("8/8/8/8/1k6/8/K1p5/8 b - - 0 1".to_owned(), 7, 567584); } #[tes...
movegen_perft_22
identifier_name
movegen.rs
; use std::iter::ExactSizeIterator; use std::mem; #[derive(Copy, Clone, PartialEq, PartialOrd)] pub struct SquareAndBitBoard { square: Square, bitboard: BitBoard, promotion: bool, } impl SquareAndBitBoard { pub fn new(sq: Square, bb: BitBoard, promotion: bool) -> SquareAndBitBoard { SquareAndB...
#[test] fn movegen_perft_2() { movegen_perft_test("8/8/1k6/8/2pP4/8/5BK1/8 b - d3 0 1".to_owned(), 6, 824064); // Invalid FEN } #[test] fn movegen_perft_3() { movegen_perft_test("8/8/1k6/2b5/2pP4/8/5K2/8 b - d3 0 1".to_owned(), 6, 1440467); } #[test] fn movegen_perft_4() { movegen_perft_test("8/5k2/...
{ movegen_perft_test("8/5bk1/8/2Pp4/8/1K6/8/8 w - d6 0 1".to_owned(), 6, 824064); // Invalid FEN }
identifier_body
update_menu.rs
//! Buttons and Dropdowns. use plotly_derive::FieldSetter; use serde::Serialize; use serde_json::{Map, Value}; use crate::{ color::Color, common::{Anchor, Font, Pad}, Relayout, Restyle, }; /// Sets the Plotly method to be called on click. If the `skip` method is used, /// the API updatemenu will function...
() { let button = Button::new() .args(json!([ { "visible": [true, false] }, { "width": 20}, ])) .args2(json!([])) .execute(true) .label("Label") .method(ButtonMethod::Update) .name("Name") .t...
test_serialize_button
identifier_name
update_menu.rs
use plotly_derive::FieldSetter; use serde::Serialize; use serde_json::{Map, Value}; use crate::{ color::Color, common::{Anchor, Font, Pad}, Relayout, Restyle, }; /// Sets the Plotly method to be called on click. If the `skip` method is used, /// the API updatemenu will function as normal but will perform ...
//! Buttons and Dropdowns.
random_line_split
update_menu.rs
//! Buttons and Dropdowns. use plotly_derive::FieldSetter; use serde::Serialize; use serde_json::{Map, Value}; use crate::{ color::Color, common::{Anchor, Font, Pad}, Relayout, Restyle, }; /// Sets the Plotly method to be called on click. If the `skip` method is used, /// the API updatemenu will function...
"execute": true, "label": "Label", "method": "update", "name": "Name", "templateitemname": "Template", "visible": true, }); assert_eq!(to_value(button).unwrap(), expected); } #[test] fn test_button_builder() { ...
{ let button = Button::new() .args(json!([ { "visible": [true, false] }, { "width": 20}, ])) .args2(json!([])) .execute(true) .label("Label") .method(ButtonMethod::Update) .name("Name") ...
identifier_body
index_lookup.rs
// Copyright 2019 Zhizhesihai (Beijing) Technology Limited. // // 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 a...
} pub fn set_document(&mut self, doc_id: i32) -> Result<()> { let mut current_doc_pos = self.current_doc(); if current_doc_pos < doc_id { current_doc_pos = self.postings.as_mut().unwrap().advance(doc_id)?; } if current_doc_pos == doc_id && doc_id < NO_MORE_DOCS { ...
{ NO_MORE_DOCS }
conditional_block
index_lookup.rs
// Copyright 2019 Zhizhesihai (Beijing) Technology Limited. // // 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 a...
fn current_doc(&self) -> DocId { if let Some(ref postings) = self.postings { postings.doc_id() } else { NO_MORE_DOCS } } pub fn set_document(&mut self, doc_id: i32) -> Result<()> { let mut current_doc_pos = self.current_doc(); if current_doc...
{ self.freq }
identifier_body
index_lookup.rs
// Copyright 2019 Zhizhesihai (Beijing) Technology Limited. // // 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 a...
<T: PostingIterator> { postings: Option<T>, flags: u16, iterator: LeafPositionIterator, #[allow(dead_code)] identifier: Term, freq: i32, } impl<T: PostingIterator> LeafIndexFieldTerm<T> { pub fn new<TI: TermIterator<Postings = T>, Tm: Terms<Iterator = TI>, F: Fields<Terms = Tm>>( te...
LeafIndexFieldTerm
identifier_name
index_lookup.rs
// Copyright 2019 Zhizhesihai (Beijing) Technology Limited. // // 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 a...
LeafIndexFieldTerm<<<T::Terms as Terms>::Iterator as TermIterator>::Postings>, >, field_name: String, doc_id: DocId, fields: T, } /// // Script interface to all information regarding a field. // impl<T: Fields + Clone> LeafIndexField<T> { pub fn new(field_name: &str, doc_id: DocId, fields: ...
terms: HashMap< String,
random_line_split
main.rs
use clap::*; use gre::*; use noise::*; use rand::prelude::*; use rayon::prelude::*; use std::f64::consts::PI; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Parser)] #[clap()] pub struct Opts { #[clap(short, long, default_value = "image.svg")] file: String, #[clap(short, long, default_va...
() { let opts: Opts = Opts::parse(); let groups = art(&opts); let mut document = base_document("white", opts.width, opts.height); for g in groups { document = document.add(g); } svg::save(opts.file, &document).unwrap(); } struct PaintMask { mask: Vec<bool>, precision: f64, width: f64, height: f...
main
identifier_name
main.rs
use clap::*; use gre::*; use noise::*; use rand::prelude::*; use rayon::prelude::*; use std::f64::consts::PI; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Parser)] #[clap()] pub struct Opts { #[clap(short, long, default_value = "image.svg")] file: String, #[clap(short, long, default_va...
passage.count_once_from(&localpassage); } routes = paths; let bounds = (pad, pad, width - pad, height - pad); let in_shape = |p: (f64, f64)| -> bool { !mask.is_painted(p) && strictly_in_boundaries(p, bounds) }; let does_overlap = |c: &VCircle| { in_shape((c.x, c.y)) && circle_route((c.x...
{ paths.push(path); }
conditional_block
main.rs
use clap::*; use gre::*; use noise::*; use rand::prelude::*; use rayon::prelude::*; use std::f64::consts::PI; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Parser)] #[clap()] pub struct Opts { #[clap(short, long, default_value = "image.svg")] file: String, #[clap(short, long, default_va...
fn index(self: &Self, (x, y): (f64, f64)) -> usize { let wi = (self.width / self.granularity).ceil() as usize; let hi = (self.height / self.granularity).ceil() as usize; let xi = ((x / self.granularity).round() as usize).max(0).min(wi - 1); let yi = ((y / self.granularity).round() as usize).max(0).mi...
{ let wi = (width / granularity).ceil() as usize; let hi = (height / granularity).ceil() as usize; let counters = vec![0; wi * hi]; Passage2DCounter { granularity, width, height, counters, } }
identifier_body
main.rs
use clap::*; use gre::*; use noise::*; use rand::prelude::*; use rayon::prelude::*; use std::f64::consts::PI; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Parser)] #[clap()] pub struct Opts { #[clap(short, long, default_value = "image.svg")] file: String, #[clap(short, long, default_va...
routes.push(heart(x, y, r, ang)); } routes } fn art(opts: &Opts) -> Vec<Group> { let width = opts.width; let height = opts.height; let cw = width / 2.; let ch = height / 2.; let pad = 5.; let cols = (width / cw).floor() as usize; let rows = (height / ch).floor() as usize; let offsetx = 0.0;...
PI + (c.x - width / 2.0).atan2(c.y - height / 2.0) };
random_line_split
runner.rs
comn::TickNum, ReceivedState>, received_events: BTreeMap<comn::TickNum, Vec<comn::Event>>, prediction: Option<Prediction>, interp_game_time: comn::GameTime, next_tick_num: Option<comn::TickNum>, start_time: Instant, recv_tick_time: GameTimeEstimation, next_time_warp_factor: f32, ping...
if!self.recv_tick_time.has_started() { // If this is the first tick we have recevied from the server, reset // to the correct time self.interp_game_time = recv_game_time; info!("Starting tick stream at recv_game_time={}", recv_game_time); } let m...
{ let recv_tick_num = tick.diff.tick_num; let recv_game_time = self.settings.tick_game_time(recv_tick_num); // Keep some statistics for debugging... self.stats.loss.record_received(recv_tick_num.0 as usize); if let Some(my_last_input_num) = tick.your_last_input_num.as_ref() { ...
identifier_body
runner.rs
<comn::TickNum, ReceivedState>, received_events: BTreeMap<comn::TickNum, Vec<comn::Event>>, prediction: Option<Prediction>, interp_game_time: comn::GameTime, next_tick_num: Option<comn::TickNum>, start_time: Instant, recv_tick_time: GameTimeEstimation, next_time_warp_factor: f32, pin...
} state } pub fn next_entities(&self) -> BTreeMap<comn::EntityId, (comn::GameTime, comn::Entity)> { let mut entities = BTreeMap::new(); // Add entities from authorative state, if available. let next_state = self .next_tick_num .and_then(|key| self...
.map(|(entity_id, entity)| (*entity_id, entity.clone())), ); }
random_line_split
runner.rs
comn::TickNum, ReceivedState>, received_events: BTreeMap<comn::TickNum, Vec<comn::Event>>, prediction: Option<Prediction>, interp_game_time: comn::GameTime, next_tick_num: Option<comn::TickNum>, start_time: Instant, recv_tick_time: GameTimeEstimation, next_time_warp_factor: f32, ping...
(&self) -> &Stats { &self.stats } pub fn ping(&self) -> &PingEstimation { &self.ping } pub fn interp_game_time(&self) -> comn::GameTime { self.interp_game_time } fn target_time_lag(&self) -> comn::GameTime { self.settings.tick_period() * 1.5 } fn tick_...
stats
identifier_name
runner.rs
comn::TickNum, ReceivedState>, received_events: BTreeMap<comn::TickNum, Vec<comn::Event>>, prediction: Option<Prediction>, interp_game_time: comn::GameTime, next_tick_num: Option<comn::TickNum>, start_time: Instant, recv_tick_time: GameTimeEstimation, next_time_warp_factor: f32, ping...
} // Remove events for older ticks, we will no longer need them. Note, // however, that the same cannot be said about the received states, // since we may still need them as the basis for delta decoding. // Received states are only pruned when we receive new states. { ...
{ self.next_tick_num = Some(*min_ready_num); }
conditional_block
on_initialize.rs
#![allow(unused)] use crate::process::ShellCommand; use crate::stdio_server::job; use crate::stdio_server::provider::{Context, ProviderSource}; use crate::tools::ctags::ProjectCtagsCommand; use crate::tools::rg::{RgTokioCommand, RG_EXEC_CMD}; use anyhow::Result; use filter::SourceItem; use printer::{DisplayLines, Print...
Ok(Err(e)) => tracing::error!(?e, "Error occurred while initializing the provider source"), Err(_) => { // The initialization was not super fast. tracing::debug!(timeout =?TIMEOUT, "Did not receive value in time"); let source_cmd: Vec<String> = ctx.vim.bare_call("pro...
{ // Skip the initialization. match ctx.provider_id() { "grep" | "live_grep" => return Ok(()), _ => {} } if ctx.env.source_is_list { let ctx = ctx.clone(); ctx.set_provider_source(ProviderSource::Initializing); // Initialize the list-style providers in another ta...
identifier_body
on_initialize.rs
#![allow(unused)] use crate::process::ShellCommand; use crate::stdio_server::job; use crate::stdio_server::provider::{Context, ProviderSource}; use crate::tools::ctags::ProjectCtagsCommand; use crate::tools::rg::{RgTokioCommand, RG_EXEC_CMD}; use anyhow::Result; use filter::SourceItem; use printer::{DisplayLines, Print...
(ctx: &Context, init_display: bool) -> Result<()> { // Skip the initialization. match ctx.provider_id() { "grep" | "live_grep" => return Ok(()), _ => {} } if ctx.env.source_is_list { let ctx = ctx.clone(); ctx.set_provider_source(ProviderSource::Initializing); //...
initialize_provider
identifier_name
on_initialize.rs
#![allow(unused)] use crate::process::ShellCommand; use crate::stdio_server::job; use crate::stdio_server::provider::{Context, ProviderSource}; use crate::tools::ctags::ProjectCtagsCommand; use crate::tools::rg::{RgTokioCommand, RG_EXEC_CMD}; use anyhow::Result; use filter::SourceItem; use printer::{DisplayLines, Print...
}; return Ok(provider_source); } "help_tags" => { let helplang: String = ctx.vim.eval("&helplang").await?; let runtimepath: String = ctx.vim.eval("&runtimepath").await?; let doc_tags = std::iter::once("/doc/tags".to_string()).chain( ...
} }
random_line_split
on_initialize.rs
#![allow(unused)] use crate::process::ShellCommand; use crate::stdio_server::job; use crate::stdio_server::provider::{Context, ProviderSource}; use crate::tools::ctags::ProjectCtagsCommand; use crate::tools::rg::{RgTokioCommand, RG_EXEC_CMD}; use anyhow::Result; use filter::SourceItem; use printer::{DisplayLines, Print...
}) .collect::<Vec<_>>(); on_initialized_source(to_small_provider_source(lines), &ctx, init_display)?; } Ok(()) } pub async fn initialize_provider(ctx: &Context, init_display: bool) -> Result<()> { // Skip the initialization. match ctx.provider_id() { "grep" | "l...
{ None }
conditional_block
mod.rs
use std::path::{Path}; use std::fs::{File, PathExt}; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use std::ffi::CString; use alsa::{PCM, Stream, Mode, Format, Access, Prepared}; use std::collections::VecDeque; use std; use num; #[derive(Clone)] pub struct Complex<T> { pub i: T, ...
else { self.tapi - ti }; si += self.tapvi[off] * self.taps[ti]; sq += self.tapvq[off] * self.taps[ti]; } self.tapi += 1; if self.tapi >= self.taps.len() { self.tapi = 0; } ...
{ self.taps.len() - (ti - self.tapi)}
conditional_block
mod.rs
use std::path::{Path}; use std::fs::{File, PathExt}; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use std::ffi::CString; use alsa::{PCM, Stream, Mode, Format, Access, Prepared}; use std::collections::VecDeque; use std; use num; #[derive(Clone)] pub struct Complex<T> { pub i: T, ...
} pub struct Alsa { sps: u32, pcm: PCM<Prepared>, } impl Alsa { pub fn new(sps: u32) -> Alsa { let pcm = PCM::open("default", Stream::Playback, Mode::Blocking).unwrap(); let mut pcm = pcm.set_parameters(Format::FloatLE, Access::Interleaved, 1, sps as usize).ok().unw...
{ let i = self.i * a.i - self.q * a.q; let q = self.i * a.q + self.q * a.i; self.i = i; self.q = q; }
identifier_body
mod.rs
use std::path::{Path}; use std::fs::{File, PathExt}; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use std::ffi::CString; use alsa::{PCM, Stream, Mode, Format, Access, Prepared}; use std::collections::VecDeque; use std; use num; #[derive(Clone)] pub struct Complex<T> { pub i: T, ...
(freq: f64, sps: f64, amp: f32) -> Option<Vec<Complex<f32>>> { // Do not build if too low in frequency. if freq.abs() < 500.0 { return Option::Some(vec![Complex { i: 1.0, q: 0.0 } ]); } if freq * 4.0 > sps { return Option::None; } // How many of our smallest units of time r...
buildsine
identifier_name
mod.rs
use std::path::{Path}; use std::fs::{File, PathExt}; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use std::ffi::CString; use alsa::{PCM, Stream, Mode, Format, Access, Prepared}; use std::collections::VecDeque; use std; use num; #[derive(Clone)] pub struct Complex<T> { pub i: T, ...
// let tmp = mem::transmute::<&Vec<i8>, &Vec<u8>>(buf); // fd.write(tmp.as_slice()); //} } pub struct FileSource { fp: File, } impl FileSource { pub fn new(path: String) -> FileSource { FileSource { fp: File::open(path).unwrap(), } } ...
for x in 0..buf.len() { fd.write_f32::<LittleEndian>(buf[x]); } //unsafe {
random_line_split
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ Overwrite, // str is the extension of the new file NewFile(&'static str), // Write the output to stdout. Display, // Return the result as a mapping from filenames to StringBuffers. Return(&'static Fn(HashMap<String, String>)), } #[derive(Copy, Clone, Eq, PartialEq, Debug)] enum BraceStyl...
WriteMode
identifier_name
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[cfg(test)] mod test { use std::collections::HashMap; use std::fs; use std::io::Read; use std::sync::atomic; use super::*; use super::run; // For now, the only supported regression tests are idempotent tests - the input and // output must match exactly. // FIXME(#28) would be good ...
random_line_split
main.rs
extern crate chrono; extern crate fastcgi; extern crate htmlescape; extern crate postgres; extern crate quick_xml; extern crate regex; extern crate reqwest; extern crate rss; extern crate serde; extern crate tiny_keccak; extern crate uuid; use std::io; use std::io::Write; type UtcDateTime = chrono::DateTime<chrono::U...
<W: Write>(url: &str, pages: &[Page], out: &mut W) -> Result<(), PagefeedError> { #[derive(serde::Serialize)] #[serde(rename = "opml")] struct Opml<'a> { version: &'a str, head: Head, body: Body<'a>, } #[derive(serde::Serialize)] struct Head {} #[derive(serde::Seria...
build_opml
identifier_name
main.rs
extern crate chrono; extern crate fastcgi; extern crate htmlescape; extern crate postgres; extern crate quick_xml; extern crate regex; extern crate reqwest; extern crate rss; extern crate serde; extern crate tiny_keccak; extern crate uuid; use std::io; use std::io::Write; type UtcDateTime = chrono::DateTime<chrono::U...
fn update_page_changed( conn: &mut postgres::Transaction, page: &Page, new_etag: &Option<String>, new_hash: &Vec<u8>, ) -> Result<(), postgres::error::Error> { let query = " update pages set last_checked = current_timestamp, last_modified = current_timestamp, last_error = null, item_id...
{ let query = " update pages set last_checked = current_timestamp where slug = $1 "; conn.execute(query, &[&page.slug])?; Ok(()) }
identifier_body
main.rs
extern crate chrono; extern crate fastcgi; extern crate htmlescape; extern crate postgres; extern crate quick_xml; extern crate regex; extern crate reqwest; extern crate rss; extern crate serde; extern crate tiny_keccak; extern crate uuid; use std::io; use std::io::Write; type UtcDateTime = chrono::DateTime<chrono::U...
fn describe_page_status(page: &Page) -> String { page.last_error.as_ref().map_or_else( || format!("{} was updated.", page.name), |err| format!("Error while checking {}: {}", page.name, err), ) } fn build_opml<W: Write>(url: &str, pages: &[Page], out: &mut W) -> Result<(), PagefeedError> { #...
random_line_split
main.rs
extern crate chrono; extern crate fastcgi; extern crate htmlescape; extern crate postgres; extern crate quick_xml; extern crate regex; extern crate reqwest; extern crate rss; extern crate serde; extern crate tiny_keccak; extern crate uuid; use std::io; use std::io::Write; type UtcDateTime = chrono::DateTime<chrono::U...
else { handle_feed_request(slug, &mut w) } } fn handle_opml_request<W: Write>(url: &str, out: &mut W) -> Result<(), PagefeedError> { let mut conn = database_connection()?; let mut trans = conn.transaction()?; let pages = get_enabled_pages(&mut trans)?; trans.commit()?; out.write_all(b"...
{ handle_opml_request(&url, &mut w) }
conditional_block
rally.rs
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::Time, ecs::prelude::{Dispatcher, DispatcherBuilder, Entity}, input::{is_close_requested, is_key_down, BindingTypes}, prelude::*, renderer::{ debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams}, ImageForm...
StateEvent::Input(_input) => { //log::info!("Input Event detected: {:?}.", input); Trans::None } } } fn update(&mut self, data: &mut StateData<'_, GameData<'_, '_>>) -> SimpleTrans { if let Some(dispatcher) = self.dispatcher.as_mut() { ...
{ // log::info!( // "[HANDLE_EVENT] You just interacted with a ui element: {:?}", // ui_event // ); Trans::None }
conditional_block
rally.rs
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::Time, ecs::prelude::{Dispatcher, DispatcherBuilder, Entity}, input::{is_close_requested, is_key_down, BindingTypes}, prelude::*, renderer::{ debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams}, ImageForm...
} fn on_resume(&mut self, _data: StateData<'_, GameData<'_, '_>>) { self.paused = false; } fn on_stop(&mut self, data: StateData<'_, GameData<'_, '_>>) { if let Some(root_entity) = self.ui_root { data.world .delete_entity(root_entity) .expect("...
fn on_pause(&mut self, _data: StateData<'_, GameData<'_, '_>>) { self.paused = true;
random_line_split
rally.rs
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::Time, ecs::prelude::{Dispatcher, DispatcherBuilder, Entity}, input::{is_close_requested, is_key_down, BindingTypes}, prelude::*, renderer::{ debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams}, ImageForm...
} #[derive(Debug)] pub struct MovementBindingTypes; impl BindingTypes for MovementBindingTypes { type Axis = AxisBinding; type Action = ActionBinding; }
{ write!(f, "{:?}", self) }
identifier_body
rally.rs
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::Time, ecs::prelude::{Dispatcher, DispatcherBuilder, Entity}, input::{is_close_requested, is_key_down, BindingTypes}, prelude::*, renderer::{ debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams}, ImageForm...
(&mut self, data: StateData<'_, GameData<'_, '_>>) { if let Some(root_entity) = self.ui_root { data.world .delete_entity(root_entity) .expect("Failed to remove Game Screen"); } let fetched_game_score = data.world.try_fetch::<GameScore>(); if le...
on_stop
identifier_name
judger.rs
use crate::config::Config; use crate::{WsMessage, WsStream}; use heng_utils::container::inject; use heng_protocol::common::JudgeResult; use heng_protocol::error::ErrorCode; use heng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudge...
}; let _ = self.session.sender.send(Close(Some(close_frame))).await; return Err(err.into()); } }; match rpc_msg { RpcMessage::Request { seq, body,.....
{ info!("starting main loop"); while let Some(frame) = ws_stream.next().await { use tungstenite::Message::*; let frame = frame?; match frame { Close(reason) => { warn!(?reason, "ws session closed"); return Ok((...
identifier_body
judger.rs
use crate::config::Config; use crate::{WsMessage, WsStream}; use heng_utils::container::inject; use heng_protocol::common::JudgeResult; use heng_protocol::error::ErrorCode; use heng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudge...
(ws_stream: WsStream) -> Result<()> { let config = inject::<Config>(); let (ws_sink, ws_stream) = ws_stream.split(); let (tx, rx) = mpsc::channel::<WsMessage>(4096); task::spawn( ReceiverStream::new(rx) .map(Ok) .forward(ws_sink) ...
run
identifier_name
judger.rs
use crate::config::Config; use crate::{WsMessage, WsStream}; use heng_utils::container::inject; use heng_protocol::common::JudgeResult; use heng_protocol::error::ErrorCode; use heng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudge...
let judger = Arc::new(Self { settings: Settings { status_report_interval: AtomicU64::new(1000), }, session: WsSession { sender: tx, seq: AtomicU32::new(0), callbacks: DashMap::new(), }, c...
ReceiverStream::new(rx) .map(Ok) .forward(ws_sink) .inspect_err(|err| error!(%err, "ws forward error")), );
random_line_split
compile.rs
use std::fs; use std::path::{Path, PathBuf}; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::term::{self, termcolor}; use termcolor::{ColorChoice, StandardStream}; use typst::diag::{bail, Severity, SourceDiagnostic, StrResult}; use typst::doc::Document; use typst::eval::{eco_format, Tr...
Severity::Warning => Diagnostic::warning(), } .with_message(diagnostic.message.clone()) .with_notes( diagnostic .hints .iter() .map(|e| (eco_format!("hint: {e}")).into()) .collect(), ) .with_labels(v...
for diagnostic in warnings.iter().chain(errors.iter()) { let diag = match diagnostic.severity { Severity::Error => Diagnostic::error(),
random_line_split
compile.rs
use std::fs; use std::path::{Path, PathBuf}; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::term::{self, termcolor}; use termcolor::{ColorChoice, StandardStream}; use typst::diag::{bail, Severity, SourceDiagnostic, StrResult}; use typst::doc::Document; use typst::eval::{eco_format, Tr...
.iter() .map(|e| (eco_format!("hint: {e}")).into()) .collect(), ) .with_labels(vec![Label::primary( diagnostic.span.id(), world.range(diagnostic.span), )]); term::emit(&mut w, &config, world, &diag)?; // Stackt...
{ let mut w = match diagnostic_format { DiagnosticFormat::Human => color_stream(), DiagnosticFormat::Short => StandardStream::stderr(ColorChoice::Never), }; let mut config = term::Config { tab_width: 2, ..Default::default() }; if diagnostic_format == DiagnosticFormat::Short { co...
identifier_body
compile.rs
use std::fs; use std::path::{Path, PathBuf}; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::term::{self, termcolor}; use termcolor::{ColorChoice, StandardStream}; use typst::diag::{bail, Severity, SourceDiagnostic, StrResult}; use typst::doc::Document; use typst::eval::{eco_format, Tr...
(&'a self, id: FileId) -> CodespanResult<Self::Name> { let vpath = id.vpath(); Ok(if let Some(package) = id.package() { format!("{package}{}", vpath.as_rooted_path().display()) } else { // Try to express the path relative to the working directory. vpath ...
name
identifier_name
main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[macro_use] extern crate error_chain; use std::cell::{Cell, RefCell}; use std::f32; use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, ...
#[cfg(not(feature = "networking"))] /// Always returns false without the `networking` feature. fn check_for_updates() -> bool { false } #[cfg(feature = "networking")] /// Returns true if updates are available. fn check_for_updates() -> bool { let client; match reqwest::blocking::Client::builder().user_agent("emuls...
random_line_split
main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[macro_use] extern crate error_chain; use std::cell::{Cell, RefCell}; use std::f32; use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, ...
() -> bool { false } #[cfg(feature = "networking")] /// Returns true if updates are available. fn check_for_updates() -> bool { let client; match reqwest::blocking::Client::builder().user_agent("emulsion").build() { Ok(c) => client = c, Err(e) => { println!("Could not build client for version request: {}", e...
check_for_updates
identifier_name
main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[macro_use] extern crate error_chain; use std::cell::{Cell, RefCell}; use std::f32; use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, ...
if!cache_folder.exists() { std::fs::create_dir_all(&cache_folder).unwrap(); } (config_folder.join("cfg.toml"), cache_folder.join("cache.toml")) } #[cfg(not(feature = "networking"))] /// Always returns false without the `networking` feature. fn check_for_updates() -> bool { false } #[cfg(feature = "networking"...
{ std::fs::create_dir_all(&config_folder).unwrap(); }
conditional_block
mod.rs
//! The central Framework struct that ties everything together. // Prefix and slash specific implementation details mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::di...
else { (self.options.on_error)( err, crate::ErrorContext::Command(crate::CommandErrorContext::Prefix(ctx)), ) .await; } } } Event::M...
{ (on_error)(err, ctx).await; }
conditional_block
mod.rs
//! The central Framework struct that ties everything together. // Prefix and slash specific implementation details mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::di...
(&self) -> &U { // We shouldn't get a Message event before a Ready event. But if we do, wait until // the Ready event does come and the resulting data has arrived. loop { match self.user_data.get() { Some(x) => break x, None => tokio::time::sleep(std::...
get_user_data
identifier_name
mod.rs
//! The central Framework struct that ties everything together. // Prefix and slash specific implementation details mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::di...
); return false; } None => return false, }; // If member not in cache (probably because presences intent is not enabled), retrieve via HTTP let member = match guild.members.get(&ctx.author().id) { Some(x) => x.clone(), None => match ctx .di...
{ if required_permissions.is_empty() { return true; } let guild_id = match ctx.guild_id() { Some(x) => x, None => return true, // no permission checks in DMs }; let guild = match ctx.discord().cache.guild(guild_id) { Some(x) => x, None => return false, // Gu...
identifier_body
mod.rs
//! The central Framework struct that ties everything together. // Prefix and slash specific implementation details mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::di...
pub fn application_id(&self) -> serenity::ApplicationId { self.application_id } /// Returns the serenity's client shard manager. pub fn shard_manager(&self) -> std::sync::Arc<tokio::sync::Mutex<ShardManager>> { self.shard_manager .lock() .unwrap() .clone...
&self.options } /// Returns the application ID given to the framework on its creation.
random_line_split
render.rs
extern crate gl; extern crate libc; use vecmath::Vec2; use gl::types::*; use std::ffi::CString; use libc::{c_char, c_int}; use std::mem::{uninitialized, transmute, size_of}; use std::ptr; use std::slice; use std::vec::Vec; use assets; macro_rules! check_error( () => ( match gl::GetError() { gl...
pub fn loaded(&self) -> bool { self.vbo!= 0 } pub unsafe fn load(&mut self) { let mut texture = load_texture(self.filename); texture.generate_texcoords_buffer(self.frame_width, self.frame_height, self.texcoords()); self.texture = texture; gl::GenBuffers(1, &mut self.vbo); ...
{ let count_ptr: *mut usize = &mut self.texcoord_count; slice::from_raw_parts_mut::<Texcoords>( transmute(count_ptr.offset(1)), self.texcoord_count ) }
identifier_body
render.rs
extern crate gl; extern crate libc; use vecmath::Vec2; use gl::types::*; use std::ffi::CString; use libc::{c_char, c_int}; use std::mem::{uninitialized, transmute, size_of}; use std::ptr; use std::slice; use std::vec::Vec; use assets; macro_rules! check_error( () => ( match gl::GetError() { gl...
} } /* fn put_texcoord(&mut self, index: usize, texcoord: Texcoords) { self.texcoords_mut()[index] = texcoord; } */ // NOTE this should be properly merged with add_frames. pub fn generate_texcoords_buffer( &mut self, frame_width: usize, frame_height: usize, space: ...
{ gl::Uniform2fv( frames_uniform, frames_len as GLint * 4, transmute(&(&*self.texcoords_space)[0]) ); }
conditional_block
render.rs
extern crate gl; extern crate libc; use vecmath::Vec2; use gl::types::*; use std::ffi::CString; use libc::{c_char, c_int}; use std::mem::{uninitialized, transmute, size_of}; use std::ptr; use std::slice; use std::vec::Vec; use assets; macro_rules! check_error( () => ( match gl::GetError() { gl...
macro_rules! check_log( ($typ:expr, $get_iv:ident | $get_log:ident $val:ident $status:ident $on_error:ident) => ( unsafe { let mut status = 0; gl::$get_iv($val, gl::$status, &mut status); if status == 0 { let mut len = 0; gl::$get_iv($val,...
color = texture(tex, texcoord); } ";
random_line_split
render.rs
extern crate gl; extern crate libc; use vecmath::Vec2; use gl::types::*; use std::ffi::CString; use libc::{c_char, c_int}; use std::mem::{uninitialized, transmute, size_of}; use std::ptr; use std::slice; use std::vec::Vec; use assets; macro_rules! check_error( () => ( match gl::GetError() { gl...
(&mut self) -> &mut [Texcoords] { let count_ptr: *mut usize = &mut self.texcoord_count; slice::from_raw_parts_mut::<Texcoords>( transmute(count_ptr.offset(1)), self.texcoord_count ) } pub fn loaded(&self) -> bool { self.vbo!= 0 } pub unsafe fn load(&mut self...
texcoords
identifier_name
vault.rs
// ENV: https://www.vaultproject.io/docs/commands/#environment-variables use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Debug; use log::{debug, info, warn}; use reqwest::{Client as HttpClient, ClientBuilder}; use serde::{Deserialize, Serialize}; /// Vault API Client #[derive(Clone, Debug)] pub str...
() -> Result<(), crate::Error> { let client = Client::new(vault_address(), "vault_token", false, None)?; let request = client.build_nomad_token_request("nomad", "default")?; assert_eq!( format!("{}/v1/nomad/creds/default", vault_address()), request.url().to_string() ...
nomad_token_request_is_built_properly
identifier_name
vault.rs
// ENV: https://www.vaultproject.io/docs/commands/#environment-variables use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Debug; use log::{debug, info, warn}; use reqwest::{Client as HttpClient, ClientBuilder}; use serde::{Deserialize, Serialize}; /// Vault API Client #[derive(Clone, Debug)] pub str...
fn build_nomad_token_request( &self, nomad_path: &str, nomad_role: &str, ) -> Result<reqwest::Request, crate::Error> { let vault_address = url::Url::parse(self.address())?; let vault_address = vault_address.join(&format!("/v1/{}/creds/{}", nomad_path, nomad_...
{ let vault_address = url::Url::parse(self.address())?; let vault_address = vault_address.join("/v1/auth/token/revoke-self")?; Ok(self .client .post(vault_address) .header("X-Vault-Token", self.token.as_str()) .build()?) }
identifier_body
vault.rs
// ENV: https://www.vaultproject.io/docs/commands/#environment-variables use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Debug; use log::{debug, info, warn}; use reqwest::{Client as HttpClient, ClientBuilder}; use serde::{Deserialize, Serialize}; /// Vault API Client #[derive(Clone, Debug)] pub str...
/// List of tokens directly assigned to token pub token_policies: Vec<String>, /// Arbitrary metadata pub metadata: HashMap<String, String>, /// Lease Duration for the token pub lease_duration: u64, /// Whether the token is renewable pub renewable: bool, /// UUID for the entity p...
pub client_token: crate::Secret, /// The accessor for the Token pub accessor: String, /// List of policies for token, including from Identity pub policies: Vec<String>,
random_line_split
timer.rs
use std::fmt; use std::mem; use std::pin::Pin; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::{Arc, Mutex, Weak}; use std::task::{Context, Poll}; use std::time::Instant; use std::future::Future; use super::AtomicWaker; use super::{global, ArcList, Heap, HeapTimer, Node, Sl...
(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Pin::new(&mut self.inner).waker.register(cx.waker()); let mut list = self.inner.list.take(); while let Some(node) = list.pop() { let at = *node.at.lock().unwrap(); match at { Some(at)...
poll
identifier_name
timer.rs
use std::fmt; use std::mem; use std::pin::Pin; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::{Arc, Mutex, Weak}; use std::task::{Context, Poll}; use std::time::Instant; use std::future::Future; use super::AtomicWaker; use super::{global, ArcList, Heap, HeapTimer, Node, Sl...
} fallback = HANDLE_FALLBACK.load(SeqCst); } // At this point our fallback handle global was configured so we use // its value to reify a handle, clone it, and then forget our reified // handle as we don't actually have an owning reference to it. assert!(...
random_line_split
main.rs
use { serde::Deserialize, serde_json, serde_repr::Deserialize_repr, std::{collections::BTreeMap, io::Read, fs::File, process::Command}, }; fn main() -> Result<(), Failure> { let mut file = File::open("token")?; let mut token = String::new(); file.read_to_string(&mut token)?; token.inser...
(u64); #[derive(Debug, Deserialize)] struct Filter { id: FilterId, name: String, query: String, color: Color, item_order: Order, is_deleted: Flag, is_favorite: Flag, } #[derive(Debug, Deserialize)] struct FilterId(u64); #[derive(Debug, Deserialize)] struct Collaborator { id: Collabora...
LabelId
identifier_name
main.rs
use {
std::{collections::BTreeMap, io::Read, fs::File, process::Command}, }; fn main() -> Result<(), Failure> { let mut file = File::open("token")?; let mut token = String::new(); file.read_to_string(&mut token)?; token.insert_str(0, "token="); let output = &Command::new("curl").args(&["https://api.t...
serde::Deserialize, serde_json, serde_repr::Deserialize_repr,
random_line_split
lib.rs
#![recursion_limit = "1024"] #[macro_use] extern crate derive_new; #[macro_use] extern crate derive_setters; #[macro_use] extern crate log; #[macro_use] extern crate thiserror; pub mod checksum; mod range; mod systems; pub use self::systems::*; use std::{ fmt::Debug, io, num::{NonZeroU16, NonZeroU32, No...
async fn supports_range( client: &Client, uri: &str, length: u64, ) -> Result<bool, Error> { let response = client .head(uri) .header("Expect", "") .header("range", range::to_string(0, length).as_str()) .await?; if response.status() == StatusCode::PartialContent { ...
}
random_line_split
lib.rs
#![recursion_limit = "1024"] #[macro_use] extern crate derive_new; #[macro_use] extern crate derive_setters; #[macro_use] extern crate log; #[macro_use] extern crate thiserror; pub mod checksum; mod range; mod systems; pub use self::systems::*; use std::{ fmt::Debug, io, num::{NonZeroU16, NonZeroU32, No...
{ /// Signals that this file was already fetched. AlreadyFetched, /// States that we know the length of the file being fetched. ContentLength(u64), /// Notifies that the file has been fetched. Fetched, /// Notifies that a file is being fetched. Fetching, /// Reports the amount of by...
FetchEvent
identifier_name
lib.rs
#![recursion_limit = "1024"] #[macro_use] extern crate derive_new; #[macro_use] extern crate derive_setters; #[macro_use] extern crate log; #[macro_use] extern crate thiserror; pub mod checksum; mod range; mod systems; pub use self::systems::*; use std::{ fmt::Debug, io, num::{NonZeroU16, NonZeroU32, No...
trait ResponseExt { fn content_length(&self) -> Option<u64>; fn last_modified(&self) -> Option<DateTime<Utc>>; } impl ResponseExt for Response { fn content_length(&self) -> Option<u64> { let header = self.header("content-lenght")?.get(0)?; header.as_str().parse::<u64>().ok() } fn...
{ let status = response.status(); if status.is_informational() || status.is_success() { Ok(response) } else { Err(Error::Status(status)) } }
identifier_body
credential.rs
//! Internal `Credential` and external `CredentialId` ("keyhandle"). use core::cmp::Ordering; use trussed::{client, syscall, try_syscall, types::KeyId}; pub(crate) use ctap_types::{ // authenticator::{ctap1, ctap2, Error, Request, Response}, ctap2::credential_management::CredentialProtectionPolicy, sizes...
<UP: UserPresence, T: client::Client + client::Chacha8Poly1305>( authnr: &mut Authenticator<UP, T>, rp_id_hash: &Bytes<32>, id: &[u8], ) -> Result<Self> { let mut cred: Bytes<MAX_CREDENTIAL_ID_LENGTH> = Bytes::new(); cred.extend_from_slice(id) .map_err(|_| Error::I...
try_from_bytes
identifier_name
credential.rs
//! Internal `Credential` and external `CredentialId` ("keyhandle"). use core::cmp::Ordering; use trussed::{client, syscall, try_syscall, types::KeyId}; pub(crate) use ctap_types::{ // authenticator::{ctap1, ctap2, Error, Request, Response}, ctap2::credential_management::CredentialProtectionPolicy, sizes...
#[derive(Copy, Clone, Debug, serde::Deserialize, serde::Serialize)] pub enum CtapVersion { U2fV2, Fido20, Fido21Pre, } /// External ID of a credential, commonly known as "keyhandle". #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct CredentialId(pub Bytes<MAX_CREDENTIAL_ID_L...
/// As signaled in `get_info`. /// /// Eventual goal is full support for the CTAP2.1 specification.
random_line_split
credential.rs
//! Internal `Credential` and external `CredentialId` ("keyhandle"). use core::cmp::Ordering; use trussed::{client, syscall, try_syscall, types::KeyId}; pub(crate) use ctap_types::{ // authenticator::{ctap1, ctap2, Error, Request, Response}, ctap2::credential_management::CredentialProtectionPolicy, sizes...
} } pub fn try_from<UP: UserPresence, T: client::Client + client::Chacha8Poly1305>( authnr: &mut Authenticator<UP, T>, rp_id_hash: &Bytes<32>, descriptor: &PublicKeyCredentialDescriptor, ) -> Result<Self> { Self::try_from_bytes(authnr, rp_id_hash, &descriptor.id) ...
{ info_now!("could not deserialize {:?}", bytes); Err(Error::Other) }
conditional_block
lib.rs
/* * Copyright 2015-2017 Two Pore Guys, Inc. * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of...
{ code: u32, message: String, stack_trace: Box<Value>, extra: Box<Value> } #[link(name = "rpc")] extern { /* rpc/object.h */ pub fn rpc_get_type(value: *mut RawObject) -> RawType; pub fn rpc_hash(value: *mut RawObject) -> u32; pub fn rpc_null_create() -> *mut RawObject; pub fn rpc_...
Error
identifier_name
lib.rs
/* * Copyright 2015-2017 Two Pore Guys, Inc. * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of...
Uint64, Int64, Double, Date, String, Binary, Fd, Dictionary, Array, Error, } #[repr(C)] #[derive(Debug)] pub enum CallStatus { InProgress, MoreAvailable, Done, Error, Aborted, Ended } pub enum RawObject {} pub enum RawConnection {} pub enum RawClient {} ...
random_line_split
type_check.rs
use std::collections::HashMap; use std::rc::Rc; use parsing::{AST, Statement, Declaration, Signature, Expression, ExpressionType, Operation, Variant, TypeName, TypeSingletonName}; // from Niko's talk /* fn type_check(expression, expected_ty) -> Ty { let ty = bare_type_check(expression, expected_type); if ty ...
{ symbol_table: HashMap<PathSpecifier, TypeContextEntry>, evar_table: HashMap<u64, Type>, existential_type_label_count: u64 } impl TypeContext { pub fn new() -> TypeContext { TypeContext { symbol_table: HashMap::new(), evar_table: HashMap::new(), existential_type_label_count: 0, } }...
ypeContext
identifier_name
type_check.rs
use std::collections::HashMap; use std::rc::Rc; use parsing::{AST, Statement, Declaration, Signature, Expression, ExpressionType, Operation, Variant, TypeName, TypeSingletonName}; // from Niko's talk /* fn type_check(expression, expected_ty) -> Ty { let ty = bare_type_check(expression, expected_type); if ty ...
}, (ref t1, &TVar(Exist(ref a))) => { let x = self.evar_table.get(a).map(|x| x.clone()); match x { Some(ref t2) => self.unify(t2.clone().clone(), t1.clone().clone()), None => { self.evar_table.insert(*a, t1.clone().clone()); Ok(t1.clone().clone()) ...
}
random_line_split
keyboard.rs
// Copyright 2020 The Druid Authors. // // 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...
0x004D => Code::NumLock, 0x004E => Code::ScrollLock, 0x004F => Code::Numpad7, 0x0050 => Code::Numpad8, 0x0051 => Code::Numpad9, 0x0052 => Code::NumpadSubtract, 0x0053 => Code::Numpad4, 0x0054 => Code::Numpad5, 0x0055 => Code::Numpad6, 0x005...
0x0049 => Code::F7, 0x004A => Code::F8, 0x004B => Code::F9, 0x004C => Code::F10,
random_line_split
keyboard.rs
// Copyright 2020 The Druid Authors. // // 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...
(code: Code, m: Modifiers) -> Key { fn a(s: &str) -> Key { Key::Character(s.into()) } fn s(mods: Modifiers, base: &str, shifted: &str) -> Key { if mods.contains(Modifiers::SHIFT) { Key::Character(shifted.into()) } else { Key::Character(base.into()) } ...
code_to_key
identifier_name
keyboard.rs
// Copyright 2020 The Druid Authors. // // 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...
fn n(mods: Modifiers, base: Key, num: &str) -> Key { if mods.contains(Modifiers::NUM_LOCK)!= mods.contains(Modifiers::SHIFT) { Key::Character(num.into()) } else { base } } match code { Code::KeyA => s(m, "a", "A"), Code::KeyB => s(m, "b", "B")...
{ if mods.contains(Modifiers::SHIFT) { Key::Character(shifted.into()) } else { Key::Character(base.into()) } }
identifier_body
watched_bitfield.rs
use crate::{BitField8, Error}; use std::{ fmt::{self, Display}, str::FromStr, }; /// (De)Serializable field that tracks which videos have been watched /// and the latest one watched. /// /// This is a [`WatchedBitField`] compatible field, (de)serialized /// without the knowledge of `videos_ids`. /// /// `{anch...
} /// Module containing all the impls of the `serde` feature #[cfg(feature = "serde")] mod serde { use std::str::FromStr; use serde::{de, Serialize}; use super::WatchedField; impl<'de> serde::Deserialize<'de> for WatchedField { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> ...
{ watched.bitfield }
identifier_body
watched_bitfield.rs
use crate::{BitField8, Error}; use std::{ fmt::{self, Display}, str::FromStr, }; /// (De)Serializable field that tracks which videos have been watched /// and the latest one watched. /// /// This is a [`WatchedBitField`] compatible field, (de)serialized /// without the knowledge of `videos_ids`. /// /// `{anch...
() { let watched = WatchedBitField::construct_and_resize("undefined:1:eJwDAAAAAAE=", vec![]); assert_eq!( watched, Ok(WatchedBitField { bitfield: BitField8::new(0), video_ids: vec![] }) ); } }
deserialize_empty
identifier_name
watched_bitfield.rs
use crate::{BitField8, Error}; use std::{ fmt::{self, Display}, str::FromStr, }; /// (De)Serializable field that tracks which videos have been watched /// and the latest one watched. /// /// This is a [`WatchedBitField`] compatible field, (de)serialized /// without the knowledge of `videos_ids`. /// /// `{anch...
} pub fn set(&mut self, idx: usize, v: bool) { self.bitfield.set(idx, v); } pub fn set_video(&mut self, video_id: &str, v: bool) { if let Some(pos) = self.video_ids.iter().position(|s| *s == video_id) { self.bitfield.set(pos, v); } } } impl fmt::Display for Wa...
{ false }
conditional_block