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/pagetree.rs
manuel-rhdt/lemon_pdf
e85d52d391a6dbc34fe4b33e437d788e62fd12a0
use std::collections::HashMap; use std::f64::consts::SQRT_2; use std::io::Result; use crate as lemon_pdf; use lemon_pdf_derive::PdfFormat; use crate::array::Array; use crate::content::PageContext; use crate::document::DocumentContext; use crate::font::Font; use crate::object::{IndirectReference, Object, Value}; use...
use std::collections::HashMap; use std::f64::consts::SQRT_2; use std::io::Result; use crate as lemon_pdf; use lemon_pdf_derive::PdfFormat; use crate::array::Array; use crate::content::PageContext; use crate::document::DocumentContext; use crate::font::Font; use crate::object::{IndirectReference, Object, Value}; use...
pub fn set_media_box(&mut self, media_box: MediaBox) { self.media_box = media_box.as_array() } fn get_context<'context, 'borrow>( &mut self, context: &'borrow mut DocumentContext<'context>, stream_filter: Option<StreamFilter>, ) -> PageContext<'_, 'context, 'borrow> { ...
pub fn new() -> Self { Page { resources: None, media_box: MediaBox::paper_din_a(4).as_array(), parent: None, contents: Vec::new(), } }
function_block-full_function
[ { "content": "pub trait PdfFormat: std::fmt::Debug {\n\n fn write(&self, output: &mut Formatter) -> Result<()>;\n\n}\n\n\n\nimpl<'a> PdfFormat for &'a str {\n\n fn write(&self, output: &mut Formatter) -> Result<()> {\n\n // TODO: proper escaping\n\n write!(output, \"/{}\", self)\n\n }\n\n...
Rust
src/interpreter/stdlib/special_forms/_match.rs
emirayka/nia_interpreter_core
8b212e44fdede3d49cd75eddb255091a1d67b0e5
use crate::interpreter::environment::EnvironmentId; use crate::interpreter::error::Error; use crate::interpreter::interpreter::Interpreter; use crate::interpreter::value::Value; use crate::interpreter::library; pub fn _match( interpreter: &mut Interpreter, environment_id: EnvironmentId, values: Vec<Value>...
use crate::interpreter::environment::EnvironmentId; use crate::interpreter::error::Error; use crate::interpreter::interpreter::Interpreter; use crate::interpreter::value::Value; use crate::interpreter::library; pub fn _match( interpreter: &mut Interpreter, environment_id: EnvironmentId, values: Vec<Value>...
#[test] fn able_to_destructurize_objects() { let mut interpreter = Interpreter::new(); let pairs = vec![ ( "(match {:a 1 :b 2 :c 3} (#{:a} (list:new a)))", "(list:new 1)", ), ( "(match {:a 1 :b 2 :c 3} (#{:a :...
terpreter = Interpreter::new(); let pairs = vec![ ( "(match '() (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c) (list:new a b c)))", "()", ), ( "(match '(1) (()) ('(a) (list:new a)) ('(a b) (list:new a b)) ('(a b c)...
function_block-function_prefixed
[ { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let pairs: Vec<(&str, SpecialFormFunctionType)> = vec![\n\n (\"and\", and::and),\n\n (\"call-with-this\", call_with_this::call_with_this),\n\n (\"cond\", cond::cond),\n\n (\"quote\", quote::quote...
Rust
krapao/src/state.rs
shigedangao/jiemi
beffe848cb5606a4bee02647f8a6743e09301e45
use std::sync::{Arc, Mutex}; use std::fs; use std::collections::HashMap; use dirs::home_dir; use serde::{Serialize, Deserialize}; use crate::repo::config::GitConfig; use crate::err::Error; use crate::helper; const REPO_FILE_PATH: &str = "list.json"; const REPO_PATH: &str = "workspace/repo"; pub type State = Arc<Mutex...
use std::sync::{Arc, Mutex}; use std::fs; use std::collections::HashMap; use dirs::home_dir; use serde::{Serialize, Deserialize}; use crate::repo::config::GitConfig; use crate::err::Error; use crate::helper; const REPO_FILE_PATH: &str = "list.json"; const REPO_PATH: &str = "workspace/repo"; pub type State = Arc<Mutex...
} pub fn create_state() -> Result<State, Error> { let mut workspace_dir = home_dir().unwrap_or_default(); workspace_dir.push(REPO_PATH); helper::create_path(&workspace_dir)?; let saved_state = match List::read_persistent_state() { Ok(res) => res, Err(_) => { ...
fn save_list_to_persistent_state(&self) -> Result<(), Error> { let mut file_path = home_dir().unwrap_or_default(); file_path.push(REPO_PATH); file_path.push(REPO_FILE_PATH); let json = serde_json::to_string_pretty(&self)?; fs::write(file_path, json)?; Ok(()) ...
function_block-full_function
[ { "content": "/// Delete an item in the state. This case is used when a CRD is delete. w/o removing the item, when a crd containing the sma\n\n/// name is applied. The crd might not take into account the update\n\n/// \n\n/// # Arguments\n\n/// * `state` - State\n\n/// * `key` - &str\n\npub fn delete_item_in_st...
Rust
src/windows.rs
chadbrewbaker/filebuffer
38193fc0c9cb54363a8dcf59c303a6605e2ba8c5
use std::fs; use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::ptr; extern crate winapi; #[derive(Debug)] pub struct PlatformData { #[allow(dead_code)] file: fs::File, mapping_handle: winapi::um::winnt::HANDLE, } impl Drop for PlatformData { fn drop (&mut self) { ...
use std::fs; use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::ptr; extern crate winapi; #[derive(Debug)] pub struct PlatformData { #[allow(dead_code)] file: fs::File, mapping_handle: winapi::um::winnt::HANDLE, } impl Drop for PlatformData { fn drop (&mut self) { ...
e { let mut sysinfo: winapi::um::sysinfoapi::SYSTEM_INFO = unsafe { mem::zeroed() }; unsafe { winapi::um::sysinfoapi::GetSystemInfo(&mut sysinfo); } sysinfo.dwPageSize as usize }
function_block-function_prefixed
[ { "content": "/// Writes whether the pages in the range starting at `buffer` with a length of `length` bytes\n\n/// are resident in physical memory into `residency`. The size of `residency` must be at least\n\n/// `length / page_size`. Both `buffer` and `length` must be a multiple of the page size.\n\npub fn ge...
Rust
src/browser/url/search.rs
AlterionX/seed
ba2d8d36c68feda991d73a961ddc630fb67df949
use crate::browser::url::Url; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, collections::BTreeMap, fmt}; #[allow(clippy::module_name_repetitions)] #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct UrlSearch { search: BTreeMap<String, Vec<String>>, pub(super) invalid_c...
use crate::browser::url::Url; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, collections::BTreeMap, fmt}; #[allow(clippy::module_name_repetitions)] #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct UrlSearch { search: BTreeMap<String, Vec<String>>, pub(super) invalid_c...
pub fn insert(&mut self, key: String, values: Vec<String>) -> Option<Vec<String>> { self.search.insert(key, values) } pub fn remove(&mut self, key: impl AsRef<str>) -> Option<Vec<String>> { self.search.remove(key.as_ref()) } pub fn iter(&self) -...
let key = key.into(); if self.search.contains_key(key.as_ref()) { self.search.get_mut(key.as_ref()).unwrap().push(value); } else { self.search.insert(key.into_owned(), vec![value]); } }
function_block-function_prefix_line
[ { "content": "/// Attach given `key` to the `El`.\n\n///\n\n/// The keys are used by the diffing algorithm to determine the correspondence between old and\n\n/// new elements and helps to optimize the insertion, removal and reordering of elements.\n\npub fn el_key(key: &impl ToString) -> ElKey {\n\n ElKey(ke...
Rust
src/node.rs
pmuens/anova
c7d160b5df49bd3d6fbf9cf664025836997f12ab
use crate::{ block::Block, chain::Chain, transaction::Transaction, utils::{Keccak256, Sender}, }; use crate::{mempool::Mempool, utils::hash}; use rand::prelude::SliceRandom; pub struct Node { chain: Chain, mempool: Mempool, nonce: u64, } impl Node { pub fn new() ->...
use crate::{ block::Block, chain::Chain, transaction::Transaction, utils::{Keccak256, Sender}, }; use crate::{mempool::Mempool, utils::hash}; use rand::prelude::SliceRandom; pub struct Node { chain: Chain, mempool: Mempool, nonce: u64, } impl Node { pub fn new() ->...
#[test] fn add_transactions() { let mut node = Node::new(); let tx_1 = Transaction::new(vec![0, 1, 2, 3, 4], 1); let tx_2 = Transaction::new(vec![5, 6, 7, 8, 9], 1); let transactions = vec![tx_1, tx_2]; node.add_transactions(transactions); assert_eq!(node.mempo...
1); node.add_transaction(tx); assert_eq!(node.mempool.len(), 1); assert_eq!(node.nonce, 1); }
function_block-function_prefixed
[ { "content": "use bincode;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::utils;\n\nuse super::utils::{BinEncoding, Keccak256, Sender};\n\n\n\n/// A Transaction which includes a reference to its sender and a nonce.\n\n#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]\n\npub struct Transactio...
Rust
cli/src/command/list/list.rs
bennyboer/worklog
bce3c3954c3a14cca7c029caf2641ec1f5af4478
use std::collections::HashMap; use cmd_args::{arg, option, Group}; use colorful::Colorful; use persistence::calc::{Status, WorkItem}; use crate::command::command::Command; use std::ops::Sub; pub struct ListCommand {} impl Command for ListCommand { fn build(&self) -> Group { Group::new( Box:...
use std::collections::HashMap; use cmd_args::{arg, option, Group}; use colorful::Colorful; use persistence::calc::{Status, WorkItem}; use crate::command::command::Command; use std::ops::Sub; pub struct ListCommand {} impl Command for ListCommand { fn build(&self) -> Group { Group::new( Box:...
fn format_item(item: &WorkItem) -> String { let id_str = format!( "#{}", item.id().expect("Work item must have an ID at this point!") ) .color(colorful::Color::DodgerBlue3); let time_str = shared::time::get_local_date_time(item.created_timestamp()) .format("%H:%M") .to...
pub(crate) fn calculate_total_work_time(items: &[&WorkItem]) -> i64 { let mut time_events: Vec<shared::calc::TimeEvent> = items .iter() .flat_map(|i| { i.events() .iter() .map(|e| shared::calc::TimeEvent::new(e.is_start(), e.timestamp())) }) ...
function_block-full_function
[ { "content": "/// Format a duration given in seconds in the form \"Xh Xm Xs\".\n\npub fn format_duration(mut seconds: u32) -> String {\n\n let hours = seconds / 60 / 60;\n\n seconds -= hours * 60 * 60;\n\n\n\n let minutes = seconds / 60;\n\n seconds -= minutes * 60;\n\n\n\n let mut result = Vec::...
Rust
nachricht-serde/src/ser.rs
yasammez/nachricht
846d60dec1da1ddd5ffa2c1fa1ab7ec5d7386bce
use serde::ser::{self, Serialize, Impossible}; use nachricht::{EncodeError, Header, Refable}; use std::io::Write; use crate::error::{Error, Result}; pub struct Serializer<W> { symbols: Vec<(Refable, String)>, output: W, } pub fn to_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> { let buf = Vec::new();...
use serde::ser::{self, Serialize, Impossible}; use nachricht::{EncodeError, Header, Refable}; use std::io::Write; use crate::error::{Error, Result}; pub struct Serializer<W> { symbols: Vec<(Refable, String)>, output: W, } pub fn to_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> { let buf = Vec::new();...
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { match len { Some(len) => { Header::Bag(len).encode(&mut self.output)?; Ok(self) }, None => Err(Error::Length) } } fn serialize_struct(self, _name:...
t)?; self.serialize_refable(variant, Refable::Key)?; Header::Bag(len).encode(&mut self.output)?; Ok(self) }
function_block-function_prefixed
[ { "content": "fn symbol(i: &str) -> IResult<&str, String> {\n\n alt((\n\n map(tuple((tag(\"#\"), identifier)), |(_,i)| String::from(i)),\n\n map(tuple((tag(\"#\"), escaped_string)), |(_,i)| i)\n\n ))(i)\n\n}\n\n\n", "file_path": "nachricht-nq/src/parser.rs", "rank": 1, "s...
Rust
packages/connector/src/cf.rs
hahnlee/canter
274f0ccb55892b6b8387007f0ea24f2187da5648
use core_foundation::base::{ kCFAllocatorDefault, Boolean, CFGetTypeID, CFIndex, CFRange, ToVoid, }; use core_foundation::boolean::{kCFBooleanTrue, CFBooleanGetTypeID, CFBooleanRef}; use core_foundation::data::{ CFDataCreate, CFDataGetBytePtr, CFDataGetLength, CFDataGetTypeID, CFDataRef, }; use core_foundation:...
use core_foundation::base::{ kCFAllocatorDefault, Boolean, CFGetTypeID, CFIndex, CFRange, ToVoid, }; use core_foundation::boolean::{kCFBooleanTrue, CFBooleanGetTypeID, CFBooleanRef}; use core_foundation::data::{ CFDataCreate, CFDataGetBytePtr, CFDataGetLength, CFDataGetTypeID, CFDataRef, }; use core_foundation:...
return; } if object_type == ValueType::Number { let value = unknown.coerce_to_number().unwrap(); let cf_number = to_cf_number(value, env); unsafe { CFDictionaryAddValue(dict_ref, key, cf_number.to_void()); } } } fn to_cf_number(value: JsNumber, env: &Env)...
::Object { if unknown.is_typedarray().unwrap() { let object = unknown.coerce_to_object().unwrap(); let properties = object.get_property_names().unwrap(); let length = properties.get_array_length_unchecked().unwrap(); let mut data: Vec<u8> = vec![]; for...
random
[ { "content": "pub fn receive_message(\n\n connection_ref: bridge::AMDServiceConnectionRef,\n\n) -> Result<CFDictionaryRef, i32> {\n\n unsafe {\n\n let response: CFDictionaryRef = std::ptr::null_mut();\n\n let code = bridge::AMDServiceConnectionReceiveMessage(\n\n connection_ref,\n...
Rust
rootfm-core/src/envelope.rs
Kintaro/rootfm
0c535d8c108a94bae144d6d146778f93bb4626e4
use crate::{MINIMUM_LEVEL, SAMPLE_RATE}; use libm::{fmaxf, logf}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum State { Start, Delay, Attack, Hold, Decay, Sustain, Release, Off, } impl Default for State { fn default() -> State { State::Start } } impl State { ...
use crate::{MINIMUM_LEVEL, SAMPLE_RATE}; use libm::{fmaxf, logf}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum State { Start, Delay, Attack, Hold, Decay, Sustain, Release, Off, } impl Default for State { fn default() -> State { State::Start } } impl State { ...
} impl EnvelopeSettings { fn value_for_state(&self, state: State) -> f32 { match state { State::Start => 0.0, State::Delay => self.delay, State::Attack => self.attack, State::Hold => self.hold, State::Decay => self.decay, State::Susta...
pub const fn new( delay: f32, attack: f32, hold: f32, decay: f32, sustain: f32, release: f32, ) -> EnvelopeSettings { EnvelopeSettings { delay, attack, hold, decay, sustain, release, ...
function_block-full_function
[ { "content": "fn number_samples_from_ms(delay: f32) -> f32 {\n\n SAMPLE_RATE * delay * 0.001\n\n}\n\n\n\nimpl DelayLine {\n\n pub fn new(delay: f32) -> DelayLine {\n\n let samples = delay as f32 * 0.001 * SAMPLE_RATE;\n\n let fraction = floorf(number_samples_from_ms(delay) - samples);\n\n ...
Rust
models/src/input.rs
alsacoin/alsacoin
389ae5aef90011414f545fa8575b5137731adc55
use crate::account::Account; use crate::address::Address; use crate::error::Error; use crate::result::Result; use crate::transaction::Transaction; use crypto::ecc::ed25519::{KeyPair, PublicKey, SecretKey, Signature}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Clone, Eq, PartialEq, ...
use crate::account::Account; use crate::address::Address; use crate::error::Error; use crate::result::Result; use crate::transaction::Transaction; use crypto::ecc::ed25519::{KeyPair, PublicKey, SecretKey, Signature}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Clone, Eq, PartialEq, ...
pub fn sign(&mut self, secret_key: &SecretKey, msg: &[u8]) -> Result<()> { let public_key = secret_key.to_public(); if !self.account.signers.lookup(&public_key) { let err = Error::NotFound; return Err(err); } let signature = self.calc_signature(secret...
pub fn calc_signature(&self, secret_key: &SecretKey, seed: &[u8]) -> Result<Signature> { let kp = KeyPair::from_secret(secret_key)?; if !self.account.signers.lookup(&kp.public_key) { let err = Error::NotFound; return Err(err); } let msg = self.signature_message(...
function_block-full_function
[ { "content": "/// `address_to_bytes` converts a SocketAddrV4 to a vector of bytes.\n\npub fn address_to_bytes(address: &SocketAddrV4) -> Result<Vec<u8>> {\n\n let mut buf = Vec::new();\n\n\n\n for n in &address.ip().octets() {\n\n buf.write_u8(*n)?;\n\n }\n\n\n\n buf.write_u16::<BigEndian>(ad...
Rust
src/test_md.rs
puru1761/kcapi-sys
ef3a7e91e6fb5e355fb41e75464322dd13b69349
/* * $Id$ * * Copyright (c) 2021, Purushottam A. Kulkarni. * 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, *...
/* * $Id$ * * Copyright (c) 2021, Purushottam A. Kulkarni. * 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, *...
#[test] fn test_sha224() { let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA224]; let out_exp = [ 0xcb, 0xa2, 0x25, 0xbd, 0x2d, 0xed, 0x28, 0xf5, 0xb9, 0xb3, 0xfa, 0xee, 0x8e, 0xca, 0xed, 0x82, 0xba, 0x8, 0xd2, 0xbb, 0x5a, 0xee, 0x2c, 0x37, 0x40, 0xe7, 0xff, 0x8a...
let inp = [0x41u8; 16]; let out = [0u8; SIZE_SHA1]; let out_exp = [ 0x19, 0xb1, 0x92, 0x8d, 0x58, 0xa2, 0x3, 0xd, 0x8, 0x2, 0x3f, 0x3d, 0x70, 0x54, 0x51, 0x6d, 0xbc, 0x18, 0x6f, 0x20, ]; let ret: i64; unsafe { ret = kcapi_md_sha1( ...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let out_path = PathBuf::from(env::var(\"OUT_DIR\").unwrap());\n\n let include_path = out_path.join(\"include\");\n\n let wrapper_h_path = include_path.join(\"wrapper.h\");\n\n let build_path = out_path.join(\"libkcapi\");\n\n\n\n /*\n\n * Copy the libkcapi source...
Rust
web_glitz_macros/src/resources.rs
RSSchermer/web_glitz.rs
a2e26ef0156705f0b5ac7707c4fc24a4a994d84b
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Attribute, Data, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type}; use crate::util::ErrorLog; pub fn expand_derive_resources(input: &DeriveInput) -> Result<TokenStream, String> { if let D...
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Attribute, Data, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type}; use crate::util::ErrorLog; pub fn expand_derive_resources(input: &DeriveInput) -> Result<TokenStream, String> { if let D...
enum ResourcesField { Resource(ResourceField), Excluded, } impl ResourcesField { pub fn from_ast(ast: &Field, position: usize, log: &mut ErrorLog) -> Self { let field_name = ast .ident .clone() .map(|i| i.to_string()) .unwrap_or(position.to_string()...
let mut resource_fields: Vec<ResourceField> = Vec::new(); for (position, field) in data.fields.iter().enumerate() { match ResourcesField::from_ast(field, position, &mut log) { ResourcesField::Resource(resource_field) => { for field in resource_fields.iter() { ...
function_block-function_prefix_line
[ { "content": "pub fn expand_derive_vertex(input: &DeriveInput) -> Result<TokenStream, String> {\n\n if let Data::Struct(ref data) = input.data {\n\n let struct_name = &input.ident;\n\n let mod_path = quote!(web_glitz::pipeline::graphics);\n\n let mut log = ErrorLog::new();\n\n\n\n ...
Rust
src/components/memory.rs
rust-motd/rust-motd
d9fdf32019993f7abc10bb01c0bdf7ef8224f44e
use serde::Deserialize; use systemstat::{saturating_sub_bytes, Platform, System}; use termion::{color, style}; use thiserror::Error; use crate::constants::{GlobalSettings, INDENT_WIDTH}; #[derive(Error, Debug)] pub enum MemoryError { #[error("Could not find memory quantity {quantity:?}")] MemoryNotFound { qua...
use serde::Deserialize; use systemstat::{saturating_sub_bytes, Platform, System}; use termion::{color, style}; use thiserror::Error; use crate::constants::{GlobalSettings, INDENT_WIDTH}; #[derive(Error, Debug)] pub enum MemoryError { #[error("Could not find memory quantity {quantity:?}")] MemoryNotFound { qua...
fn full_color(ratio: f64) -> String { match (ratio * 100.) as usize { 0..=75 => color::Fg(color::Green).to_string(), 76..=95 => color::Fg(color::Yellow).to_string(), _ => color::Fg(color::Red).to_string(), } } pub fn disp_memory( config: MemoryCfg, global_settings: &GlobalSett...
fn print_bar( global_settings: &GlobalSettings, full_color: String, bar_full: usize, bar_empty: usize, ) { print!( "{}", [ " ".repeat(INDENT_WIDTH), global_settings.progress_prefix.to_string(), full_color, global_settings ...
function_block-full_function
[ { "content": "fn print_row<'a>(items: [&str; 6], column_sizes: impl IntoIterator<Item = &'a usize>) {\n\n println!(\n\n \"{}\",\n\n Itertools::intersperse(\n\n items\n\n .iter()\n\n .zip(column_sizes.into_iter())\n\n .map(|(name, size)| fo...
Rust
task-scheduler-rust/src/apply.rs
gyuho/task-scheduler-examples
bd9475b90679d060fdcb9bf856e5a81ed15917c2
use std::{ io, io::{Error, ErrorKind}, string::String, sync::Arc, time::{Duration, Instant}, }; use tokio::{ select, sync::mpsc, task::{self, JoinHandle}, time::timeout, }; use crate::echo; use crate::id; use crate::notify; #[derive(Debug)] pub struct Request { pub echo_reques...
use std::{ io, io::{Error, ErrorKind}, string::String, sync::Arc, time::{Duration, Instant}, }; use tokio::{ select, sync::mpsc, task::{self, JoinHandle}, time::timeout, }; use crate::echo; use crate::id; use crate::notify; #[derive(Debug)] pub struct Request { pub echo_reques...
pub async fn apply_async( notifier: Arc<notify::Notifier>, mut request_rx: mpsc::UnboundedReceiver<(u64, Request)>, mut stop_rx: mpsc::Receiver<()>, mut echo_manager: echo::Manager, ) -> io::Result<()> { println!("running apply loop"); 'outer: loop { let (req_id, req) =...
function_block-full_function
[ { "content": "pub fn parse_request(b: &[u8]) -> io::Result<Request> {\n\n serde_json::from_slice(b).map_err(|e| {\n\n return Error::new(ErrorKind::InvalidInput, format!(\"invalid JSON: {}\", e));\n\n })\n\n}\n\n\n", "file_path": "task-scheduler-rust/src/echo.rs", "rank": 0, "score": 142...
Rust
src/discord_client/serenity_discord_client.rs
Hammatt/tougou_bot
47f0457f66ef3815791d2d47e0eb503c7a72f996
use crate::discord_client::{CommandHandler, DiscordClient}; use log; use serenity::{ client, model::{channel::Message, gateway::Ready}, prelude::*, }; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; type BoxedThreadsafeCommandHandler = Box<Arc<Mutex<CommandHandler + Send>>>; p...
use crate::discord_client::{CommandHandler, DiscordClient}; use log; use serenity::{ client, model::{channel::Message, gateway::Ready}, prelude::*, }; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; type BoxedThreadsafeCommandHandler = Box<Arc<Mutex<CommandHandler + Send>>>; p...
} impl EventHandler for SerenityDiscordHandler { fn message(&self, ctx: Context, msg: Message) { if let Some(command) = self.get_command_name(&msg.content) { if let Some(command_handler) = self.command_callbacks.lock().unwrap().get(&command) { if let Err(err) = command_handler....
8()..]) { result = Some(command.to_string()); } } } result }
function_block-function_prefixed
[ { "content": "fn parse_command(command: &str) -> Vec<&str> {\n\n command.split_ascii_whitespace().skip(1).collect()\n\n}\n\n\n\nimpl JishoCommand {\n\n pub fn new(jisho_repository: Box<JishoRepository + Send>) -> JishoCommand {\n\n JishoCommand { jisho_repository }\n\n }\n\n}\n\n\n\nimpl Command...
Rust
src/search.rs
dskleingeld/minimal_timeseries
0d03039ec4663a918a8adbe7a78fee2237dfe69a
use byteorder::{ByteOrder, LittleEndian}; use chrono::{DateTime, Utc}; use std::io::{Read, Seek, SeekFrom}; use crate::data::FullTime; use crate::header::SearchBounds; use crate::ByteSeries; use crate::Error; #[derive(thiserror::Error, Debug)] pub enum SeekError { #[error("could not find timestamp in this series"...
use byteorder::{ByteOrder, LittleEndian}; use chrono::{DateTime, Utc}; use std::io::{Read, Seek, SeekFrom}; use crate::data::FullTime; use crate::header::SearchBounds; use crate::ByteSeries; use crate::Error; #[derive(thiserror::Error, Debug)] pub enum SeekError { #[error("could not find timestamp in this series"...
pub fn get_bounds( &mut self, start_time: DateTime<Utc>, end_time: DateTime<Utc>, ) -> Result<(u64, u64, FullTime), SeekError> { if self.data_size == 0 { return Err(SeekError::EmptyFile); } if start_time.timestamp() >= self.last_time_in_dat...
self.data.seek(SeekFrom::Start(start))?; self.data.read_exact(&mut buf)?; for line_start in (0..buf.len().saturating_sub(2)).step_by(self.full_line_size) { if LittleEndian::read_u16(&buf[line_start..line_start + 2]) >= start_time.timestamp() as u16 { ...
function_block-function_prefix_line
[ { "content": "fn insert_vector(ts: &mut Series, t_start: DateTime<Utc>, t_end: DateTime<Utc>, data: &[f32]) {\n\n let dt = (t_end - t_start) / (data.len() as i32);\n\n let mut time = t_start;\n\n\n\n for x in data {\n\n ts.append(time, &x.to_be_bytes()).unwrap();\n\n time = time + dt;\n\n...
Rust
src/synth_ui/widgets.rs
GorgeousMooseNipple/beep-boop
834cdea5a011be9c992ecbcb55c433cf341c2667
use std::sync::MutexGuard; use druid::widget::prelude::*; use druid::widget::{Flex, Slider, CrossAxisAlignment}; use druid::Code as KeyCode; use druid::KeyEvent; use super::{ model::{SynthUIData, SynthUIEvent, OscSettings, EnvSettings}, layout::{slider_log, LOG_SCALE_BASE}, constants::{WAVEFORMS, DefaultPar...
use std::sync::MutexGuard; use druid::widget::prelude::*; use druid::widget::{Flex, Slider, CrossAxisAlignment}; use druid::Code as KeyCode; use druid::KeyEvent; use super::{ model::{SynthUIData, SynthUIEvent, OscSettings, EnvSettings}, layout::{slider_log, LOG_SCALE_BASE}, constants::{WAVEFORMS, DefaultPar...
if new.decay != old.decay { synth.set_env_parameter(new.id, ADSRParam::Decay(LOG_SCALE_BASE.powf(new.decay).round() as f32)) } if new.sustain != old.sustain { synth.set_env_parameter(new.id, ADSRParam::Sustain(new.sustain as f32)) } if new.release != old....
if new.attack != old.attack { synth.set_env_parameter(new.id, ADSRParam::Attack(LOG_SCALE_BASE.powf(new.attack).round() as f32)) }
if_condition
[ { "content": "pub fn build_ui() -> impl Widget<SynthUIData> {\n\n let mut synth_ui = SynthUI::new();\n\n\n\n synth_ui.root.add_child(Flex::column()\n\n .cross_axis_alignment(CrossAxisAlignment::Center)\n\n .with_child(oscillator_layout(\"Osc1\", SynthUIData::o...
Rust
vendor/dwrote/src/font_face.rs
vcapra1/alacritty
64026e22f889004c04297dfece71b2a65edb7f38
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cell::UnsafeCell; use std::mem::{self, zeroed}; use std::ptr; use std::slice; use winapi::ctypes::c_void;...
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cell::UnsafeCell; use std::mem::{self, zeroed}; use std::ptr; use std::slice; use winapi::ctypes::c_void;...
pub fn get_font_table(&self, opentype_table_tag: u32) -> Option<Vec<u8>> { unsafe { let mut table_data_ptr: *const u8 = ptr::null_mut(); let mut table_size: u32 = 0; let mut table_context: *mut c_void = ptr::null_mut(); let mut exists: BO...
2, transform: *const DWRITE_MATRIX, use_gdi_natural: bool, glyph_indices: &[u16], is_sideways: bool, ) -> Vec<DWRITE_GLYPH_METRICS> { unsafe { let mut metrics: Vec<DWRITE_GLYPH_METRICS> = vec![zeroed(); glyph_indices.len()]; let hr = (*self.native.get(...
function_block-function_prefixed
[]
Rust
src/options/new_Session/tests.rs
hugo-k-m/tmux-session-generator
dcde680cc5f2128004ea94691f6fa17f14ab23de
use super::*; use crate::options::Opts; use lib::{ dir::create_dir, err::ScriptError, produce_script_error, test::{TestObject, TestSessionDir, TestSessionDirGroupScript, TestTmuxHomeDir}, }; use std::fs; #[test] fn create_session_script_success() -> CustomResult<()> { const SESSION_NAME: &str = "ne...
use super::*; use crate::options::Opts; use lib::{ dir::create_dir, err::ScriptError, produce_script_error, test::{TestObject, TestSessionDir, TestSessionDirGroupScript, TestTmuxHomeDir}, }; use std::fs; #[test] fn create_session_script_success() -> CustomResult<()> { const SESSION_NAME: &str = "ne...
#[test] fn create_session_directory_success() -> CustomResult<()> { let session_name = "new_session".to_owned(); let tsg_test = TestTmuxHomeDir::setup()?; let tsg_home_dir_path = tsg_test.test_tmuxsg_path; let s_dir_expected = PathBuf::from(&format!( "{}/{}", &tsg_home_dir_path.displ...
dy_exists() -> CustomResult<()> { let session_name = "test_session"; let tsg_test = TestSessionDir::setup()?; let session_dir = tsg_test.test_session_path; assert!(create_script(session_dir, session_name).is_err()); Ok(()) }
function_block-function_prefixed
[ { "content": "/// Creates the script and opens it in write-only mode.\n\npub fn create_script(session_dir: PathBuf, script_name: &str) -> CustomResult<File> {\n\n let script_path = session_dir.join(&format!(\"{}.sh\", script_name));\n\n\n\n if script_path.is_file() {\n\n produce_script_error!(forma...
Rust
db/tests/unit/collection_items.rs
taritom/bn-api
6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f
use db::dev::TestProject; use db::prelude::*; #[test] fn commit() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let even...
use db::dev::TestProject; use db::prelude::*; #[test] fn commit() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let even...
#[test] fn find() { let project = TestProject::new(); let conn = project.get_connection(); let user1 = project.create_user().finish(); let name1 = "Collection1"; let collection1 = Collection::create(name1, user1.id).commit(conn).unwrap(); let event1 = project.create_event().with_ticket_pricing...
t collection_item1_collectible2 = CollectionItem::create(collection1.id, collectible_id2).commit(conn); let collectible1_dup = CollectionItem::create(collection1.id, collectible_id1).commit(conn); assert!(collection_item1_collectible1.is_ok()); assert!(collection_item1_collectible2.is_ok()); assert!(co...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn commit() {\n\n let project = TestProject::new();\n\n let name = \"Name\";\n\n let connection = project.get_connection();\n\n let venue = Venue::create(name.clone(), None, \"America/Los_Angeles\".into())\n\n .commit(connection)\n\n .unwrap();\n\n let stage...
Rust
ciborium-ll/src/dec.rs
roman-kashitsyn/ciborium
b6d9ae284ece285011f48d7a70456d5d93da0cdc
use super::*; use ciborium_io::Read; #[derive(Debug)] pub enum Error<T> { Io(T), Syntax(usize), } impl<T> From<T> for Error<T> { #[inline] fn from(value: T) -> Self { Self::Io(value) } } pub struct Decoder<R: Read> { reader: R, offset: usize, bu...
use super::*; use ciborium_io::Read; #[derive(Debug)] pub enum Error<T> { Io(T), Syntax(usize), } impl<T> From<T> for Error<T> { #[inline] fn from(value: T) -> Self { Self::Io(value) } } pub struct Decoder<R: Read> { reader: R, offset: usize, bu...
} impl<R: Read> Decoder<R> { #[inline] fn pull_title(&mut self) -> Result<Title, Error<R::Error>> { if let Some(title) = self.buffer.take() { self.offset += title.1.as_ref().len() + 1; return Ok(title); } let mut prefix = [0u8; 1]; self.read_exact(&mut ...
rt!(self.buffer.is_none()); self.reader.read_exact(data)?; self.offset += data.len(); Ok(()) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn from_reader<'de, T: de::Deserialize<'de>, R: Read>(reader: R) -> Result<T, Error<R::Error>>\n\nwhere\n\n R::Error: core::fmt::Debug,\n\n{\n\n let mut scratch = [0; 4096];\n\n\n\n let mut reader = Deserializer {\n\n decoder: reader.into(),\n\n scratch: &mu...
Rust
kimchi/src/tests/lookup.rs
chee-chyuan/proof-systems
b883501b06375da79fc9965c1c17e02a72e9ded7
use super::framework::{print_witness, TestFramework}; use crate::circuits::{ gate::{CircuitGate, GateType}, lookup::{ runtime_tables::{RuntimeTable, RuntimeTableCfg, RuntimeTableSpec}, tables::LookupTable, }, polynomial::COLUMNS, wires::Wire, }; use ark_ff::Zero; use array_init::arra...
use super::framework::{print_witness, TestFramework}; use crate::circuits::{ gate::{CircuitGate, GateType}, lookup::{ runtime_tables::{RuntimeTable, RuntimeTableCfg, RuntimeTableSpec}, tables::LookupTable, }, polynomial::COLUMNS, wires::Wire, }; use ark_ff::Zero; use array_init::arra...
#[test] fn test_indexed_runtime_table() { runtime_table(5, true); } #[test] fn test_custom_runtime_table() { runtime_table(5, false); }
2, first_column: [8u32, 9, 8, 7, 1].into_iter().map(Into::into).collect(), } }; runtime_tables_setup.push(cfg); } let data: Vec<Fp> = [0u32, 2, 3, 4, 5].into_iter().map(Into::into).collect(); let runtime_tables: Vec<RuntimeTable<Fp>> = runtime_tables_setup ...
function_block-function_prefixed
[ { "content": "fn chacha_setup_bad_lookup(table_id: i32) {\n\n // circuit gates: one 'real' ChaCha0 and one 'fake' one.\n\n let gates = vec![\n\n GateType::ChaCha0,\n\n GateType::Zero,\n\n GateType::ChaCha0,\n\n GateType::Zero,\n\n ];\n\n let gates: Vec<CircuitGate<Fp>> = ...
Rust
crates/notion-core/src/distro/yarn.rs
acorncom/notion
6458f41a8c32b2e0618a6c4dd8eb5eca31ba0cd7
use std::fs::{rename, File}; use std::path::PathBuf; use std::string::ToString; use super::{Distro, Fetched}; use archive::{Archive, Tarball}; use distro::error::DownloadError; use distro::DistroVersion; use fs::ensure_containing_dir_exists; use inventory::YarnCollection; use path; use style::{progress_bar, Action};...
use std::fs::{rename, File}; use std::path::PathBuf; use std::string::ToString; use super::{Distro, Fetched}; use archive::{Archive, Tarball}; use distro::error::DownloadError; use distro::DistroVersion; use fs::ensure_containing_dir_exists; use inventory::YarnCollection; use path; use style::{progress_bar, Action};...
fn remote(version: Version, url: &str) -> Fallible<Self> { let distro_file_name = path::yarn_distro_file_name(&version.to_string()); let distro_file = path::yarn_inventory_dir()?.join(&distro_file_name); if distro_is_valid(&distro_file) { return YarnDistro::local(version,...
rmat!( "{}/v{}/{}", public_yarn_server_root(), version_str, distro_file_name ); YarnDistro::remote(version, &url) }
function_block-function_prefixed
[ { "content": "pub fn yarn_distro_file_name(version: &str) -> String {\n\n format!(\"{}.tar.gz\", yarn_archive_root_dir_name(version))\n\n}\n\n\n", "file_path": "crates/notion-core/src/path/mod.rs", "rank": 0, "score": 365902.2436720986 }, { "content": "pub fn node_distro_file_name(version...
Rust
src/clock_gettime.rs
GoCodeIT-Inc/cpu-time
d36927e013565bd3cf1a06813e45e764558cf30a
use std::io::{Result, Error}; use std::marker::PhantomData; use std::rc::Rc; use std::time::Duration; use libc::{clock_gettime, timespec}; use libc::{CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ProcessTime(Duration); #[derive(Copy, Clone, PartialE...
use std::io::{Result, Error}; use std::marker::PhantomData; use std::rc::Rc; use std::time::Duration; use libc::{clock_gettime, timespec}; use libc::{CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub struct ProcessTime(Duration); #[derive(Copy, Clone, PartialE...
pub fn now() -> Self { Self::try_now().expect("CLOCK_PROCESS_CPUTIME_ID unsupported") } pub fn try_elapsed(&self) -> Result<Duration> { Ok(Self::try_now()?.duration_since(*self)) } pub ...
pec { tv_sec: 0, tv_nsec: 0, }; if unsafe { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut time) } == -1 { return Err(Error::last_os_error()); } Ok(ProcessTime(Duration::new( time.tv_sec as u64, time.tv_nsec as u32, ...
function_block-function_prefixed
[ { "content": "fn to_duration(kernel_time: FILETIME, user_time: FILETIME) -> Duration {\n\n // resolution: 100ns\n\n let kns100 = ((kernel_time.dwHighDateTime as u64) << 32) + kernel_time.dwLowDateTime as u64;\n\n let uns100 = ((user_time.dwHighDateTime as u64) << 32) + user_time.dwLowDateTime as u64;\n...
Rust
cli/src/opts.rs
djKooks/Viceroy
6462271f1c9176f79ac059cc87bfdde61d65ac62
use { std::net::{IpAddr, Ipv4Addr}, std::{ net::SocketAddr, path::{Path, PathBuf}, }, structopt::StructOpt, viceroy_lib::Error, }; #[derive(Debug, StructOpt)] #[structopt(name = "viceroy", author)] pub struct Opts { #[structopt(long = "addr")] socket_addr: Option<Sock...
use { std::net::{IpAddr, Ipv4Addr}, std::{ net::SocketAddr, path::{Path, PathBuf}, }, structopt::StructOpt, viceroy_lib::Error, }; #[derive(Debug, StructOpt)] #[structopt(name = "viceroy", author)] pub struct Opts { #[structopt(long = "addr")] socket_addr: Option<Sock...
#[test] fn binary_format_is_accepted() -> TestResult { let args = &["dummy-program-name", &test_file("minimal.wasm")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } } }
s = &["dummy-program-name", &test_file("minimal.wat")]; match Opts::from_iter_safe(args) { Ok(_) => Ok(()), res => panic!("unexpected result: {:?}", res), } }
function_block-function_prefixed
[]
Rust
src/xor_repair.rs
sc2021anonym/slp-ec
e8afdff36311f4897f73b4e6c1593b8211e10282
use crate::bitmatrix::*; use crate::fast_repair::SortOrder; use crate::repair::{bitvec_distance, bitvec_xor}; use crate::slp::*; use crate::*; fn replace_by(m: &mut SLP, a: usize, b: usize, v: usize) { for i in 0..m.height() { if m[i][a] && m[i][b] { m[i][a] = false; m[i][b] = false...
use crate::bitmatrix::*; use crate::fast_repair::SortOrder; use crate::repair::{bitvec_distance, bitvec_xor}; use crate::slp::*; use crate::*; fn replace_by(m: &mut SLP, a: usize, b: usize, v: usize) { for i in 0..m.height() { if m[i][a] && m[i][b] { m[i][a] = false; m[i][b] = false...
candidates.push((i, j)); } Ordering::Less => { candidates = vec![(i, j)]; count_max = count; } _ => {} } } } match order { ...
which_var = Some(var); current_min = count; } } if let Some(var) = which_var { depends[valuation.num_of_original_constants() + var] = true; rest = bitvec_xor(&rest, &valuation[var]); } else { for idx in 0..rest.len() { ...
random
[ { "content": "fn execute_slp_rec(slp: &SLP, var: usize, valuation: &mut HashMap<usize, Vec<bool>>) {\n\n if valuation.contains_key(&var) {\n\n // already visited\n\n return;\n\n }\n\n\n\n let num_constants = slp.num_of_original_constants();\n\n let mut val: Vec<bool> = vec![false; num_...
Rust
netidx-netproto/src/glob.rs
dtolnay-contrib/netidx
40fd1189d0d6df684e3b575421186e135e9c3208
use anyhow::Result; use bytes::{Buf, BufMut}; use globset; use netidx_core::{ chars::Chars, pack::{Pack, PackError}, path::Path, pool::{Pool, Pooled}, utils, }; use std::{ cmp::{Eq, PartialEq}, ops::Deref, result, sync::Arc, }; use arcstr::ArcStr; #[derive(Debug, Clone, Copy, Partia...
use anyhow::Result; use bytes::{Buf, BufMut}; use globset; use netidx_core::{ chars::Chars, pack::{Pack, PackError}, path::Path, pool::{Pool, Pooled}, utils, }; use std::{ cmp::{Eq, PartialEq}, ops::Deref, result, sync::Arc, }; use arcstr::ArcStr; #[derive(Debug, Clone, Copy, Partia...
} } } } } pub fn new(raw: Chars) -> Result<Glob> { if !Path::is_absolute(&raw) { bail!("glob paths must be absolute") } let base = { let mut cur = "/"; let mut iter = Path::dirnames(&raw); ...
if utils::is_escaped(s, '\\', i) { s = &s[i + 1..]; } else { break true; }
if_condition
[ { "content": "pub fn is_escaped(s: &str, esc: char, i: usize) -> bool {\n\n let b = s.as_bytes();\n\n !s.is_char_boundary(i) || {\n\n let mut res = false;\n\n for j in (0..i).rev() {\n\n if s.is_char_boundary(j) && b[j] == (esc as u8) {\n\n res = !res;\n\n ...
Rust
src/vendor/h3c/reply.rs
jiegec/netconf-rs
ea67624060fcf7f1ff29e58d38bfbd010297c1c0
use serde_derive::Deserialize; #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct RpcReply { pub data: Data, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Data { pub top: Option<Top>, #[serde(rename = "netconf-state")] pub netconf_state: Option<NetconfState>, } #[derive(Debug, Deseri...
use serde_derive::Deserialize; #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct RpcReply { pub data: Data, } #[derive(Debug, Deserialize, PartialEq, Eq)] pub struct Data { pub top: Option<Top>, #[serde(rename = "netconf-state")] pub netconf_state: Option<NetconfState>, } #[derive(Debug, Deseri...
}
1, mac_address: String::from("12-34-56-78-90-AB"), port_index: 634, status: 2, aging: true }, ...
function_block-function_prefixed
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct Capabilities {\n\n pub capability: Vec<String>,\n\n}\n\n\n\n/// A connection to NETCONF server\n\npub struct Connection {\n\n pub(crate) transport: Box<dyn Transport + Send + 'static>,\n\n}\n\n\n\nimpl Connection {\n\n pub fn new(transport: impl Tra...
Rust
src/triple.rs
MattsSe/nom-sparql
c0ea67ba8c5aed5ebed46bb9f1bb6257c6c64d06
use nom::{ branch::alt, bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n}, character::complete::char, character::is_digit, combinator::map_res, combinator::{map, opt}, multi::{many0, many1, separated_nonempty_list}, sequence::{delimited, pair, separated_pa...
use nom::{ branch::alt, bytes::complete::{escaped, tag, tag_no_case, take_while1, take_while_m_n}, character::complete::char, character::is_digit, combinator::map_res, combinator::{map, opt}, multi::{many0, many1, separated_nonempty_list}, sequence::{delimited, pair, separated_pa...
assert_eq!(triples_template("(true())."), Ok(("", vec![nil.clone()]))); assert_eq!( triples_template("(true()).(true())"), Ok(("", vec![nil.clone(), nil.clone()])) ); assert_eq!( triples_template("(true()).[ a (),()\t] a false,()"), ...
let nil = TriplesSameSubject::Node { triples_node: TriplesNode::Collection(Collection(vec![ GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::BooleanLiteral(true))), GraphNode::VarOrTerm(VarOrTerm::Term(GraphTerm::Nil)), ])), property_list: None, ...
assignment_statement
[ { "content": "fn plx(i: &str) -> IResult<&str, &str> {\n\n recognize(alt((\n\n pair(tag(\"%\"), hex_primary),\n\n pair(tag(\"\\\\\"), recognize(one_of(\"_~.-!$&'()*+,;=/?#@%\"))),\n\n )))(i)\n\n}\n\n\n\npub(crate) fn pn_local(i: &str) -> IResult<&str, &str> {\n\n recognize(pair(\n\n ...
Rust
basis-universal/src/transcoding/transcoding_tests.rs
fintelia/basis-universal-rs
4a23939034479de8119d52fd0eb1737cad5e46ee
use super::*; #[test] fn test_get_bytes_per_block_or_pixel() { assert_eq!( TranscoderTextureFormat::BC1_RGB.bytes_per_block_or_pixel(), 8 ); } #[test] fn test_get_format_name() { assert_eq!(TranscoderTextureFormat::BC1_RGB.format_name(), "BC1_RGB"); } #[test] fn test_transcoder_format_has...
use super::*; #[test] fn test_get_bytes_per_block_or_pixel() { assert_eq!( TranscoderTextureFormat::BC1_RGB.bytes_per_block_or_pixel(), 8 ); } #[test] fn test_get_format_name() { assert_eq!(TranscoderTextureFormat::BC1_RGB.format_name(), "BC1_RGB"); } #[test] fn test_transcoder_format_has...
let _result = transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::RGBA32, TranscodeParameters { image_index: 0, level_index: 0, ..Default::default() }, ) .unwrap(); trans...
if transcoder.basis_texture_format(basis_file) == BasisTextureFormat::ETC1S { transcoder .transcode_image_level( basis_file, TranscoderTextureFormat::FXT1_RGB, TranscodeParameters { image_index: 0, level_index: 0...
if_condition
[ { "content": "#[test]\n\nfn bindgen_test_layout_Transcoder() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Transcoder>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Transcoder))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Transcoder>(),\n\n 8usize,\n\n ...
Rust
src/macros.rs
activeledger/SDK-Rust-TxBuilder
505e9a7a4b2240a08dcb01786bcf7d92d7f60a49
/* * MIT License (MIT) * Copyright (c) 2019 Activeledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use,...
/* * MIT License (MIT) * Copyright (c) 2019 Activeledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use,...
c![$($data)*] }; } #[macro_export] #[doc(hidden)] macro_rules! input_unexpected { () => {}; }
expr) => { $crate::PacketValue::Object($e) }; } #[macro_export] macro_rules! signees { [$({$streamid: expr => $key:expr}),+] => {{ let mut signees = $crate::Signees::new(); $( signees.add($key, $streamid); )* signees }}; ($key:expr) => {{ let m...
random
[ { "content": "# Activeledger - Transaction Helper\n\n\n\n<img src=\"https://www.activeledger.io/wp-content/uploads/2018/09/Asset-23.png\" alt=\"Activeledger\" width=\"300\"/>\n\n\n\nActiveledger is a powerful distributed ledger technology.\n\nThink about it as a single ledger, which is updated simultaneously in...
Rust
src/librand/distributions/normal.rs
oxidation/rust
f1bb6c2f46f08c1d7b6d695f5b3cf93142cb8860
use core::num::Float; use {Rng, Rand, Open01}; use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; #[derive(Copy)] pub struct StandardNormal(pub f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { ...
use core::num::Float; use {Rng, Rand, Open01}; use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; #[derive(Copy)] pub struct StandardNormal(pub f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(
} #[derive(Copy)] pub struct Normal { mean: f64, std_dev: f64, } impl Normal { pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev ...
x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let ...
function_block-function_prefixed
[ { "content": "/// Randomly sample up to `amount` elements from an iterator.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust\n\n/// use std::rand::{thread_rng, sample};\n\n///\n\n/// let mut rng = thread_rng();\n\n/// let sample = sample(&mut rng, 1..100, 5);\n\n/// println!(\"{:?}\", sample);\n\n/// ```\n\npub fn...
Rust
fuzzy_log_packets/src/storeables.rs
JLockerman/delos-rust
400a458c28524040b790e33f8e58809c60a948c5
use std::{mem, ptr, slice}; pub trait Storeable { fn size(&self) -> usize; unsafe fn ref_to_bytes(&self) -> &u8; unsafe fn ref_to_slice(&self) -> &[u8]; unsafe fn bytes_to_ref(&u8, usize) -> &Self; unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self; unsafe fn bytes_to_mut(&mut u8, usize)...
use std::{mem, ptr, slice}; pub trait Storeable { fn size(&self) -> usize; unsafe fn ref_to_bytes(&self) -> &u8; unsafe fn ref_to_slice(&self) -> &[u8]; unsafe fn bytes_to_ref(&u8, usize) -> &Self; unsafe fn slice_to_ref(val: &[u8], size: usize) -> &Self; unsafe fn bytes_to_mut(&mut u8, usize)...
pl<V> Storeable for [V] { fn size(&self) -> usize { mem::size_of::<V>() * self.len() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self.as_ptr()) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const _ as *const u8; let size = self.size(); ...
<Self as Storeable>::bytes_to_mut(bytes, size) } } impl<V> Storeable for V { fn size(&self) -> usize { mem::size_of::<Self>() } unsafe fn ref_to_bytes(&self) -> &u8 { mem::transmute(self) } unsafe fn ref_to_slice(&self) -> &[u8] { let ptr = self as *const V as *con...
random
[ { "content": "pub fn slice_to_multi(bytes: &mut [u8]) {\n\n bytes[0] = unsafe { ::std::mem::transmute(EntryKind::Multiput) };\n\n unsafe { debug_assert!(EntryContents::try_ref(bytes).is_ok()) }\n\n}\n\n\n", "file_path": "fuzzy_log_packets/src/lib.rs", "rank": 0, "score": 302795.3422425555 },...
Rust
crates/ra_ide_api_light/src/typing.rs
hdhoang/rust-analyzer
da3802b2ce4796461a9fff22f4e9c6fd890879b2
use ra_syntax::{ AstNode, SourceFile, SyntaxKind::*, SyntaxNode, TextUnit, TextRange, algo::{find_node_at_offset, find_leaf_at_offset, LeafAtOffset}, ast::{self, AstToken}, }; use crate::{LocalEdit, TextEditBuilder, formatting::leading_indent}; pub fn on_enter(file: &SourceFile, offset: TextUnit) -> O...
use ra_syntax::{ AstNode, SourceFile, SyntaxKind::*, SyntaxNode, TextUnit, TextRange, algo::{find_node_at_offset, find_leaf_at_offset, LeafAtOffset}, ast::{self, AstToken}, }; use crate::{LocalEdit, TextEditBuilder, formatting::leading_indent}; pub fn on_enter(file: &SourceFile, offset: TextUnit) -> O...
#[test] fn indents_middle_of_chain_call() { type_dot( r" fn source_impl() { let var = enum_defvariant_list().unwrap() <|> .nth(92) .unwrap(); } ", r" fn sourc...
fn indents_continued_chain_call() { type_dot( r" pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> { self.child_impl(db, name) .first() <|> } ", r" pub ...
function_block-full_function
[]
Rust
vm_control/src/client.rs
google/crosvm
df929efce3261ca5383f66eea6c7041b3439eb77
use crate::*; use base::{info, validate_raw_descriptor, RawDescriptor, Tube, UnixSeqpacket}; use remain::sorted; use thiserror::Error; use std::fs::OpenOptions; use std::num::ParseIntError; use std::path::{Path, PathBuf}; #[sorted] #[derive(Error, Debug)] enum ModifyBatError { #[error("{0}")] BatControlErr(...
use crate::*; use base::{info, validate_raw_descriptor, RawDescriptor, Tube, UnixSeqpacket}; use remain::sorted; use thiserror::Error; use std::fs::OpenOptions; use std::num::ParseIntError; use std::path::{Path, PathBuf}; #[sorted] #[derive(Error, Debug)] enum ModifyBatError { #[error("{0}")] BatControlErr(...
let request = VmRequest::BatCommand(type_, cmd); Ok(handle_request(&request, socket_path)?) } Err(e) => Err(ModifyBatError::BatControlErr(e)), }, Err(e) => Err(ModifyBatError::BatControlErr(e)), }; match response { Ok(response) => { ...
ryType>() { Ok(type_) => match BatControlCommand::new(property.to_string(), target.to_string()) { Ok(cmd) => {
function_block-random_span
[ { "content": "pub fn win32_wide_string(value: &str) -> Vec<u16> {\n\n OsStr::new(value).encode_wide().chain(once(0)).collect()\n\n}\n\n\n\n/// Returns the length, in u16 words (*not* UTF-16 chars), of a null-terminated u16 string.\n\n/// Safe when `wide` is non-null and points to a u16 string terminated by a...
Rust
glib/src/wrapper.rs
abdulrehman-git/gtk-rs
068311ececbb9d84e3697412e789add054f33f83
#[macro_export] macro_rules! glib_wrapper { ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, } ) => { $crate::glib_boxed_wrapp...
#[macro_export] macro_rules! glib_wrapper { ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $copy_expr:expr, free => |$free_arg:ident| $free_expr:expr, } ) => { $crate::glib_boxed_wrapp...
name, $ffi_class_name, @get_type $get_type_expr, @extends [], @implements [$($implements),+]); }; ( $(#[$attr:meta])* pub struct $name:ident(Object<$ffi_name:ty>) @extends $($extends:path),+, @implements $($implements:path),+; match fn { get_type => || $get...
=> { $crate::glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr, @free $free_arg $free_expr, @get_type $get_type_expr); }; ( $(#[$attr:meta])* pub struct $name:ident(Boxed<$ffi_name:ty>); match fn { copy => |$copy_arg:ident| $co...
random
[ { "content": "/// Same as [`set_prgname()`].\n\n///\n\n/// [`set_prgname()`]: fn.set_prgname.html\n\npub fn set_program_name(name: Option<&str>) {\n\n set_prgname(name)\n\n}\n\n\n", "file_path": "glib/src/utils.rs", "rank": 0, "score": 251826.54139678564 }, { "content": "pub fn accelerato...
Rust
src/parser/values.rs
ithinuel/async-gcode
0f7ee3efc4fa0023766e3f436472573ef1fb0f5b
#![allow(clippy::useless_conversion)] use futures::{Stream, StreamExt}; #[cfg(all(not(feature = "std"), feature = "string-value"))] use alloc::string::String; use crate::{ stream::PushBackable, types::{Literal, ParseResult}, utils::skip_whitespaces, Error, }; #[cfg(not(feature = "parse-expressions")...
#![allow(clippy::useless_conversion)] use futures::{Stream, StreamExt}; #[cfg(all(not(feature = "std"), feature = "string-value"))] use alloc::string::String; use crate::{ stream::PushBackable, types::{Literal, ParseResult}, utils::skip_whitespaces, Error, }; #[cfg(not(feature = "parse-expressions")...
async fn parse_real_literal<S, E>(input: &mut S) -> Option<ParseResult<f64, E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut b = try_result!(input.next()); let mut negativ = false; if b == b'-' || b == b'+' { negativ = b == b'-'; t...
pub(crate) async fn parse_number<S, E>(input: &mut S) -> Option<Result<(u32, u32), E>> where S: Stream<Item = Result<u8, E>> + Unpin + PushBackable<Item = u8>, { let mut n = 0; let mut order = 1; let res = loop { let b = match input.next().await? { Ok(b) => b, Err(e) => r...
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nenum Error {\n\n Io(std::io::Error),\n\n Parse(async_gcode::Error),\n\n}\n\nimpl From<async_gcode::Error> for Error {\n\n fn from(f: async_gcode::Error) -> Self {\n\n Self::Parse(f)\n\n }\n\n}\n", "file_path": "examples/cli.rs", "rank": 0, "score"...
Rust
core/src/snapshot_packager_service.rs
glottologist/solana
770bdec924481038ed93962bd79da6ccc0e799bf
use solana_gossip::cluster_info::{ClusterInfo, MAX_SNAPSHOT_HASHES}; use solana_runtime::{ snapshot_archive_info::SnapshotArchiveInfoGetter, snapshot_package::PendingSnapshotPackage, snapshot_utils, }; use solana_sdk::{clock::Slot, hash::Hash}; use std::{ sync::{ atomic::{AtomicBool, Ordering}, ...
use solana_gossip::cluster_info::{ClusterInfo, MAX_SNAPSHOT_HASHES}; use solana_runtime::{ snapshot_archive_info::SnapshotArchiveInfoGetter, snapshot_package::PendingSnapshotPackage, snapshot_utils, }; use solana_sdk::{clock::Slot, hash::Hash}; use std::{ sync::{ atomic::{AtomicBool, Ordering}, ...
cluster_info.push_snapshot_hashes(hashes.clone()); loop { if exit.load(Ordering::Relaxed) { break; } let snapshot_package = pending_snapshot_package.lock().unwrap().take(); if snapsh...
if let Some(starting_snapshot_hash) = starting_snapshot_hash { hashes.push(starting_snapshot_hash); }
if_condition
[ { "content": "#[cfg(feature = \"full\")]\n\npub fn new_rand<R: ?Sized>(rng: &mut R) -> Hash\n\nwhere\n\n R: rand::Rng,\n\n{\n\n let mut buf = [0u8; HASH_BYTES];\n\n rng.fill(&mut buf);\n\n Hash::new(&buf)\n\n}\n", "file_path": "sdk/src/hash.rs", "rank": 0, "score": 337905.97106482985 }...
Rust
src/client.rs
thallada/BazaarRealmClient
dffe435c5908045b4e20de01b01125b1f6d9fddf
use std::{ffi::CStr, ffi::CString, os::raw::c_char, path::Path}; use anyhow::Result; use log::LevelFilter; use reqwest::{blocking::Response, Url}; use uuid::Uuid; #[cfg(not(test))] use log::{error, info}; #[cfg(test)] use std::{println as info, println as error}; use crate::{ error::extract_error_from_response, ...
use std::{ffi::CStr, ffi::CString, os::raw::c_char, path::Path}; use anyhow::Result; use log::LevelFilter; use reqwest::{blocking::Response, Url}; use uuid::Uuid; #[cfg(not(test))] use log::{error, info}; #[cfg(test)] use std::{println as info, println as error}; use crate::{ error::extract_error_from_response, ...
#[no_mangle] pub extern "C" fn status_check(api_url: *const c_char) -> FFIResult<bool> { let api_url = unsafe { CStr::from_ptr(api_url) }.to_string_lossy(); info!("status_check api_url: {:?}", api_url); fn inner(api_url: &str) -> Result<()> { #[cfg(not(test))] let api_url = Url::parse(api...
r() { Some(mut log_dir) => { log_dir.push(Path::new( r#"My Games\Skyrim Special Edition\SKSE\BazaarRealmClient.log"#, )); match simple_logging::log_to_file(log_dir, LevelFilter::Info) { Ok(_) => true, Err(_) => false, ...
function_block-function_prefixed
[ { "content": "pub fn log_server_error(resp: Response) {\n\n let status = resp.status();\n\n if let Ok(text) = resp.text() {\n\n error!(\"Server error: {} {}\", status, text);\n\n }\n\n error!(\"Server error: {}\", status);\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn free_string(ptr: *mut ...
Rust
capsules/src/nrf51822_serialization.rs
jettr/tock
419f293f649989bf208af731f343886ff0fe3748
use core::cmp; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::hil; use kernel::hil::uart; use kernel::{ CommandReturn, Driver, ErrorCode, Grant, ProcessId, ReadOnlyProcessBuffer, ReadWriteProcessBuffer, ReadableProcessBuffer, WriteableProcessBuffer, }; use crate::driver; pub const DRIVER_N...
use core::cmp; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::hil; use kernel::hil::uart; use kernel::{ CommandReturn, Driver, ErrorCode, Grant, ProcessId, ReadOnlyProcessBuffer, ReadWriteProcessBuffer, ReadableProcessBuffer, WriteableProcessBuffer, }; use crate::driver; pub const DRIVER_N...
fn command( &self, command_type: usize, arg1: usize, _: usize, appid: ProcessId, ) -> CommandReturn { match command_type { 0 /* check if present */ => CommandReturn::suc...
e) }) .map_err(ErrorCode::from) } _ => Err(ErrorCode::NOSUPPORT), }; if let Err(e) = res { Err((slice, e)) } else { Ok(slice) } }
function_block-function_prefixed
[ { "content": "pub fn u16_to_network_slice(short: u16, slice: &mut [u8]) {\n\n slice[0] = (short >> 8) as u8;\n\n slice[1] = (short & 0xff) as u8;\n\n}\n", "file_path": "capsules/src/net/util.rs", "rank": 0, "score": 343884.3090572432 }, { "content": "/// This test should be called with...
Rust
engine/src/graphics/mod.rs
arcana-engine/arcana
e641ecfdf48c2844cf886834ad3aa981d3be7168
#[macro_export] macro_rules! vertex_location { ($offset:ident, $elem:ty as $semantics:literal) => { VertexLocation { format: <$elem as $crate::graphics::FormatElement>::FORMAT, semantics: $crate::graphics::Semantics::new($semantics), offset: { let offse...
#[macro_export] macro_rules! vertex_location { ($offset:ident, $elem:ty as $semantics:literal) => { VertexLocation { format: <$elem as $crate::graphics::FormatElement>::FORMAT, semantics: $crate::graphics::Semantics::new($semantics), offset: { let offse...
#[inline] #[tracing::instrument(skip(self, data))] pub fn upload_buffer<T>( &mut self, buffer: &Buffer, offset: u64, data: &[T], ) -> Result<(), OutOfMemory> where T: Pod, { self.uploader .upload_buffer(&self.device, buffer, offset, d...
pub fn create_surface( &self, window: &impl HasRawWindowHandle, ) -> Result<Surface, CreateSurfaceError> { self.device.graphics().create_surface(window) }
function_block-full_function
[ { "content": "pub trait FormatElement: Clone + Copy + Debug + Default + PartialEq + PartialOrd + Pod {\n\n const FORMAT: Format;\n\n}\n\n\n\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\n#[cfg_attr(feature = \"serde-1\", derive(serde::Serialize, serde::Deserialize))]\n\n#[cf...
Rust
15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.rs
TomaszWaszczyk/rust-raspberrypi-OS-tutorials
b1c438dc6693431885e597890daeb5536a991e0b
use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical, Virtual}, }; use core::intrinsics::unlikely; use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; struct MemoryManagementUnit; pub type Granule512MiB = TranslationGranu...
use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical, Virtual}, }; use core::intrinsics::unlikely; use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; struct MemoryManagementUnit; pub type Granule512MiB = TranslationGranu...
fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner ...
fn set_up_mair(&self) { MAIR_EL1.write( MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ...
function_block-full_function
[ { "content": "/// Return a reference to the MMU instance.\n\npub fn mmu() -> &'static impl memory::mmu::interface::MMU {\n\n &MMU\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// OS Interface Code\n\n//---------------------------------------------------------...
Rust
src/gens/csharp/mod.rs
fizruk/trans-gen
9a5b4635b39a18e9844a4bf40e8ca582fc3ffca2
use super::*; fn conv(name: &str) -> String { name.replace("Int32", "Int") .replace("Int64", "Long") .replace("Float32", "Float") .replace("Float64", "Double") .replace("Params", "Parameters") } pub struct Generator { main_namespace: String, files: HashMap<String, String>, ...
use super::*; fn conv(name: &str) -> String { name.replace("Int32", "Int") .replace("Int64", "Long") .replace("Float32", "Float") .replace("Float64", "Double") .replace("Params", "Parameters") } pub struct Generator { main_namespace: String, files: HashMap<String, String>, ...
}
let schema: &Schema = &schema; vec![File { path: "Runner.cs".to_owned(), content: include_templing!("src/gens/csharp/TcpReadWrite.cs.templing"), }] }
function_block-function_prefix_line
[ { "content": "fn struct_impl(definition: &Struct, base: Option<(&Name, usize)>) -> String {\n\n include_templing!(\"src/gens/python/struct_impl.templing\")\n\n}\n\n\n", "file_path": "src/gens/python/mod.rs", "rank": 0, "score": 497748.56248176645 }, { "content": "fn struct_impl(definition...
Rust
src/rust/grapl-observe/src/statsd_formatter.rs
alexjmacdonald/grapl
44d5fcabef02d11548018742c3dc00785ca7b571
use crate::metric_error::MetricError; use crate::metric_error::MetricError::{MetricInvalidCharacterError, MetricInvalidSampleRateError}; use crate::metric_reporter::TagPair; use lazy_static::lazy_static; use regex::Regex; use std::fmt::Write; lazy_static! { static ref INVALID_CHARS: Regex = Regex::new("[|#,=:]").u...
use crate::metric_error::MetricError; use crate::metric_error::MetricError::{MetricInvalidCharacterError, MetricInvalidSampleRateError}; use crate::metric_reporter::TagPair; use lazy_static::lazy_static; use regex::Regex; use std::fmt::Write; lazy_static! { static ref INVALID_CHARS: Regex = Regex::new("[|#,=:]").u...
#[test] fn test_statsd_format_tags() -> Result<(), MetricError> { let mut buf: String = String::with_capacity(256); statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, None, &make_tags(), )?; ...
fn test_statsd_format_specify_bad_rate() -> Result<(), String> { let mut buf: String = String::with_capacity(256); let result = statsd_format( &mut buf, VALID_STR, VALID_VALUE, MetricType::Counter, 1.5, &make_empty_tags(), )...
function_block-full_function
[ { "content": "/// Converts a Sysmon UTC string to UNIX Epoch time\n\n///\n\n/// If the provided string is not parseable as a UTC timestamp, an error is returned.\n\npub fn utc_to_epoch(utc: &str) -> Result<u64, Error> {\n\n let dt = NaiveDateTime::parse_from_str(utc, \"%Y-%m-%d %H:%M:%S%.3f\")?;\n\n\n\n l...
Rust
src/distribution/internal.rs
Twister915/statrs
c5536a8c916852259832b2064a9b845b68751c8f
pub fn is_valid_multinomial(arr: &[f64], incl_zero: bool) -> bool { let mut sum = 0.0; for &elt in arr { if incl_zero && elt < 0.0 || !incl_zero && elt <= 0.0 || elt.is_nan() { return false; } sum += elt; } sum != 0.0 } #[cfg(test)] pub mod tests { use super::i...
pub fn is_valid_multinomial(arr: &[f64], incl_zero: bool) -> bool { let mut sum = 0.0; for &elt in arr { if incl_zero && elt < 0.0 || !incl_zero && elt <= 0.0 || elt.is_nan() { return false; } sum += elt; } sum != 0.0 } #[cfg(test)] pub mod tests { use super::i...
fn check_sum_pmf_is_cdf<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>(dist: &D, x_max: u64) { let mut sum = 0.0; for i in 0..x_max + 3 { let prob = dist.pmf(i); assert!(prob >= 0.0); assert!(prob <= 1.0); sum += prob; i...
fn check_integrate_pdf_is_cdf<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>( dist: &D, x_min: f64, x_max: f64, step: f64, ) { let mut prev_x = x_min; let mut prev_density = dist.pdf(x_min); let mut sum = 0.0; loop { let x = prev_x + s...
function_block-full_function
[ { "content": "/// Computes the inverse of the regularized incomplete beta function\n\n//\n\n// This code is based on the implementation in the [\"special\"][1] crate,\n\n// which in turn is based on a [C implementation][2] by John Burkardt. The\n\n// original algorithm was published in Applied Statistics and is...
Rust
gensokyo/src/config/core/device.rs
Usami-Renko/hakurei
cccc69fe71d6efd75089d1c03c9c49fefde8e2ca
use toml; use serde_derive::Deserialize; use crate::config::engine::ConfigMirror; use crate::error::{ GsResult, GsError }; use gsvk::core::device::DeviceConfig; use gsvk::core::device::QueueRequestStrategy; use crate::utils::time::TimePeriod; use std::time::Duration; #[derive(Deserialize)] pub(crate) struct Devic...
use toml; use serde_derive::Deserialize; use crate::config::engine::ConfigMirror; use crate::error::{ GsResult, GsError }; use gsvk::core::device::DeviceConfig; use gsvk::core::device::QueueRequestStrategy; use crate::utils::time::TimePeriod; use std::time::Duration; #[derive(Deserialize)] pub(crate) struct Devic...
e = match time_out.as_str() { | "Infinite" => TimePeriod::Infinite, | "Immediate" => TimePeriod::Immediate, | "Timing" => TimePeriod::Time(Duration::from_millis(duration)), | _ => return Err(GsError::config(time_out)), }; Ok(time) }
e_name"))?.to_owned(); } if let Some(v) = v.get("device_api_version") { self.print_device_api = v.as_bool() .ok_or(GsError::config("core.device.print.device_api_version"))?.to_owned(); } if let Some(v) = v.get("device_type") { ...
random
[]
Rust
src/config.rs
meltinglava/rust-osauth
aef0567d48508d98686c7c000b62311564f691f6
use std::collections::HashMap; use std::env; use std::fs::File; use std::path::{Path, PathBuf}; use dirs; use log::warn; use serde::Deserialize; use serde_yaml; use super::identity::Password; use super::{Error, ErrorKind, Session}; use osproto::identity::IdOrName; #[derive(Debug, Deserialize)] struct Auth { a...
use std::collections::HashMap; use std::env; use std::fs::File; use std::path::{Path, PathBuf}; use dirs; use log::
r("OS_CLOUD") { from_config(cloud_name) } else { let auth_url = _get_env("OS_AUTH_URL")?; let user_name = _get_env("OS_USERNAME")?; let password = _get_env("OS_PASSWORD")?; let user_domain = env::var("OS_USER_DOMAIN_NAME").unwrap_or_else(|_| String::from("Default"...
warn; use serde::Deserialize; use serde_yaml; use super::identity::Password; use super::{Error, ErrorKind, Session}; use osproto::identity::IdOrName; #[derive(Debug, Deserialize)] struct Auth { auth_url: String, password: String, #[serde(default)] project_name: Option<String>, #[serde(default)] ...
random
[ { "content": "use log::{debug, trace};\n\nuse reqwest::header::HeaderMap;\n\nuse reqwest::r#async::{RequestBuilder, Response};\n\nuse reqwest::{Method, Url};\n\nuse serde::de::DeserializeOwned;\n\nuse serde::Serialize;\n\n\n\nuse super::cache;\n\nuse super::protocol::ServiceInfo;\n\nuse super::request;\n\nuse s...
Rust
src/query/iter/iter.rs
LechintanTudor/sparsey
024d4e7997172d6144f7ae59a255b20694ef3fa9
use crate::query::iter::{DenseIter, SparseIter}; use crate::query::{self, EntityIterator, Query}; use crate::storage::Entity; pub enum Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { Sparse(SparseIter<'a, G, I, E>), Dense(DenseIter<'a, G>), } impl<'a, G, I, E> Iter<'a...
use crate::query::iter::{DenseIter, SparseIter}; use crate::query::{self, EntityIterator, Query}; use crate::storage::Entity; pub enum Iter<'a, G, I, E> where G: Query<'a>, I: Query<'a>, E: Query<'a>, { Sparse(SparseIter<'a, G, I, E>), Dense(DenseIter<'a, G>), } impl<'a, G, I, E> Iter<'a...
; unsafe { Self::Sparse(SparseIter::new(entities, sparse, include, exclude, components)) } } } } pub fn is_sparse(&self) -> bool { matches!(self, Self::Sparse(_)) } pub fn is_dense(&self) -> bool { match...
match (get_entities, sparse_entities) { (Some(e1), Some(e2)) => { if e1.len() <= e2.len() { e1 } else { e2 } } (Some(e1), None) => e...
if_condition
[ { "content": "#[doc(hidden)]\n\npub trait EntityIterator: Iterator {\n\n fn next_with_entity(&mut self) -> Option<(Entity, Self::Item)>;\n\n\n\n fn fold_with_entity<B, F>(mut self, mut init: B, mut f: F) -> B\n\n where\n\n Self: Sized,\n\n F: FnMut(B, (Entity, Self::Item)) -> B,\n\n {\...
Rust
src/techblox/parsing_tools.rs
NGnius/libfj
2b1033449e50086c2768e3bbd4dafc0d5bb257f6
use std::io::{Read, Write}; use crate::techblox::Parsable; use half::f16; pub fn parse_header_u32(reader: &mut dyn Read) -> std::io::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) } pub fn parse_u8(reader: &mut dyn Read) -> std:...
use std::io::{Read, Write}; use crate::techblox::Parsable; use half::f16; pub fn parse_header_u32(reader: &mut dyn Read) -> std::i
pub fn parse_u8(reader: &mut dyn Read) -> std::io::Result<u8> { let mut u8_buf = [0; 1]; reader.read(&mut u8_buf)?; Ok(u8_buf[0]) } pub fn parse_u32(reader: &mut dyn Read) -> std::io::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) } pub fn...
o::Result<u32> { let mut u32_buf = [0; 4]; reader.read(&mut u32_buf)?; Ok(u32::from_le_bytes(u32_buf)) }
function_block-function_prefixed
[ { "content": "pub fn lookup_hashname(hash: u32, data: &mut dyn Read) ->\n\n std::io::Result<Box<dyn Block>> {\n\n Ok(match hash {\n\n 1357220432 /*StandardBlockEntityDescriptorV4*/ => Box::new(BlockEntity::parse(data)?),\n\n 2281299333 /*PilotSeatEntityDescriptorV4*/ => Box::new(PilotSeatEnt...
Rust
fork-off/src/fetching.rs
aleph-zero-foundation/aleph-node
7c4e6a4948e661cbe46d8957cf0e0eab901d8ed3
use std::{collections::HashMap, sync::Arc}; use crate::Storage; use futures::future::join_all; use log::info; use parking_lot::Mutex; use reqwest::Client; use serde_json::Value; use crate::types::{BlockHash, Get, StorageKey, StorageValue}; const KEYS_BATCH_SIZE: u32 = 1000; pub struct StateFetcher { client: Cli...
use std::{collections::HashMap, sync::Arc}; use crate::Storage; use futures::future::join_all; use log::info; use parking_lot::Mutex; use reqwest::Client; use serde_json::Value; use crate::types::{BlockHash, Get, StorageKey, StorageValue}; const KEYS_BATCH_SIZE: u32 = 1000; pub struct StateFetcher { client: Cli...
, output_guard.len()); } } info!("Worker {:?} finished", id); } async fn make_request<T: serde::de::DeserializeOwned>(&self, body: Value) -> T { make_request_and_parse_result::<T>(&self.client, &self.http_rpc_endpoint, body).await } pub async fn get_most_recent_bloc...
= output.lock(); output_guard.insert(key, value); if output_guard.len() % LOG_PROGRESS_FREQUENCY == 0 { info!("Fetched {} values"
function_block-random_span
[ { "content": "fn json_req(method: &str, params: Value, id: u32) -> Value {\n\n json!({\n\n \"method\": method,\n\n \"params\": params,\n\n \"jsonrpc\": \"2.0\",\n\n \"id\": id.to_string(),\n\n })\n\n}\n\n\n", "file_path": "aleph-client/src/rpc.rs", "rank": 0, "score...
Rust
src/language_features/hover.rs
jcai849/kak-lsp
9444ad4bcb7019c1ff34c2b2ac8493b0ff2aba08
use crate::context::*; use crate::markup::*; use crate::types::*; use crate::util::*; use itertools::Itertools; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use url::Url; pub fn text_document_hover(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = PositionParams::des...
use crate::context::*; use crate::markup::*; use crate::types::*; use crate::util::*; use itertools::Itertools; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use url::Url; pub fn text_document_hover(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = PositionParams::des...
}
fn plaintext(self) -> String { match self { MarkedString::String(contents) => contents, MarkedString::LanguageString(contents) => contents.value, } }
function_block-full_function
[ { "content": "pub fn text_document_formatting(meta: EditorMeta, params: EditorParams, ctx: &mut Context) {\n\n let params = FormattingOptions::deserialize(params)\n\n .expect(\"Params should follow FormattingOptions structure\");\n\n let req_params = DocumentFormattingParams {\n\n text_docum...
Rust
crates/storage/src/traits/impls/tuples.rs
tetcoin/ink
8609b374ed19d23a48382393caee8c02bcf5f86a
use crate::traits::{ KeyPtr, PackedLayout, SpreadLayout, }; use pro_primitives::Key; macro_rules! impl_layout_for_tuple { ( $($frag:ident),* $(,)? ) => { impl<$($frag),*> SpreadLayout for ($($frag),* ,) where $( $frag: SpreadLayout, )* {...
use crate::traits::{ KeyPtr, PackedLayout, SpreadLayout, }; use pro_primitives::Key; macro_rules! impl_layout_for_tuple { ( $($frag:ident),* $(,)? ) => { impl<$($frag),*> SpreadLayout for ($($frag),* ,) where $( $frag: SpreadLayout, )* {...
Default::default() ) ] ); }
); )* } fn clear_spread(&self, ptr: &mut KeyPtr) { #[allow(non_snake_case)] let ($($frag),*,) = self; $( <$frag as SpreadLayout>::clear_spread($frag, ptr); )* } fn pull_s...
random
[ { "content": "/// Asserts that the given `footprint` is below `FOOTPRINT_CLEANUP_THRESHOLD`.\n\nfn assert_footprint_threshold(footprint: u64) {\n\n let footprint_threshold = crate::traits::FOOTPRINT_CLEANUP_THRESHOLD;\n\n assert!(\n\n footprint <= footprint_threshold,\n\n \"cannot clean-up a...
Rust
crates/api/src/event/mouse.rs
michalsieron/orbtk
f0d53cd645f55f632173a89aee2fa85edbd9e96f
use std::rc::Rc; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, shell::MouseButton, utils::*, }; pub fn check_mouse_condition(mouse_position: Point, widget: &WidgetContainer<'_>) -> bool { let enabled = widget.get::<bool>("enabled"); if !enabled { return false; } ...
use std::rc::Rc; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, shell::MouseButton, utils::*, }; pub fn check_mouse_condition(mouse_position: Point, widget: &WidgetContainer<'_>) -> bool { let enabled = widget.get::<bool>("enabled"); if !enabled { return false; } ...
fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<MouseMoveEvent>() } } #[derive(IntoHandler)] pub struct ScrollEventHandler { handler: Rc<PositionHandlerFunction>, } impl EventHandler for ScrollEventHandler { fn handle_event(&self, state_context: &mut StatesContext, event:...
fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool { event .downcast_ref::<MouseMoveEvent>() .ok() .map_or(false, |event| (self.handler)(state_context, event.position)) }
function_block-full_function
[ { "content": "fn get_mouse_button(button: event::MouseButton) -> MouseButton {\n\n match button {\n\n event::MouseButton::Wheel => MouseButton::Middle,\n\n event::MouseButton::Right => MouseButton::Right,\n\n _ => MouseButton::Left,\n\n }\n\n}\n\n\n", "file_path": "crates/shell/sr...
Rust
day10/src/main.rs
jtempest/advent_of_code_2019-rs
d1da25c963428fe1d1cb8a26bf80cc777979c110
use aoc::geom::{Dimensions, Vector2D}; use std::collections::HashSet; use std::fmt; #[derive(Debug)] struct AsteroidField { asteroids: HashSet<Vector2D>, dimensions: Dimensions, } impl AsteroidField { fn new(input: &str) -> AsteroidField { let lines = input.trim().lines(); let dimensions...
use aoc::geom::{Dimensions, Vector2D}; use std::collections::HashSet; use std::fmt; #[derive(Debug)] struct AsteroidField { asteroids: HashSet<Vector2D>, dimensions: Dimensions, } impl AsteroidField { fn new(input: &str) -> AsteroidField { let lines = input.trim().lines(); let dimensions...
#[test] fn test_day10() { let (part1, part2) = day10(); assert_eq!(part1, 292); assert_eq!(part2, 317); } }
assert_eq!(order[99], Vector2D { x: 10, y: 16 }); assert_eq!(order[198], Vector2D { x: 9, y: 6 }); assert_eq!(order[199], Vector2D { x: 8, y: 2 }); assert_eq!(order[200], Vector2D { x: 10, y: 9 }); assert_eq!(order[298], Vector2D { x: 11, y: 1 }); }
function_block-function_prefix_line
[ { "content": "fn max_signal<R: Iterator<Item = i64>, F: Fn(&mut Amplifier) -> i64>(\n\n program: &Program,\n\n settings: R,\n\n run_func: F,\n\n) -> i64 {\n\n let num_settings = settings.size_hint().1.unwrap();\n\n (settings)\n\n .permutations(num_settings)\n\n .fold(0, |max, settin...
Rust
crates/server/src/ctrl/gateway/ready.rs
Lantern-chat/server
7dfc00130dd4f8ee6a7b9efac9b7866ebf067e6d
use futures::{StreamExt, TryStreamExt}; use hashbrown::{hash_map::Entry, HashMap}; use schema::Snowflake; use thorn::pg::Json; use crate::{ ctrl::{auth::Authorization, util::encrypted_asset::encrypt_snowflake_opt, Error, SearchMode}, permission_cache::PermMute, ServerState, }; pub async fn ready( sta...
use futures::{StreamExt, TryStreamExt}; use hashbrown::{hash_map::Entry, HashMap}; use schema::Snowflake; use thorn::pg::Json; use crate::{ ctrl::{auth::Authorization, util::encrypted_ass
async { crate::ctrl::party::emotes::get_custom_emotes_raw(&db, SearchMode::Many(&ids)) .await? .try_collect::<Vec<_>>() .await }, ) .await; let (roles, emotes) = (roles?, emotes?); for role...
et::encrypt_snowflake_opt, Error, SearchMode}, permission_cache::PermMute, ServerState, }; pub async fn ready( state: ServerState, conn_id: Snowflake, auth: Authorization, ) -> Result<sdk::models::events::Ready, Error> { use sdk::models::*; log::trace!("Processing Ready Event for {}", auth...
random
[ { "content": "pub fn gateway(route: Route<crate::ServerState>) -> Response {\n\n let addr = match real_ip::get_real_ip(&route) {\n\n Ok(addr) => addr,\n\n Err(_) => return ApiError::bad_request().into_response(),\n\n };\n\n\n\n let query = match route.query() {\n\n Some(Ok(query)) ...
Rust
src/db/model/stardust/block/output/nft.rs
grtlr/inx-chronicle
9d9da951b97c0db2c65b66eb87e0491c653863f3
use std::str::FromStr; use bee_block_stardust::output as bee; use serde::{Deserialize, Serialize}; use super::{Feature, NativeToken, OutputAmount, UnlockCondition}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct NftId(#[serde(with = "serde_bytes")] pub Box<[u8]>); ...
use std::str::FromStr; use bee_block_stardust::output as bee; use serde::{Deserialize, Serialize}; use super::{Feature, NativeToken, OutputAmount, UnlockCondition}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct NftId(#[serde(with = "serde_bytes")] pub Box<[u8]>); ...
.try_into() .unwrap(), get_test_metadata_block().try_into().unwrap(), get_test_tag_block().try_into().unwrap(), ]) .with_immutable_features(vec![ get_test_issuer_block(bee_test::rand::address::rand_addres...
llect::<Result<Vec<_>, _>>()?, ) .with_features( Vec::from(value.features) .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, _>>()?, ) .with_immutable_features( Vec::f...
random
[ { "content": "/// Spawn a tokio task. The provided name will be used to configure the task if console tracing is enabled.\n\npub fn spawn_task<F>(name: &str, task: F) -> tokio::task::JoinHandle<F::Output>\n\nwhere\n\n F: 'static + Future + Send,\n\n F::Output: 'static + Send,\n\n{\n\n log::trace!(\"Spa...
Rust
route-rs-runtime/src/link/primitive/output_channel_link.rs
scgruber/route-rs
8c8cd4b3376c1c394960184b419b05acf32e30a8
use crate::link::{Link, LinkBuilder, PacketStream}; use futures::prelude::*; use futures::task::{Context, Poll}; use std::pin::Pin; #[derive(Default)] pub struct OutputChannelLink<Packet> { in_stream: Option<PacketStream<Packet>>, channel_sender: Option<crossbeam::Sender<Packet>>, } impl<Packet> OutputChannel...
use crate::link::{Link, LinkBuilder, PacketStream}; use futures::prelude::*; use futures::task::{Context, Poll}; use std::pin::Pin; #[derive(Default)] pub struct OutputChannelLink<Packet> { in_stream: Option<PacketStream<Packet>>, channel_sender: Option<crossbeam::Sender<Packet>>, } impl<Packet> OutputChannel...
}
fn small_queue() { let packets = vec![0, 1, 2, 420, 1337, 3, 4, 5, 6, 7, 8, 9]; let mut runtime = initialize_runtime(); let results = runtime.block_on(async { let (send, recv) = crossbeam_channel::bounded::<i32>(2); let recv_thread = thread::spawn(move || { ...
function_block-full_function
[ { "content": "struct StreamFromChannel<Packet> {\n\n channel_receiver: crossbeam::Receiver<Packet>,\n\n}\n\n\n\nimpl<Packet> Unpin for StreamFromChannel<Packet> {}\n\n\n\nimpl<Packet> Stream for StreamFromChannel<Packet> {\n\n type Item = Packet;\n\n\n\n fn poll_next(self: Pin<&mut Self>, _cx: &mut Con...
Rust
libs/user-facing-errors/src/lib.rs
ever0de/prisma-engines
4c9d4edf238ad9c4a706eb5b7201ee0b4ebee93e
#![deny(warnings, rust_2018_idioms)] mod panic_hook; pub mod common; pub mod introspection_engine; pub mod migration_engine; #[cfg(feature = "sql")] pub mod quaint; pub mod query_engine; use serde::{Deserialize, Serialize}; use std::borrow::Cow; pub use panic_hook::set_panic_hook; pub trait UserFacingError: serde::...
#![deny(warnings, rust_2018_idioms)] mod panic_hook; pub mod common; pub mod introspection_engine; pub mod migration_engine; #[cfg(feature = "sql")] pub mod quaint; pub mod query_engine; use serde::{Deserialize, Serialize}; use std::borrow::Cow; pub use panic_hook::set_panic_hook; pub trait UserFacingError: serde::...
pub fn from_dyn_error(err: &dyn std::error::Error) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message: err.to_string(), backtrace: None, }), is_panic: false, } } pub fn new_in_panic_hook(panic_in...
pub fn new_non_panic_with_current_backtrace(message: String) -> Self { Error { inner: ErrorType::Unknown(UnknownError { message, backtrace: Some(format!("{:?}", backtrace::Backtrace::new())), }), is_panic: false, } }
function_block-full_function
[]
Rust
vm/src/atomic_ref.rs
jazz-lang/JazzLight
a0df2f6c19efdc1b640d40d4f5680900bee59dea
#![allow(unsafe_code)] #![deny(missing_docs)] use std::cell::UnsafeCell; use std::cmp; use std::fmt; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; use std::sync::atomic; use std::sync::atomic::AtomicU32; pub struct AtomicRefCell<T: ?Sized> { borrow: AtomicU32, value: UnsafeCell<T>, } impl<T> Atomic...
#![allow(unsafe_code)] #![deny(missing_docs)] use std::cell::UnsafeCell; use std::cmp; use std::fmt; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; use std::sync::atomic; use std::sync::atomic::AtomicU32; pub struct AtomicRefCell<T: ?Sized> { borrow: AtomicU32, value: UnsafeCell<T>, } impl<T> Atomic...
#[inline] pub fn as_ptr(&self) -> *mut T { self.value.get() } #[inline] pub fn get_mut(&mut self) -> &mut T { debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0); unsafe { &mut *self.value.get() } } } const HIGH_BIT:...
pub fn borrow_mut(&self) -> AtomicRefMut<T> { AtomicRefMut { value: unsafe { &mut *self.value.get() }, borrow: AtomicBorrowRefMut::new(&self.borrow), } }
function_block-full_function
[ { "content": "pub fn new_native_fn(x: fn(&[Value]) -> Result<Value, Value>, argc: i32) -> Value {\n\n Value::Function(Ref(Function {\n\n native: true,\n\n address: x as usize,\n\n env: Value::Null,\n\n module: None,\n\n argc,\n\n }))\n\n}\n\n\n", "file_path": "vm/src...
Rust
dao-contracts/tests/test_kyc_voter.rs
make-software/dao-contracts
aba3ed15d4c52ad411e6cd320f7daf1ef85715ac
use casper_dao_contracts::{ DaoOwnedNftContractTest, KycVoterContractTest, ReputationContractTest, VariableRepositoryContractTest, }; use casper_dao_utils::{Address, TestContract, TestEnv}; use casper_types::U256; use speculate::speculate; speculate! { use casper_types::U256; use casper_dao_utils::Erro...
use casper_dao_contracts::{ DaoOwnedNftContractTest, KycVoterContractTest, ReputationContractTest, VariableRepositoryContractTest, }; use casper_dao_utils::{Addre
get_kyc_token_address(), kyc_token.address() ) } context "applicant_is_not_kyced" { before { assert_eq!(kyc_token.balance_of(applicant), U256::zero()); } test "voting_creation_succeeds" { assert_eq!( ...
ss, TestContract, TestEnv}; use casper_types::U256; use speculate::speculate; speculate! { use casper_types::U256; use casper_dao_utils::Error; use std::time::Duration; use casper_dao_contracts::voting::VotingId; use casper_dao_contracts::voting::Choice; before { #[allow(unused_variabl...
random
[ { "content": "fn setup() -> (TestEnv, ReputationContractTest) {\n\n let env = TestEnv::new();\n\n let contract = ReputationContractTest::new(&env);\n\n\n\n (env, contract)\n\n}\n\n\n", "file_path": "dao-contracts/tests/test_reputation.rs", "rank": 0, "score": 26852.55778664241 }, { ...
Rust
rusoto/credential/src/container.rs
svenwb/rusoto
e7a7f7c123266d82ff5a97b757d328523ff8a3e2
use std::time::Duration; use async_trait::async_trait; use hyper::{Body, Request}; use crate::request::HttpClient; use crate::{ non_empty_env_var, parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials, }; const AWS_CREDENTIALS_PROVIDER_IP: &str = "169.254.170.2"; const...
use std::time::Duration; use async_trait::async_trait; use hyper::{Body, Request}; use crate::request::HttpClient; use crate::{ non_empty_env_var, parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials, }; const AWS_CREDENTIALS_PROVIDER_IP: &str = "169.254.170.2"; const...
fn new_request(uri: &str, env_var_name: &str) -> Result<Request<Body>, CredentialsError> { Request::get(uri).body(Body::empty()).map_err(|error| { CredentialsError::new(format!( "Error while parsing URI '{}' derived from environment variable '{}': {}", uri, env_var_name, error ...
e() { Ok(parsed_token) => { request.headers_mut().insert("authorization", parsed_token); } Err(err) => { return Err(CredentialsError::new(format!( "failed to pa...
function_block-function_prefixed
[ { "content": "#[inline]\n\n#[doc(hidden)]\n\npub fn encode_uri_path(uri: &str) -> String {\n\n utf8_percent_encode(uri, &STRICT_PATH_ENCODE_SET).collect::<String>()\n\n}\n\n\n", "file_path": "rusoto/signature/src/signature.rs", "rank": 1, "score": 339822.9463685929 }, { "content": "#[inli...
Rust
prost-derive/src/lib.rs
Max-Meldrum/prost
6f3c60f136be096194a3c6e0e77e25a9e1356669
#![doc(html_root_url = "https://docs.rs/prost-derive/0.6.1")] #![recursion_limit = "4096"] extern crate proc_macro; use anyhow::bail; use quote::quote; use anyhow::Error; use itertools::Itertools; use proc_macro::TokenStream; use proc_macro2::Span; use syn::{ punctuated::Punctuated, Data, DataEnum, DataStruct, ...
#![doc(html_root_url = "https://docs.rs/prost-derive/0.6.1")] #![recursion_limit = "4096"] extern crate proc_macro; use anyhow::bail; use quote::quote; use anyhow::Error; use itertools::Itertools; use proc_macro::TokenStream; use proc_macro2::Span; use syn::{ punctuated::Punctuated, Data, DataEnum, DataStruct, ...
_doc = format!("Returns `true` if `value` is a variant of `{}`.", ident); let from_i32_doc = format!( "Converts an `i32` to a `{}`, or `None` if `value` is not a valid variant.", ident ); let expanded = quote! { impl #ident { #[doc=#is_valid_doc] pub fn is_va...
iants { match fields { Fields::Unit => (), Fields::Named(_) | Fields::Unnamed(_) => { bail!("Enumeration variants may not have fields") } } match discriminant { Some((_, expr)) => variants.push((ident, expr)), None ...
function_block-random_span
[ { "content": "pub fn skip_field<B>(wire_type: WireType, tag: u32, buf: &mut B, ctx: DecodeContext) -> Result<(), DecodeError>\n\nwhere\n\n B: Buf,\n\n{\n\n ctx.limit_reached()?;\n\n let len = match wire_type {\n\n WireType::Varint => decode_varint(buf).map(|_| 0)?,\n\n WireType::ThirtyTwo...
Rust
src/page.rs
matthiasbeyer/elefren
04dbf66451e9d93be971f3409a05d2f8a14a6e04
use super::{deserialise_blocking, Mastodon, Result}; use crate::entities::itemsiter::ItemsIter; use hyper_old_types::header::{parsing, Link, RelationType}; use reqwest::{header::LINK, Response}; use serde::Deserialize; use url::Url; macro_rules! pages { ($($direction:ident: $fun:ident),*) => { $( ...
use super::{deserialise_blocking, Mastodon, Result}; use crate::entities::itemsiter::ItemsIter; use hyper_old_types::header::{parsing, Link, RelationType}; use reqwest::{header::LINK, Response}; use serde::Deserialize; use url::Url; macro_rules! pages { ($($direction:ident: $fun:ident),*) => { $( ...
if relations.contains(&RelationType::Prev) { prev = Some(Url::parse(value.link())?); } } } } Ok((prev, next)) }
if relations.contains(&RelationType::Next) { next = Some(Url::parse(value.link())?); }
if_condition
[ { "content": "fn get_links(response: &Response) -> Result<(Option<Url>, Option<Url>)> {\n\n let mut prev = None;\n\n let mut next = None;\n\n\n\n if let Some(link_header) = response.header(LINK) {\n\n let link_header = link_header.as_str();\n\n let link_header = link_header.as_bytes();\n\...
Rust
src/writers/syslog_writer.rs
ijackson/flexi_logger
674d0b8c9f8f8291b4a2a14f53fd84b40e71e788
use crate::deferred_now::DeferredNow; use crate::writers::log_writer::LogWriter; use std::cell::RefCell; use std::ffi::OsString; use std::io::Error as IoError; use std::io::Result as IoResult; use std::io::{BufWriter, ErrorKind, Write}; use std::net::{TcpStream, ToSocketAddrs, UdpSocket}; #[cfg(target_os = "linux")] us...
use crate::deferred_now::DeferredNow; use crate::writers::log_writer::LogWriter; use std::cell::RefCell; use std::ffi::OsString; use std::io::Error as IoError; use std::io::Result as IoResult; use std::io::{BufWriter, ErrorKind, Write}; use std::net::{TcpStream, ToSocketAddrs, UdpSocket}; #[cfg(target_os = "linux")] us...
et) => { socket.send(&message[..]) } } } fn flush(&mut self) -> IoResult<()> { match *self { #[cfg(target_os = "linux")] Self::Datagram(_) => Ok(()), #[cfg(target_os = "linux")] Self::Stream(ref mut w)...
tor>>, max_log_level: log::LevelFilter, } impl SyslogWriter { pub fn try_new( facility: SyslogFacility, determine_severity: Option<LevelToSyslogSeverity>, max_log_level: log::LevelFilter, ...
random
[ { "content": "fn number_infix(idx: u32) -> String {\n\n format!(\"_r{:0>5}\", idx)\n\n}\n\n\n", "file_path": "src/writers/file_log_writer.rs", "rank": 0, "score": 146125.11405953576 }, { "content": "#[cfg(feature = \"colors\")]\n\npub fn style<T>(level: log::Level, item: T) -> Paint<T> {\...
Rust
zircon-loader/src/lib.rs
Lincyaw/zCore
152733a670e5bec222349279de238e2f37bc4a97
#![no_std] #![feature(asm)] #![feature(global_asm)] #![deny(warnings, unused_must_use)] #[macro_use] extern crate alloc; #[macro_use] extern crate log; use { alloc::{boxed::Box, sync::Arc, vec::Vec}, kernel_hal::GeneralRegs, xmas_elf::ElfFile, zircon_object::{dev::*, ipc::*, object::*, task::*, util::...
#![no_std] #![feature(asm)] #![feature(global_asm)] #![deny(warnings, unused_must_use)] #[macro_use] extern crate alloc; #[macro_use] extern crate log; use { alloc::{boxed::Box, sync::Arc, vec::Vec}, kernel_hal::GeneralRegs, xmas_elf::ElfFile, zircon_object::{dev::*, ipc::*, object::*, task::*, util::...
flags ); match thread .proc() .vmar() .handle_page_fault(kernel_hal::fetch_fault_vaddr(), flags) { Ok(()) => {} Err(e) =>...
(&mut cx); let time = kernel_hal::timer_now().as_nanos() - tmp_time; thread.time_add(time); trace!("back from user: {:#x?}", cx); EXCEPTIONS_USER.add(1); #[cfg(target_arch = "aarch64")] match cx.trap_num { 0 => exit = handle_syscall...
function_block-random_span
[]
Rust
src/cargo/sources/registry/local.rs
quark-zju/cargo
62180bf27d83e1d8785b32bbe4d6f6fb07fff4bc
use crate::core::{InternedString, PackageId}; use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData}; use crate::util::errors::CargoResult; use crate::util::paths; use crate::util::{Config, Filesystem, Sha256}; use std::fs::File; use std::io::prelude::*; use std::io::SeekFrom; use std::path::Path; pub...
use crate::core::{InternedString, PackageId}; use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData}; use crate::util::errors::CargoResult; use crate::util::paths; use crate::util::{Config, Filesystem, Sha256}; use std::fs::File; use std::io::prelude::*; use std::io::SeekFrom; use std::path::Path; pub...
fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> { let crate_file = format!("{}-{}.crate", pkg.name(), pkg.version()); let path = self.root.join(&crate_file).into_path_unlocked(); let mut crate_file = File::open(&path)?; ...
fn update_index(&mut self) -> CargoResult<()> { let root = self.root.clone().into_path_unlocked(); if !root.is_dir() { anyhow::bail!("local registry path is not a directory: {}", root.display()) } let index_path = self.index_path.clone().into_path_u...
function_block-full_function
[ { "content": "/// Determines the root directory where installation is done.\n\npub fn resolve_root(flag: Option<&str>, config: &Config) -> CargoResult<Filesystem> {\n\n let config_root = config.get_path(\"install.root\")?;\n\n Ok(flag\n\n .map(PathBuf::from)\n\n .or_else(|| env::var_os(\"CAR...
Rust
src/power/battery-manager/battery-cli/src/commands.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { rustyline::{ completion::Completer, error::ReadlineError, highlight::Highlighter, hint::Hinter, Helper, }, std::{ borrow::Cow::{self, Borrowed, Owned}, fmt, str::FromStr, }, }; macro_rules! gen_commands { ($name:ident { $($variant:ident = ($val:expr, ...
use { rustyline::{ completion::Completer, error::ReadlineError, highlight::Highlighter, hint::Hinter, Helper, }, std::{ borrow::Cow::{self, Borrowed, Owned}, fmt, str::FromStr, }, }; macro_rules! gen_commands { ($name:ident { $($variant:ident = ($val:expr, ...
} impl Hinter for CmdHelper { fn hint(&self, line: &str, _pos: usize) -> Option<String> { let needs_space = !line.ends_with(" "); line.trim() .parse::<Command>() .map(|cmd| { format!("{}{}", if needs_space { " " } else { "" }, cmd.arguments().to_string(...
fn complete(&self, line: &str, _pos: usize) -> Result<(usize, Vec<String>), ReadlineError> { let mut variants = Vec::new(); for variant in Command::variants() { if variant.starts_with(line) { variants.push(variant) } } Ok((0, variants)) }
function_block-full_function
[]
Rust
bot/src/module/promotions.rs
Abendstolz/OxidizeBot
9c217e2c68bef0ff6e5ed9fb68aded6576d27186
use crate::auth; use crate::command; use crate::db; use crate::irc; use crate::module; use crate::prelude::*; use crate::utils; use chrono::Utc; pub struct Handler { enabled: settings::Var<bool>, promotions: injector::Ref<db::Promotions>, } #[async_trait] impl command::Handler for Handler { async fn handl...
use crate::auth; use crate::command; use crate::db; use crate::irc; use crate::module; use crate::prelude::*; use crate::utils; use chrono::Utc; pub struct Handler { enabled: settings::Var<bool>, promotions: injector::Ref<db::Promotions>, } #[async_trait] impl command::Handler for Handler { async fn handl...
>")?; let template = ctx.rest_parse("<name> <frequency> <template..>")?; promotions .edit(ctx.channel(), &name, frequency, template) .await?; respond!(ctx, "Edited promo."); } None | Some(..) => { ...
load().await { return Ok(()); } let promotions = match self.promotions.load().await { Some(promotions) => promotions, None => return Ok(()), }; let next = command_base!(ctx, promotions, "promotion", PromoEdit); match next.as_deref() { ...
function_block-random_span
[ { "content": "/// Extract a settings key from the context.\n\nfn key(ctx: &mut command::Context) -> Result<String> {\n\n let key = ctx.next().ok_or_else(|| respond_err!(\"Expected <key>\"))?;\n\n\n\n if key.starts_with(\"secrets/\") {\n\n respond_bail!(\"Cannot access secrets through chat!\");\n\n ...
Rust
system/kernel/src/mem/mm.rs
meg-os/maystorm
e1709de563f0d356898ad9681d29c630efea97e4
use super::slab::*; use crate::{ arch::cpu::Cpu, arch::page::*, sync::{fifo::EventQueue, semaphore::Semaphore}, system::System, task::scheduler::*, }; use alloc::{boxed::Box, sync::Arc}; use bitflags::*; use bootprot::*; use core::{ alloc::Layout, ffi::c_void, fmt::Write, mem::Mayb...
use super::slab::*; use crate::{ arch::cpu::Cpu, arch::page::*, sync::{fifo::EventQueue, semaphore::Semaphore}, system::System, task::scheduler::*, }; use alloc::{boxed::Box, sync::Arc}; use bitflags::*; use bootprot::*; use core::{ alloc::Layout, ffi::c_void, fmt::Write, mem::Mayb...
r: base | (size << 32), } } #[inline] pub fn alloc(&self, size: usize) -> Result<usize, ()> { let size = (size + Self::PAGE_SIZE - 1) / Self::PAGE_SIZE; let p: &AtomicU64 = unsafe { transmute(&self.inner) }; let mut data = p.load(Ordering::SeqCst); loop { ...
e: usize, size: usize) -> Self { let base = (base / Self::PAGE_SIZE) as u64; let size = (size / Self::PAGE_SIZE) as u64; Self { inne
function_block-random_span
[ { "content": "fn format_bytes(sb: &mut dyn Write, val: usize) -> core::fmt::Result {\n\n let kb = (val >> 10) & 0x3FF;\n\n let mb = (val >> 20) & 0x3FF;\n\n let gb = val >> 30;\n\n\n\n if gb >= 10 {\n\n // > 10G\n\n write!(sb, \"{:4}G\", gb)\n\n } else if gb >= 1 {\n\n // 1G~...
Rust
src/str/ascii.rs
LaudateCorpus1/ari
b01265230dec54b1608e6277d7be4b1a1957a11b
#[rustfmt::skip] pub trait AsciiExt { type Owned; fn is_ascii(&self) -> bool; fn to_ascii_uppercase(&self) -> Self::Owned; fn to_ascii_lowercase(&self) -> Self::Owned; fn eq_ignore_ascii_case(&self, other: &Self) -> bool; fn make_ascii_uppercase(&mut self); fn make_ascii_lowercase(&mut se...
#[rustfmt::skip] pub trait AsciiExt { type Owned; fn is_ascii(&self) -> bool; fn to_ascii_uppercase(&self) -> Self::Owned; fn to_ascii_lowercase(&self) -> Self::Owned; fn eq_ignore_ascii_case(&self, other: &Self) -> bool; fn make_ascii_uppercase(&mut self); fn make_ascii_lowercase(&mut se...
alphanumeric(&self) -> bool { self.iter().all(|b| b.is_ascii_alphanumeric()) } #[inline] fn is_ascii_digit(&self) -> bool { self.iter().all(|b| b.is_ascii_digit()) } #[inline] fn is_ascii_hexdigit(&self) -> bool { self.iter().all(|b| b.is_ascii_hexdigit()) } #[...
meric() } #[inline] fn is_ascii_digit (&self) -> bool { self.is_ascii_digit() } #[inline] fn is_ascii_hexdigit (&self) -> bool { self.is_ascii_hexdigit() } #[inline] fn is_ascii_punctuation (&self) -> bool { self.is_ascii_punctuation() } #[inline] fn is_ascii_graphic (&self)...
random
[ { "content": "/// returns true if `ari` has been initialized.\n\npub fn initialized() -> bool {\n\n INITIALIZED.state() != OnceState::Done\n\n}\n\n\n\n/// keep `x`, preventing llvm from optimizing it away.\n", "file_path": "src/core/mod.rs", "rank": 0, "score": 147101.8094612884 }, { "con...
Rust
arch/rv32i/src/syscall.rs
wjakobczyk/tock
af1efe87f3f52f9dc923f0ca936091f7681ce59a
use core::fmt::Write; use crate::csr::mcause; use kernel; use kernel::syscall::ContextSwitchReason; #[derive(Default)] #[repr(C)] pub struct Riscv32iStoredState { regs: [usize; 31], pc: usize, mcause: usize, mtval: usize, } const R_RA: usize = 0; cons...
use core::fmt::Write; use crate::csr::mcause; use kernel; use kernel::syscall::ContextSwitchReason; #[derive(Default)] #[repr(C)] pub struct Riscv32iStoredState { regs: [usize; 31], pc: usize, mcause: usize, mtval: usize, } const R_RA: usize = 0; cons...
unsafe fn set_syscall_return_value( &self, _stack_pointer: *const usize, state: &mut Self::StoredState, return_value: isize, ) { state.regs[R_A0] = return_value as usize; } unsafe fn set_process_function( &self, stack_pointer:...
unsafe fn initialize_process( &self, stack_pointer: *const usize, _stack_size: usize, state: &mut Self::StoredState, ) -> Result<*const usize, ()> { state.regs.iter_mut().for_each(|x| *x = 0); state.pc = 0; state.mcause = 0; ...
function_block-full_function
[ { "content": "/// State that is stored in each process's grant region to support IPC.\n\nstruct IPCData<const NUM_PROCS: usize> {\n\n /// An array of app slices that this application has shared with other\n\n /// applications.\n\n shared_memory: [Option<AppSlice<Shared, u8>>; NUM_PROCS],\n\n /// An ...
Rust
src/rtc0.rs
cvetaevvitaliy/nrf52840-pac
bf07243a5a043883d915999f0f8ccd6cbf6229b8
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start RTC COUNTER"] pub tasks_start: TASKS_START, #[doc = "0x04 - Stop RTC COUNTER"] pub tasks_stop: TASKS_STOP, #[doc = "0x08 - Clear RTC COUNTER"] pub tasks_clear: TASKS_CLEAR, #[doc = "0x0c - Set COUNTER to ...
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start RTC COUNTER"
top; #[doc = "Clear RTC COUNTER"] pub struct TASKS_CLEAR { register: ::vcell::VolatileCell<u32>, } #[doc = "Clear RTC COUNTER"] pub mod tasks_clear; #[doc = "Set COUNTER to 0xFFFFF0"] pub struct TASKS_TRIGOVRFLW { register: ::vcell::VolatileCell<u32>, } #[doc = "Set COUNTER to 0xFFFFF0"] pub mod tasks_trigovrfl...
] pub tasks_start: TASKS_START, #[doc = "0x04 - Stop RTC COUNTER"] pub tasks_stop: TASKS_STOP, #[doc = "0x08 - Clear RTC COUNTER"] pub tasks_clear: TASKS_CLEAR, #[doc = "0x0c - Set COUNTER to 0xFFFFF0"] pub tasks_trigovrflw: TASKS_TRIGOVRFLW, _reserved0: [u8; 240usize], #[doc = "0x10...
random
[ { "content": "#[doc = r\" Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\nimpl super::COUNTER {\n\n #[doc = r\" Reads the contents of the register\"]\n\n #[inline]\n\n pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\...
Rust
src/lexer.rs
mdlayher/monkey-rs
f7d7287a28c33c1cc833ffa0444405e5f5a3f04e
use crate::token::{Float, Integer, Radix, Token}; use std::error; use std::fmt; use std::num; use std::result; use std::str::FromStr; pub struct Lexer<'a> { input: &'a str, position: usize, read_position: usize, ch: char, } impl<'a> Lexer<'a> { pub fn new(input: &'a str) -> Self { ...
use crate::token::{Float, Integer, Radix, Token}; use std::error; use std::fmt; use std::num; use std::result; use std::str::FromStr; pub struct Lexer<'a> { input: &'a str, position: usize, read_position: usize, ch: char, } impl<'a> Lexer<'a> { pub fn new(input: &'a str) -> Self { ...
]' => Token::RightBracket, '"' => self.read_string()?, '\u{0000}' => Token::Eof, _ => { if is_letter(self.ch) { let ident = self.read_identifier(); if let Some(key) = lookup_keyword(&i...
pub fn lex(&mut self) -> Result<Vec<Token>> { let mut tokens = vec![]; loop { match self.next_token()? { t @ Token::Eof => { tokens.push(t); return Ok(tokens); } t => { t...
random
[ { "content": "fn compile(input: &str) -> Bytecode {\n\n let l = lexer::Lexer::new(input);\n\n\n\n let mut p = parser::Parser::new(l).expect(\"failed to create parser\");\n\n\n\n let prog = ast::Node::Program(p.parse().expect(\"failed to parse program\"));\n\n\n\n let mut c = Compiler::new();\n\n ...
Rust
runner/src/main.rs
Riey/gm-benchmark
afcabdebb82bdee9ab7fed69d46b3974ef44bff4
use ansi_term::Color; use anyhow::Context; use serde::{Deserialize, Serialize}; use std::fmt; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; use structopt::StructOpt; pub fn unknown_impl<T>(implementation: &str) -> anyhow::Result...
use ansi_term::Color; use anyhow::Context; use serde::{Deserialize, Serialize}; use std::fmt; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; use structopt::StructOpt; pub fn unknown_impl<T>(implementation: &str) -> anyhow::Result...
, other => return unknown_impl(other), }, LangType::Cpp => match implementation { "g++" | "clang++" => Some( Command::new(implementation) .current_dir(&opt.build_output) .stderr(Stdio::inherit())...
Some( Command::new("rustc") .current_dir(&opt.build_output) .stderr(Stdio::inherit()) .arg("-Ctarget-cpu=native") .arg("-Copt-level=2") .arg(program_path) ....
call_expression
[ { "content": "fn main() {\n\n let stdin = io::stdin();\n\n let stdin = stdin.lock();\n\n let mut stdin = BufReader::with_capacity(8196, stdin);\n\n let stdout = io::stdout();\n\n let stdout = stdout.lock();\n\n let mut stdout = BufWriter::with_capacity(8196, stdout);\n\n\n\n let source_leng...
Rust
core/bin/zksync_api/src/fee_ticker/mod.rs
vikkkko/zksyncM
e7376b09429f4d261e1038876f1ee9b1b8d26fc9
use std::collections::{HashMap, HashSet}; use bigdecimal::BigDecimal; use futures::{ channel::{mpsc::Receiver, oneshot}, StreamExt, }; use num::{ rational::Ratio, traits::{Inv, Pow}, BigUint, }; use serde::{Deserialize, Serialize}; use tokio::task::JoinHandle; use zksync_config::{FeeTickerOption...
use std::collections::{HashMap, HashSet}; use bigdecimal::BigDecimal; use futures::{ channel::{mpsc::Receiver, oneshot}, StreamExt, }; use num::{ rational::Ratio, traits::{Inv, Pow}, BigUint, }; use serde::{Deserialize, Serialize}; use tokio::task::JoinHandle; use zksync_config::{FeeTickerOption...
; self.api .get_last_quote(token) .await .map(|price| ratio_to_big_decimal(&(price.usd_price / factor), 100)) } async fn is_account_new(&mut self, address: Address) -> bool { self.info.is_account_new(address).await } async fn is_token_subs...
match request_type { TokenPriceRequestType::USDForOneWei => { let token_decimals = self.api.get_token(token.clone()).await?.decimals; BigUint::from(10u32).pow(u32::from(token_decimals)) } TokenPriceRequestType::USDForOneToken => BigUint::from(1u32), ...
if_condition
[ { "content": "/// Runs the massive API spam routine.\n\n///\n\n/// This process will continue until the cancel command is occurred or the limit is reached.\n\npub fn run(monitor: Monitor) -> (ApiTestsFuture, CancellationToken) {\n\n let cancellation = CancellationToken::default();\n\n\n\n let token = canc...
Rust
devolutions-gateway/src/rdp/sequence_future/post_mcs.rs
Devolutions/devolutions-gateway
80d83f7a07cd7a695f1f5ec30968efd59161b513
mod licensing; use std::io; use bytes::BytesMut; use ironrdp::mcs::SendDataContext; use ironrdp::rdp::server_license::LicenseEncryptionData; use ironrdp::{ClientInfoPdu, McsPdu, PduParsing, ShareControlHeader, ShareControlPdu}; use slog_scope::{debug, trace, warn}; use tokio::net::TcpStream; use tokio_rustls::TlsStre...
mod licensing; use std::io; use bytes::BytesMut; use ironrdp::mcs::SendDataContext; use ironrdp::rdp::server_license::LicenseEncryptionData; use ironrdp::{ClientInfoPdu, McsPdu, PduParsing, ShareControlHeader, ShareControlPdu}; use slog_scope::{debug, trace, warn}; use tokio::net::TcpStream; use tokio_rustls::TlsStre...
fn next_receiver(&self) -> NextStream { match self.sequence_state { SequenceState::ServerLicenseRequest | SequenceState::ServerChallenge | SequenceState::ServerUpgradeLicense | SequenceState::Finished => NextStream::Server, SequenceState::ServerDe...
e => NextStream::Server, SequenceState::Finished => panic!( "In RDP Connection Sequence, the future must not require a next sender in the Finished sequence state" ), } }
function_block-function_prefixed
[ { "content": "pub fn connect_as_server(mut stream: impl io::Write + io::Read, host: String) -> io::Result<Uuid> {\n\n let message = JetMessage::JetAcceptReq(JetAcceptReq {\n\n version: JET_VERSION_V1 as u32,\n\n host,\n\n association: Uuid::nil(),\n\n candidate: Uuid::nil(),\n\n ...
Rust
linkerd/app/outbound/src/target.rs
19h/linkerd2-proxy
20619fb1782216df515cd7927c764cfa58b6e46c
use linkerd_app_core::{ metrics, profiles, proxy::{ api_resolve::{ConcreteAddr, Metadata}, resolve::map_endpoint::MapEndpoint, }, svc::{self, stack::Param}, tls, transport, transport_header, Addr, Conditional, Error, }; use std::net::SocketAddr; #[derive(Copy, Clone)] pub struct End...
use linkerd_app_core::{ metrics, profiles, proxy::{ api_resolve::{ConcreteAddr, Metadata}, resolve::map_endpoint::MapEndpoint, }, svc::{self, stack::Param}, tls, transport, transport_header, Addr, Conditional, Error, }; use std::net::SocketAddr; #[derive(Copy, Clone)] pub struct End...
} impl<P> From<(ConcreteAddr, Logical<P>)> for Concrete<P> { fn from((resolve, logical): (ConcreteAddr, Logical<P>)) -> Self { Self { resolve, logical } } } impl<P> Param<ConcreteAddr> for Concrete<P> { fn param(&self) -> ConcreteAddr { self.resolve.clone() } } impl<P> Endpoint<P> { ...
ClientTls, ) -> impl Fn(Self) -> Result<svc::Either<Self, Endpoint<P>>, Error> + Copy { move |logical: Self| { let should_resolve = match logical.profile.as_ref() { Some(p) => { let p = p.borrow(); p.endpoint.is_none() && (p.name.is_some() ...
function_block-function_prefixed
[ { "content": "pub fn new<K: Eq + Hash + FmtLabels>(retain_idle: Duration) -> (Registry<K>, Report<K>) {\n\n let inner = Arc::new(Mutex::new(Inner::new()));\n\n let report = Report {\n\n metrics: inner.clone(),\n\n retain_idle,\n\n };\n\n (Registry(inner), report)\n\n}\n\n\n\n/// Implem...
Rust
src/lib.rs
zklapow/sbus
9ca73cb0d58d7a13db3d48103de5fdb51e6d9154
#![no_std] mod taranis; pub use taranis::TaranisX7SBusPacket; use arraydeque::{ArrayDeque, Wrapping}; const SBUS_FLAG_BYTE_MASK: u8 = 0b11110000; const SBUS_HEADER_BYTE: u8 = 0x0F; const SBUS_FOOTER_BYTE: u8 = 0b00000000; const SBUS_PACKET_SIZE: usize = 25; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Cl...
#![no_std] mod taranis; pub use taranis::TaranisX7SBusPacket; use arraydeque::{ArrayDeque, Wrapping}; const SBUS_FLAG_BYTE_MASK: u8 = 0b11110000; const SBUS_HEADER_BYTE: u8 = 0x0F; const SBUS_FOOTER_BYTE: u8 = 0b00000000; const SBUS_PACKET_SIZE: usize = 25; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Cl...
} fn is_flag_set(flag_byte: u8, idx: u8) -> bool { flag_byte & 1 << idx == 1 }
channels[14] = ((((data_bytes[20] >> 2) | (data_bytes[21] << 6)) as u16) & 0x07FF).into(); channels[15] = ((((data_bytes[21] >> 5) | (data_bytes[22] << 3)) as u16) & 0x07FF).into(); let flag_byte = self.buffer.pop_front().unwrap_or(0); return Some(SB...
function_block-function_prefix_line
[ { "content": "use crate::SBusPacket;\n\n\n\nconst X7_MIN: u16 = 172;\n\nconst X7_MAX: u16 = 1811;\n\nconst X7_RANGE: f32 = (X7_MAX - X7_MIN) as f32;\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TaranisX7SBusPacket {\n\n pub channels: [f32; 16],\n\n failsafe: bool,\n\n frame_lost: bool,\n\n}\n\n\n...
Rust
sdk/storage/src/file/share/mod.rs
elemount/azure-sdk-for-rust
ba0cc92ba5245f93ade4270aa54a897cc8f78d92
pub mod access_tier; pub mod requests; pub mod responses; use crate::parsing_xml::{cast_must, cast_optional, traverse}; use access_tier::AccessTier; use azure_core::headers::{ META_PREFIX, SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME, SHARE_PROVISIONED_EGRESS_MBPS, SHARE_PROVISIONED_INGRESS_MBPS, SHARE_PROVISIONED_...
pub mod access_tier; pub mod requests; pub mod responses; use crate::parsing_xml::{cast_must, cast_optional, traverse}; use access_tier::AccessTier; use azure_core::headers::{ META_PREFIX, SHARE_NEXT_ALLOWED_QUOTA_DOWNGRADE_TIME, SHARE_PROVISIONED_EGRESS_MBPS, SHARE_PROVISIONED_INGRESS_MBPS, SHARE_PROVISIONED_...
let provisioned_ingress_mbps = match headers.get(SHARE_PROVISIONED_INGRESS_MBPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, }; let provisioned_egress_mbps = match headers.get(SHARE_PROVISIONED_EGRESS_MBPS) { Some(value) => Some(va...
let provisioned_iops = match headers.get(SHARE_PROVISIONED_IOPS) { Some(value) => Some(value.to_str()?.parse::<u64>()?), None => None, };
assignment_statement
[]
Rust
dora/src/gc/swiper/sweep.rs
dinfuehr/dora
bcfdac576b729e2bbb2422d0239426b884059b2c
use parking_lot::Mutex; use scoped_threadpool::Pool; use std::sync::Arc; use crate::driver::cmd::Args; use crate::gc::root::{get_rootset, Slot}; use crate::gc::swiper::card::CardTable; use crate::gc::swiper::controller::{self, HeapConfig, SharedHeapConfig}; use crate::gc::swiper::crossing::CrossingMap; use crate::gc::...
use parking_lot::Mutex; use scoped_threadpool::Pool; use std::sync::Arc; use crate::driver::cmd::Args; use crate::gc::root::{get_rootset, Slot}; use crate::gc::swiper::card::CardTable; use crate::gc::swiper::controller::{self, HeapConfig, SharedHeapConfig}; use crate::gc::swiper::crossing::CrossingMap; use crate::gc::...
} impl Collector for SweepSwiper { fn supports_tlab(&self) -> bool { true } fn alloc_tlab_area(&self, _vm: &VM, _size: usize) -> Option<Region> { unimplemented!() } fn alloc(&self, vm: &VM, size: usize, array_ref: bool) -> Address { if size < LARGE_OBJECT_SIZE { ...
n(args.min_heap_size()); let mut config = HeapConfig::new(min_heap_size, max_heap_size); controller::init(&mut config, args); let card_size = mem::page_align((4 * max_heap_size) >> CARD_SIZE_BITS); let crossing_size = mem::page_align(max_heap_size >> CARD_SIZE_BITS)...
function_block-function_prefixed
[ { "content": "pub fn start(rootset: &[Slot], heap: Region, perm: Region, threadpool: &mut Pool) {\n\n let number_workers = threadpool.thread_count() as usize;\n\n let mut workers = Vec::with_capacity(number_workers);\n\n let mut stealers = Vec::with_capacity(number_workers);\n\n let injector = Injec...
Rust
src/p6/p6iv.rs
lukasl93/msp430fr5994
41eb5ada14476ab7b986f6b6f5c327d46e01b558
#[doc = "Reader of register P6IV"] pub type R = crate::R<u16, super::P6IV>; #[doc = "Writer for register P6IV"] pub type W = crate::W<u16, super::P6IV>; #[doc = "Register P6IV `reset()`'s with value 0"] impl crate::ResetValue for super::P6IV { type Type = u16; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register P6IV"] pub type R = crate::R<u16, super::P6IV>; #[doc = "Writer for register P6IV"] pub type W = crate::W<u16, super::P6IV>; #[doc = "Register P6IV `reset()`'s with value 0"] impl crate::ResetValue for super::P6IV { type Type = u16; #[inline(always)] fn reset_value() -> Self::Typ...
IV_A::P6IFG7) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x1f) | ((value as u16) & 0x1f); self.w } } impl R { #[doc = "Bits 0:4 - 4:0\\] Port 6 interrupt vector value"] #[inline...
} #[doc = "Interrupt Source: Port 6.5 interrupt; Interrupt Flag: P6IFG5"] #[inline(always)] pub fn p6ifg5(self) -> &'a mut W { self.variant(P6IV_A::P6IFG5) } #[doc = "Interrupt Source: Port 6.6 interrupt; Interrupt Flag: P6IFG6"] #[inline(always)] pub fn p6ifg6(self) -> &'a mut W {...
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
src/osm_io/o5m/varint.rs
Vadeen/vadeen_osm
80aa4f862ed7a9ee135e7e818a332a7650511976
use crate::osm_io::error::{Error, ErrorKind, Result}; use std::io::{Read, Write}; #[derive(Debug)] pub struct VarInt { bytes: Vec<u8>, } impl VarInt { pub fn new(bytes: Vec<u8>) -> Self { VarInt { bytes } } pub fn create_bytes<T: Into<VarInt>>(value: T) -> Vec<u8> { ...
use crate::osm_io::error::{Error, ErrorKind, Result}; use std::io::{Read, Write}; #[derive(Debug)] pub struct VarInt { bytes: Vec<u8>, } impl VarInt { pub fn new(bytes: Vec<u8>) -> Self { VarInt { bytes } } pub fn create_bytes<T: Into<VarInt>>(value: T) -> Vec<u8> { ...
; } let mut buf = [0u8; 1]; self.read_exact(&mut buf)?; let byte = buf[0]; bytes.push(byte); if byte & 0x80 == 0 { break; } } Ok(VarInt { bytes }) } } impl<R: Read + ?Sized> ReadVarInt for R {} pu...
Err(Error::new( ErrorKind::ParseError, Some("Varint overflow, read 9 bytes.".to_owned()), ))
call_expression
[ { "content": "/// Writer for the osm formats.\n\npub trait OsmWrite<W: Write> {\n\n fn write(&mut self, osm: &Osm) -> std::result::Result<(), Error>;\n\n\n\n fn into_inner(self: Box<Self>) -> W;\n\n}\n\n\n", "file_path": "src/osm_io.rs", "rank": 2, "score": 124140.17316385586 }, { "con...
Rust
src/nerve/github/response.rs
ustwo/github-issues
cc51621f3794d1172bb8bc333eb6be31f6736b61
use std::fmt; use hyper; use hyper::Client; use hyper::client::Response as HyperResponse; use hyper::header::{Headers, Accept, Authorization, Connection, UserAgent, qitem}; use regex::Regex; use rustc_serialize::json; use std::io::Read; use std::process; use say; use github; header! { (XRateLimitRemaining, "X-RateLim...
use std::fmt; use hyper; use hyper::Client; use hyper::client::Response as HyperResponse; use hyper::header::{Headers, Accept, Authorization, Connection, UserAgent, qitem}; use regex::Regex; use rustc_serialize::json; use std::io::Read; use std::process; use say; use github; header! { (XRateLimitRemaining, "X-RateLim...
} impl ResponseError { pub fn from_str(data: &str) -> Result<ResponseError, json::DecoderError> { json::decode(data) } } impl fmt::Display for ResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let error = self.errors.first().unwrap(); write!(f, "the ...
u32 { match headers.get() { Some(&XRateLimitRemaining(x)) => x, None => 0 } } pub fn warn_ratelimit(ratelimit: u32) { println!("{} {} {}", say::warn(), ratelimit, "Remaining requests"); } pub fn link(headers: &Headers) -> String { match headers.get() { Some(&Link(ref x)) => x.t...
random
[ { "content": "pub fn create(url: &str, token: &str, issue: &NewIssue) -> Result<Response, ResponseError> {\n\n let client = Client::new();\n\n let body = json::encode(issue).unwrap();\n\n\n\n let res = client.post(&*url.clone())\n\n .body(&body)\n\n .header(UserAge...
Rust
src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs
ohno418/rust
395a09c3dafe0c7838c9ca41d2b47bb5e79a5b6d
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_too...
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty, TypeAndMut}; use rustc_session::{declare_lint_pass, declare_too...
impl<'tcx> LateLintPass<'tcx> for SizeOfInElementCount { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = ...
fn get_pointee_ty_and_count_expr<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, ...
function_block-full_function
[]
Rust
tarpc/examples/pubsub.rs
tikue/tarpc
90bc7f741d8fc837ac436a5ac39cca13245fe558
use anyhow::anyhow; use futures::{ channel::oneshot, future::{self, AbortHandle}, prelude::*, }; use log::info; use publisher::Publisher as _; use std::{ collections::HashMap, io, net::SocketAddr, sync::{Arc, Mutex, RwLock}, }; use subscriber::Subscriber as _; use tarpc::{ client, cont...
use anyhow::anyhow; use futures::{ channel::oneshot, future::{self, AbortHandle}, prelude::*, }; use log::info; use publisher::Publisher as _; use std::{ collections::HashMap, io, net::SocketAddr, sync::{Arc, Mutex, RwLock}, }; use subscriber::Subscriber as _; use tarpc::{ client, cont...
} fn start_subscriber_gc( self, subscriber_addr: SocketAddr, client_dispatch: impl Future<Output = anyhow::Result<()>> + Send + 'static, subscriber_ready: oneshot::Receiver<()>, ) { tokio::spawn(async move { if let Err(e) = client_dispatch.await { ...
if let Ok(topics) = subscriber.topics(context::current()).await { self.clients.lock().unwrap().insert( subscriber_addr, Subscription { subscriber: subscriber.clone(), topics: topics.clone(), }, ); ...
if_condition
[ { "content": "/// The server end of an open connection with a client, streaming in requests from, and sinking\n\n/// responses to, the client.\n\n///\n\n/// The ways to use a Channel, in order of simplest to most complex, is:\n\n/// 1. [`Channel::execute`] - Requires the `tokio1` feature. This method is best fo...
Rust
src/parsers.rs
hoodie/sdp-nom
c0ffeea95aeed252ba1af2b8a04c570a0e75c942
#![allow(dead_code)] use nom::{ branch::alt, bytes::complete::{tag, take_while, take_while1}, character::{ complete::{multispace0, space1}, is_digit, }, combinator::{complete, map, map_res, opt}, error::ParseError, multi::many0, sequence::{delimited, preceded, separated_p...
#![allow(dead_code)] use nom::{ branch::alt, bytes::complete::{tag, take_while, take_while1}, character::{ complete::{multispace0, space1}, is_digit, }, combinator::{complete, map, map_res, opt}, error::ParseError, multi::many0, sequence::{delimited, preceded, separated_p...
(input) } pub fn read_everything(input: &str) -> IResult<&str, &str> { take_while(|c| c != '\n')(input) } pub fn read_string0(input: &str) -> IResult<&str, &str> { take_while(is_not_space)(input) } pub fn read_string(input: &str) -> IResult<&str, &str> { take_while1(is_not_space)(input) } pub fn read_no...
map_res( take_while1(|c: char| -> bool { c != ' ' && c != ':' && c != '/' }), |i: &str| (i).parse::<u64>(), )
call_expression
[ { "content": "pub fn rtpmap_line(input: &str) -> IResult<&str, RtpMap> {\n\n attribute(\n\n \"rtpmap\",\n\n map(\n\n tuple((\n\n read_number, // payload_typ\n\n preceded(multispace1, cowify(read_non_slash_string))...
Rust
lib/codegen/src/ir/types.rs
gmorenz/cretonne
bcf6a058841bde1f773e5a30bdaff71224d0b99a
use std::default::Default; use std::fmt::{self, Debug, Display, Formatter}; #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Type(u8); pub const VOID: Type = Type(0); const LANE_BASE: u8 = 0x70; const VECTOR_BASE: u8 = LANE_BASE + 16; include!(concat!(env!("OUT_DIR"), "/types.rs")); impl Type { ...
use std::default::Default; use std::fmt::{self, Debug, Display, Formatter}; #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Type(u8); pub const VOID: Type = Type(0); const LANE_BASE: u8 = 0x70; const VECTOR_BASE: u8 = LANE_BASE + 16; include!(concat!(env!("OUT_DIR"), "/types.rs")); impl Type { ...
pub fn log2_lane_bits(self) -> u8 { match self.lane_type() { B1 => 0, B8 | I8 => 3, B16 | I16 => 4, B32 | I32 | F32 => 5, B64 | I64 | F64 => 6, _ => 0, } } pub fn lane_bits(self) -> u8 { match self.l...
e { if self.0 < VECTOR_BASE { self } else { Type(LANE_BASE | (self.0 & 0x0f)) } }
function_block-function_prefixed
[ { "content": "/// Look for `key` in `table`.\n\n///\n\n/// The provided `hash` value must have been computed from `key` using the same hash function that\n\n/// was used to construct the table.\n\n///\n\n/// Returns `Ok(idx)` with the table index containing the found entry, or `Err(idx)` with the empty\n\n/// s...
Rust
src/command/mod.rs
rwjblue/notion
05b6b795a732602b7301e6b08a4353caa712c191
mod config; mod current; mod deactivate; mod fetch; mod help; mod install; mod shim; mod use_; mod version; pub(crate) use self::config::Config; pub(crate) use self::current::Current; pub(crate) use self::deactivate::Deactivate; pub(crate) use self::fetch::Fetch; pub(crate) use self::help::Help; pub(crate) use self::i...
mod config; mod current; mod deactivate; mod fetch; mod help; mod install; mod shim; mod use_; mod version; pub(crate) use self::config::Config; pub(crate) use self::current::Current; pub(crate) use self::deactivate::Deactivate; pub(crate) use self::fetch::Fetch; pub(crate) use self::help::Help; pub(crate) use self::i...
}
else { throw!(err.with_context(CliParseError::from_docopt)); } } } }
function_block-function_prefix_line
[]
Rust
token-lending/program/tests/borrow_obligation_liquidity.rs
panoptesDev/panoptis-program-library
fe410cc1081742ebdf09f22ad21eb8cc511f9918
#![cfg(feature = "test-bpf")] mod helpers; use helpers::*; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, pubkey::Pubkey, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, }; use spl_token_lending::{ error::LendingError, instruction::{bor...
#![cfg(feature = "test-bpf")] mod helpers; use helpers::*; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, pubkey::Pubkey, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, }; use spl_token_lending::{ error::LendingError, instruction::{bor...
test.set_bpf_compute_max_units(60_000); const FEE_AMOUNT: u64 = 5000; const HOST_FEE_AMOUNT: u64 = 1000; const USDC_DEPOSIT_AMOUNT_FRACTIONAL: u64 = 2_000 * FRACTIONAL_TO_USDC * INITIAL_COLLATERAL_RATIO; const PANO_BORROW_AMOUNT_LAMPORTS: u64 = 50 * LAMPORTS_TO_PANO; const USDC_...
let mut test = ProgramTest::new( "spl_token_lending", spl_token_lending::id(), processor!(process_instruction), );
assignment_statement
[ { "content": "fn check_fee_payer_balance(config: &Config, required_balance: u64) -> Result<(), Error> {\n\n let balance = config.rpc_client.get_balance(&config.fee_payer)?;\n\n if balance < required_balance {\n\n Err(format!(\n\n \"Fee payer, {}, has insufficient balance: {} required, {}...
Rust
libs/port_io/src/lib.rs
jacob-earle/Theseus
d53038328d1a39c69ffff6e32226394e8c957e33
#![feature(llvm_asm, const_fn_trait_bound)] #![no_std] use core::marker::PhantomData; #[cfg(any(target_arch="x86", target_arch="x86_64"))] mod x86; #[cfg(any(target_arch="x86", target_arch="x86_64"))] pub use x86::{inb, outb, inw, outw, inl, outl}; pub trait PortIn { unsafe fn port_in(port: u16) -> Self;...
#![feature(llvm_asm, const_fn_trait_bound)] #![no_std] use core::marker::PhantomData; #[cfg(any(target_arch="x86", target_arch="x86_64"))] mod x86; #[cfg(any(target_arch="x86", target_arch="x86_64"))] pub use x86::{inb, outb, inw, outw, inl, outl}; pub trait PortIn { unsafe fn port_in(port: u16) -> Self;...
pub unsafe fn write(&self, value: T) { T::port_out(self.port, value); } }
port_in(self.port) } } } #[derive(Debug)] pub struct PortWriteOnly<T: PortOut> { port: u16, _phantom: PhantomData<T>, } impl<T: PortOut> PortWriteOnly<T> { pub const fn new(port: u16) -> PortWriteOnly<T> { PortWriteOnly { port: port, _phantom: PhantomData } } pub const f...
random
[ { "content": "/// write data to the second ps2 data port and return the response\n\npub fn data_to_port2(value: u8) -> u8 {\n\n ps2_write_command(0xD4);\n\n data_to_port1(value)\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 0, "score": 298433.0900723853 }, { "content": "//...
Rust
src/app.rs
iamcodemaker/euca
00387b2e368231a3e0e25ebe0e63b951231cf61f
pub mod detach; pub mod model; pub mod dispatch; pub mod side_effect; pub mod application; pub use crate::app::detach::Detach; pub use crate::app::model::{Update, Render}; pub use crate::app::dispatch::Dispatcher; pub use crate::app::side_effect::{SideEffect, Processor, Commands}; pub use crate::app::application::{A...
pub mod detach; pub mod model; pub mod dispatch; pub mod side_effect; pub mod application; pub use crate::app::detach::Detach; pub use crate::app::model::{Update, Render}; pub use crate::app::dispatch::Dispatcher; pub use crate::app::side_effect::{SideEffect, Processor, Commands}; pub use crate::app::application::{A...
window .add_event_listener_with_callback(event, closure.as_ref().unchecked_ref()) .expect("failed to add event listener"); app_rc.borrow_mut().push_listener((event.to_string(), closure)); } for cmd in comman...
let closure = Closure::wrap( Box::new(move |_event| { let url = document.url() .expect_throw("couldn't get document url"); if let Some(msg) = router.route(&url) { dispatcher.dispatch(msg); ...
assignment_statement
[ { "content": "/// Some helpers to make testing a model easier.\n\npub trait Model<Message, Command> {\n\n /// Update a model with the given message.\n\n ///\n\n /// This function is a helper function designed to make testing models simpler. Normally during\n\n /// an update to a model, the `Commands...
Rust
world/src/consensus/ethash.rs
Fantom-foundation/fantom-rust-vm
a68fbe71f63365a8f3d05d2d84990e20a0bce45d
#![allow(dead_code)] #![allow(clippy::many_single_char_names)] use bigint_miner::{H256, H512, H64, U256}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use sha3::{Digest, Keccak256, Keccak512}; use std::ops::BitXor; use super::miller_rabin::is_prime; const DATASET_BYTES_INIT: usize = 1_073_741_824; co...
#![allow(dead_code)] #![allow(clippy::many_single_char_names)] use bigint_miner::{H256, H512, H64, U256}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use sha3::{Digest, Keccak256, Keccak512}; use std::ops::BitXor; use super::miller_rabin::is_prime; const DATASET_BYTES_INIT: usize = 1_073_741_824; co...
pub fn mine( header: &block::Header, full_size: usize, dataset: &[u8], nonce_start: H64, difficulty: U256, ) -> (H64, H256) { let target = cross_boundary(difficulty); let header = rlp::encode(header).to_vec(); let mut nonce_current = nonce_start; loop { let (_, result) = h...
pub fn cross_boundary(val: U256) -> U256 { if val <= U256::one() { U256::max_value() } else { ((U256::one() << 255) / val) << 1 } }
function_block-full_function
[ { "content": "fn mod_exp(mut x: usize, mut d: usize, n: usize) -> usize {\n\n let mut ret: usize = 1;\n\n while d != 0 {\n\n if d % 2 == 1 {\n\n ret = mod_mul(ret, x, n)\n\n }\n\n d /= 2;\n\n x = mod_sqr(x, n);\n\n }\n\n ret\n\n}\n\n\n", "file_path": "world...
Rust
src/request.rs
auula/poem
b3d15f83e994389b97ccd614d9361d48e3730002
use std::{ any::Any, convert::{TryFrom, TryInto}, sync::Arc, }; use crate::{ body::Body, error::{Error, ErrorBodyHasBeenTaken, Result}, http::{ header::{self, HeaderMap, HeaderName, HeaderValue}, Extensions, Method, Uri, Version, }, route_recognizer::Params, web::Coo...
use std::{ any::Any, convert::{TryFrom, TryInto}, sync::Arc, }; use crate::{ body::Body, error::{Error, ErrorBodyHasBeenTaken, Result}, http::{ header::{self, HeaderMap, HeaderName, HeaderValue}, Extensions, Method, Uri, Version, }, route_recognizer::Params, web::Coo...
HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<Error>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<Error>, { Self(self.0.and_then(move |mut parts| { let key = <HeaderName as TryFrom<K>>::try_from(key).map_err(Into::into)?; ...
body: Option<Body>, state: RequestState, } impl Request { pub(crate) fn from_hyper_request(req: hyper::Request<hyper::Body>) -> Result<Self> { let (parts, body) = req.into_parts(); let mut cookie_jar = ::cookie::CookieJar::new(); for header in parts.headers.get_all(header...
random
[]
Rust
datafusion/src/datasource/memory.rs
andts/arrow-datafusion
1c39f5ce865e3e1225b4895196073be560a93e82
use futures::StreamExt; use std::any::Any; use std::sync::Arc; use arrow::datatypes::SchemaRef; use arrow::record_batch::RecordBatch; use async_trait::async_trait; use crate::datasource::TableProvider; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::logical_pla...
use futures::StreamExt; use std::any::Any; use std::sync::Arc; use arrow::datatypes::SchemaRef; use arrow::record_batch::RecordBatch; use async_trait::async_trait; use crate::datasource::TableProvider; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::logical_pla...
pub async fn load( t: Arc<dyn TableProvider>, batch_size: usize, output_partitions: Option<usize>, runtime: Arc<RuntimeEnv>, ) -> Result<Self> { let schema = t.schema(); let exec = t.scan(&None, batch_size, &[], None).await?; let partition_count = e...
pub fn try_new(schema: SchemaRef, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> { if partitions .iter() .flatten() .all(|batches| schema.contains(&batches.schema())) { Ok(Self { schema, batches: partitions, ...
function_block-full_function
[]
Rust
src/utils/random.rs
xiangminghu/native_spark
f6199cce8ec546b9f16e14b7d098801f28b08018
use std::any::Any; use std::rc::Rc; use downcast_rs::Downcast; use rand::{Rng, SeedableRng}; use rand_distr::{Bernoulli, Distribution, Poisson}; use rand_pcg::Pcg64; use crate::{Data, Deserialize, Serialize}; const DEFAULT_MAX_GAP_SAMPLING_FRACTION: f64 = 0.4; const RNG_EPSILON: f64 = 5e-11; const ROUNDING_EPSILON...
use std::any::Any; use std::rc::Rc; use downcast_rs::Downcast; use rand::{Rng, SeedableRng}; use rand_distr::{Bernoulli, Distribution, Poisson}; use rand_pcg::Pcg64; use crate::{Data, Deserialize, Serialize}; const DEFAULT_MAX_GAP_SAMPLING_FRACTION: f64 = 0.4; const RNG_EPSILON: f64 = 5e-11; const ROUNDING_EPSILON...
= 1e-10; pub(super) fn get_upper_bound(delta: f64, n: u64, fraction: f64) -> f64 { let gamma = -delta.log(std::f64::consts::E) / n as f64; let max = MIN_SAMPLING_RATE .max(fraction + gamma + (gamma * gamma + 2.0 * gamma * fraction).sqrt()); max.min(1.0) } }
vec![] } }) .collect() } }) } } #[derive(Clone, Serialize, Deserialize)] pub(crate) struct BernoulliSampler { fraction: f64, } impl BernoulliSampler { pub fn new(fraction: f64) -> BernoulliSampler ...
random
[ { "content": "pub trait ShuffleDependencyTrait: Serialize + Deserialize + Send + Sync {\n\n fn get_shuffle_id(&self) -> usize;\n\n // fn get_partitioner(&self) -> &dyn PartitionerBox;\n\n fn is_shuffle(&self) -> bool;\n\n fn get_rdd_base(&self) -> Arc<dyn RddBase>;\n\n fn do_shuffle_task(&self...
Rust
crates/wast/src/ast/memory.rs
peterhuene/wasm-tools
bb96b2431f01e5a0e7c83fb1f6bcb08ccb8cb073
use crate::ast::{self, kw}; use crate::parser::{Lookahead1, Parse, Parser, Peek, Result}; #[derive(Debug)] pub struct Memory<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub exports: ast::InlineExport<'a>, pub kind:...
use crate::ast::{self, kw}; use crate::parser::{Lookahead1, Parse, Parser, Peek, Result}; #[derive(Debug)] pub struct Memory<'a> { pub span: ast::Span, pub id: Option<ast::Id<'a>>, pub name: Option<ast::NameAnnotation<'a>>, pub exports: ast::InlineExport<'a>, pub kind:...
} #[derive(Debug)] #[allow(missing_docs)] pub enum DataVal<'a> { String(&'a [u8]), Integral(Vec<u8>), } impl DataVal<'_> { pub fn len(&self) -> usize { match self { DataVal::String(s) => s.len(), DataVal::Integral(s) => s.len(), } } pub fn p...
fn parse(parser: Parser<'a>) -> Result<Self> { let span = parser.parse::<kw::data>()?.0; let id = parser.parse()?; let name = parser.parse()?; let kind = if parser.peek::<kw::passive>() { parser.parse::<kw::passive>()?; DataKind::Passive ...
function_block-full_function
[ { "content": "/// Construct a dummy memory for the given memory type.\n\npub fn dummy_memory<T>(store: &mut Store<T>, ty: MemoryType) -> Result<Memory> {\n\n Memory::new(store, ty)\n\n}\n", "file_path": "crates/fuzz-stats/src/dummy.rs", "rank": 0, "score": 415256.02069778426 }, { "content...
Rust
http/src/request/channel/invite/create_invite.rs
dawn-rs/dawn
294f80cc0ab556925c53bb6cf8d1297e150f49bc
use crate::{ client::Client, error::Error as HttpError, request::{self, AuditLogReason, Request, TryIntoRequest}, response::ResponseFuture, routing::Route, }; use serde::Serialize; use twilight_model::{ id::{ marker::{ApplicationMarker, ChannelMarker, UserMarker}, Id, }, ...
use crate::{ client::Client, error::Error as HttpError, request::{self, AuditLogReason, Request, TryIntoRequest}, response::ResponseFuture, routing::Route, }; use serde::Serialize; use twilight_model::{ id::{ marker::{ApplicationMarker, ChannelMarker, UserMarker}, Id, }, ...
lidationError> { if let Err(source) = validate_invite_max_age(max_age) { return Err(source); } self.fields.max_age = Some(max_age); Ok(self) } ...
none")] target_type: Option<TargetType>, #[serde(skip_serializing_if = "Option::is_none")] unique: Option<bool>, } #[must_use = "requests must be configured and executed"] pub struct CreateInvite<'a> { channel_id: Id<ChannelMarker>, fields: CreateInviteFields, http: &'a Client, reason: Opti...
random
[ { "content": "struct PresenceVisitor(Id<GuildMarker>);\n\n\n\nimpl<'de> Visitor<'de> for PresenceVisitor {\n\n type Value = Presence;\n\n\n\n fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n f.write_str(\"Presence struct\")\n\n }\n\n\n\n fn visit_map<M: MapAccess<'de>>(self, map:...
Rust
src/cli/src/cluster/install/tls.rs
simlay/fluvio
a42283200e667223d3a52b217d266db8927db4eb
use std::path::PathBuf; use tracing::debug; use structopt::StructOpt; use fluvio::config::{TlsPolicy, TlsPaths}; use std::convert::TryFrom; use crate::CliError; #[derive(Debug, StructOpt)] pub struct TlsOpt { #[structopt(long)] pub tls: bool, #[structopt(long)] pub domain: Option<String>, ...
use std::path::PathBuf; use tracing::debug; use structopt::StructOpt; use fluvio::config::{TlsPolicy, TlsPaths}; use std::convert::TryFrom; use crate::CliError; #[derive(Debug, StructOpt)] pub struct TlsOpt { #[structopt(long)] pub tls: bool, #[structopt(long)] pub domain: Option<String>, ...
d, TlsPolicy::Disabled)); } let policies = (|| -> Option<(TlsPolicy, TlsPolicy)> { let domain = opt.domain?; let ca_cert = opt.ca_cert?; let client_cert = opt.client_cert?; let client_key = opt.client_key?; let server_cert = opt.serve...
: Option<PathBuf>, } impl TryFrom<TlsOpt> for (TlsPolicy, TlsPolicy) { type Error = CliError; fn try_from(opt: TlsOpt) -> Result<Self, Self::Error> { if !opt.tls { debug!("no optional tls"); return Ok((TlsPolicy::Disable
random
[ { "content": "#[derive(Debug, StructOpt)]\n\nstruct VersionCmd {}\n\n\n", "file_path": "src/cli/src/root_cli.rs", "rank": 0, "score": 78096.27395499004 }, { "content": "#[derive(Debug, StructOpt)]\n\nstruct CompletionOpt {\n\n #[structopt(long, default_value = \"fluvio\")]\n\n name: St...
Rust
eventually-redis/tests/store.rs
J3A/eventually-rs
866a471479a8c2781966339287a4e57ca9838b38
use std::sync::Arc; use eventually::inmemory::Projector; use eventually::store::{Expected, Persisted, Select}; use eventually::sync::RwLock; use eventually::{EventStore, EventSubscriber, Projection}; use eventually_redis::{Builder, EventStore as RedisEventStore}; use async_trait::async_trait; use futures::stream::Tr...
use std::sync::Arc; use eventually::inmemory::Projector; use eventually::store::{Expected, Persisted, Select}; use eventually::sync::RwLock; use eventually::{EventStore, EventSubscriber, Projection}; use eventually_redis::{Builder, EventStore as RedisEventStore}; use async_trait::async_trait; use futures::stream::Tr...
mat!("redis://127.0.0.1:{}/", node.get_host_port(6379).unwrap()); let client = redis::Client::open(dsn).expect("failed to connect to Redis"); let events_count: usize = 3; let builder = Builder::new(client) .stream_page_size(128) .source_name("test-stream"); let builder_clone = builder...
function_block-function_prefixed
[ { "content": "#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n\nenum Event {\n\n A,\n\n B,\n\n C,\n\n}\n\n\n\n#[tokio::test]\n\nasync fn different_types_can_share_id() {\n\n let docker = testcontainers::clients::Cli::default();\n\n let postgres_image = testcontainers::images::post...