lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/convert/exec.rs
zaphar/ucg
74f6cb89e599e4655b8e732f869a998dbb709e21
use std; use std::io::{Cursor, Write}; use std::rc::Rc; use crate::build::Val; use crate::build::Val::Tuple; use crate::convert; use crate::convert::traits::{ConvertResult, Converter}; use crate::error::BuildError; use crate::error::ErrorType; pub struct ExecConverter {} impl ExecConverter { pub fn new() -> Se...
use std; use std::io::{Cursor, Write}; use std::rc::Rc; use crate::build::Val; use crate::build::Val::Tuple; use crate::convert; use crate::convert::traits::{ConvertResult, Converter}; use crate::error::BuildError; use crate::error::ErrorType; pub struct ExecConverter {} impl ExecConverter { pub fn new() -> Se...
}
fn convert_command_with_arg_test() { let i_paths = Vec::new(); let out: Vec<u8> = Vec::new(); let err: Vec<u8> = Vec::new(); let env = RefCell::new(Environment::new(out, err)); let mut b = FileBuilder::new(std::env::current_dir().unwrap(), &i_paths, &env); let conv = Exec...
function_block-full_function
[ { "content": "fn fmt_command(matches: &clap::ArgMatches) -> std::result::Result<(), Box<dyn Error>> {\n\n let files = matches.values_of(\"INPUT\");\n\n let recurse = matches.is_present(\"recurse\");\n\n let overwrite = matches.is_present(\"write\");\n\n let indent = match matches.value_of(\"indent\"...
Rust
src/box_internal/actions.rs
Trouv/black-box
d73da6d2d36242419ede50d4829c116e00a4af9f
use crate::box_internal::components::BoxState; use serde::{Deserialize, Serialize}; use std::fmt; #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub enum Action { Set(Val, usize), Add(Val, Val, usize), AddEq(Val, usize), Mult(Val, Val, usiz...
use crate::box_internal::components::BoxState; use serde::{Deserialize, Serialize}; use std::fmt; #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub enum Action {
} } #[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub enum Val { C(f32), G(usize), } impl Val { fn evaluate(&self, state: &BoxState) -> f32 { match self { Val::C(val) => *val, Val::G(i) => state[*i], } }...
Set(Val, usize), Add(Val, Val, usize), AddEq(Val, usize), Mult(Val, Val, usize), Mod(Val, Val, usize), Equals(Val, Val, usize), IfElse(Val, Val, Val, usize), Do(Vec<Action>), IfElseDo(Val, Vec<Action>, Vec<Action>), PrintInt(Val...
random
[ { "content": "#[derive(Debug, Clone, PartialEq, Eq, Hash, SystemLabel)]\n\nenum SystemLabels {\n\n // Left as an enum for potential future labels\n\n InputLabel,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 41974.69818567553 }, { "content": "pub fn walk(\n\n mut velo...
Rust
simple-math-lib/src/parser.rs
jD91mZM2/math-test-rust
90c30ef58cc0c988890458098bd3a73103550717
use bigdecimal::BigDecimal; use calculator::CalcError; use std::{fmt, mem}; #[derive(Clone, Debug, Eq, PartialEq)] pub enum Token { BlockName(String), Num(BigDecimal), ParenClose, ParenOpen, Separator, VarAssign(String), VarGet(String), Add, And, BitshiftLeft, BitshiftRight...
use bigdecimal::BigDecimal; use calculator::CalcError; use std::{fmt, mem}; #[derive(Clone, Debug, Eq, PartialEq)] pub enum Token { BlockName(String), Num(BigDecimal), ParenClose, ParenOpen, Separator, VarAssign(String), VarGet(String), Add, And, BitshiftLeft, BitshiftRight...
} #[derive(Debug, Fail)] pub enum ParseError { #[fail(display = "Character '{}' neither a number nor a valid letter \ in a function or variable name.", _0)] DisallowedChar(char), #[fail(display = "You may only use whole numbers in this context")] DisallowedDecimal, #[fail(dis...
Token::Pow => write!(f, "Exponential (**)"), Token::Rem => write!(f, "Remainder (%)"), Token::Sub => write!(f, "Minus (-)"), Token::Xor => write!(f, "Bitwise XOR (^)") } }
function_block-function_prefix_line
[ { "content": "/// Calculates `num` to the power of `power`\n\npub fn pow(num: BigDecimal, power: BigDecimal, acc: Option<BigDecimal>, times: u8) -> Result<BigDecimal, CalcError> {\n\n if times == std::u8::MAX {\n\n return Err(CalcError::TooDeep);\n\n }\n\n require_positive(&num)?;\n\n require...
Rust
gist/src/lib.rs
mike-engel/gistcard
5c9cef04b25aa218d10903b1d44832b03d02a0bc
use html5ever::rcdom::{NodeData, RcDom}; use html5ever::tendril::TendrilSink; use html5ever::tree_builder::TreeBuilderOpts; use html5ever::{parse_document, Attribute, ParseOpts}; use http::header; use log::debug; use regex::Regex; use reqwest::Client; use serde::Deserialize; use std::collections::HashMap; pub enum Gis...
use html5ever::rcdom::{NodeData, RcDom}; use html5ever::tendril::TendrilSink; use html5ever::tree_builder::TreeBuilderOpts; use html5ever::{parse_document, Attribute, ParseOpts}; use http::header; use log::debug; use regex::Regex; use reqwest::Client; use serde::Deserialize; use std::collections::HashMap; pub enum Gis...
pub fn get_media_tags(id: &str) -> Result<Vec<String>, GistError> { debug!("collecting meta tags"); let markup = get_gist_markup(id)?; let opts = ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() ...
fn extract_media_prop(name: &str, attrs: &Vec<Attribute>) -> Option<(String, String)> { attr(name, attrs).and_then(|property| { if property.starts_with("og:") || (property.starts_with("twitter:") && !property.starts_with("twitter:image:src")) { attr("content", attrs).map(|con...
function_block-function_prefixed
[ { "content": "fn decode_image(blob: &str) -> Result<Vec<u8>, GistError> {\n\n let base64_data = blob.replace(\"data:image/png;base64,\", \"\");\n\n\n\n base64::decode(&base64_data).map_err(|err| {\n\n debug!(\"Error decoding image data: {:?}\", err);\n\n\n\n GistError::ImageError\n\n })\n...
Rust
src/atom.rs
kiwiyou/paradocs
0f12aa0b08f07ab483881363abd3a20ea488c09f
use ego_tree::NodeRef; use scraper::Node; use selectors::attr::CaseSensitivity; #[derive(Debug)] pub enum Paragraph<'a> { Text(Vec<TextPart<'a>>), List(Vec<Vec<TextPart<'a>>>), Code(Vec<TextPart<'a>>), } pub fn parse_p(maybe_p: NodeRef<Node>) -> Option<Vec<TextPart>> { let p = maybe_p.value().as_eleme...
use ego_tree::NodeRef; use scraper::Node; use selectors::attr::CaseSensitivity; #[derive(Debug)] pub enum Paragraph<'a> { Text(Vec<TextPart<'a>>), List(Vec<Vec<TextPart<'a>>>), Code(Vec<TextPart<'a>>), }
pub fn parse_list(maybe_list: NodeRef<Node>) -> Option<Vec<Vec<TextPart>>> { let list = maybe_list.value().as_element()?; if !(list.name() == "ul" || list.name() == "ol") { return None; } let mut list = vec![]; for child in maybe_list.children() { if let Some(li) = child.value()...
pub fn parse_p(maybe_p: NodeRef<Node>) -> Option<Vec<TextPart>> { let p = maybe_p.value().as_element()?; if p.name() != "p" { return None; } Some(parse_text_inside(maybe_p)) }
function_block-full_function
[ { "content": "pub fn parse_document(html: &Html) -> Option<Document> {\n\n let select_main = Selector::parse(\"#main\").unwrap();\n\n let main = html.select(&select_main).next()?;\n\n\n\n let mut children = main.children();\n\n\n\n let maybe_fqn = children.next()?;\n\n let fqn = parse_fqn(maybe_f...
Rust
eip3156-1/flashlender/src/flashlend.rs
Jiuhong-casperlabs/eip3156workspace
4720ec3a427c557692c752890a0b2fc46bf5fc84
use crate::constants::{ ADDRESS_RUNTIME_ARG_NAME, AMOUNT_RUNTIME_ARG_NAME, BALANCE_OF_ENTRY_POINT_NAME, CALLBACK_STRING, DATA_RUNTIME_ARG_NAME, FEE_RUNTIME_ARG_NAME, INITIATOR_RUNTIME_ARG_NAME, ON_FLASH_LOAN_ENTRY_POINT_NAME, OWNER_RUNTIME_ARG_NAME, RECIPIENT_RUNTIME_ARG_NAME, TOKEN_RUNTIME_ARG_NAME, TR...
use crate::constants::{ ADDRESS_RUNTIME_ARG_NAME, AMOUNT_RUNTIME_ARG_NAME, BALANCE_OF_ENTRY_POINT_NAME, CALLBACK_STRING, DATA_RUNTIME_ARG_NAME, FEE_RUNTIME_ARG_NAME, INITIATOR_RUNTIME_ARG_NAME, ON_FLASH_LOAN_ENTRY_POINT_NAME, OWNER_RUNTIME_ARG_NAME, RECIPIENT_RUNTIME_ARG_NAME, TOKEN_RUNTIME_ARG_NAME, TR...
pub fn flash_fee(fee: U256, amount: U256) -> Result<U256, Error> { _flash_fee(fee, amount) }
pub fn max_flash_loan(token: Address) -> U256 { let token_package_hash = match token { Address::Contract(contractpackagehash) => contractpackagehash, _ => panic!("error"), }; let topstack = runtime::get_call_stack().pop().unwrap(); runtime::call_versioned_contract::<U256>( toke...
function_block-full_function
[ { "content": "pub fn flash_borrow(lender: Address, token: Address, amount: U256) -> Result<(), Error> {\n\n // allowance start\n\n let erc20_package_hash = match token {\n\n Address::Contract(contractpkhash) => contractpkhash,\n\n _ => panic!(\"incorrect token\"),\n\n };\n\n\n\n let mu...
Rust
lapce-core/src/word.rs
SingingBush/lapce
510274f3a932444b4788e63c9c2b8c308eb93d59
use xi_rope::{Cursor, Rope, RopeInfo}; use crate::syntax::{matching_char, matching_pair_direction}; #[derive(Copy, Clone, PartialEq)] pub enum WordProperty { Cr, Lf, Space, Punctuation, Other, } #[derive(PartialEq, Eq)] enum WordBoundary { Interior, Start, End, Both, } impl ...
use xi_rope::{Cursor, Rope, RopeInfo}; use crate::syntax::{matching_char, matching_pair_direction}; #[derive(Copy, Clone, PartialEq)] pub enum WordProperty { Cr, Lf, Space, Punctuation, Other, } #[derive(PartialEq, Eq)] enum WordBoundary { Interior, Start, End, Both, } impl ...
ize, usize) { let initial = self.inner.pos(); let end = self.next_code_boundary(); self.inner.set(initial); let start = self.prev_code_boundary(); (start, end) } pub fn select_word_old(&mut self) -> (usize, usize) { let initial = self.inner.pos(); ...
Other { break; } candidate = self.inner.pos(); } candidate } pub fn next_code_boundary(&mut self) -> usize { let mut candidate = self.inner.pos(); while let Some(prev) = self.inner.next_codepoint() { let prop_prev = get_word_pr...
random
[ { "content": "#[inline]\n\npub fn char_is_line_ending(ch: char) -> bool {\n\n matches!(ch, '\\u{000A}')\n\n}\n\n\n\n/// Determine whether a character qualifies as (non-line-break)\n\n/// whitespace.\n", "file_path": "lapce-core/src/chars.rs", "rank": 0, "score": 204976.88215096525 }, { "c...
Rust
src/frontend/dead_code.rs
burjui/rambo
447aa4d4c7714cc087b7accfb81ffffe92cbe060
use crate::ir::get_statement_operands_mut; use crate::ir::get_statement_value_operands; use crate::ir::get_value_operands_mut; use crate::ir::value_storage::ValueId; use crate::ir::value_storage::ValueStorage; use crate::ir::BasicBlock; use crate::ir::ControlFlowGraph; use crate::ir::FunctionMap; use crate::ir::Stateme...
use crate::ir::get_statement_operands_mut; use crate::ir::get_statement_value_operands; use crate::ir::get_value_operands_mut; use crate::ir::value_storage::ValueId; use crate::ir::value_storage::ValueStorage; use crate::ir::BasicBlock; use crate::ir::ControlFlowGraph; use crate::ir::FunctionMap; use crate::ir::Stateme...
fn remove_unused_values( definitions: &mut HashMap<ValueId, StatementLocation>, values: &mut ValueStorage, functions: &mut FunctionMap, cfg: &mut ControlFlowGraph, program_result: &mut ValueId, ) { for (_, value_id) in values.iter() { if !definitions.contains_key(&value_id) { ...
t()) .collect_vec(); for target in targets { cfg.add_edge(block, target); } cfg.remove_node(successor); } } }
function_block-function_prefixed
[ { "content": "fn unit_statements_count(module: &IRModule) -> usize {\n\n let functions = module.values.iter().filter_map(|(value, _)| match value {\n\n Value::Function(fn_id, _) => Some(&module.functions[fn_id]),\n\n _ => None,\n\n });\n\n module\n\n .cfg\n\n .node_indices()...
Rust
d03/src/main.rs
syphar/advent_of_code_2021
4a7bbbb488695a8aa3b17b2e80475bb4b9f4b553
use bitvec::prelude::*; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let input: Vec<_> = BufReader::new(File::open("input.txt").unwrap()) .lines() .map(|line| { line.unwrap() .chars() .map(|c| (c == '1')) .collect::<Bi...
use bitvec::prelude::*; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let input: Vec<_> = BufReader::new(File::open("input.txt").unwrap()) .lines() .map(|line| { line.unwrap() .chars() .map(|c| (c == '1')) .collect::<Bi...
ner::<_, _, N>(numbers.iter(), false) } fn part_2_inner<T, I, const N: usize>(input: I, reverse: bool) -> usize where T: AsRef<BitSlice<Msb0>>, I: Iterator<Item = T>, { let mut numbers: Vec<BitVec<Msb0>> = input.map(|bs| bs.as_ref().to_bitvec()).collect(); for bit in 0..N { let (ones, zeroes) ...
T: AsRef<BitSlice<Msb0>>, I: Iterator<Item = T>, { let numbers: Vec<BitVec<Msb0>> = input.map(|bs| bs.as_ref().to_bitvec()).collect(); part_2_inner::<_, _, N>(numbers.iter(), true) * part_2_in
function_block-random_span
[ { "content": "fn part_1(input: Input) -> usize {\n\n input\n\n .0\n\n .iter()\n\n .map(|l| l.1.clone())\n\n .flatten()\n\n .filter(|digit| matches!(digit.0.len(), 2 | 4 | 3 | 7))\n\n .count()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n sta...
Rust
process-with-lua/src/process_templates_with_headers.rs
wooters/enwikt-dump-rs
cc9b2a120b3474e799bee3d969d67a7253d30177
use dump_parser::{ parse_wiki_text::Positioned, wiktionary_configuration, Node, }; use rlua::{ Context, Error as LuaError, Function, Result as LuaResult, ToLua, Value, }; use std::borrow::Cow; use std::collections::{BTreeMap, HashSet}; use std::convert::From; use std::io::BufRead; use std::ops::{Deref, DerefMut...
use dump_parser::{ parse_wiki_text::Positioned, wiktionary_configuration, Node, }; use rlua::{ Context, Error as LuaError, Function, Result as LuaResult, ToLua, Value, }; use std::borrow::Cow; use std::collections::{BTreeMap, HashSet}; use std::convert::From; use std::io::BufRead; use std::ops::{Deref, DerefMut...
e).map(|result| { result.unwrap_or_else(|e| { exit_with_error!("Error while parsing dump: {}", e); }) }); for page in parser { if namespaces.contains(&page.namespace) { let wikitext = &page.text; let parser_output = configuration.parse(&page.text); ...
function_block-function_prefixed
[ { "content": "pub fn process_comments_and_headers_with_function<R: BufRead>(\n\n dump_file: R,\n\n lua_func: Function,\n\n namespaces: HashSet<Namespace>,\n\n) -> LuaResult<()> {\n\n let configuration = wiktionary_configuration();\n\n let parser = dump_parser::parse(dump_file).map(|result| {\n\n ...
Rust
src/main.rs
bobgates/stm32f7-cnc-ui
fc0606a6c3776919d7a49db344c11a5df5c2016b
#![no_main] #![no_std] use cortex_m_rt::entry; use ft5336::Ft5336; #[allow(unused_imports)] use panic_semihosting; use rtt_target::{rprintln, rtt_init_print}; use stm32f7xx_hal::{ delay::Delay, gpio::Speed, i2c::{BlockingI2c, Mode}, ltdc::{Layer, PixelFormat}, pac, prelude::*, rcc::{HS...
#![no_main] #![no_std] use cortex_m_rt::entry; use ft5336::Ft5336; #[allow(unused_imports)] use panic_semihosting; use rtt_target::{rprintln, rtt_init_print}; use stm32f7xx_hal::{ delay::Delay, gpio::Speed, i2c::{BlockingI2c, Mode}, ltdc::{Layer, PixelFormat}, pac, prelude::*, rcc::{HS...
one, &mut display); } else { let t = touch.get_touch(&mut i2c, 1).unwrap(); view.process_button(view.button_id_from_coords(t.y, t.x), &mut display); } touch.delay_ms(10); } }
function_block-function_prefixed
[ { "content": "pub fn draw_background(display: &mut Stm32F7DiscoDisplay<u16>) {\n\n let c = BACKGROUND_COLOR;\n\n let background_color: u32 =\n\n c.b() as u32 & 0x1F | ((c.g() as u32 & 0x3F) << 5) | ((c.r() as u32 & 0x1F) << 11);\n\n\n\n unsafe {\n\n display\n\n .controller\n\n ...
Rust
src/i2s0/tcr3.rs
thorhs/mk66f18
ea5a3c933656be9f2f548b28dee91d0bb7821923
#[doc = "Reader of register TCR3"] pub type R = crate::R<u32, super::TCR3>; #[doc = "Writer for register TCR3"] pub type W = crate::W<u32, super::TCR3>; #[doc = "Register TCR3 `reset()`'s with value 0"] impl crate::ResetValue for super::TCR3 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register TCR3"] pub type R = crate::R<u32, super::TCR3>; #[doc = "Writer for register TCR3"] pub type W = crate::W<u32, super::TCR3>; #[doc = "Register TCR3 `reset()`'s with value 0"] impl crate::ResetValue for super::TCR3 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
lf) -> &'a mut W { self.variant(CFR0_AW::_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } ...
#[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(TCE0_A::_0) } #[doc = "Transmit data channel N is enabled."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(TCE0_A::_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self)...
random
[ { "content": " ///\n\n ///Registers marked with `Readable` can be also `modify`'ed\n\n pub trait Writable { } ///Reset value of the register\n", "file_path": "lib.rs", "rank": 0, "score": 220323.13240861555 }, { "content": " ///\n\n ///This value is initial value for `write` method.\n\n ///I...
Rust
src/kernel_controller/bench.rs
parallel-programming-hwr/opencl-primes-rust
1cc4db121131a7cf36a43d05ed4c0306026400a0
/* * opencl demos with rust * Copyright (C) 2021 trivernis * See LICENSE for more information */ use std::fmt::{self, Display, Formatter}; use std::ops::Deref; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use ocl_stream::executor::context::ExecutorContext; use ocl_stream::ex...
/* * opencl demos with rust * Copyright (C) 2021 trivernis * See LICENSE for more information */ use std::fmt::{self, Display, Formatter}; use std::ops::Deref; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use ocl_stream::executor::context::ExecutorContext; use ocl_stream::ex...
} impl KernelController { pub fn bench_global_size( &self, local_size: usize, global_size_start: usize, global_size_step: usize, global_size_stop: usize, calc_count: u32, repetitions: usize, ) -> OCLStreamResult<OCLStream<BenchStatistics>> { ...
e!( f, "Calculation Count: {}\nTask Count: {}\nLocal Size: {}\nWrite Duration: {} ms\nGPU Duration: {} ms\nRead Duration: {} ms", self.calc_count, self.global_size, self.local_size, self.write_duration.as_secs_f64() * 1000f64, self.calc...
function_block-function_prefixed
[ { "content": "/// Initializes the env_logger with a custom format\n\n/// that also logs the thread names\n\npub fn init_logger() {\n\n fern::Dispatch::new()\n\n .format(|out, message, record| {\n\n let color = get_level_style(record.level());\n\n let mut thread_name = format!(\n\...
Rust
src/gates/cy.rs
frogtd/q1tsim
ec6f923da2c78ef9a9dcda9d74ca1e726b026eb4
use crate::gates::Gate; use crate::stabilizer::PauliOp; #[derive(Clone)] pub struct CY { cgate: crate::gates::C<crate::gates::Y> } impl CY { pub fn new() -> Self { CY { cgate: crate::gates::C::new(crate::gates::Y::new()) } } pub fn cost() -> f64 { ...
use crate::gates::Gate; use crate::stabilizer::PauliOp; #[derive(Clone)] pub struct CY { cgate: crate::gates::C<crate::gates::Y> } impl CY { pub fn new() -> Self { CY { cgate: crate::gates::C::new(crate::gates::Y::new()) } } pub fn cost() -> f64 { ...
:I) => (false, PauliOp::Y, PauliOp::Y), (PauliOp::Y, PauliOp::Z) => (true, PauliOp::X, PauliOp::X), (PauliOp::Y, PauliOp::X) => (false, PauliOp::X, PauliOp::Z), (PauliOp::Y, PauliOp::Y) => (false, PauliOp::Y, PauliOp::I), }; ops[0] = op0; ops[1] = op1; ...
{ self.cgate.apply_slice(state); } fn apply_mat_slice(&self, state: crate::cmatrix::CMatSliceMut) { self.cgate.apply_mat_slice(state); } fn is_stabilizer(&self) -> bool { true } fn conjugate(&self, ops: &mut [crate::stabilizer::PauliOp]) -> crate::error::Result<bo...
random
[ { "content": "/// Check a measurement result\n\n///\n\n/// Check if the measurement result `count` is probably correct, with an error\n\n/// chance of less than `tol`, assuming a binomial distribution of size\n\n/// `nr_shots` and success probability `p`.\n\n/// NOTE: this is a statistical result. It can be exp...
Rust
src/compact_sched.rs
waynexia/helixdb
c8a18d2bc27f675ac6150f1df945e8ec97633d3a
use std::cell::RefCell; use std::collections::VecDeque; use std::mem; use std::rc::Rc; use std::time::Duration; use async_trait::async_trait; use glommio::timer::TimerActionRepeat; use glommio::{Local, TaskQueueHandle}; use crate::error::Result; use crate::level::Levels; use crate::types::LevelId; #[async_trait(?Sen...
use std::cell::RefCell; use std::collections::VecDeque; use std::mem; use std::rc::Rc; use std::time::Duration; use async_trait::async_trait; use glommio::timer::TimerActionRepeat; use glommio::{Local, TaskQueueHandle}; use crate::error::Result; use crate::level::Levels; use crate::types::LevelId; #[async_trait(?Sen...
#[cfg(test)] crate fn default() -> (Rc<Self>, TaskQueueHandle) { let tq = Local::create_task_queue( glommio::Shares::default(), glommio::Latency::NotImportant, "test_comp_tq", ); let this = Self { is_compacti...
async fn schedule(self: Rc<Self>) -> Option<Duration> { if *self.is_compacting.borrow() || self.queue.borrow().len() < self.delay_num { return Some(self.interval); } let level_id = self.queue.borrow_mut().pop_front().unwrap(); *self.is_compacting.borrow_mut() = true; ...
function_block-full_function
[ { "content": "fn main() -> Result<()> {\n\n let status = Command::new(\"flatc\")\n\n .arg(\"--rust\")\n\n .arg(\"-o\")\n\n .arg(OUT_DIR)\n\n .arg(IN_DIR)\n\n .status();\n\n\n\n match status {\n\n Ok(status) if !status.success() => panic!(\"`flatc` failed to compil...
Rust
kamu-cli/examples/pull-root-multi.rs
kamu-data/kamu-cli
29f1c2a374863fb323df3f87b709fb410c64d82b
use kamu::domain::*; use kamu::infra::MetadataRepositoryNull; use kamu_cli::commands::*; use kamu_cli::output::OutputConfig; use opendatafabric::*; use chrono::{DateTime, Utc}; use std::sync::Arc; fn main() { let pull_svc = Arc::new(TestPullService {}); let mut cmd = PullCommand::new( pull_svc, ...
use kamu::domain::*; use kamu::infra::MetadataRepositoryNull; use kamu_cli::commands::*; use kamu_cli::output::OutputConfig; use opendatafabric::*; use chrono::{DateTime, Utc}; use std::sync::Arc; fn main() { let pull_svc = Arc::new(TestPullService {}); let mut cmd = PullCommand::new( pull_svc, ...
let mut results = ingest_results; results.extend(transform_handles.into_iter().map(|h| h.join().unwrap())); results } fn sync_from( &self, _remote_ref: &DatasetRefRemote, _local_name: &DatasetName, _options: PullOptions, _listener: Option<Arc<dy...
let transform_handles: Vec<_> = ["com.acme.census.normalized", "com.acme.census.geolocated"] .into_iter() .map(|s| { DatasetHandle::new( DatasetID::from_pub_key_ed25519(s.as_bytes()), s.try_into().unwrap(), ...
assignment_statement
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n tonic_build::compile_protos(\"schemas/engine.proto\")?;\n\n Ok(())\n\n}\n", "file_path": "opendatafabric/build.rs", "rank": 0, "score": 257817.52619602333 }, { "content": "pub fn get_parquet_physical_hash(data_path...
Rust
src/test/instruction_tests/instr_vpcmpuq.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpcmpuq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPCMPUQ, ope...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpcmpuq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPCMPUQ, ope...
#[test] fn vpcmpuq_12() { run_test( &Instruction { mnemonic: Mnemonic::VPCMPUQ, operand1: Some(Direct(K4)), operand2: Some(Direct(YMM3)), operand3: Some(Indirect(RAX, Some(OperandSize::Qword), None)), operand4: Some(Literal8(75)), loc...
n { mnemonic: Mnemonic::VPCMPUQ, operand1: Some(Direct(K6)), operand2: Some(Direct(YMM1)), operand3: Some(Indirect(RSI, Some(OperandSize::Ymmword), None)), operand4: Some(Literal8(81)), lock: false, rounding_mode: None, merg...
function_block-function_prefixed
[ { "content": "fn encode16_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
src/styles/text_input.rs
Kijewski/pyiced
be8db4c55d61f3f9f48bd5c8c8700b665ffd3e1b
#![allow(clippy::needless_option_as_deref)] use iced::text_input::{Style, StyleSheet}; use iced::Color; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::{PyDict, PyString}; use crate::wrapped::WrappedColor; use crate::{dyn_style_proto, extract_multiple, getters}; pub(crate) fn init_mod(_py:...
#![allow(clippy::needless_option_as_deref)] use iced::text_input::{Style, StyleSheet}; use iced::Color; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::{PyDict, PyString}; use crate::wrapped::WrappedColor; use crate::{dyn_style_proto, extract_multiple, getters}; pub(crate) fn init_mod(_py:...
} getters! { WrappedTextInputStyle => |&WrappedTextInputStyle(TextInputStyle(ref o))| o, background -> "Color" WrappedColor, border_radius -> "float" f32, border_width -> "float" f32, border_color -> "Color" WrappedColor, } #[pyclass(name = "TextInputStyleSheet", module = "pyiced")] #[derive(Debu...
e!( kwargs, TextInputStyle(proto), background, border_radius, border_width, border_color, ) }
function_block-function_prefixed
[ { "content": "#[pymodule]\n\nfn _pyiced(py: Python, m: &PyModule) -> PyResult<()> {\n\n init_mod(py, m)?;\n\n m.add(\"__version__\", env!(\"pyiced-version\"))?;\n\n m.add(\"__author__\", env!(\"CARGO_PKG_AUTHORS\"))?;\n\n m.add(\"__license__\", env!(\"CARGO_PKG_LICENSE\"))?;\n\n Ok(())\n\n}\n\n\n...
Rust
libs/acpi/src/fadt.rs
toku-sa-n/tokunux
1753dd92dd80d8471ab78b2613198cdff5364cf6
use { crate::{error_unless, wrapping_sum_of_first_n_bytes, Error, GenericAddressStructure, Result}, accessor::{single::ReadOnly, Mapper}, bit_field::BitField, core::convert::TryInto, x86_64::PhysAddr, }; pub use r_acpi::PM_TIMER_FREQUENCY_HZ; const NULL_GAS: r_acpi::GenericAddressStructure = r_acp...
use { crate::{error_unless, wrapping_sum_of_first_n_bytes, Error, GenericAddressStructure, Result}, accessor::{single::ReadOnly, Mapper}, bit_field::BitField, core::convert::TryInto, x86_64::PhysAddr, }; pub use r_acpi::PM_TIMER_FREQUENCY_HZ; const NULL_GAS: r_acpi::GenericAddressStructure = r_acp...
fn pm_tmr_blk_exists(fadt: &r_acpi::Fadt) -> bool { fadt.pm_tmr_blk != 0 } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TimerRegisterWidth { Bits32, Bits24, } impl From<r_acpi::Fadt> for TimerRegisterWidth { fn from(f: r_acpi::Fadt) -> Self { (&f).into() } } impl Fr...
fn x_pm_tmr_blk_exists(fadt: &r_acpi::Fadt) -> bool { let major_version = fadt.header.revision; let blk = fadt.x_pm_tmr_blk; major_version >= 2 && blk != NULL_GAS }
function_block-full_function
[ { "content": "/// # Errors\n\n///\n\n/// This function returns an error if there is no process with PID `from` specifies.\n\npub fn try_receive(from: ReceiveFrom) -> Result<Message, Error> {\n\n let mut m = MaybeUninit::uninit();\n\n\n\n let from = match from {\n\n ReceiveFrom::Any => -1,\n\n ...
Rust
pulse-opl/src/pad.rs
xaynetwork/tract
fb397adfc61e7f054149ad757ee33411c16bbc59
use tract_core::ndarray::*; use tract_core::ops::array::PadMode; use tract_nnef::internal::*; #[derive(Debug, Clone, Default, Hash)] struct PulsePadOpState { current_pos: usize, last_valid_frame: Option<Tensor>, } impl OpState for PulsePadOpState { fn eval( &mut self, session: &mut Session...
use tract_core::ndarray::*; use tract_core::ops::array::PadMode; use tract_nnef::internal::*; #[derive(Debug, Clone, Default, Hash)] struct PulsePadOpState { current_pos: usize, last_valid_frame: Option<Tensor>, } impl OpState for PulsePadOpState { fn eval( &mut self, session: &mut Session...
} op_pulse!(); op_as_typed_op!(); } impl EvalOp for PulsePad { fn is_stateless(&self) -> bool { false } fn state( &self, _session: &mut SessionState, _node_id: usize, ) -> TractResult<Option<Box<dyn OpState>>> { Ok(Some(Box::new(PulsePadOpState::de...
Ok(vec![format!( "Mode: {:?}, axis: {} before: {} after: {}", self.mode, self.axis, self.before, self.after, )])
call_expression
[]
Rust
src/k8s_table.rs
jakeswenson/click
10c769fe7f60fd985a3f324a9424b11ffcb22e84
use k8s_openapi::{ apimachinery::pkg::apis::meta::v1::ObjectMeta, http::{Request, StatusCode}, RequestError, Response, ResponseBody, ResponseError, }; use serde::Deserializer; use serde_json::Value; use crate::{ kobj::{KObj, ObjType}, output::ClickWriter, table::CellSpec, }; #[derive(Deseria...
use k8s_openapi::{ apimachinery::pkg::apis::meta::v1::ObjectMeta, http::{Request, StatusCode}, RequestError, Response, ResponseBody, ResponseError, }; use serde::Deserializer; use serde_json::Value; use crate::{ kobj::{KObj, ObjType}, output::ClickWriter, table::CellSpec, }; #[derive(Deseria...
ponseBody::new)), Err(err) => Err(RequestError::Http(err)), } }
sult, read) = if buf.is_empty() { (Ok(None), 0) } else { match crate::serde_json::from_slice(buf) { Ok(value) => (Ok(Some(value)), buf.len()), Err(ref err) if err.is_eof() => return Err(ResponseError::NeedMoreData), ...
random
[ { "content": "#[allow(clippy::ptr_arg)]\n\npub fn print_table(titles: Row, specs: Vec<Vec<CellSpec<'_>>>, writer: &mut ClickWriter) {\n\n let mut table = Table::new();\n\n table.set_titles(titles);\n\n for (index, t_spec) in specs.iter().enumerate() {\n\n let row_vec: Vec<Cell> = t_spec.iter().m...
Rust
crates/network-proxy/src/sshforwarding.rs
lideen999/flow
a6ac6c958c47d9102716227c0aedc25a280ddacf
use super::logging::Must; use super::errors::Error; use super::networkproxy::NetworkProxy; use async_trait::async_trait; use base64::decode; use futures::pin_mut; use std::net::SocketAddr; use std::sync::Arc; use thrussh::{client::{Handle, Session}, client}; use thrussh_keys::key; use tokio::net::{TcpListener, TcpStre...
use super::logging::Must; use super::errors::Error; use super::networkproxy::NetworkProxy; use async_trait::async_trait; use base64::decode; use futures::pin_mut; use std::net::SocketAddr; use std::sync::Arc; use thrussh::{client::{Handle, Session}, client}; use thrussh_keys::key; use tokio::net::{TcpListener, TcpStre...
pub async fn prepare_local_listener(&mut self) -> Result<(), Error> { if self.config.local_port == 0 { return Err(Error::ZeroLocalPort); } let local_listen_addr: SocketAddr = format!("127.0.0.1:{}", self.config.local_port).parse()?; self.local_listener = Some(TcpListene...
pub async fn prepare_ssh_client(&mut self) -> Result<(), Error> { let ssh_addrs = Url::parse(&self.config.ssh_endpoint)?.socket_addrs(|| Some(Self::DEFAULT_SSH_PORT))?; let ssh_addr = ssh_addrs.get(0).ok_or(Error::InvalidSshEndpoint)?; let config = Arc::new(client::Config::default()); le...
function_block-full_function
[ { "content": "pub fn index() -> String {\n\n prefixed(\"/connectors\")\n\n}\n\n\n", "file_path": "crates/control/src/controllers/connectors/routes.rs", "rank": 0, "score": 229263.47238033186 }, { "content": "pub fn index() -> String {\n\n prefixed(\"/connector_images\")\n\n}\n\n\n", ...
Rust
wechaty/src/context.rs
keycodinggood/rust-wechaty
2cf5545fb677a9da2e983892b8320ef0294dc62d
use std::collections::HashMap; use std::sync::{Arc, Mutex, MutexGuard}; use futures::StreamExt; use log::{debug, error}; use wechaty_puppet::{ ContactPayload, ContactQueryFilter, FriendshipPayload, FriendshipSearchQueryFilter, MessagePayload, MessageQueryFilter, Puppet, PuppetImpl, RoomInvitationPayload, RoomP...
use std::collections::HashMap; use std::sync::{Arc, Mutex, MutexGuard}; use futures::StreamExt; use log::{debug, error}; use wechaty_puppet::{ ContactPayload, ContactQueryFilter, FriendshipPayload, FriendshipSearchQueryFilter, MessagePayload, MessageQueryFilter, Puppet, PuppetImpl, RoomInvitationPayload, RoomP...
} else { let contact_id_list = contact_list.into_iter().map(|x| x.id()).collect(); match self.puppet().room_create(contact_id_list, topic).await { Ok(room_id) => { let mut room = Room::new(room_id, self.clone(), None); room.sync()....
Err(WechatyError::InvalidOperation( "Need at least 2 contacts to create a room".to_owned(), ))
call_expression
[ { "content": "pub trait IntoAsyncFnPtr<Payload, Context, Result>\n\nwhere\n\n Payload: 'static,\n\n{\n\n fn into(self) -> AsyncFnPtr<Payload, Context, Result>;\n\n}\n\n\n\nimpl<F, Payload, Context, Result, Fut> IntoAsyncFnPtr<Payload, Context, Result> for F\n\nwhere\n\n F: Fn(Payload, Context) -> Fut +...
Rust
gstreamer-base/src/flow_combiner.rs
cotigao/gstreamer-rs
962da8a63d1b61bbdf44f4486f55fb6c13864c36
use glib::object::IsA; use glib::translate::*; use gobject_sys; use gst; use gst_base_sys; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct FlowCombiner(Shared<gst_base_sys::GstFlowCombiner>); match fn { ref => |ptr| gobject_sys::g_boxed_copy(gst_base_sys::gst_fl...
use glib::object::IsA; use glib::translate::*; use gobject_sys; use gst; use gst_base_sys; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct FlowCombiner(Shared<gst_base_sys::GstFlowCombiner>); match fn { ref => |ptr| gobject_sys::g_boxed_copy(gst_base_sys::gst_fl...
pub fn reset(&self) { unsafe { gst_base_sys::gst_flow_combiner_reset(self.to_glib_none().0); } } pub fn update_flow<FRet: Into<gst::FlowReturn>>( &self, fret: FRet, ) -> Result<gst::FlowSuccess, gst::FlowError> { let fret: gst::FlowReturn = fret.int...
pub fn remove_pad<P: IsA<gst::Pad>>(&self, pad: &P) { unsafe { gst_base_sys::gst_flow_combiner_remove_pad( self.to_glib_none().0, pad.as_ref().to_glib_none().0, ); } }
function_block-full_function
[ { "content": "pub fn type_find_helper<P: IsA<gst::Pad>>(\n\n src: &P,\n\n size: u64,\n\n) -> Result<gst::Caps, glib::BoolError> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n Option::<_>::from_glib_full(gst_base_sys::gst_type_find_helper(\n\n src.as_ref().to_glib_none()....
Rust
src/tracking/osu_queue.rs
JoshiDhima/Bathbot
7a8dd8a768caede285df4f8ea5aead27bdbbf660
use std::{ cmp::Reverse, sync::atomic::{AtomicBool, Ordering}, }; use chrono::{DateTime, Duration, Utc}; use dashmap::DashMap; use hashbrown::hash_map::{DefaultHashBuilder, HashMap}; use parking_lot::RwLock; use priority_queue::PriorityQueue; use rosu_v2::model::GameMode; use smallvec::SmallVec; use tokio::tim...
use std::{ cmp::Reverse, sync::atomic::{AtomicBool, Ordering}, }; use chrono::{DateTime, Duration, Utc}; use dashmap::DashMap; use hashbrown::hash_map::{DefaultHashBuilder, HashMap}; use parking_lot::RwLock; use priority_queue::PriorityQueue; use rosu_v2::model::GameMode; use smallvec::SmallVec; use tokio::tim...
.collect(); for key in to_remove { let is_empty = match self.users.get(&key) { Some(guard) => guard.value().channels.is_empty(), None => continue, }; if is_empty { psql.remove_osu_tracking(key.user_id...
}; pub use super::{osu_tracking_loop, process_osu_tracking}; lazy_static::lazy_static! { pub static ref OSU_TRACKING_INTERVAL: Duration = Duration::minutes(120); pub static ref OSU_TRACKING_COOLDOWN: f32 = 5000.0; } type TrackingQueue = RwLock<PriorityQueue<TrackingEntry, Reverse<DateTime<Utc>>, Default...
random
[ { "content": "type BotResult<T> = std::result::Result<T, Error>;\n\n\n", "file_path": "src/main.rs", "rank": 1, "score": 109586.09741009944 }, { "content": "#[allow(dead_code)]\n\npub fn string_to_date(date: String) -> BotResult<DateTime<Utc>> {\n\n Ok(Utc.datetime_from_str(&date, DATE_FO...
Rust
src/main.rs
snoe/xi-win
30b25809d557e77cb828d98e2a7d90075e4fa572
#![windows_subsystem = "windows"] extern crate winapi; extern crate direct2d; extern crate directwrite; extern crate serde; #[macro_use] extern crate serde_json; extern crate xi_core_lib; extern crate xi_rpc; #[macro_use] extern crate druid_win_shell; extern crate druid; mod edit_view; mod linecache; mod menus; m...
#![windows_subsystem = "windows"] extern crate winapi; extern crate direct2d; extern crate directwrite; extern crate serde; #[macro_use] extern crate serde_json; extern crate xi_core_lib; extern crate xi_rpc; #[macro_use] extern crate druid_win_shell; extern crate druid; mod edit_view; mod linecache; mod menus; m...
} impl Handler for AppDispatcher { fn notification(&self, method: &str, params: &Value) { if let Some(ref app) = *self.app.lock().unwrap() { app.handle_cmd(method, params); } } } fn extract_string_from_file_dialog(result: Result<std::ffi::OsString, druid::Error>)...
e(); let view_state = &state.views[&state.get_focused()]; app.send_notification("save", &json!({ "view_id": &state.focused, "file_path": view_state.filename.clone().unwrap(), })); ...
function_block-function_prefixed
[ { "content": "type Method = String;\n", "file_path": "src/edit_view.rs", "rank": 0, "score": 127210.41719410697 }, { "content": "// Helper function for choosing between normal and shifted action\n\nfn s<'a>(mods: u32, normal: &'a str, shifted: &'a str) -> &'a str {\n\n if (mods & M_SHIFT)...
Rust
src/parser.rs
asmarques/mrtd
44a5a8ab07ea0e4826b4c89155c684ff77fe9c65
use crate::document::*; use crate::error::Error; use chrono::prelude::*; use lazy_static::lazy_static; use regex::Regex; use std::str; use std::str::FromStr; lazy_static! { static ref VALID_MRZ: Regex = Regex::new(r"^[A-Z0-9<]{88}$").unwrap(); } const DATE_FORMAT: &str = "%y%m%d"; pub(crate) fn parse(data: &str,...
use crate::document::*; use crate::error::Error; use chrono::prelude::*; use lazy_static::lazy_static; use regex::Regex; use std::str; use std::str::FromStr; lazy_static! { static ref VALID_MRZ: Regex = Regex::new(r"^[A-Z0-9<]{88}$").unwrap(); } const DATE_FORMAT: &str = "%y%m%d"; pub(crate) fn parse(data: &str,...
#[test] fn parse_passport_invalid_length() { let mrz = "ABC<<"; let error = parse(mrz, true).unwrap_err(); assert_eq!(error, Error::InvalidFormat); } #[test] fn parse_passport_invalid_encoding() { let mrz = "🕶️"; let error = parse(mrz, true).unwrap_err(); ...
fn parse_passport_multiple_names() { let mrz = "P<UTOERIKSSON<JOHNSON<<ANNA<MARIA<<<<<<<<<<<\ L898902C36UTO7408122F1204159ZE184226B<<<<<10"; match parse(mrz, true).unwrap() { Document::Passport(passport) => { assert_eq!(passport.country, "UTO"); ...
function_block-full_function
[ { "content": "/// Parse a Machine-readable Zone (MRZ) returning the corresponding travel document.\n\n/// Does not perform error checking using the included check digits.\n\npub fn parse_without_checks(data: &str) -> Result<Document, Error> {\n\n parser::parse(data, false)\n\n}\n", "file_path": "src/lib....
Rust
src/tables/glyf.rs
manuel-rhdt/font_parse
0d6c47e788729085862bd4ac28122a3fc7536546
use nom::{self, be_i16, be_u16, rest}; use crate::error::ParserError; use crate::tables::SfntTable; #[derive(Debug, Copy, Clone)] pub struct Glyf<'a> { data: &'a [u8], } impl<'a> SfntTable<'a> for Glyf<'a> { const TAG: &'static [u8; 4] = b"glyf"; type Context = (); type Err = ParserError; fn f...
use nom::{self, be_i16, be_u16, rest}; use crate::error::ParserError; use crate::tables::SfntTable; #[derive(Debug, Copy, Clone)] pub struct Glyf<'a> { data: &'a [u8], } impl<'a> SfntTable<'a> for Glyf<'a> { const TAG: &'static [u8; 4] = b"glyf"; type Context = (); type Err = ParserError; fn f...
} #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct GlyphPoint { pub x: i32, pub y: i32, pub on_curve: bool, } impl GlyphPoint { pub fn new(x: i32, y: i32, on_curve: bool) -> GlyphPoint { GlyphPoint { x, y, on_curve } } } #[derive(Debug, Clone)] pub struct GlyphPoint...
e { 0 }; x_size += delta_x_size * repeat_count; remaining_points -= repeat_count as u16; } let flags_size = self.outline.len() - flags.len(); let x_size = x_size as usize; GlyphPointIter { flags: FlagsIter { ...
function_block-function_prefixed
[ { "content": "pub fn parse(data: &[u8]) -> Result<FontFile, nom::Err<&[u8]>> {\n\n match parse_slice(data) {\n\n Ok((_, parsed)) => Ok(parsed),\n\n Err(err) => Err(err),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn it_works() {\n\n as...
Rust
service/src/app/download_events_loop/mod.rs
marioweid/rustorrent
dcfb8280f0e6236da1bea5692561d851399e45a3
use super::*; use serde_with::skip_serializing_none; use std::path::PathBuf; mod action; mod add_torrent; mod current_torrents; mod delete_torrent; mod torrent_announces; mod torrent_detail; mod torrent_file_download; mod torrent_files; mod torrent_peers; mod torrent_pieces; pub use crate::storage::RsbtFileDownloadSt...
use super::*; use serde_with::skip_serializing_none; use std::path::PathBuf; mod action; mod add_torrent; mod current_torrents; mod delete_torrent; mod torrent_announces; mod torrent_detail; mod torrent_file_download; mod torrent_files; mod torrent_peers; mod torrent_pieces; pub use crate::storage::RsbtFileDownloadSt...
pub(crate) fn find_torrent( torrents: &[TorrentDownload], id: usize, ) -> Result<&TorrentDownload, RsbtError> { torrents .iter() .find(|x| x.id == id) .ok_or_else(|| RsbtError::TorrentNotFound(id)) }
e) => { debug!("torrent's peers"); let response = torrent_peers(request_response.request(), &torrents).await; if let Err(err) = request_response.response(response) { error!("cannot send response for torrent's peers: {}", err); } ...
function_block-function_prefixed
[ { "content": "/// Adds matching (new) pieces ( downloaded_pieces[i] & a ) to pieces (list of indexes).\n\nfn match_pieces(pieces: &mut Vec<usize>, downloaded_pieces: &[u8], i: usize, a: u8) {\n\n let new = if let Some(d) = downloaded_pieces.get(i) {\n\n a & !d\n\n } else {\n\n a\n\n };\n\...
Rust
crates/shim/src/cgroup.rs
Burning1020/rust-extensions
f37796ec04f6e3eaccd967d7f30fdec7b5af0e14
/* Copyright The containerd 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 to...
/* Copyright The containerd 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 to...
fn write_process_oom_score(pid: u32, score: i64) -> Result<()> { fs::write(format!("/proc/{}/oom_score_adj", pid), score.to_string()) .map_err(io_error!(e, "write oom score")) } pub fn collect_metrics(pid: u32) -> Result<Metrics> { let mut metrics = Metrics::new(); let path = get_cgr...
oom score"))?; let score = content .trim() .parse::<i64>() .map_err(other_error!(e, "parse oom score"))?; Ok(score) }
function_block-function_prefixed
[ { "content": "pub fn read_pid_from_file(pid_path: &Path) -> crate::Result<i32> {\n\n let pid_str = read_file_to_str(pid_path)?;\n\n let pid = pid_str.parse::<i32>()?;\n\n Ok(pid)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 7, "score": 347217.7813538273 }, { ...
Rust
src/complement.rs
natir/nuc2bit
5013377f21f378f2c55466bbc1f44653ff0c64b3
#[cfg(target_arch = "x86")] use std::arch::x86::*; #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use std::{alloc, ptr}; pub fn complement(bits: &[u64]) -> Vec<u64> { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { if is_x86_feature_detected!("avx2") { return unsafe {...
#[cfg(target_arch = "x86")] use std::arch::x86::*; #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use std::{alloc, ptr}; pub fn complement(bits: &[u64]) -> Vec<u64> { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { if is_x86_feature_detected!("avx2") { return unsafe {...
}
fn test_complement_sse() { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { if is_x86_feature_detected!("sse2") { assert!(encoding_equals( &unsafe { complement_sse(&encode(b"AUCGATCGATCGATCGATCGATCGATCGATCG")) }, &encode(b"TAG...
function_block-full_function
[ { "content": "pub fn hamming(a: &[u64], b: &[u64], len: usize) -> usize {\n\n if len / 64 <= 8 {\n\n return hamming_scalar(a, b, len);\n\n }\n\n\n\n #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n\n {\n\n if is_x86_feature_detected!(\"avx2\") {\n\n return unsa...
Rust
src/lib.rs
Ruide/spire-workload-rs
d943facdea4003ee0f6f7b77113e8d74eac39eb6
#![allow(clippy::len_zero)] #[macro_use] extern crate lazy_static; extern crate anyhow; pub mod authenticator; mod der; mod jwt; mod pki; pub mod spiffe; mod spire; mod verifier; mod workload; pub use authenticator::SpiffeIdAuthorizer; pub use jwt::{JwtBundle, JwtKey}; pub use spiffe::{SpiffeID, SpiffeIDMatcher}; ...
#![allow(clippy::len_zero)] #[macro_use] extern crate lazy_static; extern crate anyhow; pub mod authenticator; mod der; mod jwt; mod pki; pub mod spiffe; mod spire; mod verifier; mod workload; pub use authenticator::SpiffeIdAuthorizer; pub use jwt::{JwtBundle, JwtKey}; pub use spiffe::{SpiffeID, SpiffeIDMatcher}; ...
, authorizer, require_client_auth, }); let mut config = rustls::ServerConfig::new(dyn_resolver_verifier.clone()); config.key_log = Arc::new(rustls::KeyLogFile::new()); config.cert_resolver = dyn_resolver_verifier; config.set_protocols(protocols); config }
let bundle = parse_der_cert_chain(bundle)?; Self::from_rustls(bundle, certs, key) } pub fn from_rustls( bundle: Vec<Certificate>, certs: Vec<Certificate>, key: PrivateKey, ) -> Result<Identity> { let cert_key = CertifiedKey::new( certs, Ar...
random
[ { "content": "// splits concatenated DER files (why doesn't rustls/webpki do this?)\n\npub fn split_der(der_blob: &[u8]) -> Result<Vec<&[u8]>> {\n\n let mut index = 0usize;\n\n let mut start_index = 0usize;\n\n let mut results = vec![];\n\n while index < der_blob.len() {\n\n if der_blob[index...
Rust
crates/bevy_audio/src/asset_player.rs
gaxxx/bevy
890f4092c53fbd0b528a9e1bd50c637556253484
use bevy_ecs::event::Events; use rodio::Sink; use std::fmt; use std::fmt::Debug; use bevy_asset::{Asset, Assets, Handle}; use bevy_ecs::world::{World, WorldBorrowMut}; use bevy_utils::tracing::info; use crate::{AudioOutput, AudioSource, Decodable}; #[derive(Default)] pub struct AssetPlayer { audios: Vec<Handle<A...
use bevy_ecs::event::Events; use rodio::Sink; use std::fmt; use std::fmt::Debug; use bevy_asset::{Asset, Assets, Handle}; use bevy_ecs::world::{World, WorldBorrowMut}; use bevy_utils::tracing::info; use crate::{AudioOutput, AudioSource, Decodable}; #[derive(Default)] pub struct AssetPlayer { audios: Vec<Handle<A...
pub fn stop(&mut self) { if let Some(sink) = self.sink.as_mut() { sink.stop(); } } pub fn pause(&mut self) { if let Some(sink) = self.sink.as_mut() { sink.pause(); } } pub fn resume(&mut self) { if let Some(sink) = se...
self.sink = Some(sink) } else if let Some(sink) = self.sink.as_mut() { sink.append(audio_source.decoder()); } } }
function_block-function_prefix_line
[ { "content": "/// Plays audio currently queued in the [`Audio`] resource through the [`AudioOutput`] resource\n\npub fn play_queued_audio_system<Source: Asset>(world: &mut World)\n\nwhere\n\n Source: Decodable,\n\n{\n\n let world = world.cell();\n\n let audio_output = world.get_non_send::<AudioOutput<S...
Rust
network-grpc/src/service/subscription.rs
atixlabs/chain-libs
dc3904d64be2989fa632031b52f87fde9926b6c7
use super::{request_stream::Forward, response_stream}; use crate::convert::{encode_node_id, error_into_grpc, FromProtobuf, IntoProtobuf}; use chain_core::property; use network_core::error as core_error; use network_core::gossip::NodeId; use network_core::server::request_stream::MapResponse; use futures::prelude::*; us...
use super::{request_stream::Forward, response_stream}; use crate::convert::{encode_node_id, error_into_grpc, FromProtobuf, IntoProtobuf}; use chain_core::property; use network_core::error as core_error; use network_core::gossip::NodeId; use network_core::server::request_stream::MapResponse; use futures::prelude::*; us...
} enum InboundOutcome { Continue, Closed, } impl<T, In, S> Subscription<T, In, S> where In: Stream<Error = Status>, S: Sink<SinkError = core_error::Error>, S: MapResponse, S::SinkItem: FromProtobuf<In::Item>, { fn process_inbound(&mut self) -> Poll<InboundOutcome, Status> { use In...
fn new(inbound: In, core_subscription: S) -> Self { let forward = Forward::new(inbound, core_subscription); Subscription { state: State::Full(forward), _phantom: PhantomData, } }
function_block-full_function
[ { "content": "pub fn poll_and_convert<T, S>(stream: &mut S) -> Poll<Option<T>, Status>\n\nwhere\n\n S: Stream<Error = core_error::Error>,\n\n S::Item: IntoProtobuf<T>,\n\n{\n\n match stream.poll() {\n\n Ok(Async::NotReady) => Ok(Async::NotReady),\n\n Ok(Async::Ready(Some(item))) => {\n\n ...
Rust
src/server/mod.rs
mittelab/spaceapi-server-rs
1396a26fdc378e1df15142aef2bdae12134604c7
use std::net::ToSocketAddrs; use std::sync::Arc; use std::time::Duration; use r2d2; use r2d2_redis::RedisConnectionManager; use iron::Iron; use router::Router; use redis::{IntoConnectionInfo, ConnectionInfo}; use serde_json::Value; use serde_json::map::Map; mod handlers; use crate::api; use crate::sensors; use c...
use std::net::ToSocketAddrs; use std::sync::Arc; use std::time::Duration; use r2d2; use r2d2_redis::RedisConnectionManager; use iron::Iron; use router::Router; use redis::{IntoConnectionInfo, ConnectionInfo}; use serde_json::Value; use serde_json::map::Map; mod handlers; use crate::api; use crate::sensors; use c...
} } pub struct SpaceapiServer { status: api::Status, redis_pool: RedisPool, sensor_specs: sensors::SafeSensorSpecs, status_modifiers: Vec<Box<modifiers::StatusModifier>>, } impl SpaceapiServer { fn route(self) -> Router { let mut router = Router::new(); router.get("/", ...
Ok(SpaceapiServer { status: self.status, redis_pool: pool, sensor_specs: Arc::new(self.sensor_specs), status_modifiers: self.status_modifiers, })
call_expression
[ { "content": "/// Return own crate version. Used in API responses.\n\npub fn get_version() -> &'static str {\n\n env!(\"CARGO_PKG_VERSION\")\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::get_version;\n\n\n\n #[test]\n\n fn test_get_version() {\n\n let version = get_version();\n\n ...
Rust
src/util/options.rs
wks/mmtk-core
3d9861da1836ed7dd40778687aa732a121263491
use crate::util::constants::DEFAULT_STRESS_FACTOR; use std::cell::UnsafeCell; use std::default::Default; use std::ops::Deref; custom_derive! { #[derive(Copy, Clone, EnumFromStr, Debug)] pub enum NurseryZeroingOptions { Temporal, Nontemporal, Concurrent, Adaptive, } } custom...
use crate::util::constants::DEFAULT_STRESS_FACTOR; use std::cell::UnsafeCell; use std::default::Default; use std::ops::Deref; custom_derive! { #[derive(Copy, Clone, EnumFromStr, Debug)] pub enum NurseryZeroingOptions { Temporal, Nontemporal, Concurrent, Adaptive, } } custom...
#[test] fn test_str_option_default() { serial_test(|| { let options = Options::default(); assert_eq!(&options.example_string_option as &str, "hello world"); }) } #[test] fn test_str_option_from_env_var() { serial_test(|| { with_cleanup( ...
fn with_invalid_env_var_key() { serial_test(|| { with_cleanup( || { std::env::set_var("MMTK_ABC", "42"); let options = Options::default(); assert_eq!(options.stress_factor, DEFAULT_STRESS_FACTOR); ...
function_block-full_function
[ { "content": "/// Process MMTk run-time options.\n\n///\n\n/// Arguments:\n\n/// * `mmtk`: A reference to an MMTk instance.\n\n/// * `name`: The name of the option.\n\n/// * `value`: The value of the option (as a string).\n\npub fn process<VM: VMBinding>(mmtk: &'static MMTK<VM>, name: &str, value: &str) -> bool...
Rust
src/codegen/inheritance_walker.rs
xxx/lpc-rs
dd34332c1448d9e449ee70161e9a61351b2e9557
use crate::{ ast::inherit_node::InheritNode, codegen::tree_walker::{ContextHolder, TreeWalker}, compilation_context::CompilationContext, compiler::Compiler, core::EFUN, util::path_maker::LpcPath, LpcError, Result, }; #[derive(Debug, Default)] pub struct InheritanceWalker { context:...
use crate::{ ast::inherit_node::InheritNode, codegen::tree_walker::{ContextHolder, TreeWalker}, compilation_context::CompilationContext, compiler::Compiler, core::EFUN, util::path_maker::LpcPath, LpcError, Result, }; #[derive(Debug, Default)] pub struct InheritanceWalker { context:...
if let Some(namespace) = &node.namespace { self.context .inherit_names .insert(namespace.clone(), self.context.inherits.len()); } self.context.num_globals += program.num_globals; self.c...
if self .context .inherits .iter() .any(|x| x.filename == program.filename) { let err = LpcError::new(format!( "`{}` is already being inherited from", progr...
if_condition
[ { "content": "/// Resolve an expression node down to a single type, recursively if necessary\n\n/// Handles type promotion when necessary.\n\n///\n\n/// # Arguments\n\n/// * `node` - The `ExpressionNode` whose type we would like to resolve.\n\n/// * `context` - The current [`CompilationContext`]\n\n///\n\n/// #...
Rust
src/widget/scroll.rs
scholtzan/druid
a92f85fcec867d0880f39e5e08c1e9fa0d0ab02d
use std::f64::INFINITY; use std::time::{Duration, Instant}; use log::error; use crate::{ Action, BaseState, BoxConstraints, Data, Env, Event, EventCtx, LayoutCtx, PaintCtx, Point, Rect, Size, TimerToken, UpdateCtx, Vec2, Widget, WidgetPod, }; use crate::piet::RenderContext; use crate::theme; use crate::ku...
use std::f64::INFINITY; use std::time::{Duration, Instant}; use log::error; use crate::{ Action, BaseState, BoxConstraints, Data, Env, Event, EventCtx, LayoutCtx, PaintCtx, Point, Rect, Size, TimerToken, UpdateCtx, Vec2, Widget, WidgetPod, }; use crate::piet::RenderContext; use crate::theme; use crate::ku...
pub fn vertical(mut self) -> Self { self.direction = ScrollDirection::Vertical; self } pub fn horizontal(mut self) -> Self { self.direction = ScrollDirection::Horizontal; self } fn draw_bars(&self, paint_ctx: &mut PaintCtx, viewport: &Rect...
ax(0.0); offset.y = offset.y.min(self.child_size.height - size.height).max(0.0); if (offset - self.scroll_offset).hypot2() > 1e-12 { self.scroll_offset = offset; true } else { false } }
function_block-function_prefixed
[ { "content": "fn pad<T: Data>(inner: impl Widget<T> + 'static) -> impl Widget<T> {\n\n Padding::uniform(5.0, inner)\n\n}\n\n\n", "file_path": "examples/calc.rs", "rank": 0, "score": 241127.02153671434 }, { "content": "fn build_widget() -> impl Widget<u32> {\n\n let mut col = Column::ne...
Rust
oom-backend/oom-api/src/lib.rs
tbrand/OutOfMemory
781883cdd0394ecc8e05926fec96c0d78a3b9da3
#![deny(warnings)] #![recursion_limit = "128"] #[macro_use] extern crate warp; #[macro_use] extern crate log; #[macro_use] extern crate serde; pub mod answers; pub mod api_error; pub mod auth; pub mod comments; pub mod config; pub mod cors; pub mod login; pub mod posts; pub mod questions; pub mod state; pub mod tag...
#![deny(warnings)] #![recursion_limit = "128"] #[macro_use] extern crate warp; #[macro_use] extern crate log; #[macro_use] extern crate serde; pub mod answers; pub mod api_error; pub mod auth; pub mod comments; pub mod config; pub mod cors; pub mod login; pub mod posts; pub mod questions; pub mod state; pub mod tag...
let posts_comments_by_post_id = path!("posts" / u32 / "comments") .and(warp::path::end()) .and(warp::get2()) .and(state.clone()) .and_then(comments::by_post_id); let posts_tags = path!("posts" / u32 / "tags") .and(warp::path::end()) .and(warp::get2()) ....
let posts_comments_create = path!("posts" / u32 / "comments") .and(warp::path::end()) .and(warp::post2()) .and(state.clone()) .and(auth_header()) .and(warp::body::content_length_limit(BODY_SIZE_LIMIT)) .and(warp::body::json()) .and_then(comments::create);
assignment_statement
[ { "content": "pub fn tags(post_id: u32, state: Arc<Mutex<State>>) -> Result<impl warp::Reply, warp::Rejection> {\n\n use crate::db::tags::by_post_id;\n\n\n\n let conn = state.lock().unwrap().pool.get().unwrap();\n\n\n\n by_post_id(&conn, post_id)\n\n .map(|t| warp::reply::json(&t))\n\n .m...
Rust
compiler/rustc_mir_transform/src/elaborate_box_derefs.rs
ghishadow/rust
10f4ce324baf7cfb7ce2b2096662b82b79204944
use crate::MirPass; use rustc_hir::def_id::DefId; use rustc_index::vec::Idx; use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::visit::MutVisitor; use rustc_middle::mir::*; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{Ty, TyCtxt}; pub fn build_ptr_tys<'tcx>( tcx: TyCtxt<'tcx>, point...
use crate::MirPass; use rustc_hir::def_id::DefId; use rustc_index::vec::Idx; use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::visit::MutVisitor; use rustc_middle::mir::*; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{Ty, TyCtxt}; pub fn build_ptr_tys<'tcx>( tcx: TyCtxt<'tcx>, point...
} pub struct ElaborateBoxDerefs; impl<'tcx> MirPass<'tcx> for ElaborateBoxDerefs { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if let Some(def_id) = tcx.lang_items().owned_box() { let unique_did = tcx.adt_def(def_id).non_enum_variant().fields[0].did; let Some(n...
fn visit_place( &mut self, place: &mut Place<'tcx>, context: visit::PlaceContext, location: Location, ) { let tcx = self.tcx; let base_ty = self.local_decls[place.local].ty; if place.projection.first() == Some(&PlaceElem::Deref) && base_ty.is_box() ...
function_block-full_function
[]
Rust
src/dbtype/change_result.rs
benkard/couchdb-rs
faffb797ff4f7fd58889bcd1da6901d33638481e
use serde; use std; use ChangeItem; use ChangeItemBuilder; use DocumentId; use Revision; #[derive(Debug)] pub struct ChangeResultBuilder { target: ChangeResult, } impl ChangeResultBuilder { pub fn new<I: Into<DocumentId>>(seq: u64, doc_id: I) -> Self { ChangeResultBuilde...
use serde; use std; use ChangeItem; use ChangeItemBuilder; use DocumentId; use Revision; #[derive(Debug)] pub struct ChangeResultBuilder { target: ChangeResult, } impl ChangeResultBuilder { pub fn new<I: Into<DocumentId>>(seq: u64, doc_id: I) -> Self { ChangeResultBuilde...
} try!(visitor.end()); let changes = match changes { Some(x) => x, None => try!(visitor.missing_field("changes")), }; let deleted = deleted.unwrap_or(false); let id = match id { ...
match try!(visitor.visit_key()) { Some(Field::Changes) => { changes = Some(try!(visitor.visit_value())); } Some(Field::Deleted) => { deleted = Some(try!(visitor.visit_value())); ...
if_condition
[ { "content": "pub fn from_str(s: &str) -> Option<[u8; 16]> {\n\n\n\n if s.len() != 32 {\n\n return None;\n\n }\n\n\n\n let mut h = [0 as u8; 32];\n\n let mut i = 0;\n\n for c in s.chars() {\n\n h[i] = match c.to_digit(16) {\n\n None => {\n\n return None;\n\...
Rust
zyklop/src/token.rs
jedahan/hex
7f4cf6631f490b647895cc93e0693523bc16456c
use std::fs::File; use std::thread; use std::time::Duration; use std::sync::mpsc::Sender; use std::path::{Path, PathBuf}; use rand::{thread_rng, Rng}; use hex_database::{Track, Token, TrackKey}; use hex_music_container::{Container, Configuration}; use error::{Error, Result}; pub struct Stream { pub track: Track,...
use std::fs::File; use std::thread; use std::time::Duration; use std::sync::mpsc::Sender; use std::path::{Path, PathBuf}; use rand::{thread_rng, Rng}; use hex_database::{Track, Token, TrackKey}; use hex_music_container::{Container, Configuration}; use error::{Error, Result}; pub struct Stream { pub track: Track,...
} pub fn shuffle(&mut self) { thread_rng().shuffle(&mut self.not_played); } }
if self.played.is_empty() { let elm = self.not_played.remove(0); self.stream = self.create_stream(elm, &self.data_path); self.token.pos = Some(0.0); } else { let elm = self.played.pop().unwrap(); self.stream = self.create_stream(elm, &self.data_path); ...
if_condition
[ { "content": "pub fn sync_tracks(tracks: Vec<Track>, sender: Sender<TrackKey>, data_path: PathBuf) {\n\n let length = tracks.len();\n\n for track in tracks {\n\n print!(\"Syncing track: {}\", track.key.to_string());\n\n io::stdout().flush().unwrap();\n\n\n\n sender.send(track.key.clon...
Rust
src/rtccntl/state0.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
#[doc = "Reader of register STATE0"] pub type R = crate::R<u32, super::STATE0>; #[doc = "Writer for register STATE0"] pub type W = crate::W<u32, super::STATE0>; #[doc = "Register STATE0 `reset()`'s with value 0"] impl crate::ResetValue for super::STATE0 { type Type = u32; #[inline(always)] fn reset_value() ...
#[doc = "Reader of register STATE0"] pub type R = crate::R<u32, super::STATE0>; #[doc = "Writer for register STATE0"] pub type W = crate::W<u32, super::STATE0>; #[doc = "Register STATE0 `reset()`'s with value 0"] impl crate::ResetValue for super::STATE0 { type Type = u32; #[inline(always)] fn reset_value() ...
(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `SW_CPU_INT`"] pub struct SW_CPU_INT_W<'a> { w: &'a mut W, } impl<'a> SW_CPU_INT_W<'a> { #[doc = r"Sets the field ...
a mut W, } impl<'a> SLP_REJECT_CAUSE_CLR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
2015/03/src/main.rs
PsypherPunk/advent-of-code
5da9cea793d0dd326d01ccaa307bfbb13ab8c06f
use std::collections::HashSet; use std::fs::File; use std::io::prelude::*; use std::iter::FromIterator; fn read_input() -> String { let filename = "input.txt"; match File::open(filename) { Ok(mut file) => { let mut content = String::new(); file.read_to_string(&mut content).unwra...
use std::collections::HashSet; use std::fs::File; use std::io::prelude::*; use std::iter::FromIterator; fn read_input() -> String { let filename = "input.txt"; match File::open(filename) { Ok(mut file) => { let mut content = String::new(); file.read_to_string(&mut content).unwra...
t one present? {}", format_number(count_houses(&input)), ); println!( "…at least one present? {}", format_number(count_houses_with_robo_santa(&input)), ); } #[cfg(test)] mod tests { use super::*; #[test] fn test_two() { assert_eq!(count_houses(String::from(">"))...
'<' => (x - 1, y), _ => panic!("Invalid character: {}", instruction), }, ); } for instruction in robo_santa_instructions { let (x, y) = robo_santa_stops[0]; robo_santa_stops.insert( 0, match instruction { '^' =...
random
[ { "content": "pub fn find_floor(instructions: String) -> i32 {\n\n let mut floor = 0;\n\n let mut position = 0;\n\n for line in instructions.lines() {\n\n for ch in line.chars() {\n\n position += 1;\n\n match ch {\n\n '(' => floor += 1,\n\n ')'...
Rust
src/from.rs
RagibHasin/duration_utils-rs
050ed5a23855b701d9b9cb2ba0edcb58ecc6e700
use regex::Regex; use std::ops::Range; use std::time::Duration; const VALID_SECS: Range<u32> = 0..60; #[inline] pub fn try_from_hms(h: u32, m: u32, s: u32) -> Option<Duration> { if VALID_SECS.contains(&s) && VALID_SECS.contains(&m) { Some(Duration::from_secs((h * 3600 + m * 60 + s) as u64)) } else { ...
use regex::Regex; use std::ops::Range; use std::time::Duration; const VALID_SECS: Range<u32> = 0..60; #[inline] pub fn try_from_hms(h: u32, m: u32, s: u32) -> Option<Duration> { if VALID_SECS.contains(&s) && VALID_SECS.contains(&m) { Some(Duration::from_secs((h * 3600 + m * 60 + s) as u64)) } else { ...
#[cfg(test)] mod tests { use super::*; #[test] fn from_hms_opt_s() { assert_eq!(try_from_hms(2, 30, 60), None) } #[test] fn from_hms_opt_m() { assert_eq!(try_from_hms(2, 60, 0), None) } #[test] fn from_hms_milli_opt_milli() { assert_eq!(try_from_hms_milli...
pub fn from_iso8601(value: &str) -> Option<Duration> { let pattern = Regex::new( r"([-+]?)P(?:([-+]?[0-9]+)D)?(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?").unwrap(); if let Some(caps) = pattern.captures(value) { if caps.get(3).map_or(true, |t| t.as_str() !...
function_block-full_function
[ { "content": "/// ISO 8601 serialization format for `std::time::Duration`.\n\npub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n serializer.serialize_str(to_iso8601(duration).as_str())\n\n}\n\n\n", "file_path": "src/direct_serde.rs",...
Rust
src/test/instruction_tests/instr_vpsignw.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpsignw_1() { run_test( &Instruction { mnemonic: Mnemonic::VPSIGNW, ope...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpsignw_1() { run_test( &Instruction { mnemonic: Mnemonic::VPSIGNW, ope...
#[test] fn vpsignw_7() { run_test( &Instruction { mnemonic: Mnemonic::VPSIGNW, operand1: Some(Direct(YMM5)), operand2: Some(Direct(YMM3)), operand3: Some(Direct(YMM0)), operand4: None, lock: false, rounding_mode: None, ...
fn vpsignw_6() { run_test( &Instruction { mnemonic: Mnemonic::VPSIGNW, operand1: Some(Direct(YMM4)), operand2: Some(Direct(YMM5)), operand3: Some(IndirectScaledDisplaced( EDI, Eight, 1049655259, S...
function_block-full_function
[ { "content": "fn encode32_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
fruity_core/fruity_ecs/src/entity/entity_query/serialized/params.rs
DoYouRockBaby/fruity_game_engine
299a8fe641efb142a551640f6d1aa4868e1ad670
use crate::entity::archetype::Archetype; use crate::entity::entity_query::serialized::SerializedQueryParam; use crate::entity::entity_reference::EntityReference; use fruity_any::*; use fruity_core::convert::FruityInto; use fruity_core::serialize::serialized::Serialized; #[derive(FruityAny, Clone)] pub struct WithEntit...
use crate::entity::archetype::Archetype; use crate::entity::entity_query::serialized::SerializedQueryParam; use crate::entity::entity_reference::EntityReference; use fruity_any::*; use fruity_core::convert::FruityInto; use fruity_core::serialize::serialized::Serialized; #[derive(FruityAny, Clone)] pub struct WithEntit...
.collect::<Vec<_>>(); if components.len() > 0 { components } else { vec![Serialized::Null] } } }
get_components_by_type_identifier(&self.identifier) .into_iter() .map(|component| component.fruity_into()) .collect::<Vec<_>>() } } #[derive(FruityAny, Clone)] pub struct WithOptional { pub identifier: String, } impl SerializedQueryParam for WithOptional { fn duplicate(...
random
[ { "content": "#[topo::nested]\n\npub fn use_memo<T: Clone + 'static, U: Clone + Eq + 'static>(\n\n mut data_fn: impl FnMut(U) -> T,\n\n dependency: U,\n\n) -> T {\n\n let value_state = use_state(|| data_fn(dependency.clone()));\n\n let dependency_state = use_state(|| dependency.clone());\n\n\n\n ...
Rust
src/matrix.rs
Faudil/linear_algebra
f9a8f60ccbfae609eca99632116426bff2214ea4
use std::fmt; use std::ops::{Index, Mul}; use std::cmp::{PartialEq}; pub struct Matrix { _height: usize, _width: usize, _bound: usize, _value: Vec<f64> } impl fmt::Debug for Matrix { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let str_list = self._value.iter().map(|&x| x.to_stri...
use std::fmt; use std::ops::{Index, Mul}; use std::cmp::{PartialEq}; pub struct Matrix { _height: usize, _width: usize, _bound: usize, _value: Vec<f64> } impl fmt::Debug for Matrix { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let str_list = self._value.iter().map(|&x| x.to_stri...
pub fn add(&mut self, other: &Matrix) { for i in 0..self._bound { self._value[i] += other._value[i]; } } pub fn sub(&mut self, other: &Matrix) { for i in 0..self._bound { self._value[i] -= other._value[i]; } } pub fn transpose(&self) -> Mat...
fn mul_line(&self, other: &Matrix, i: usize, j: usize) -> f64{ let mut res = 0.0; for k in 0..other._width { res += self._value[i * self._width + k] * other._value[k * self._width + j] } res }
function_block-full_function
[ { "content": "#[cfg(test)]\n\nextern crate linear_algebra;\n\n\n\nmod matrix_tests {\n\n use linear_algebra::matrix::Matrix;\n\n #[test]\n\n fn it_works() {\n\n assert_eq!(2 + 2, 4);\n\n }\n\n #[test]\n\n fn simple_addition() {\n\n let mut m = Matrix::new_init(2, 2, vec![1.0, 1.0...
Rust
src/networking.rs
martoko/kredit
bc179846004db3370edf4b92af1f95e5cf878071
use std::{ fmt::{Display, Formatter}, io::{BufWriter, ErrorKind, Read}, io, net::{SocketAddr, TcpListener, TcpStream}, sync::mpsc::{channel, Receiver, Sender, SendError, TryRecvError}, thread::{JoinHandle, sleep}, time::Duration, }; use crate::{ Direction::{Inbound, Outbound}, Direc...
use std::{ fmt::{Display, Formatter}, io::{BufWriter, ErrorKind, Read}, io, net::{SocketAddr, TcpListener, TcpStream}, sync::mpsc::{channel, Receiver, Sender, SendError, TryRecvError}, thread::{JoinHandle, sleep}, time::Duration, }; use crate::{ Direction::{Inbound, Outbound}, Direc...
sleep(Duration::from_millis(10)); } Ok(()) }); self.connections.push(Connection { addr: remote_addr, thread: connection_thread, sender: connection_sender, direction, }); Ok(remote_addr) } pub fn is_con...
break 'stream_events; } Ok(1) => { let message = NetworkedMessage::receive(&stream, buffer[0]).unwrap(); node_sender.send(Incoming::Message(remote_addr, message)).unwrap(); } ...
random
[ { "content": "fn main() -> io::Result<()> {\n\n let args = Args::from_args();\n\n let should_mine_on_startup = args.mine;\n\n\n\n let quit_requested = Arc::new(AtomicBool::new(false));\n\n {\n\n let quit_requested = quit_requested.clone();\n\n ctrlc::set_handler(move || {\n\n ...
Rust
src/audio_compo/cassette_deck.rs
muzudho/rust-kifuwarabe-wcsc29-lib
5f18ee2417a51035921164640c045fbc1613be5c
use media::cassette_tape::*; use media::cassette_tape_box::*; use sheet_music_format::kifu_rpm::rpm_tape_box::*; use sheet_music_format::tape_label::TapeLabel; use sound::shogi_move::ShogiMove; use sound::shogi_note::ShogiNote; use studio::application::Application; use studio::board_size::BoardSize; use studio::common:...
use media::cassette_tape::*; use media::cassette_tape_box::*; use sheet_music_format::kifu_rpm::rpm_tape_box::*; use sheet_music_format::tape_label::TapeLabel; use sound::shogi_move::ShogiMove; use sound::shogi_note::ShogiNote; use studio::application::Application; use studio::board_size::BoardSize; use studio::common:...
pub fn add_tapes_from_file( &mut self, box_file_name: &str, slot: Slot, board_size: BoardSize, app: &Application, ) { let tape_box = &mut self.slots[slot as usize]; let rpm_tape_box = RpmTapeBox::from_box_file(&box_file_name, &app); ...
pub fn new(app: &Application) -> Self { if app.is_debug() { app.comm.println("[#Deck:new]"); } let mut training_tape_box = CassetteTapeBox::new_empty_tape_box(Slot::Training, &app); training_tape_box.set_file_name_without_extension( &RpmTapeBox::create_file_full_...
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct Args {\n\n path: Option<String>,\n\n}\n\n\n", "file_path": "examples/eat_a_csa.rs", "rank": 0, "score": 60084.36749817907 }, { "content": "#[derive(Debug)]\n\nstruct Args {\n\n path: Option<String>,\n\n}\n\n\n", "file_path": "examples/usi_to...
Rust
src/main.rs
White-Green/bnf_lr1_checker
d034abe6990b6fa81b6b3c142dec979eac17c222
use clap::{crate_authors, crate_description, crate_name, crate_version, Arg}; use parser::enum_index::EnumIndex; use parser::{LR1Parser, Rule, Syntax}; use std::collections::HashMap; use std::error::Error; use std::fs; use std::hash::Hash; use syn::parse::{Parse, ParseStream}; use syn::{bracketed, token, Expr, Ident, L...
use clap::{crate_authors, crate_description, crate_name, crate_version, Arg}; use parser::enum_index::EnumIndex; use parser::{LR1Parser, Rule, Syntax}; use std::collections::HashMap; use std::error::Error; use std::fs; use std::hash::Hash; use syn::parse::{Parse, ParseStream}; use syn::{bracketed, token, Expr, Ident, L...
} } enum BNFTerminalSymbol { Named { _bracket: token::Bracket, name: Ident }, Raw(LitStr), } impl Parse for BNFTerminalSymbol { fn parse(input: ParseStream) -> syn::Result<Self> { if input.peek(token::Bracket) { let name; Ok(BNFTerminalSymbol::Named { _bracket: bracket...
if input.peek(LitStr) { let s: LitStr = input.parse()?; Ok(TokenKey::Raw(s.value())) } else { let s: Ident = input.parse()?; Ok(TokenKey::Named(s.to_string())) }
if_condition
[]
Rust
examples/example-ssl.rs
advection/kafka-client
9951d74e5268f0cd253e36a0ef561a84e50c1e59
#[macro_use] extern crate log; #[tokio::main] async fn main() { example::main().await; } #[cfg(feature = "security")] mod example { extern crate env_logger; extern crate getopts; use std::env; use std::fs; use std::io::BufReader; use std::process; use kafka::client::{FetchOffset, Kaf...
#[macro_use] extern crate log; #[tokio::main] async fn main() { example::main().await; } #[cfg(feature = "security")] mod example { extern crate env_logger; extern crate getopts; use std::env; use std::fs; use std::io::BufReader; use std::process; use kafka::client::{FetchOffset, Kaf...
.map(|s| s.trim().to_owned()) .filter(|s| !s.is_empty()) .collect() }) .unwrap_or_else(|| vec!["localhost:9092".into()]); if brokers.is_empty() { return Err("Invalid --brokers specified!"....
(); let cfg = match Config::from_cmdline() { Ok(cfg) => cfg, Err(e) => { println!("{}", e); process::exit(1); } }; let rustls_config = { let mut config = rustls::ClientConfig::new(); config ...
random
[ { "content": "pub fn test_consumer() -> Consumer {\n\n test_consumer_with_client(new_ready_kafka_client())\n\n}\n\n\n", "file_path": "tests/integration/consumer_producer/mod.rs", "rank": 0, "score": 115516.19252569397 }, { "content": "pub fn test_producer() -> Producer {\n\n let client...
Rust
src/tabix.rs
shahamran/bgzip-rs
c34417defe25ffd833a0bc12f4d041acabf99e79
use crate::*; use std::collections::HashMap; use std::convert::TryInto; use std::i32; use std::io::{self, BufRead, Read, Result}; #[derive(Debug, Clone, PartialEq)] pub struct TabixChunk { pub begin: u64, pub end: u64, } impl TabixChunk { fn from_reader<R: Read + BinaryReader>(reader: &mut R) -> Result<Se...
use crate::*; use std::collections::HashMap; use std::convert::TryInto; use std::i32; use std::io::{self, BufRead, Read, Result}; #[derive(Debug, Clone, PartialEq)] pub struct TabixChunk { pub begin: u64, pub end: u64, } impl TabixChunk { fn from_reader<R: Read + BinaryReader>(reader: &mut R) -> Result<Se...
} #[derive(Debug, Clone, PartialEq)] pub struct TabixSequence { pub number_of_distinct_bin: i32, pub bins: HashMap<u32, TabixBin>, pub number_of_intervals: i32, pub intervals: Vec<u64>, } impl TabixSequence { fn from_reader<R: Read + BinaryReader>(reader: &mut R) -> Result<Self> { let num...
fn from_reader<R: Read + BinaryReader>(reader: &mut R) -> Result<Self> { let bin = reader.read_le_u32()?; let number_of_chunk = reader.read_le_i32()?; let mut chunks = Vec::new(); for _ in 0..number_of_chunk { chunks.push(TabixChunk::from_reader(reader)?); } ...
function_block-function_prefix_line
[ { "content": "fn main() -> Result<(), BGZFError> {\n\n let matches = App::new(\"bgzip\")\n\n .version(\"0.1.0\")\n\n .author(\"Okamura, Yasunobu\")\n\n .about(\"Rust implementation of bgzip\")\n\n .arg(\n\n Arg::with_name(\"decompress\")\n\n .short(\"d\")...
Rust
crates/competitive/src/tools/scanner.rs
to-omer/competitive-library
50f00872254c2cfb169d4c674786e0f8c0d27484
use std::{ iter::{from_fn, repeat_with, FromIterator}, marker::PhantomData, }; pub fn read_stdin_all() -> String { use std::io::Read as _; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).expect("io error"); s } pub fn read_stdin_all_unchecked() -> String { use std::io::Re...
use std::{ iter::{from_fn, repeat_with, FromIterator}, marker::PhantomData, }; pub fn read_stdin_all() -> String { use std::io::Read as _; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).expect("io error"); s }
pub fn read_all(mut reader: impl std::io::Read) -> String { let mut s = String::new(); reader.read_to_string(&mut s).expect("io error"); s } pub fn read_all_unchecked(mut reader: impl std::io::Read) -> String { let mut buf = Vec::new(); reader.read_to_end(&mut buf).expect("io error"); unsafe { ...
pub fn read_stdin_all_unchecked() -> String { use std::io::Read as _; let mut buf = Vec::new(); std::io::stdin().read_to_end(&mut buf).expect("io error"); unsafe { String::from_utf8_unchecked(buf) } }
function_block-full_function
[ { "content": "pub fn init_logger(target: String) -> Result<(), log::SetLoggerError> {\n\n env_logger::builder()\n\n .format(move |buf, record| log_formatter(buf, record, &target))\n\n .is_test(true)\n\n .try_init()\n\n}\n", "file_path": "crates/tools/verify/src/lib.rs", "rank": 2...
Rust
libjose/src/jwt/header.rs
adrian-grassl/identity.rs
41fbd548438eee908134c90f8cf8cc26f551d675
use url::Url; use crate::jose::JoseHeader; use crate::jwk::Jwk; use crate::lib::*; #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct JwtHeader { #[serde(skip_serializing_if = "Option::is_none")] jku: Option<Url>, #[serde(skip_serializing_if = "Option::is_no...
use url::Url; use crate::jose::JoseHeader; use crate::jwk::Jwk; use crate::lib::*; #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct JwtHeader { #[serde(skip_serializing_if = "Option::is_none")] jku: Option<Url>, #[serde(skip_serializing_if = "Option::is_no...
pub fn jku(&self) -> Option<&Url> { self.jku.as_ref() } pub fn set_jku(&mut self, value: impl Into<Url>) { self.jku = Some(value.into()); } pub fn jwk(&self) -> Option<&Jwk> { self.jwk.as_ref() } pub fn set_jwk(&mut self, value: impl Into<Jwk>) { self.jwk = Some(value.into...
x5c: None, x5t: None, x5t_s256: None, typ: None, cty: None, crit: None, url: None, nonce: None, } }
function_block-function_prefix_line
[ { "content": "/// Implement the Debug trait on a derived struct.\n\npub fn debug_impl(input: &InputModel) -> TokenStream {\n\n // collect relevant fields.\n\n let svariant = input.s_variant();\n\n let diff = input.diff();\n\n let fields = input.fields();\n\n let param_decls = input.param_decls();\n\n let ...
Rust
src/mbr.rs
DianaNites/parts
cc9c443931a9dbdbc899c41cd924faf79133dd81
use crate::{gpt::error::*, types::*}; use core::{convert::TryFrom, mem::size_of}; pub const MBR_SIZE: usize = 512; #[derive(Copy, Clone)] #[repr(transparent)] struct BootCode([u8; 440]); impl PartialEq for BootCode { fn eq(&self, other: &Self) -> bool { self.0[..] == other.0[..] } } impl Default fo...
use crate::{gpt::error::*, types::*}; use core::{convert::TryFrom, mem::size_of}; pub const MBR_SIZE: usize = 512; #[derive(Copy, Clone)] #[repr(transparent)] struct BootCode([u8; 440]); impl PartialEq for BootCode { fn eq(&self, other: &Self) -> bool { self.0[..] == other.0[..] } } impl Default fo...
}
MBR_SIZE]; let my_mbr = ProtectiveMbr::from_bytes(raw_mbr)?; let mut raw_my_mbr = [0u8; MBR_SIZE]; my_mbr.to_bytes(&mut raw_my_mbr)?; assert_eq!(&raw_my_mbr[..], &raw_mbr[..]); let parsed_raw_my_mbr = ProtectiveMbr::from_bytes(&raw_my_mbr)?; assert_eq!(parsed_raw...
function_block-function_prefixed
[ { "content": "/// Validate the Gpt Headers.\n\n///\n\n/// Calls `cb` when going through the primary partition array.\n\n/// This is used to add partitions in `GptC`\n\n///\n\n/// Per the GPT Spec this checks:\n\n///\n\n/// - The signature (Checked in [`Header::from_bytes`])\n\n/// - Header CRC (Checked in [`Hea...
Rust
src/main.rs
piropaolo/cleora
7846461f785b8dfdb6e77f60d38e1e0ae0988666
use std::time::Instant; use clap::{crate_authors, crate_description, crate_name, crate_version, App, Arg}; use cleora::configuration; use cleora::configuration::Configuration; use cleora::configuration::OutputFormat; use cleora::persistence::entity::InMemoryEntityMappingPersistor; use cleora::pipeline::{build_graphs, ...
use std::time::Instant; use clap::{crate_authors, crate_description, crate_name, crate_version, App, Arg}; use cleora::configuration; use cleora::configuration::Configuration; use cleora::configuration::OutputFormat; use cleora::persistence::entity::InMemoryEntityMappingPersistor; use cleora::pipeline::{build_graphs, ...
elapsed().as_secs() ); train(config, in_memory_entity_mapping_persistor, sparse_matrices); info!("Finished in {} sec", now.elapsed().as_secs()); }
function_block-function_prefixed
[ { "content": "/// Read file line by line. Pass every valid line to handler for parsing.\n\nfn read_file<F>(config: &Configuration, mut line_handler: F)\n\nwhere\n\n F: FnMut(&str),\n\n{\n\n let input_file = File::open(&config.input).expect(\"Can't open file\");\n\n let mut buffered = BufReader::new(inp...
Rust
src/builder.rs
dndx/tokio-tun
f44a6561067bf7db04ef0b084ed2cc83f8aa1cd0
use super::result::Result; #[cfg(target_os = "linux")] use crate::linux::params::Params; #[cfg(target_os = "linux")] use crate::tun::Tun; use core::convert::From; use libc::{IFF_NO_PI, IFF_TAP, IFF_TUN}; use std::net::Ipv4Addr; pub struct TunBuilder<'a> { name: &'a str, is_tap: bool, packet_info: bool, ...
use super::result::Result; #[cfg(target_os = "linux")] use crate::linux::params::Params; #[cfg(target_os = "linux")] use crate::tun::Tun; use co
Option<i32>, owner: Option<i32>, group: Option<i32>, address: Option<Ipv4Addr>, destination: Option<Ipv4Addr>, broadcast: Option<Ipv4Addr>, netmask: Option<Ipv4Addr>, } impl<'a> Default for TunBuilder<'a> { fn default() -> Self { Self { name: "", owner: None...
re::convert::From; use libc::{IFF_NO_PI, IFF_TAP, IFF_TUN}; use std::net::Ipv4Addr; pub struct TunBuilder<'a> { name: &'a str, is_tap: bool, packet_info: bool, persist: bool, up: bool, mtu:
random
[ { "content": "use std::net::Ipv4Addr;\n\n\n\n/// Represents parameters for creating a new Tun/Tap device on Linux.\n\n#[cfg(target_os = \"linux\")]\n\npub struct Params {\n\n pub name: Option<String>,\n\n pub flags: i16,\n\n pub persist: bool,\n\n pub up: bool,\n\n pub mtu: Option<i32>,\n\n pu...
Rust
colour_math/src/hcv.rs
pwil3058/rs_colour_math_obsolete
ac3fcab63c44975e8de901aa93da7f5c5cffde7e
use std::marker::PhantomData; use crate::chroma::HueData; use crate::urgb::UnsignedComponent; use crate::{ chroma, image, ColourComponent, ColourInterface, HueConstants, HueIfce, IndicesValueOrder, RGBConstants, CCI, RGB, URGB, }; use normalised_angles::Degrees; use std::cmp::Ordering; #[derive(Debug, Clone,...
use std::marker::PhantomData; use crate::chroma::HueData; use crate::urgb::UnsignedComponent; use crate::{ chroma, image, ColourComponent, ColourInterface, HueConstants, HueIfce, IndicesValueOrder, RGBConstants, CCI, RGB, URGB, }; use normalised_angles::Degrees; use std::cmp::Ordering; #[derive(Debug, Clone,...
} } impl<F: ColourComponent> Ord for HCV<F> { fn cmp(&self, other: &Self) -> Ordering { self.partial_cmp(other).unwrap() } } pub trait ChromaTolerance { const COMA_TOLERANCE: Self; } impl ChromaTolerance for f32 { const COMA_TOLERANCE: Self = 0.000_001; } impl ChromaTolerance for f64 { ...
if other.hue_data.is_some() { Some(Ordering::Less) } else { self.sum.partial_cmp(&other.sum) }
if_condition
[ { "content": "pub fn calc_other_from_xy<F: ColourComponent>(xy: (F, F)) -> F {\n\n if xy.0.abs() * F::SQRT_3 > xy.1.abs() {\n\n let divisor = xy.0.abs() * F::SQRT_3 + xy.1.abs();\n\n debug_assert!(divisor != F::ZERO);\n\n let x = xy.0 * F::SQRT_3 / divisor;\n\n if xy.0 >= F::ZERO ...
Rust
src/req_types/mod.rs
nickdonnelly/req
1161ba541f48f5fc5e00ed15831457f6e910068d
use hyper::{ self, Method, StatusCode }; use hyper_tls::HttpsConnector; use super::encode::Encoding; use super::options::*; use std::result; use std::str::FromStr; mod display; pub mod req; pub use self::req::*; type Result<T> = result::Result<T, ReqError>; #[derive(PartialEq, Debug, Clone)] pub enum ReqContentTyp...
use hyper::{ self, Method, StatusCode }; use hyper_tls::HttpsConnector; use super::encode::Encoding; use super::options::*; use std::result; use std::str::FromStr; mod display; pub mod req; pub use self::req::*; type Result<T> = result::Result<T, ReqError>; #[derive(PartialEq, Debug, Clone)] pub enum ReqContentTyp...
#[test] fn test_head_request_terminates() { let pl = Payload::new(vec![1,2,3], "application/octet-stream"); let config = ReqConfig::new() .command(ReqCommand::Request(RequestMethod::Get)) .host_str("https://google.com") .port(443) .timeout(10000)...
fn test_request_working() { let pl = Payload::new(vec![1,2,3], "application/octet-stream"); let config = ReqConfig::new() .command(ReqCommand::Request(RequestMethod::Get)) .host_str("https://google.com") .port(443) .timeout(10000) .payload(pl);...
function_block-full_function
[ { "content": "/// Return a body that is the pretty version of the given request.\n\npub fn pretty_print(headers: HeaderMap, req_meth: Method, req_path: String) -> String \n\n{\n\n let mut headerstring = String::new();\n\n let methstr = format!(\"{} {}\\n\", req_meth, req_path);\n\n\n\n headerstring.pus...
Rust
src/os/linux/ps/stat.rs
wojciechkepka/rsys
e45e0c815d3c95b16aafa7abb70f13c23879da65
use crate::linux::ps::{stat_process, ProcessState}; use crate::linux::SysPath; use crate::{ util::{next, skip}, Result, }; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use std::str::SplitAsciiWhitespace; #[derive(Debug, Eq, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize, ...
use crate::linux::ps::{stat_process, ProcessState}; use crate::linux::SysPath; use crate::{ util::{next, skip},
b processor: u32, } impl ProcessStat { pub fn update(&mut self) -> Result<()> { let p = stat_process(self.pid)?; self.pid = p.pid; self.name = p.name; self.state = p.state; self.ppid = p.ppid; self.pgrp = p.pgrp; self.session = p.session; self.tt...
Result, }; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use std::str::SplitAsciiWhitespace; #[derive(Debug, Eq, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub struct ProcessStat { pub pid: i32, pub name: String, pub state: ProcessState, pub p...
random
[ { "content": "pub fn skip<I, T>(n: usize, iter: &mut I) -> &mut I\n\nwhere\n\n I: Iterator<Item = T>,\n\n{\n\n for _ in 0..n {\n\n iter.next();\n\n }\n\n iter\n\n}\n", "file_path": "src/util.rs", "rank": 0, "score": 41515.050971902136 }, { "content": "use crate::macos::Mac...
Rust
swim_server/src/plane/router/tests/mod.rs
swimos/swim-rust
f1a2be7bb4eb8f38e6ecc19bba4a8c876016183c
use crate::plane::router::{PlaneRouter, PlaneRouterFactory}; use crate::routing::{PlaneRoutingRequest, TopLevelServerRouter, TopLevelServerRouterFactory}; use futures::future::join; use swim_runtime::error::{ ConnectionError, ProtocolError, ResolutionErrorKind, RouterError, Unresolvable, }; use swim_runtime::remo...
use crate::plane::router::{PlaneRouter, PlaneRouterFactory}; use crate::routing::{PlaneRoutingRequest, TopLevelServerRouter, TopLevelServerRouterFactory}; use futures::future::join; use swim_runtime::error::{ ConnectionError, ProtocolError, ResolutionErrorKind, RouterError, Unresolvable, }; use swim_runtime::remo...
t3, Err(RouterError::NoAgentAtRoute(name)) if name == "/node")); }; join(provider_task, send_task).await; }
.send_ok(RawRoute::new(send_tx.clone(), drop_rx.clone())) .is_ok()); } else { assert!(request.send_err(Unresolvable(id)).is_ok()); } } else { panic!("Unexpected request {:?}!", req); } ...
random
[ { "content": "type ResolutionRequest = Request<Result<RoutingAddr, RouterError>>;\n\n\n\n/// Requests that can be serviced by the plane event loop.\n\n#[derive(Debug)]\n\npub enum PlaneRoutingRequest {\n\n /// Get a handle to an agent (starting it where necessary).\n\n Agent {\n\n name: RelativeUri...
Rust
src/main.rs
grigala/gitout
106ccc74a96f48f4449759bd5a13b0ec94ebc67c
use std::collections::HashSet; use std::io::Write; use std::path::PathBuf; use std::{fs, io}; use git2::{Cred, FetchOptions, RemoteCallbacks, Repository}; use reqwest::blocking::Client; mod args; mod config; mod github; fn main() { let args = args::parse_args(); if args.verbose { dbg!(&args); } let args::Args ...
use std::collections::HashSet; use std::io::Write; use std::path::PathBuf; use std::{fs, io}; use git2::{Cred, FetchOptions, RemoteCallbacks, Repository}; use reqwest::blocking::Client; mod args; mod config; mod github; fn main() { let args = args::parse_args(); if args.verbose { dbg!(&args); } let args::Args ...
} if updated { println!("Done") } }
if !dry_run { let mut repo_dir = dir.clone(); repo_dir.push(repository); let repo_exists = fs::metadata(&repo_dir).map_or_else(|_| false, |m| m.is_dir()); let repository: Repository; let mut origin = if repo_exists { repository = Repository::open_bare(&repo_dir).unwrap(); repository.find_remote...
if_condition
[ { "content": "pub fn archive_repo(client: &Client, dir: &PathBuf, repository: &str, token: &str) {\n\n\tlet migration_request = MigrationRequest {\n\n\t\trepositories: vec![repository.to_owned()],\n\n\t};\n\n\tlet create_response: MigrationResponse = client\n\n\t\t.post(\"https://api.github.com/user/migrations\...
Rust
src/lib.rs
xmr-rs/portable-storage
bd219bf2ecba9e0c433caffa7af34c6ee664333f
use bytes::{Buf, BufMut, BytesMut}; use linked_hash_map::LinkedHashMap; use std::{convert::TryFrom, ops::Index}; use thiserror::Error; pub mod de; pub mod ser; pub use de::from_section; pub use ser::to_section; #[macro_export] macro_rules! ensure_eof { ($buf:expr, $needed:expr) => { if $buf.remaining()...
use bytes::{Buf, BufMut, BytesMut}; use linked_hash_map::LinkedHashMap; use std::{convert::TryFrom, ops::Index}; use thiserror::Error; pub mod de; pub mod ser; pub use de::from_section; pub use ser::to_section; #[macro_export] macro_rules! ensure_eof { ($buf:expr, $needed:expr) => { if $buf.remaining()...
pub fn len(&self) -> usize { self.array.len() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn push(&mut self, entry: StorageEntry) -> std::result::Result<(), Error> { if let Some(serialize_type) = self.serialize_type { let entry_type = entry.serial...
pub fn with_capacity(capacity: usize) -> Array { Array { array: Vec::with_capacity(capacity), serialize_type: None, } }
function_block-full_function
[ { "content": "/// Reads a \"raw size\" value from `buf`.\n\n///\n\n/// # Errors\n\n///\n\n/// This function may return an `Error::UnexpectedEof` error if `buf` doesn't\n\n/// hold the needed bytes that the raw size marker specifies.\n\npub fn read<B: Buf>(buf: &mut B) -> Result<u64, Error> {\n\n ensure_eof!(...
Rust
2021/src/day15.rs
helmutschneider/aoc
261bb903df29f8fdca4265afba8d7fc87f3df77a
use std::collections::BinaryHeap; use std::collections::HashSet; use std::hash::Hash; use std::hash::Hasher; pub fn run() { let input = std::fs::read_to_string("src/day15_input.txt").unwrap(); let first = parse::<100>(&input); println!("Day 15A: {}", get_risk_of_safest_path(first)); let second =...
use std::collections::BinaryHeap; use std::collections::HashSet; use std::hash::Hash; use std::hash::Hasher; pub fn run() { let input = std::fs::read_to_string("src/day15_input.txt").unwrap(); let first = parse::<100>(&input); println!("Day 15A: {}", get_risk_of_safest_path(first)); let second =...
fn grow<const N: usize, const R: usize>(grid: &Grid<N>) -> Grid<R> { const RISK_VALUES: [i16; 9] = [9, 1, 2, 3, 4, 5, 6, 7, 8]; assert_eq!(0, R % N); let repeat_times = R / N; let mut second = Grid { data: [[Node::EMPTY; R]; R], }; for y in 0..N { for x in 0..N { ...
fn get_risk_of_safest_path<const N: usize>(grid: Grid<N>) -> i16 { let mut data = grid.data; let mut visited = HashSet::<Node>::new(); let mut keyed_stack = HashSet::<Node>::new(); let mut sorted_stack = BinaryHeap::<Node>::new(); data[0][0].least_risky_path = 0; sorted_stack.push(data[0][0]);...
function_block-full_function
[ { "content": "fn parse_lights<const N: usize>(input: &str) -> Lights<N> {\n\n let mut lights = [[LightState::Off; N]; N];\n\n let mut i = 0;\n\n\n\n for line in input.lines() {\n\n let mut k = 0;\n\n\n\n for ch in line.chars() {\n\n lights[i][k] = if ch == '#' {\n\n ...
Rust
src/serde_introspection.rs
vityafx/serde_aux
86c2d7a2b1cf4fe201589778d7dbfaef8f15b602
use serde::de::{self, Deserialize, Deserializer, Visitor}; pub fn serde_introspect<'de, T>() -> &'static [&'static str] where T: Deserialize<'de>, { struct StructFieldsDeserializer<'a> { fields: &'a mut Option<&'static [&'static str]>, } impl<'de, 'a> Deserializer<'de> for StructFieldsDeserial...
use serde::de::{self, Deserialize, Deserializer, Visitor}; pub fn serde_introspect<'de, T>() -> &'static [&'static str] where T: Deserialize<'de>, { struct StructFieldsDeserializer<'a> { fields: &'a mut Option<&'static [&'static str]>, } impl<'de, 'a> Deserializer<'de> for StructFieldsDeserial...
ename = "b")] EnumB, } let names = serde_introspect::<SomeEnum>(); assert_eq!(names[0], "a"); assert_eq!(names[1], "b"); } }
struct map enum identifier ignored_any } } struct EnumVariantsDeserializer<'a> { variants: &'a mut Option<&'static [&'static str]>, } impl<'de, 'a> Deserializer<'de> for EnumVariantsDeserializer<'a> { type Error = serde::de::value::Error; fn deserialize_any<V>(self, _v...
random
[ { "content": "/// Deserializes boolean from anything (string, number, boolean). If input is a string,\n\n/// it is expected, that it is possible to convert it to a number. The return boolean is\n\n/// `true` if the number was either `1` or `1.0` after parsing.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust\n\n//...
Rust
src/lib.rs
sy1ntexx/serde-enum
f567728b2d3ed4f19e6e587fd39b856a4fcda033
use quote::quote; use syn::*; use lazy_static::lazy_static; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use std::collections::HashMap; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum NamingStyle { SnakeCase, CamelCase, ScreamingSnakeCase, None, } lazy_static! { ...
use quote::quote; use syn::*; use lazy_static::lazy_static; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use std::collections::HashMap; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum NamingStyle { SnakeCase, CamelCase, ScreamingSnakeCase, None, } lazy_static! { ...
fn to_snake_case(v: &str) -> String { let mut out = String::with_capacity(v.len()); if v.is_empty() { out.push(v.chars().next().unwrap().to_ascii_lowercase()); } for c in v.chars().skip(1) { if c.is_uppercase() { out.push('_'); out.push(c.to_ascii_lowercase());...
fn format_variant(v: &Variant, parent_style: NamingStyle) -> String { if let Some(s) = get_variant_alias(v) { return s; } let own_style = get_naming_style(v.attrs.iter()); match own_style { NamingStyle::None => match parent_style { NamingStyle::None => v.ident.to_string(), ...
function_block-full_function
[]
Rust
src/html.rs
jgm/pulldown-cmark
eb4896a60a07bdc14b2a224dbf7c23b9c3a45d5d
use std::collections::HashMap; use std::io::{self, Write}; use crate::parse::{LinkType, Event, Tag, Alignment}; use crate::parse::Event::*; use crate::strings::CowStr; use crate::escape::{escape_html, escape_href}; enum TableState { Head, Body, } struct HtmlWriter<'a, I, W> where W: Write, { i...
use std::collections::HashMap; use std::io::{self, Write}; use crate::parse::{LinkType, Event, Tag, Alignment}; use crate::parse::Event::*; use crate::strings::CowStr; use crate::escape::{escape_html, escape_href}; enum TableState { Head, Body, } struct HtmlWriter<'a, I, W> where W: Write, { i...
fn raw_text(&mut self) -> io::Result<()> { let mut nest = 0; while let Some(event) = self.iter.next() { match event { Start(_) => nest += 1, End(_) => { if nest == 0 { break; } ...
k(_) => { self.write(b"</code></pre>", true)?; } Tag::List(Some(_)) => { self.write(b"</ol>", true)?; } Tag::List(None) => { self.write(b"</ul>", true)?; } Tag::Item => { self.write(b"...
function_block-function_prefixed
[ { "content": "pub fn is_html_tag(tag: &str) -> bool {\n\n HTML_TAGS.binary_search_by(|probe| utils::strcasecmp(probe, tag)).is_ok()\n\n}\n\n\n", "file_path": "src/scanners.rs", "rank": 1, "score": 185541.5342097144 }, { "content": "pub fn is_ascii_alphanumeric(c: u8) -> bool {\n\n matc...
Rust
src/ahb_secure_ctrl/sec_ctrl_apb_bridge0_mem_ctrl2.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[doc = "Reader of register SEC_CTRL_APB_BRIDGE0_MEM_CTRL2"] pub type R = crate::R<u32, super::SEC_CTRL_APB_BRIDGE0_MEM_CTRL2>; #[doc = "Writer for register SEC_CTRL_APB_BRIDGE0_MEM_CTRL2"] pub type W = crate::W<u32, super::SEC_CTRL_APB_BRIDGE0_MEM_CTRL2>; #[doc = "Register SEC_CTRL_APB_BRIDGE0_MEM_CTRL2 `reset()`'s wi...
#[doc = "Reader of register SEC_CTRL_APB_BRIDGE0_MEM_CTRL2"] pub type R = crate::R<u32, super::SEC_CTRL_APB_BRIDGE0_MEM_CTRL2>; #[doc = "Writer for register SEC_CTRL_APB_BRIDGE0_MEM_CTRL2"] pub type W = crate::W<u32, super::SEC_CTRL_APB_BRIDGE0_MEM_CTRL2>; #[doc = "Register SEC_CTRL_APB_BRIDGE0_MEM_CTRL2 `reset()`'s wi...
#[doc = "Checks if the value of the field is `ENUM_NS_NP`"] #[inline(always)] pub fn is_enum_ns_np(&self) -> bool { *self == ANACTRL_RULE_A::ENUM_NS_NP } #[doc = "Checks if the value of the field is `ENUM_NS_P`"] #[inline(always)] pub fn is_enum_ns_p(&self) -> bool { *self =...
pub fn variant(&self) -> ANACTRL_RULE_A { match self.bits { 0 => ANACTRL_RULE_A::ENUM_NS_NP, 1 => ANACTRL_RULE_A::ENUM_NS_P, 2 => ANACTRL_RULE_A::ENUM_S_NP, 3 => ANACTRL_RULE_A::ENUM_S_P, _ => unreachable!(), } }
function_block-full_function
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
src/bus/mod.rs
goooosick/joy
09297bfd3debee39d649896e86d75bf663686e62
use crate::{Apu, Cartridge, Ppu}; use crate::{InterruptHandler, Timer}; use crate::{Joypad, JoypadState}; use dma::Dma; use hdma::Hdma; mod dma; mod hdma; #[derive(Copy, Clone, Eq, PartialEq)] #[repr(u8)] enum SpeedMode { Normal = 0b00, Double = 0b01, } pub struct Bus { work_ram0: Box<[u8; 0x1000]...
use crate::{Apu, Cartridge, Ppu}; use crate::{InterruptHandler, Timer}; use crate::{Joypad, JoypadState}; use dma::Dma; use hdma::Hdma; mod dma; mod hdma; #[derive(Copy, Clone, Eq, PartialEq)] #[repr(u8)] enum SpeedMode { Normal = 0b00, Double = 0b01, } pub struct Bus { work_ram0: Box<[u8; 0x1000]...
pub fn set_input(&mut self, states: JoypadState) { self.joypad.set_input(states); self.joypad.update(&mut self.interrupt_handler); } fn do_dma(&mut self) { if let Some((src, dst)) = self.dma.update() { let data = self.read_direct(src); self.ppu.dma_write...
ite(addr, data), 0xff04..=0xff07 => self.timer.write(addr, data), 0xff0f => self.interrupt_handler.write(addr, data), 0xff10..=0xff3f => self.apu.write(addr, data), 0xff46 => self.dma.write(addr, data), 0xff40..=0xff4b => self.ppu.write(addr, data), ...
function_block-function_prefixed
[ { "content": "fn freq_high(freq: u32, data: u8) -> u32 {\n\n (freq & 0x00ff) | (((data & 0b0111) as u32) << 8)\n\n}\n\n\n", "file_path": "src/apu/mod.rs", "rank": 0, "score": 201715.85461555482 }, { "content": "fn freq_low(freq: u32, data: u8) -> u32 {\n\n (freq & 0xff00) | data as u32...
Rust
src/developer/ffx/config/src/persistent_config.rs
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
use { crate::priority_config::Priority, crate::{ConfigLevel, ConfigQuery}, anyhow::{bail, Result}, serde_json::Value, std::{ fmt, io::{Read, Write}, }, }; pub(crate) struct Persistent { data: Priority, } impl Persistent { fn open<R: Read>(file: Option<R>) -> Result<Op...
use { crate::priority_config::Priority, crate::{ConfigLevel, ConfigQuery}, anyhow::{bail, Result}, serde_json::Value, std::{ fmt, io::{Read, Write}, }, }; pub(crate) struct Persistent { data: Priority, } impl Persistent { fn open<R: Read>(file: Option<R>) -> Result<Op...
pub(crate) fn save<W: Write>( &self, global: Option<W>, build: Option<W>, user: Option<W>, ) -> Result<()> { Persistent::save_config(user, &self.data.user)?; Persistent::save_config(build, &self.data.build)?; Persistent::save_config(global, &self.data.gl...
data: Priority::new( Persistent::open(user)?, Persistent::open(build)?, Persistent::open(global)?, runtime, ), }) }
function_block-function_prefix_line
[]
Rust
kin_core/src/libsodium/masterkey.rs
pcrockett/kin-backup
9f605de311df924f3fc8eaed98a8f360c4bb6931
use super::passphrase::{PassphraseDerivedKey, PassphraseSalt}; use failure::{bail, format_err}; use libsodium_sys; pub struct MasterKey { data: Vec<u8>, } pub struct EncryptedMasterKey { encrypted_data: Vec<u8>, salt: PassphraseSalt, nonce: Vec<u8>, } pub const MASTER_KEY_SIZE: usize = libsodium_...
use super::passphrase::{PassphraseDerivedKey, PassphraseSalt}; use failure::{bail, format_err}; use libsodium_sys; pub struct MasterKey { data: Vec<u8>, } pub struct EncryptedMasterKey { encrypted_data: Vec<u8>, salt: PassphraseSalt, nonce: Vec<u8>, } pub const MASTER_KEY_SIZE: usize = libsodium_...
ptr(), key.as_ptr(), ); } if result != 0 { bail!("Unable to decrypt."); } Ok(MasterKey { data: plain_text.to_vec(), }) } }
result = libsodium_sys::crypto_secretbox_open_easy( plain_text.as_mut_ptr(), self.encrypted_data.as_ptr(), self.encrypted_data.len() as u64, self.nonce.as_
function_block-random_span
[ { "content": "pub fn randombytes_into(buf: &mut [u8]) {\n\n unsafe {\n\n libsodium_sys::randombytes_buf(buf.as_mut_ptr() as *mut _, buf.len());\n\n }\n\n}\n", "file_path": "kin_core/src/libsodium/mod.rs", "rank": 0, "score": 150261.91683809322 }, { "content": "fn read_chunk(buff...
Rust
src/lib.rs
ps-dev/activity-insights-cli
5b21d2e58d8d296fd1a9d5b036f52adfad5089a2
use log::{info, warn}; use reqwest::{ blocking::{self, Client}, StatusCode, }; use serde::{Deserialize, Serialize}; use std::{ collections::HashSet, convert::TryFrom, fs, io::{self, BufWriter, Write}, path::{Path, PathBuf}, process::{Child, Command}, }; use tempfile::NamedTempFile; use t...
use log::{info, warn}; use reqwest::{ blocking::{self, Client}, StatusCode, }; use serde::{Deserialize, Serialize}; use std::{ collections::HashSet, convert::TryFrom, fs, io::{self, BufWriter, Write}, path::{Path, PathBuf}, process::{Child, Command}, }; use tempfile::NamedTempFile; use t...
#[cfg(test)] pub fn send_pulses(pulses: &[Pulse]) -> Result<StatusCode, ActivityInsightsError> { log::info!( "{:?}, {} {:?}", Client::new(), constants::PULSE_API_URL, PulseRequest::new(pulses) ); Ok(StatusCode::default()) } #[cfg(target_os = "macos")] pub fn open_brow...
pub fn send_pulses(pulses: &[Pulse]) -> Result<StatusCode, ActivityInsightsError> { if pulses.is_empty() { return Ok(StatusCode::from_u16(204).unwrap()); }; let client = Client::new(); let creds = Credentials::fetch()?; match creds.api_token() { Some(token) => { let res ...
function_block-full_function
[ { "content": "#[cfg(unix)] // Can't change the HOME dir on Windows so only run on unix\n\n#[test]\n\nfn credentials_flow() {\n\n let fake_home_dir = tempfile::tempdir().unwrap();\n\n env::set_var(\"HOME\", fake_home_dir.path());\n\n\n\n // Get denied by TOS\n\n let mut cmd = Command::cargo_bin(\"act...
Rust
common/src/lib.rs
fluffypony/tari
a933dc10f6adc2701581bb90e678781506246dfe
use clap::ArgMatches; use std::path::{Path, PathBuf}; mod configuration; #[macro_use] mod logging; pub mod protobuf_build; pub mod dir_utils; pub use configuration::{ default_config, install_default_config_file, load_configuration, CommsTransport, ConfigExtractor, ConfigurationError, Da...
use clap::ArgMatches; use std::path::{Path, PathBuf}; mod configuration; #[macro_use] mod logging; pub mod protobuf_build; pub mod dir_utils; pub use configuration::{ default_config, install_default_config_file, load_configuration, CommsTransport, ConfigExtractor, ConfigurationError, Da...
_exists = std::path::Path::new(&bootstrap.config).exists(); let log_config_exists = std::path::Path::new(&bootstrap.log_config).exists(); let cfg = load_configuration(&bootstrap); if std::path::Path::new(&dir_utils::default_subdir("", Some(dir))).exists() { std::fs...
ore your files") (@arg config: -c --config +takes_value "A path to the configuration file to use (config.toml)") (@arg log_config: -l --log_config +takes_value "A path to the logfile configuration (log4rs.yml))") (@arg init: --init "Create a default configuration file if it doesn't e...
random
[ { "content": "/// Installs a new default logfile configuration, copied from `log4rs-sample.yml` to the given path.\n\npub fn install_default_logfile_config(path: &Path) -> Result<(), std::io::Error> {\n\n let source = include_str!(\"../logging/log4rs-sample.yml\");\n\n fs::write(path, source)\n\n}\n\n\n\n...
Rust
src/parser.rs
naoto0822/toy-rsql-parser
655cb624a740725005637a02020e0fca419a3430
use crate::ast::{Column, InfixOp, PrefixOp, Statement, TableExpression, ValueExpression}; use crate::lexer::Lexer; use crate::token::{Token, TokenType}; use std::collections::HashMap; static LOWEAT: i64 = 1; static OR: i64 = 2; static AND: i64 = 3; static EQUALS: i64 = 4; static LESSGREATER: i64 = 5; static SUM: i...
use crate::ast::{Column, InfixOp, PrefixOp, Statement, TableExpression, ValueExpression}; use crate::lexer::Lexer; use crate::token::{Token, TokenType}; use std::collections::HashMap; static LOWEAT: i64 = 1; static OR: i64 = 2; static AND: i64 = 3; static EQUALS: i64 = 4; static LESSGREATER: i64 = 5; static SUM: i...
fn parse_identifier(&mut self) -> ValueExpression { match &self.current_token.value { TokenType::Ident(ident) => ValueExpression::Identifier(ident.to_string()), _ => panic!("not expected type!"), } } fn parse_number(&mut self) -> ValueExpression { match sel...
Expression { let op = self.lookup_infix(self.current_token.value.clone()); let precedence = self.lookup_precedence(self.current_token.value.clone()); self.next_token(); let right = self.parse_value_expression(precedence); ValueExpression::Infix { op, lef...
function_block-function_prefixed
[ { "content": "impl Token {\n\n pub fn start_token() -> Self {\n\n Self::new(TokenType::Start)\n\n }\n\n\n\n pub fn lookup_ident(ident: String) -> TokenType {\n\n let mut keywords = HashMap::new();\n\n keywords.insert(\"SELECT\", TokenType::Select);\n\n keywords.insert(\"FROM...
Rust
aquatic_ws_protocol/src/common.rs
greatest-ape/aquatic
614dea755b5703018ccf42c1c28c7cc5de22305e
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct PeerId( #[serde( deserialize_with = "deserialize_20_bytes", serialize_with = "serialize_20_bytes" )] pub [u...
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct PeerId( #[serde( deserialize_with = "deserialize_20_bytes", serialize_with = "serialize_20_bytes" )] pub [u...
} Ok(arr) } } #[inline] fn deserialize_20_bytes<'de, D>(deserializer: D) -> Result<[u8; 20], D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(TwentyByteVisitor) } #[cfg(test)] mod tests { use quickcheck_macros::quickcheck; use crate::common::InfoHash; fn...
if let Some(c) = char_iter.next() { if c as u32 > 255 { return Err(E::custom(format!( "character not in single byte range: {:#?}", c ))); } *a = c as u8; } else { ...
if_condition
[ { "content": "pub fn urldecode_20_bytes(value: &str) -> anyhow::Result<[u8; 20]> {\n\n let mut out_arr = [0u8; 20];\n\n\n\n let mut chars = value.chars();\n\n\n\n for i in 0..20 {\n\n let c = chars.next().with_context(|| \"less than 20 chars\")?;\n\n\n\n if c as u32 > 255 {\n\n ...
Rust
src/imp/linux_raw/arch/outline/x86.rs
sunfishcode/rustix-testing
241e16870959d79ced8c8b715c3d264dd837e7dc
#![allow(dead_code, unused_imports)] use crate::imp::reg::{ArgReg, RetReg, SyscallNumber, A0, A1, A2, A3, A4, A5, R0}; use crate::imp::vdso_wrappers::SyscallType; extern "fastcall" { fn rustix_syscall0_nr_last_fastcall(nr: SyscallNumber<'_>) -> RetReg<R0>; fn rustix_syscall1_nr_last_fastcall(a0: ArgReg<'_, ...
#![allow(dead_code, unused_imports)] use crate::imp::reg::{ArgReg, RetReg, SyscallNumber, A0, A1, A2, A3, A4, A5, R0}; use crate::imp::vdso_wrappers::SyscallType; extern "fastcall" { fn rustix_syscall0_nr_last_fastcall(nr: SyscallNumber<'_>) -> RetReg<R0>; fn rustix_syscall1_nr_last_fastcall(a0: ArgReg<'_, ...
e: SyscallType, nr: SyscallNumber<'_>, a0: ArgReg<'_, A0>, a1: ArgReg<'_, A1>, a2: ArgReg<'_, A2>, a3: ArgReg<'_, A3>, a4: ArgReg<'_, A4>, ) -> RetReg<R0> { rustix_indirect_syscall5_nr_last_fastcall(a1, a2, a0, a3, a4, nr, callee) } #[inline] pub(in crate::imp) unsafe fn indirect_syscall6( ...
, A1>, a2: ArgReg<'_, A2>, a0: ArgReg<'_, A0>, a3: ArgReg<'_, A3>, a4: ArgReg<'_, A4>, a5: ArgReg<'_, A5>, nr: SyscallNumber<'_>, callee: SyscallType, ) -> RetReg<R0>; } #[inline] pub(in crate::imp) unsafe fn indirect_syscall0( callee: SyscallType, nr...
random
[ { "content": "type ClockGettimeType = unsafe extern \"C\" fn(c::c_int, *mut Timespec) -> c::c_int;\n\n\n\n/// The underlying syscall functions are only called from asm, using the\n\n/// special syscall calling convention to pass arguments and return values,\n\n/// which the signature here doesn't reflect.\n\n#[...
Rust
src/data/pubs/spell/spell_record.rs
sorokya/eo
8805ccb6e1265a4dc7dbe88f97b12046e1df5c6e
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use num_traits::FromPrimitive; use crate::data::{ pubs::spell::{SpellTargetRestrict, SpellTargetType, SpellType, ESF_DATA_SIZE}, EOByte, EOChar, EOInt, EOShort, EOThree, Serializeable, StreamBuilder, StreamReader, }; #[derive(Debug, Clone, Defaul...
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use num_traits::FromPrimitive; use crate::data::{ pubs::spell::{SpellTargetRestrict, SpellTargetType, SpellType, ESF_DATA_SIZE}, EOByte, EOChar, EOInt, EOShort, EOThree, Serializeable, StreamBuilder, StreamReader, }; #[derive(Debug, Clone, Defaul...
fn serialize(&self) -> Vec<EOByte> { let mut builder = StreamBuilder::with_capacity(ESF_DATA_SIZE + self.name.len() + self.shout.len() + 2); builder.add_char(self.name.len() as EOChar); builder.add_char(self.shout.len() as EOChar); builder.add_string(&self.name); ...
fn deserialize(&mut self, reader: &StreamReader) { let name_length = reader.get_char(); let shout_length = reader.get_char(); self.name = reader.get_fixed_string(name_length as usize); self.shout = reader.get_fixed_string(shout_length as usize); self.icon_id = reader.get_short();...
function_block-full_function
[ { "content": "/// flattens a packet [Family] and [Action] into a single [EOInt]\n\n///\n\n/// This is useful for identifying pairs of packet [Family]s, and [Action]s.\n\n/// It is assumed there are a max of 255 actions per packet family.\n\n///\n\n/// # Example\n\n/// ```\n\n/// use eo::net::{Family, Action, pa...
Rust
src/core/x.rs
fasync/Void
3c0c1d21c5bb2c5ebe012e5137444152e8937549
/* * Copyright (c) 2020, Florian Büstgens * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list ...
/* * Copyright (c) 2020, Florian Büstgens * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list ...
new(32, win.get(), self.atoms.WM_PROTOCOLS, data); xcb::send_event( &self.conn, false, win.get(), xcb::EVENT_MASK_NO_EVENT, &event, ); } else { xcb::destroy_window(&self.conn, win.get()); ...
oms { $( pub $name: xcb::Atom ),* } impl Atoms { pub fn new(conn: &xcb::Connection) -> Result<Atoms> { Ok(Atoms { $( $name: Connection::get_atom(conn, stringify!($name))? ...
random
[]
Rust
src/lib.rs
cfallin/rust-immutable-arena
8b55f8c14e81abff4e41500a1145e79db91f3dfc
extern crate typed_arena; use std::fmt; use std::mem; use std::marker::PhantomData; use std::ops::Deref; use std::sync::atomic::{AtomicPtr, Ordering}; pub struct Arena<T> { arena: typed_arena::Arena<T>, } impl<T> Arena<T> { pub fn new() -> Arena<T> { Arena { arena: typed_arena::Arena::new() } ...
extern crate typed_arena; use std::fmt; use std::mem; use std::marker::PhantomData; use std::ops::Deref; use std::sync::atomic::{AtomicPtr, Ordering}; pub struct Arena<T> { arena: typed_arena::Arena<T>, } impl<T> Arena<T> { pub fn new() -> Arena<T> { Arena { arena: typed_arena::Arena::new() } ...
est() { let arena = Arena::new(); let x = arena.alloc(BasicTest { id: 0, a: Ref::empty(), b: Ref::empty(), }); let y = arena.alloc(BasicTest { id: 1, a: Ref::new(x), b: Ref::empty(), }); assert!(y.a....
} } } impl<'arena, T> fmt::Debug for Ref<'arena, T> where T: 'arena + fmt::Debug { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.deref().fmt(f) } } #[cfg(test)] mod test { use super::*; struct BasicTest<'arena> { id: u32, a: Ref<'arena, BasicTest<'arena...
random
[ { "content": "`immutable_arena`: an arena for immutable-once-built objects with cyclic refs\n\n=============================================================================\n\n\n\n[![Build Status](https://travis-ci.org/cfallin/rust-immutable-arena.svg?branch=master)](https://travis-ci.org/cfallin/rust-immutable...
Rust
src/lib.rs
2dav/qsh-rs
4c5f156794c0bc2faf3b01421f87473df1995161
use flate2::bufread::GzDecoder; use std::{ fs::File, io::{BufReader, Read}, path::PathBuf, }; pub mod orderbook; mod read; pub mod types; pub use read::{AuxInfoReader, DealReader, OrderLogReader, QshReader, QuotesReader}; use crate::types::Header; use anyhow as ah; use leb128::read as leb128; use std::io::...
use flate2::bufread::GzDecoder; use std::{ fs::File, io::{BufReader, Read}, path::PathBuf, }; pub mod orderbook; mod read; pub mod types; pub use read::{AuxInfoReader, DealReader, OrderLogReader, QshReader, QuotesReader}; use crate::types::Header; use anyhow as ah; use leb128::read as leb128; use std::io::...
} pub struct RecordIter<T>(T, QshParser); impl<T: QshReader> Iterator for RecordIter<T> { type Item = T::Item; fn next(&mut self) -> Option<Self::Item> { if self.1.eof() { None } else { Some(self.0.parse(&mut self.1).unwrap()) } } }
Ok(Header { version, recorder, comment, recording_time, stream: stream_type.into(), instrument, })
call_expression
[ { "content": "#[inline(always)]\n\npub fn system_record(rec: &OrderLog) -> bool {\n\n !non_system_record(rec)\n\n}\n\n\n", "file_path": "src/orderbook.rs", "rank": 2, "score": 106134.20393734031 }, { "content": "#[inline(always)]\n\npub fn non_system_record(rec: &OrderLog) -> bool {\n\n ...
Rust
src/virtualization/bin/guest-rs/src/socat.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { crate::services, anyhow::anyhow, anyhow::Context, anyhow::Error, fidl_fuchsia_virtualization::{ HostVsockAcceptorMarker, HostVsockEndpointMarker, HostVsockEndpointProxy, }, fuchsia_zircon::{self as zx, HandleBased}, fuchsia_zircon_status as zx_status, futures::TryStre...
use { crate::services, anyhow::anyhow, anyhow::Context, anyhow::Error, fidl_fuchsia_virtualization::{ HostVsockAcceptorMarker, HostVsockEndpointMarker, HostVsockEndpointProxy, }, fuchsia_zircon::{self as zx, HandleBased}, fuchsia_zircon_status as zx_status, futures::TryStre...
p_err().downcast(), Ok(zx_status::Status::CONNECTION_REFUSED) ); } #[fasync::run_until_stalled(test)] async fn socat_listen_mismatched_ports_returns_err() { let (proxy, mut stream) = create_proxy_and_stream::<HostVsockEndpointMarker>().unwrap(); let server = async move {...
.expect("Failed to send status code to client"); }; let client = handle_socat_listen(proxy, 0); let (_server_res, client_res) = join(server, client).await; assert_matches!( client_res.unwra
function_block-random_span
[]
Rust
core/src/charter.rs
GrandmasterTash/OpenRec
74b6a49a17b15d520c0ad3307539d3277c473503
use serde::Deserialize; use rust_decimal::Decimal; use std::{io::BufReader, path::Path}; use crate::{data_type::DataType, error::Error}; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct Charter { name: String, description: Option<String>, version: u64, debug: Option<bool>, mat...
use serde::Deserialize; use rust_decimal::Decimal; use std::{io::BufReader, path::Path}; use crate::{data_type::DataType, error::Error}; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct Charter { name: String, description: Option<String>, version: u64, debug: Option<bool>, mat...
pub fn jetwash(&self) -> &Option<Jetwash> { &self.jetwash } pub fn load(path: &Path) -> Result<Self, Error> { let rdr = BufReader::new(std::fs::File::open(&path) .map_err(|source| Error::CharterFileNotFound { path: path.to_string_lossy().into(), source })?); let chart...
pub fn instructions(&self) -> &[Instruction] { match &self.matching.instructions { Some(instructions) => instructions, None => &[], } }
function_block-full_function
[ { "content": "///\n\n/// Return all the columns referenced in the script specified.\n\n///\n\npub fn referenced_columns(script: &str, schema: &GridSchema) -> Vec<Column> {\n\n let mut columns = Vec::new();\n\n\n\n for cap in HEADER_REGEX.captures_iter(script) {\n\n if let Some(col) = schema.column(...
Rust
src/lib.rs
RReverser/pcisph-wasm
643f7c72103ed484700860decd8e4dac33ca7dfa
#![warn( unreachable_pub, trivial_casts, trivial_numeric_casts, unused_extern_crates, rust_2018_idioms )] use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{WebGl2RenderingContext, WebGlProgram, WebGlShader}; pub mod solver; const DAM_PARTICLES: usize = 75 * 75; const MAX_BLOCK...
#![warn( unreachable_pub, trivial_casts, trivial_numeric_casts, unused_extern_crates, rust_2018_idioms )] use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{WebGl2RenderingContext, WebGlProgram, WebGlShader}; pub mod solver; const DAM_PARTICLES: usize = 75 * 75; const MAX_BLOCK...
} }
Err(context .get_program_info_log(&program) .unwrap_or_else(|| String::from("Unknown error creating program object")))
call_expression
[ { "content": "#[derive(Debug)]\n\nstruct Neighbor {\n\n index: usize,\n\n r: f32,\n\n}\n\n\n\nimpl Neighbor {\n\n fn new(index: usize, r: f32) -> Self {\n\n Neighbor { index, r }\n\n }\n\n}\n\n\n\nimpl State {\n\n pub fn new() -> Self {\n\n let boundaries = [\n\n vec3(1.0...
Rust
telamon-gen/src/print/runtime/range.rs
adjivas/telamon
ae73bbe007d6d65885a92e14a5a821e35a542e5e
use proc_macro2::TokenStream; pub fn get() -> TokenStream { quote! { #[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[repr(C)] pub struct Range { pub min: u32, pub max: u32, } #[allow(dead_code)] impl Range { ...
use proc_macro2::TokenStream; pub fn get() -> TokenStream { quote! { #[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[repr(C)] pub struct Range { pu
ange) -> HalfRange { HalfRange { min: other.min / self.min } } fn apply_diff_mul(&mut self, diff: HalfRange) { self.min *= diff.min; } fn add_add(&mut self, diff: HalfRange) { self.min += diff.min; } fn add_mul(&...
b min: u32, pub max: u32, } #[allow(dead_code)] impl Range { pub const ALL: Range = Range { min: 0, max: std::u32::MAX }; pub const FAILED: Range = Range { min: 1, max: 0 }; pub fn all() -> Self { Self::ALL } ...
function_block-random_span
[ { "content": "/// Returns the token stream defining the runtime.\n\npub fn get() -> TokenStream {\n\n let range = range::get();\n\n let integer_set = integer_set::get();\n\n let integer_domain = integer_domain::get();\n\n quote! {\n", "file_path": "telamon-gen/src/print/runtime/mod.rs", "ran...
Rust
skulpin-renderer/src/coordinates.rs
Feuermagier/skulpin
3a2783ea4239456e1818179c263d76a107a2cfdd
use rafx::api::RafxExtents2D; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct PhysicalSize { pub width: u32, pub height: u32, } impl PhysicalSize { pub fn new( width: u32, height: u32, ) -> Self { PhysicalSize { width, height } } pub fn to_logical( se...
use rafx::api::RafxExtents2D; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct PhysicalSize { pub width: u32, pub height: u32, } impl PhysicalSize { pub fn new( width: u32, height: u32, ) -> Self { PhysicalSize { width, height } } pub fn to_logical( se...
ix(&m.into()); canvas.scale((x_scale, y_scale)); Ok(()) } None => Err(()), } } pub fn use_fixed_width( &self, canvas: &mut skia_safe::Canvas, center: skia_safe::Point, x_half_extents: f32, ) -> Result<...
window_physical_size(&self) -> PhysicalSize { self.window_physical_size } pub fn scale_factor(&self) -> f64 { self.scale_factor } pub fn use_physical_coordinates( &self, canvas: &mut skia_safe::Canvas, ) { canvas.reset_matrix(); }...
random
[ { "content": "// Will contain all the physics simulation state\n\nstruct Physics {\n\n // geometrical_world: DefaultGeometricalWorld<f32>,\n\n // mechanical_world: DefaultMechanicalWorld<f32>,\n\n //\n\n // bodies: DefaultBodySet<f32>,\n\n // colliders: DefaultColliderSet<f32>,\n\n // joint_co...
Rust
src/server.rs
omaskery/midi-orchestra-rs
ee7c0b848f52eafff46a6d91beef85c2335cd2e8
use connection::{Connection, ClientUIDFactory, ClientInfo}; use policies::{select_policy, ClientSelectionPolicy}; use midi::{MusicalEvent, Note, TimingChange}; use convert_duration::*; use packet::Packet; use midi; use std::time::{Duration, Instant}; use std::thread::{sleep, spawn}; use std::collections::HashSet; use ...
use connection::{Connection, ClientUIDFactory, ClientInfo}; use policies::{select_policy, ClientSelectionPolicy}; use midi::{MusicalEvent, Note, TimingChange}; use convert_duration::*; use packet::Packet; use midi; use std::time::{Duration, Instant}; use std::thread::{sleep, spawn}; use std::collections::HashSet; use ...
; let delay_period = Duration::from_secs(5); println!("waiting {} seconds for clients to connect...", duration_to_seconds(delay_period)); sleep(delay_period); println!("starting playback!"); let mut latest_note_end_time = Instant::now(); let start_time = Instant::now(); for event in events...
spawn(move || { println!("accepting client connections..."); let mut client_uid_factory = ClientUIDFactory::new(); for stream in listener.incoming() { match stream { Ok(s) => { let mut state = shared_state_original.lock() .e...
call_expression
[ { "content": "pub fn load_midi<P: AsRef<Path>>(path: P, verbose: bool) -> Music {\n\n let mut handler = Handler::new(verbose);\n\n\n\n {\n\n let mut midi_reader = Reader::new(\n\n &mut handler,\n\n path.as_ref(),\n\n ).unwrap();\n\n\n\n let _ = midi_reader.read()...
Rust
src/r3_port_riscv/src/mtime/imp.rs
r3-os/r3
46f460a031ad518fd4c3582ab9c87e31e9cc8806
use r3_core::kernel::{traits, Cfg, StaticInterruptHandler}; use r3_kernel::{KernelTraits, PortToKernel, System, UTicks}; use r3_portkit::tickless::{TicklessCfg, TicklessOptions, TicklessStateTrait}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::ReadWrite, }; use crate::mtime::cfg::MtimeO...
use r3_core::kernel::{traits, Cfg, StaticInterruptHandler}; use r3_kernel::{KernelTraits, PortToKernel, System, UTicks}; use r3_portkit::tickless::{TicklessCfg, TicklessOptions, TicklessStateTrait}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::ReadWrite, }; use crate::mtime::cfg::MtimeO...
pub unsafe fn pend_tick<Traits: TimerInstance>() { Traits::mtimecmp_reg32()[0].set(0); Traits::mtimecmp_reg32()[1].set(0); } pub unsafe fn pend_tick_after<Traits: TimerInstance>(tick_count_delta: UTicks) { let tcfg = &Traits::TICKLESS_CFG; let tstate = unsafe { &mut *Traits::tickless_state() }; ...
pub unsafe fn tick_count<Traits: TimerInstance>() -> UTicks { let tcfg = &Traits::TICKLESS_CFG; let hw_tick_count = Traits::mtime_reg32()[0].get(); let tstate = unsafe { &mut *Traits::tickless_state() }; tstate.tick_count(tcfg, hw_tick_count) }
function_block-full_function
[ { "content": "#[doc = include_str!(\"../common.md\")]\n\npub trait KernelStatic<System = Self>: CfgPhase2<System> {}\n\n\n\n/// The second precursor to [`KernelStatic`][].\n\n///\n\n/// The members of this trait are implementation details and not meant to be\n\n/// used externally. Use [`attach_phase2!`] or [`D...
Rust
core-lib/src/model/document.rs
LaudateCorpus1/ids-clearing-house-core
83b286115eadc9b348238b4a047b0f845e6e124b
use aes_gcm_siv::Aes256GcmSiv; use aes_gcm_siv::aead::{Aead, NewAead}; use blake2_rfc::blake2b::Blake2b; use generic_array::GenericArray; use std::collections::HashMap; use uuid::Uuid; use crate::errors::*; use crate::constants::{SPLIT_CT, SPLIT_QUOTE, SPLIT_SIGN}; use crate::model::new_uuid; use crate::model::crypto::...
use aes_gcm_siv::Aes256GcmSiv; use aes_gcm_siv::aead::{Aead, NewAead}; use blake2_rfc::blake2b::Blake2b; use generic_array::GenericArray; use std::collections::HashMap; use uuid::Uuid; use crate::errors::*; use crate::constants::{SPLIT_CT, SPLIT_QUOTE, SPLIT_SIGN}; use crate::model::new_uuid; use crate::model::crypto::...
ize()); debug!("hashed cts: '{}'", &res); res } pub fn new(id: String, pid: String, dt_id: String, ts: i64, tc: i64, keys_ct: String, cts: Vec<String>) -> EncryptedDocument { EncryptedDocument{ id, pid, dt_id, ts, tc, ...
(key); let nonce = GenericArray::from_slice(nonce); let cipher = Aes256GcmSiv::new(key); match cipher.decrypt(nonce, ct){ Ok(pt) => { let pt = String::from_utf8(pt)?; let (name, content) = restore_pt_no_dt(&pt)?; Ok(DocumentPart::new(n...
random
[ { "content": "pub fn decrypt_secret(key: &[u8], nonce: &[u8], ct: &[u8]) -> Result<String>{\n\n debug!(\"key len = {}\", key.len());\n\n debug!(\"ct len = {}\", ct.len());\n\n let key = GenericArray::from_slice(key);\n\n let nonce = GenericArray::from_slice(nonce);\n\n let cipher = Aes256GcmSiv::...
Rust
src/gui/raw_main.rs
sollyucko/winsafe
6243161c47f6f6856c2c3a0b71a9285ad5c7bb84
use std::marker::PhantomPinned; use std::pin::Pin; use std::sync::Arc; use crate::co; use crate::gui::base::Base; use crate::gui::events::WindowEventsAll; use crate::gui::privs::multiply_dpi; use crate::gui::raw_base::{Brush, Cursor, Icon, RawBase}; use crate::gui::runtime_error::RunResult; use crate::gui::v...
use std::marker::PhantomPinned; use std::pin::Pin; use std::sync::Arc; use crate::co; use crate::gui::base::Base; use crate::gui::events::WindowEventsAll; use crate::gui::privs::multiply_dpi; use crate::gui::raw_base::{Brush, Cursor, Icon, RawBase}; use crate::gui::runtime_error::RunResult; use crate::gui::v...
} else if !hchild_prev_focus.is_null() { hchild_prev_focus.SetFocus(); } } Ok(()) }); let self2 = self.clone(); self.on().wm_set_focus(move |_| { self2.0.raw_base.delegate_focus_to_first_child(); Ok(()) }); self.on().wm_nc_destroy(move || { PostQuitMessage(0); ...
if let Some(hwnd_cur_focus) = HWND::GetFocus() { if self2.hwnd().IsChild(hwnd_cur_focus) { *hchild_prev_focus = hwnd_cur_focus; } }
if_condition
[ { "content": "#[cfg_attr(docsrs, doc(cfg(feature = \"user\")))]\n\npub fn RegisterClassEx(wcx: &WNDCLASSEX) -> WinResult<ATOM> {\n\n\tmatch unsafe { user::ffi::RegisterClassExW(wcx as *const _ as _) } {\n\n\t\t0 => Err(GetLastError()),\n\n\t\tatom => Ok(ATOM(atom)),\n\n\t}\n\n}\n\n\n\n/// [`ReleaseCapture`](htt...
Rust
src/prelude.rs
alanfalloon/bumble-umble-gee
668fa21dfe9a4df4cdfa7dc3a398b2d8b13191b4
pub use crate::settings::Settings; use legion::Entity; pub use legion::{system, systems::Builder, Resources, Schedule, World}; pub use macroquad::prelude::*; use parry2d::{ math::{Point, Real}, na::Point2, shape::Polyline, }; use std::ops::Index; pub use std::time::Duration; #[derive(Clone, Copy, Debug, P...
pub use crate::settings::Settings; use legion::Entity; pub use legion::{system, systems::Builder, Resources, Schedule, World}; pub use macroquad::prelude::*; use parry2d::{ math::{Point, Real}, na::Point2, shape::Polyline, }; use std::ops::Index; pub use std::time::Duration; #[derive(Clone, Copy, Debug, P...
} pub fn scale_to_origin(&self, scale: f32) -> Self { Quad(array_init::array_init(|n| self.0[n] * scale)) } pub fn translate(&self, offset: Vec2) -> Self { Quad(array_init::array_init(|n| self.0[n] + offset)) } pub fn rotate_to(&self, unit: Vec2) -> Self { ...
Quad([ vec2(rect.left(), rect.top()), vec2(rect.right(), rect.top()), vec2(rect.right(), rect.bottom()), vec2(rect.left(), rect.bottom()), ])
call_expression
[ { "content": "#[system]\n\nfn tick(#[resource] clock: &mut GameClock) {\n\n let time = get_time();\n\n let tick = Duration::from_secs_f64(time - clock.time);\n\n clock.time = time;\n\n clock.tick = tick;\n\n}\n\n\n", "file_path": "src/backstage.rs", "rank": 0, "score": 93834.64080678651 ...
Rust
src/type_bucket.rs
storyscript/layered-nlp
a8a10e9aeec19be17a66ff3101872fbefa9852ea
#![allow(dead_code)] use std::collections::hash_map; use std::marker::PhantomData; use std::{ any::{Any, TypeId}, collections::HashMap, fmt::{self, Debug}, }; pub struct AnyAttribute(TypeId, Box<dyn Bucket + Send + Sync>, Box<dyn Any>); impl std::fmt::Debug for AnyAttribute { fn fmt(&self, f: &mut fm...
#![allow(dead_code)] use std::collections::hash_map; use std::marker::PhantomData; use std::{ any::{Any, TypeId}, collections::HashMap, fmt::{self, Debug}, }; pub struct AnyAttribute(TypeId, Box<dyn Bucket + Send + Sync>, Box<dyn Any>); impl std::fmt::Debug for AnyAttribute { fn fmt(&self, f: &mut fm...
} #[derive(Debug, Default)] pub struct TypeBucket { map: HashMap<TypeId, Box<dyn Bucket + Send + Sync>>, } impl fmt::Debug for dyn Bucket + Send + Sync { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Bucket::debug(self, f) } } trait Bucket { fn as_any(&self) -> &...
pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> &'a mut T { match self { Entry::Occupied(inner) => inner.into_mut(), Entry::Vacant(inner) => inner.insert(default()), } }
function_block-full_function
[ { "content": "/// Match any number of consecutive spaces.\n\npub fn whitespace() -> AttrEq<'static, TextTag> {\n\n attr_eq(&TextTag::SPACE)\n\n}\n", "file_path": "src/ll_line/x/functions.rs", "rank": 0, "score": 123934.35915039771 }, { "content": "struct TestResolver<F>(F)\n\nwhere\n\n ...
Rust
builder-derive/src/fields.rs
zyxw59/builder
271f03afe2974cd7f498ab5e34c8c1b622185f43
use convert_case::{Case, Casing}; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{Ident, Type}; use crate::error::Error; pub enum Fields<'a> { Named(Vec<NamedField<'a>>), Unnamed(Vec<UnnamedField<'a>>), Unit, } impl<'a> Fields<'a> { pub fn fields(&'a self) -> impl ...
use convert_case::{Case, Casing}; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{Ident, Type}; use crate::error::Error; pub enum Fields<'a> { Named(Vec<NamedField<'a>>), Unnamed(Vec<UnnamedField<'a>>), Unit, } impl<'a> Fields<'a> { pub fn fields(&'a self) -> impl ...
ld.ty.to_token_stream() }) } } impl<'a> TryFrom<&'a syn::Fields> for Fields<'a> { type Error = Error; fn try_from(fields: &'a syn::Fields) -> Result<Self, Self::Error> { match fields { syn::Fields::Named(fields) => { let mut errors = Vec::new(); l...
impl Iterator<Item = TokenStream> + 'a { self.fields().map(|field| if field.default { field.generic_ident.to_token_stream() } else { fie
function_block-random_span
[ { "content": "#[proc_macro_derive(Builder, attributes(builder))]\n\npub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = syn::parse_macro_input!(input as DeriveInput);\n\n let builder = StructAttrs::try_from(&input).unwrap();\n\n let builder_with_callback = builder...
Rust
src/bin/gen_afl_quickcheck_harness.rs
totikom/auto-fuzz-test
9df65e4efbe9a5f7a135550d72155419ee39a63f
use auto_fuzz_test::FnVisitor; use quote::quote; use std::fmt::Write; use std::io; use std::io::Read; use syn; use syn::token::{Async, Unsafe}; use syn::visit::Visit; use syn::{FnArg, FnDecl, Ident, Type}; fn main() -> io::Result<()> { let mut code = String::new(); let stdin = io::stdin(); stdin.lock().rea...
use auto_fuzz_test::FnVisitor; use quote::quote; use std::fmt::Write; use std::io; use std::io::Read; use syn; use syn::token::{Async, Unsafe}; use syn::visit::Visit; use syn::{FnArg, FnDecl, Ident, Type}; fn main() -> io::Result<()> { let mut code = String::new(); let stdin = io::stdin(); stdin.lock().rea...
_: &()| { if unsafety.is_none() && asyncness.is_none() { let mut fn_inv = String::new(); write_fn_invocation(&mut fn_inv, this, ident, decl).unwrap(); print!("{}", fn_inv); } }; let (prefix, suffix) = { let mut...
: &Ident, decl: &FnDecl, unsafety: &Option<Unsafe>, asyncness: &Option<Async>,
function_block-random_span
[]
Rust
src/connections.rs
dan-da/qp2p
b5abe96e34a8c8b88f55594f93fc052280870f0d
use super::{ api::Message, connection_pool::{ConnectionPool, ConnectionRemover}, error::{Error, Result}, wire_msg::WireMsg, }; use bytes::Bytes; use futures::{lock::Mutex, stream::StreamExt}; use log::{error, trace}; use std::{net::SocketAddr, sync::Arc}; use tokio::select; #[derive(Clone)] pub struc...
use super::{ api::Message, connection_pool::{ConnectionPool, ConnectionRemover}, error::{Error, Result}, wire_msg::WireMsg, }; use bytes::Bytes; use futures::{lock::Mutex, stream::StreamExt}; use log::{error, trace}; use std::{net::SocketAddr, sync::Arc}; use tokio::select; #[derive(Clone)] pub struc...
pub fn close(&self) { self.quic_conn.close(0u32.into(), b""); self.remover.remove(); } fn handle_error<T, E>(&self, result: Result<T, E>) -> Result<T, E> { if result.is_err() { self.remover.remove() } result } } pub struct IncomingConnections...
await { Ok(()) | Err(quinn::WriteError::Stopped(_)) => Ok(()), Err(err) => { self.handle_error(Err(err))?; Ok(()) } } }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn project_dir() -> Result<Dirs> {\n\n Err(Error::Configuration {\n\n e: \"No default project dir on non-desktop platforms. User must provide an override path.\"\n\n .to_string(),\n\n })\n\n}\n\n\n\n/// Convert binary data to a diplay-able format\n", "f...
Rust
src/after_effects/conv.rs
BrainiumLLC/celerity
752fa37bc327e8c41c8c5f454b051582313beb67
use crate::{Animatable, Scalar}; use gee::en; use thiserror::Error; pub trait FromValue: Animatable { type Error: std::error::Error; fn from_value(value: f64) -> Result<Self, Self::Error>; } pub trait FromMultiDimensional: Animatable { type Error: std::error::Error; fn from_multi_dimensional(value: ...
use crate::{Animatable, Scalar}; use gee::en; use thiserror::Error; pub trait FromValue: Animatable { type Error: std::error::Error; fn from_value(value: f64) -> Result<Self, Self::Error>; } pub trait FromMultiDimensional: Animatable { type Error: std::error::Error; fn from_multi_dimensional(value: ...
} } impl<T> std::error::Error for WrongLen<T> {} impl<T> WrongLen<T> { fn check<U>(value: &[f64], expected: usize, f: impl FnOnce(&[f64]) -> U) -> Result<U, Self> { let found = value.len(); (found == expected).then(|| f(value)).ok_or_else(|| Self { expected, found, ...
if self.expected != self.found { write!( f, "type `{}` expected {} components, but multidimensional value contained {} components", std::any::type_name::<T>(), self.expected, self.found, ) } else { ...
if_condition
[ { "content": "/// A numeric primitive.\n\n///\n\n/// Implementors of this trait automatically get a [`ComponentWise`] and\n\n/// [`Animatable`] implementation.\n\npub trait Scalar: en::Num {}\n\n\n\nimpl<S: Scalar> ComponentWise for S {\n\n type Component = Self;\n\n\n\n fn map<F>(self, f: F) -> Self\n\n ...
Rust
src/sub.rs
fengalin/option-operations
7a15e34dc8a1fbcbaad55469118d475ed14e865b
use core::ops::{Sub, SubAssign}; use crate::{Error, OptionOperations}; common_option_op!(Sub, sub, substraction); impl_for_ints!(OptionOverflowingSub, { type Output = Self; fn opt_overflowing_sub(self, rhs: Self) -> Option<(Self::Output, bool)> { Some(self.overflowing_sub(rhs)) } }); impl_for_...
use core::ops::{Sub, SubAssign}; use crate::{Error, OptionOperations}; common_option_op!(Sub, sub, substraction); impl_for_ints!(OptionOverflowingSub, { type Output = Self; fn opt_overflowing_sub(self, rhs: Self) -> Option<(Self::Output, bool)> { Some(self.overflowing_sub(rhs)) } }); impl_for_...
}
self.0.opt_wrapping_sub(rhs.0).map(MyInt) } } impl OptionWrappingSub<u64> for MyInt { type Output = MyInt; fn opt_wrapping_sub(self, rhs: u64) -> Option<Self::Output> { self.0.opt_wrapping_sub(rhs).map(MyInt) } } assert_eq...
function_block-function_prefix_line
[ { "content": " #[must_use]\n\n pub fn is_division_by_zero(&self) -> bool {\n\n matches!(self, Error::DivisionByZero)\n\n }\n\n\n\n /// Returns `true` if this [`Error`] results from an overflow.\n\n #[must_use]\n\n pub fn is_overflow(&self) -> bool {\n\n matches!(self, Error::Over...
Rust
src/textures/checkerboard.rs
alexmeli100/pbrt-rust
45f11e12a8978092335347b315ef9f9edf75ddbe
use crate::core::texture::{TextureMapping2Ds, Textures, SpectrumT, Texture, TextureMapping2D, TextureMapping3Ds, TextureMapping3D, TextureFloat, get_mapping2d, IdentityMapping3D, TextureSpec}; use std::sync::Arc; use log::{error, warn}; use crate::core::interaction::SurfaceInteraction; use crate::core::geometry::vector...
use crate::core::texture::{TextureMapping2Ds, Textures, SpectrumT, Texture, TextureMapping2D, TextureMapping3Ds, TextureMapping3D, TextureFloat, get_mapping2d, IdentityMapping3D, TextureSpec}; use std::sync::Arc; use log::{error, warn}; use crate::core::interaction::SurfaceInteraction; use crate::core::geometry::vector...
a = tp.find_string("aamode", "none"); let aam = match aa.as_str() { "none" => AAMethod::None, "closedform" => AAMethod::ClosedForm, _ => { warn!( "Antialiasing mode \"{}\" not understood by \ ...
function_block-function_prefixed
[ { "content": "pub fn get_mapping2d(t2w: &Transform, tp: &mut TextureParams) -> TextureMapping2Ds {\n\n let ty = tp.find_string(\"mapping\", \"uv\");\n\n match ty.as_str() {\n\n \"uv\" => {\n\n let su = tp.find_float(\"uscale\", 1.0);\n\n let sv = tp.find_float(\"vscale\", 1.0)...
Rust
src/notifications/discord.rs
localthomas/systemd-fail-notifications
e53469f3cbe4ed700de2441b04c9bbf1fcd8e012
/* SPDX-FileCopyrightText: 2021 localthomas SPDX-License-Identifier: MIT OR Apache-2.0 */ use anyhow::{Context, Result}; use serde_json::json; use url::Url; use crate::status::UnitStatus; use super::NotificationProvider; #[derive(Clone)] pub struct Discord { webhook_url: Url, } impl Discord { pu...
/* SPDX-FileCopyrightText: 2021 localthomas SPDX-License-Identifier: MIT OR Apache-2.0 */ use anyhow::{Context, Result}; use serde_json::json; use url::Url; use crate::status::UnitStatus; use super::NotificationProvider; #[derive(Clone)] pub struct Discord { webhook_url: Url, } impl Discord {
fn send_status(&self, status: &UnitStatus) -> Result<()> { let payload = DiscordMessage { content: "Unit Status changed!".to_string(), title: format!("{} has failed!", status.name()), description: "The following unit has entered a new state:".to_string(), ...
pub fn new(webhook_url: &str) -> Result<Self> { let url = Url::parse(webhook_url).context(format!( "could not parse discord webhook url '{}'", webhook_url ))?; Ok(Self { webhook_url: url }) }
function_block-full_function
[ { "content": "/// Creates a default set of notification providers with the given configuration.\n\n/// The list is not empty, if the `Ok` is returned.\n\n/// Any errors during the creation of any notification provider is returned and no list is created.\n\npub fn create_notifications(config: &Config) -> Result<...
Rust
src/math/conversion_unit/mod.rs
KY64/kalko
5ae8754a2b20775e2b1e3fdc77013dbd18e767c3
pub mod length; pub mod weight; pub struct Unit { pub name: String, pub alias: String, pub base: UnitMeasurement, pub prefix: PrefixUnit, pub category: Category, pub relative: Vec<RelativeUnit>, } impl Unit { pub fn convert_to(&self, target: &Self) -> Result<f32, &str> { for val in...
pub mod length; pub mod weight; pub struct Unit { pub name: String, pub alias: String, pub base: UnitMeasurement, pub prefix: PrefixUnit, pub category: Category, pub relative: Vec<RelativeUnit>, } impl Unit { pub fn convert_to(&self, target: &Self) -> Result<f32, &str> { for val in...
pub fn create_unit( string: &str, base: UnitMeasurement, category: Category, alias: &str, name: &str, conversion_units: Vec<RelativeUnit>, single_unit: bool, ) -> Option<Unit> { if conversion_units.is_empty() { return None; } let (prefix, unit_alias, unit_name) = find_...
e)), ]; for val in names.iter() { if string == val.0 || string == val.1 { if val.1.starts_with("kilo") { return (PrefixUnit::Kilo, val.0.to_string(), val.1.to_string()); } else if val.1.starts_with("hecto") { return (PrefixUnit::Hecto, val.0....
function_block-function_prefixed
[ { "content": "pub fn match_unit(string: &str, alias: &str, name: &str) -> bool {\n\n let expression = &format!(\n\n r\"(^(k|h|da|d|c|m)?{}$|^(kilo|hecto|deca|deci|centi|milli)?{}$)\",\n\n alias, name\n\n );\n\n let parse_unit = regex(expression);\n\n parse_unit.is_match(string)\n\n}\n"...