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
cli/src/commands/contract.rs
LeonLi000/toCKB
fcd07d5454518676d1f396d882ac51865187056f
use super::types::{ContractArgs, ContractSubCommand}; use anyhow::{anyhow, Result}; use ckb_sdk::{Address, AddressPayload, HttpRpcClient, HumanCapacity, SECP256K1}; use ckb_types::core::TransactionView; use ckb_types::packed::{Script, ScriptReader}; use ckb_types::prelude::Entity; use molecule::prelude::Reader; use std...
use super::types::{ContractArgs, ContractSubCommand}; use anyhow::{anyhow, Result}; use ckb_sdk::{Address, AddressPayload, HttpRpcClient, HumanCapacity, SECP256K1}; use ckb_types::core::TransactionView; use ckb_types::packed::{Script, ScriptReader}; use ckb_types::prelude::Entity; use molecule::prelude::Reader; use std...
?; let tx = sign(unsigned_tx, &mut rpc_client, &from_privkey).unwrap(); log::info!( "tx: \n{}", serde_json::to_string_pretty(&ckb_jsonrpc_types::TransactionView::from(tx.clone())) .unwrap() ); if args.wait_for_committed { send_tx_sync(&mut rpc_client, &tx, 60).map_err...
contract_tx_generator( args.config_path.clone(), args.rpc_url.clone(), args.indexer_url.clone(), args.tx_fee.clone(), from_lockscript, args.subcmd, )
call_expression
[ { "content": "// Get max mature block number\n\npub fn get_max_mature_number(rpc_client: &mut HttpRpcClient) -> Result<u64, String> {\n\n let tip_epoch = rpc_client\n\n .get_tip_header()\n\n .map(|header| EpochNumberWithFraction::from_full_value(header.inner.epoch.0))?;\n\n let tip_epoch_num...
Rust
src/ui.rs
devzbysiu/cleaboard
0d49db95ef2193f97c9018df806a8f643d431d51
use crate::keyboard::Keyboard; use crate::state::State; use druid::widget::{Button, Flex, Label}; use druid::{Env, Widget, WidgetExt}; use log::error; pub(crate) fn ui_builder(keyboard: impl Keyboard) -> impl Widget<State> { let header = Label::new(|state: &State, _env: &Env| state.log_text()) .with_text_s...
use crate::keyboard::Keyboard; use crate::state::State; use druid::widget::{Button, Flex, Label}; use druid::{Env, Widget, WidgetExt}; use log::error; pub(crate) fn ui_builder(keyboard: impl Keyboard) -> impl Widget<State> { let header = Label::new(|state: &State, _env: &Env| state.log_text()) .with_text_s...
#[cfg(test)] mod test { use super::*; use anyhow::{anyhow, Result}; #[derive(Debug, Clone, Copy)] struct ErrorKeyboardStub; impl Keyboard for ErrorKeyboardStub { fn turn_on(&self) -> Result<()> { Err(anyhow!("error stub")) } fn turn_off(&self) -> Result<()> {...
fn turn_off_keyboard(state: &mut State, keyboard: &impl Keyboard) { let res = keyboard.turn_off(); if res.is_err() { error!("failed to turn off the keyboard: {:?}", res); state.err_msg("Error while turning off keyboard"); } }
function_block-full_function
[ { "content": "fn main() -> Result<(), PlatformError> {\n\n pretty_env_logger::init();\n\n let err_msg = match check_xinput() {\n\n Ok(()) => None,\n\n Err(e) => Some(format!(\"{}\", e)),\n\n };\n\n let main_window = WindowDesc::new(ui_builder(PcKeyboard::new()?))\n\n .title(\"Cl...
Rust
src/bcossdk/bcos_ssl_native.rs
FISCO-BCOS/rust-sdk-gears
62457200d5e233acd9d2a0cf7968658d1bb869b5
/* FISCO BCOS/rust-SDK is a rust client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) FISCO BCOS/rust-SDK is free software: you can redistribute it and/or modify it under the terms of the MIT License as published by the Free Software Foundation. This project is distributed in the hope that it will be usefu...
/* FISCO BCOS/rust-SDK is a rust client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) FISCO BCOS/rust-SDK is free software: you can redistribute it and/or modify it under the terms of the MIT License as published by the Free Software Foundation. This project is distributed in the hope that it will be usefu...
return pathstr.to_string(); } pub fn openlib() -> Result<Library, KissError> { unsafe { let lib_fullpath = BcosNativeTlsClient::locate_lib_path(); let res = Library::new(lib_fullpath.as_str()); ...
ult<i32, KissError> { unsafe { let func_connect: Symbol<FUNC_SSOCK_TRY_CONNECT> = self .ssocklib .as_ref() .unwrap() .nativelib .get(b"ssock_try_connect") .unwrap(); let r = func_connect( ...
random
[ { "content": "type IBcosChannelImpl = Arc<Mutex<dyn IBcosChannel + Send + Sync>>;\n\n\n\n/// 对channel协议的组装和解析,同步异步调用是共通的,封装在BcosChannelClient\n\npub struct BcosChannelClient {\n\n pub channelimpl: IBcosChannelImpl,\n\n pub config: ChannelConfig,\n\n pub bufferqueue: BufferQueue,\n\n pub channelpackp...
Rust
etc/commenter/src/main.rs
raehik/stackage
5d4ad030c87f10abdb43d1a05926c5d44e1cadf2
use std::collections::HashMap; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; use structopt::StructOpt; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package...
use std::collections::HashMap; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; use structopt::StructOpt; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package...
(*h.entry(header).or_insert_with(Vec::new)).push(( package.to_owned(), version.to_owned(), component.to_owned(), )); } fn is_reg_match(s: &str, r: &Regex) -> bool { r.captures(s).is_some() }
} # tried {package}-{version}, but its *{component}* {cause}", cause = match header { Header::Versioned { package, version } => format!( "does not support: {package}-{version}", package = package, version = version ), Header::Mi...
random
[ { "content": "pub fn add(lib: Vec<String>, test: Vec<String>, bench: Vec<String>) {\n\n handle(true, |loc, mut lines| {\n\n lines.extend(match loc {\n\n Location::Lib => lib.clone(),\n\n Location::Test => test.clone(),\n\n Location::Bench => bench.clone(),\n\n }...
Rust
tests/parallel/setup.rs
baszalmstra/salsa
38e708b68b17bcd32081ddc394be30d2fd56cd25
use crate::signal::Signal; use salsa::Database; use salsa::ParallelDatabase; use salsa::Snapshot; use std::cell::Cell; use std::sync::Arc; #[salsa::query_group(Par)] pub(crate) trait ParDatabase: Knobs + salsa::ParallelDatabase { #[salsa::input] fn input(&self, key: char) -> usize; fn sum(&self, key: &'st...
use crate::signal::Signal; use salsa::Database; use salsa::ParallelDatabase; use salsa::Snapshot; use std::cell::Cell; use std::sync::Arc; #[salsa::query_group(Par)] pub(crate) trait ParDatabase: Knobs + salsa::ParallelDatabase { #[salsa::input] fn input(&self, key: char) -> usize; fn sum(&self, key: &'st...
fn snapshot_me(db: &impl ParDatabase) { db.snapshot(); } #[salsa::database(Par)] #[derive(Default)] pub(crate) struct ParDatabaseImpl { runtime: salsa::Runtime<ParDatabaseImpl>, knobs: KnobsStruct, } impl Database for ParDatabaseImpl { fn salsa_runtime(&self) -> &salsa::Runtime<Self> { ...
fn sum3_drop_sum(db: &impl ParDatabase, key: &'static str) -> usize { if db.knobs().sum3_drop_sum_should_panic.get() { panic!("sum3_drop_sum executed") } db.sum2_drop_sum(key) }
function_block-full_function
[ { "content": "/// We have to falvors of cancellation: based on unwindig and based on anon\n\n/// reads. This checks both,\n\nfn check_cancelation(f: impl Fn(CancelationFlag)) {\n\n f(CancelationFlag::Panic);\n\n f(CancelationFlag::SpecialValue);\n\n}\n\n\n\n/// Add test where a call to `sum` is cancelled ...
Rust
worker/src/gcp/mod.rs
openquery-io/parallax
0ddcdd82ba21f3b1e6b41ff0d07fcb567a637147
use serde::{Deserialize, Serialize}; use hyper::{client::connect::HttpConnector, Body, Request, Response, StatusCode}; use hyper_tls::HttpsConnector; use yup_oauth2::GetToken; use http::{ header::{HeaderValue, AUTHORIZATION}, method::Method, uri::Uri, }; use futures::compat::Future01CompatExt; use future...
use serde::{Deserialize, Serialize}; use hyper::{client::connect::HttpConnector, Body, Request, Response, StatusCode}; use hyper_tls::HttpsConnector; use yup_oauth2::GetToken; use http::{ header::{HeaderValue, AUTHORIZATION}, method::Method, uri::Uri, }; use futures::compat::Future01CompatExt; use future...
et_allow_from_metadata(false) .build() .expect("invalid GCP credentials") } pub fn mk_client() -> Client<impl GetToken> { let gcp_client = Client::new(mk_connector()); gcp_client } }
_runtime<O>(oauth: &mut O) -> Result<Token> where O: GetToken, { let (tx, rx) = channel::<Token>(); hyper_legacy::rt::run({ oauth .token(vec!["https://www.googleapis.com/auth/cloud-platform"]) .map(move |token| { tx.send(token); }) .ma...
random
[ { "content": "/// Creates a request with metadata from an old request\n\nfn map_meta<F, T>(from: &Request<F>, inner: T) -> Request<T> {\n\n let mut to = Request::new(inner);\n\n for kv in from.metadata().iter() {\n\n match kv {\n\n KeyAndValueRef::Ascii(key, value) => {\n\n ...
Rust
delicate-scheduler/src/actions/user.rs
Oodachi/delicate
f9025e4d6d844da319cbc2f511550902abbd8905
use super::prelude::*; pub(crate) fn config(cfg: &mut web::ServiceConfig) { cfg.service(create_user) .service(show_users) .service(update_user) .service(delete_user) .service(login_user) .service(logout_user) .service(check_user); } #[post("/api/user/create")] async ...
use super::prelude::*; pub(crate) fn config(cfg: &mut web::ServiceConfig) { cfg.service(create_user) .service(show_users) .service(update_user) .service(delete_user) .service(login_user) .service(logout_user) .service(check_user); } #[post("/api/user/create")] async ...
async fn logout_user(session: Session) -> HttpResponse { HttpResponse::Ok().json({ session.clear(); UnifiedResponseMessages::<()>::success() }) }
function_block-full_function
[ { "content": "pub fn get_encrypted_certificate_by_raw_certificate(certificate: &str) -> String {\n\n let encrypted_certificate_digest = digest(&SHA256, certificate.as_bytes());\n\n\n\n hex::encode(encrypted_certificate_digest.as_ref())\n\n}\n\n\n\n#[derive(Queryable, Identifiable, AsChangeset, Debug, Clon...
Rust
src/valueref.rs
SreeniIO/quickjs_es_runtime
a765180d98829e73705d66eb5cbe866e30f28948
use crate::quickjs_utils::{arrays, errors, functions, primitives, promises}; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use hirofa_utils::js_utils::adapters::JsValueAdapter; use hirofa_utils::js_utils::facades::JsValueType; use hirofa_utils::js_utils::JsError; use libquickjs_sys as q; use std::hash::{Ha...
use crate::quickjs_utils::{arrays, errors, functions, primitives, promises}; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use hirofa_utils::js_utils::adapters::JsValueAdapter; use hirofa_utils::js_utils::facades::JsValueType; use hirofa_utils::js_utils::JsError; use libquickjs_sys as q; use std::hash::{Ha...
ef { #[allow(dead_code)] pub(crate) fn label(&mut self, label: &str) { self.label = label.to_string() } } impl Clone for JSValueRef { fn clone(&self) -> Self { Self::new( self.context, self.value, true, true, format!("clone of ...
ms)] pub struct JSValueRef { pub(crate) context: *mut q::JSContext, value: q::JSValue, ref_ct_decr_on_drop: bool, label: String, } impl Hash for JSValueRef { fn hash<H: Hasher>(&self, state: &mut H) { let self_u = self.value.u; if self.is_i32() || self.is_bool() { unsafe...
random
[ { "content": "pub fn to_bool(value_ref: &JSValueRef) -> Result<bool, JsError> {\n\n if value_ref.is_bool() {\n\n let r = value_ref.borrow_value();\n\n let raw = unsafe { r.u.int32 };\n\n let val: bool = raw > 0;\n\n Ok(val)\n\n } else {\n\n Err(JsError::new_str(\"value i...
Rust
src/gpio/gpio_pin13.rs
ducktec/esp32c3
64b9547e200a3ee7e6587d81178be8732e99bee9
#[doc = "Reader of register GPIO_PIN13"] pub type R = crate::R<u32, super::GPIO_PIN13>; #[doc = "Writer for register GPIO_PIN13"] pub type W = crate::W<u32, super::GPIO_PIN13>; #[doc = "Register GPIO_PIN13 `reset()`'s with value 0"] impl crate::ResetValue for super::GPIO_PIN13 { type Type = u32; #[inline(always...
#[doc = "Reader of register GPIO_PIN13"] pub type R = crate::R<u32, super::GPIO_PIN13>; #[doc = "Writer for register GPIO_PIN13"] pub type W = crate::W<u32, super::GPIO_PIN13>; #[doc = "Register GPIO_PIN13 `reset()`'s with value 0"] impl crate::ResetValue for super::GPIO_PIN13 { type Type = u32; #[inline(always...
inline(always)] pub fn gpio_pin13_int_ena(&mut self) -> GPIO_PIN13_INT_ENA_W { GPIO_PIN13_INT_ENA_W { w: self } } #[doc = "Bits 11:12"] #[inline(always)] pub fn gpio_pin13_config(&mut self) -> GPIO_PIN13_CONFIG_W { GPIO_PIN13_CONFIG_W { w: self } } #[doc = "Bit 10"] #[inl...
w: &'a mut W, } impl<'a> GPIO_PIN13_WAKEUP_ENABLE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } ...
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
fuzzer/src/fuzz_main.rs
LockOne/parmesan
6a5b4b1b6c024b29dec53969cfb4d35cd25ad9a3
use crate::stats::*; use crate::dyncfg::{cfg::ControlFlowGraph, fparse::parse_targets_file}; use angora_common::defs; use chrono::prelude::Local; use std::{ collections::HashMap, fs, io::prelude::*, path::{Path, PathBuf}, sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, RwLo...
use crate::stats::*; use crate::dyncfg::{cfg::ControlFlowGraph, fparse::parse_targets_file}; use angora_common::defs; use chrono::prelude::Local; use std::{ collections::HashMap, fs, io::prelude::*, path::{Path, PathBuf}, sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, RwLo...
fn gen_path_afl(out_dir: &str) -> PathBuf { let base_path = PathBuf::from(out_dir); let create_dir_result = fs::create_dir(&base_path); if create_dir_result.is_err() { warn!("dir has existed. {:?}", base_path); } base_path.join(defs::ANGORA_DIR_NAME) } fn get_func_num(s : Option<&str>) ->...
Err(_) => { panic!("Output dir exists but no angora.csv, cond_queue.csv file!"); } } } } } } let seeds_dir = PathBuf::from(in_dir); (seeds_dir, angora_out_dir) }
function_block-function_prefix_line
[ { "content": "pub fn sync_depot(executor: &mut Executor, running: Arc<AtomicBool>, dir: &Path) {\n\n executor.local_stats.clear();\n\n let seed_dir = dir.read_dir().expect(\"read_dir call failed\");\n\n for entry in seed_dir {\n\n if let Ok(entry) = entry {\n\n if !running.load(Orderi...
Rust
src/main.rs
00nktk/cacherpc
d120044c8f6427d3a8e3ad54250a79a3eaff2a17
use std::cell::RefCell; use std::fs::File; use std::path::PathBuf; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use actix_cors::Cors; use actix_web::{guard, web, App, HttpServer}; use anyhow::{Context, Result}; use arc_swap::ArcSwap; use awc::Client; use eithe...
use std::cell::RefCell; use std::fs::File; use std::path::PathBuf; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use actix_cors::Cors; use actix_web::{guard, web, App, HttpServer}; use anyhow::{Context, Result}; use arc_swap::ArcSwap; use awc::Client; use eithe...
#[derive(serde::Deserialize, Debug, Clone)] struct Config { rpc: rpc::Config, } impl Config { fn from_file(f: File) -> Result<Config> { use std::io::{BufReader, Read}; let mut reader = BufReader::new(f); let mut buf = Vec::new(); reader.read_to_end(&mut buf)?; Ok(toml...
async fn main() -> Result<()> { let options = Options::from_args(); let writer = match &options.log_file { Some(path) => Either::Left( file_reopen::File::open(path) .with_context(|| format!("Can't open log file `{}`", path.display()))?, ), None => Either::Rig...
function_block-full_function
[ { "content": "type CacheResult<'a> = Result<HttpResponse, Error<'a>>;\n\n\n", "file_path": "src/rpc.rs", "rank": 0, "score": 124806.84719665934 }, { "content": "pub fn version() -> &'static str {\n\n static VERSION: Lazy<String> = Lazy::new(|| {\n\n let pkg_version = std::env!(\"CA...
Rust
crates/nsi-toolbelt/src/lib.rs
virtualritz/nei
adc72920b5158e7924cd2fc13ef73874ffd85746
#![cfg_attr(feature = "nightly", doc(cfg(feature = "toolbelt")))] use nsi_core as nsi; use ultraviolet as uv; #[inline] fn default_slot_objects(slot: Option<&str>) -> &str { slot.unwrap_or("objects") } #[doc(hidden)] #[cfg(debug_assertions)] pub fn generate_or_use_handle(handle: Option<&str>, prefix: Option<&str...
#![cfg_attr(feature = "nightly", doc(cfg(feature = "toolbelt")))] use nsi_core as nsi; use ultraviolet as uv; #[inline] fn default_slot_objects(slot: Option<&str>) -> &str { slot.unwrap_or("objects") } #[doc(hidden)] #[cfg(debug_assertions)] pub fn generate_or_use_handle(handle: Option<&str>, prefix: Option<&str...
pub fn look_at_bounding_box_perspective_camera( ctx: &nsi::Context, handle: Option<&str>, direction: &[f64; 3], up: &[f64; 3], vertical_fov: f32, aspect_ratio: Option<f32>, bounding_box: &[f64; 6], ) -> String { let vertical_fov = if let Some(aspect_ratio) = aspect_ratio { ...
pub fn look_at_camera( ctx: &nsi::Context, handle: Option<&str>, eye: &[f64; 3], to: &[f64; 3], up: &[f64; 3], ) { let handle = generate_or_use_handle(handle, Some("look_at")); ctx.create(handle.as_str(), nsi::NodeType::Transform, &[]); ctx.set_attribute( handle.as_str(), ...
function_block-full_function
[ { "content": "/// Render a [`Screen`](nsi::context::NodeType::Screen) inside a\n\n/// Jupyter Notebook.\n\n///\n\n/// Essentially this dumps a 16bit PNG as a BASE64 encoded binary\n\n/// blob to `stdout`.\n\n///\n\n/// The [`Context`](nsi::Context) is unchanged after this returns.\n\n/// # Example\n\n/// ```no_...
Rust
engine_io_warp/src/websocket.rs
oguzbilgener/socket.io-server-rust
7ef649fb1ab7e076c24c550c55d05f1970247bc1
use crate::adapter_warp::{AdapterResponse, AdapterWsHandle, StandaloneAdapter}; use async_trait::async_trait; use engine_io_parser::binary::encoder as binary_encoder; use engine_io_parser::decoder::{decode_packet, Encoded}; use engine_io_parser::string::encoder as string_encoder; use engine_io_server::packet::Packet; u...
use crate::adapter_warp::{AdapterResponse, AdapterWsHandle, StandaloneAdapter}; use async_trait::async_trait; use engine_io_parser::binary::encoder as binary_encoder; use engine_io_parser::decoder::{decode_packet, Encoded}; use engine_io_parser::string::encoder as string_encoder; use engine_io_server::packet::Packet; u...
); tokio::spawn(subscribe_to_socket_commands( cmd_receiver, drop_notify.clone(), websocket_sender, options, )); WarpWebsocketTransport { event_sender, options, drop_notify, } } } #[async_trait] impl ...
subscribe_to_websocket_messages( websocket_receiver, event_sender.clone(), upgrade_request_context, drop_notify.clone(), )
call_expression
[ { "content": "#[async_trait]\n\npub trait WebsocketTransport<A>\n\nwhere\n\n A: 'static + Adapter,\n\n{\n\n fn new(\n\n options: WebsocketTransportOptions,\n\n sender: broadcast::Sender<TransportEvent>,\n\n socket: A::WsHandle,\n\n upgrade_request_context: Arc<RequestContext>,\...
Rust
tests/expectations/tests/layout_arp.rs
rust-lang-nursery/rust-bindgen
5a01c551993e56d20240ef64d0ec78cd4195855d
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] pub const ETHER_ADDR_LEN: u32 = 6; pub const ARP_HRD_ETHER: u32 = 1; pub const ARP_OP_REQUEST: u32 = 1; pub const ARP_OP_REPLY: u32 = 2; pub const ARP_OP_REVREQUEST: u32 = 3; pub const ARP_OP_REVREPLY: u32 = 4; pub con...
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] pub const ETHER_ADDR_LEN: u32 = 6; pub const ARP_HRD_ETHER: u32 = 1; pub const ARP_OP_REQUEST: u32 = 1; pub const ARP_OP_REPLY: u32 = 2; pub const ARP_OP_REVREQUEST: u32 = 3; pub const ARP_OP_REVREPLY: u32 = 4; pub con...
#[repr(C, packed)] #[derive(Debug, Default, Copy, Clone)] pub struct arp_ipv4 { pub arp_sha: ether_addr, pub arp_sip: u32, pub arp_tha: ether_addr, pub arp_tip: u32, } #[test] fn bindgen_test_layout_arp_ipv4() { assert_eq!( ::std::mem::size_of::<arp_ipv4>(), 20u...
6usize, concat!("Size of: ", stringify!(ether_addr)) ); assert_eq!( ::std::mem::align_of::<ether_addr>(), 1usize, concat!("Alignment of ", stringify!(ether_addr)) ); assert_eq!( unsafe { let uninit = ::std::mem::MaybeUninit::<ether_addr>::uninit(); ...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn bindgen_test_layout_a() {\n\n assert_eq!(\n\n ::std::mem::size_of::<a>(),\n\n 3usize,\n\n concat!(\"Size of: \", stringify!(a))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<a>(),\n\n 1usize,\n\n concat!(\"Alignment of \", string...
Rust
src/database.rs
BenKurrek/fayyr-indexer
4335d548c4b2a694c2f7fdaad493ada603f4eccc
#![allow(non_snake_case)] use reqwest::Error; use reqwest::StatusCode; use std::collections::HashMap; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, Default)] pub struct MintedTokenPOSTBody { pub token_id: String, pub contract_id: String, pub tags: Vec<String>, pub...
#![allow(non_snake_case)] use reqwest::Error; use reqwest::StatusCode; use std::collections::HashMap; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, Default)] pub struct MintedTokenPOSTBody { pub token_id: String, pub contract_id: String, pub tags: Vec<String>, pub...
in_account_id: admin_account, receipt_id: clean_blockchain_receipt_id, price_near, }; eprintln!("Please Add Your API Endpoint and Uncomment Lines 126-150"); Ok(()) } pub async fn insert_token_forsale_in_database( tok_id: String, contr_id: String, price: f64, SIGNATUR...
); let clean_contract_id = str::replace(&contr_id, '"', ""); let clean_purchaser_account_id = str::replace(&purchaser_account_id, '"', ""); let clean_blockchain_receipt_id = str::replace(&blockchain_receipt_id, '"', ""); let PostBody = SellTokenPostBody { token_id: clean_token_id, contr...
random
[ { "content": "fn main() {\n\n // We use it to automatically search the for root certificates to perform HTTPS calls\n\n // (sending telemetry and downloading genesis)\n\n openssl_probe::init_ssl_cert_env_vars();\n\n init_logging();\n\n\n\n let opts: Opts = Opts::parse();\n\n\n\n let home_dir =...
Rust
src/lib.rs
dshiell15/rust-ectoken
7f9b85ed3868d0397bca97b462aab265492f791c
#![deny(missing_docs)] use aes_gcm::aead::{generic_array::typenum::U32, generic_array::GenericArray, Aead, NewAead}; use aes_gcm::Aes256Gcm; use rand::Rng; use sha2::{Digest, Sha256}; use std::error; use std::fmt; const NONCE_LEN: usize = 12; const TAG_LEN: usize = 16; #[derive(Clone, PartialEq)] pub struct Ec3Key(p...
#![deny(missing_docs)] use aes_gcm::aead::{generic_array::typenum::U32, generic_array::GenericArray, Aead, NewAead}; use aes_gcm::Aes256Gcm; use rand::Rng; use sha2::{Digest, Sha256}; use std::error; use std::fmt; const NONCE_LEN: usize = 12; const TAG_LEN: usize = 16; #[derive(Clone, PartialEq)] pub struct Ec3Key(p...
fn cause(&self) -> Option<&dyn error::Error> { match *self { DecryptionError::InvalidBase64(ref previous) => Some(previous), DecryptionError::InvalidUTF8(ref previous) => Some(previous), _ => None, } } } impl From<base64::DecodeError> for DecryptionError { ...
match *self { DecryptionError::InvalidBase64(_) => "invalid base64", DecryptionError::InvalidUTF8(_) => "invalid UTF8 string decrypted", DecryptionError::IOError(_) => "input/output error", } }
function_block-function_prefix_line
[ { "content": "#[derive(Debug)]\n\nstruct Config {\n\n action: String,\n\n key: String,\n\n text: String,\n\n}\n\n\n\nimpl Config {\n\n fn new(args: &[String]) -> Result<Config, &'static str> {\n\n match args.len() {\n\n 3 => Ok(Config {\n\n action: String::from(\"enc...
Rust
src/osu_2021_july/mod.rs
MaxOhn/rosu-pp-older
cca2407a2adc98152b454df8d51f5c52be822fcb
mod control_point_iter; mod curve; mod difficulty_object; mod osu_object; mod pp; mod skill; mod skill_kind; mod slider_state; use difficulty_object::DifficultyObject; use osu_object::OsuObject; pub use pp::{OsuAttributeProvider, OsuPP}; use skill::Skill; use skill_kind::SkillKind; use slider_state::SliderState; use ...
mod control_point_iter; mod curve; mod difficulty_object; mod osu_object; mod pp; mod skill; mod skill_kind; mod slider_state; use difficulty_object::DifficultyObject; use osu_object::OsuObject; pub use pp::{OsuAttributeProvider, OsuPP}; use skill::Skill; use skill_kind::SkillKind; use slider_state::SliderState; use ...
5.0 - val) / 5.0 } else { avg } } const OSU_OD_MAX: f32 = 20.0; const OSU_OD_AVG: f32 = 50.0; const OSU_OD_MIN: f32 = 80.0; #[inline] fn difficulty_range_od(od: f32) -> f32 { difficulty_range(od, OSU_OD_MAX, OSU_OD_AVG, OSU_OD_MIN) }
2, max: f32, avg: f32, min: f32) -> f32 { if val > 5.0 { avg + (max - avg) * (val - 5.0) / 5.0 } else if val < 5.0 { avg - (avg - min) * (
function_block-random_span
[ { "content": "#[inline]\n\nfn count_iterations(mut start: f32, step: f32, end: f32) -> usize {\n\n let mut count = 0;\n\n\n\n while start < end {\n\n count += 1;\n\n start += step;\n\n }\n\n\n\n count\n\n}\n\n\n", "file_path": "src/fruits_ppv1/mod.rs", "rank": 0, "score": 2...
Rust
src/server/net/mod.rs
Unary-Byte-Software/Composition
6bd701b41a91cbf74f3d9458d31ed17d4a0ee112
pub mod packets; use super::messages::*; use crate::mctypes::*; use log::*; use packets::*; use std::{ collections::VecDeque, sync::mpsc::Sender, time::{Duration, Instant}, }; use tokio::net::TcpStream; #[derive(PartialEq, Debug)] pub enum NetworkClientState { Handshake, Status, Login, P...
pub mod packets; use super::messages::*; use crate::mctypes::*; use log::*; use packets::*; use std::{ collections::VecDeque, sync::mpsc::Sender, time::{Duration, Instant}, }; use tokio::net::TcpStream; #[derive(PartialEq, Debug)] pub enum NetworkClientState { Handshake, Status, Login, P...
pub fn read_packet(&mut self) -> Option<Packet> { self.packets.pop_front() } pub async fn send_packet<P: PacketCommon>(&mut self, packet: P) -> tokio::io::Result<()> { debug!("Sent {:?} {:#04X?} {:?}", self.state, P::id(), packet); packet.write(&mut self.stream).await ...
k>().await), 0x06 => Some( self.get_wrapped_packet::<ServerboundPlayerPositionAndLook>() .await, ), 0x07 => None, 0x08 => None, 0x09 => None, 0x0a => None, 0x0b...
function_block-function_prefixed
[ { "content": "#[async_trait::async_trait]\n\npub trait PacketCommon: Into<Packet> + core::fmt::Debug + Clone\n\nwhere\n\n Self: Sized,\n\n{\n\n fn new() -> Self;\n\n fn id() -> u8;\n\n fn as_packet(&self) -> Packet {\n\n self.clone().into()\n\n }\n\n async fn read(t: &mut TcpStream) -> ...
Rust
src/main.rs
testinggg-art/miniserve
c0a194b39759e6f1de6ae6809cc5ca8b08a9e8f8
use std::io; use std::io::Write; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::thread; use std::time::Duration; use actix_web::web; use actix_web::{ http::{header::ContentType, StatusCode}, Responder, }; use actix_web::{middleware, App, HttpRequest, HttpResponse}; use anyhow::Result; use log::{error, ...
use std::io; use std::io::Write; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::thread; use std::time::Duration; use actix_web::web; use actix_web::{ http::{header::ContentType, StatusCode}, Responder, }; use actix_web::{middleware, App, HttpRequest, HttpResponse}; use anyhow::Result; use log::{error, ...
#[actix_web::main(miniserve)] async fn run(miniserve_config: MiniserveConfig) -> Result<(), ContextualError> { if cfg!(windows) && !Paint::enable_windows_ascii() { Paint::disable(); } let log_level = if miniserve_config.verbose { simplelog::LevelFilter::Info } else { simplelog...
args::CliArgs::clap().gen_completions_to("miniserve", shell, &mut std::io::stdout()); return Ok(()); } let miniserve_config = MiniserveConfig::try_from_args(args)?; match run(miniserve_config) { Ok(()) => (), Err(e) => errors::log_error_chain(e.to_string()), } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Parse authentication requirement\n\nfn parse_auth(src: &str) -> Result<auth::RequiredAuth, ContextualError> {\n\n let mut split = src.splitn(3, ':');\n\n let invalid_auth_format = Err(ContextualError::InvalidAuthFormat);\n\n\n\n let username = match split.next() {\n\n Some(user...
Rust
neovim/src/api/global.rs
EdenEast/nvim-compleet
8e9dc5207c62a97840a3bffa4820c13861b649ef
use mlua::{FromLua, Function, Result, Table}; use super::Api; impl<'a> Api<'a> { pub fn add_user_command( &self, name: &str, command: Function, opts: Table, ) -> Result<()> { self.0 .get::<&str, Function>("nv...
use mlua::{FromLua, Function, Result, Table}; use super::Api; impl<'a> Api<'a> { pub fn add_user_command( &self, name: &str, command: Function, opts: Table, ) -> Result<()> { self.0 .get::<&str, Function>("nv...
str, Function>("nvim_get_option")?.call(name) } pub fn notify<S: AsRef<str>>( &self, msg: S, level: super::LogLevel, ) -> Result<()> { self.0.get::<&str, Function>("nvim_notify")?.call(( msg.as_ref(), level as u...
), hl_group], None => vec![c.0.as_ref()], }) .collect::<Vec<Vec<&str>>>(); self.0.get::<&str, Function>("nvim_echo")?.call(( chunks, history, Vec::<u8>::new(), )) } pub fn get_current_buf(&self) -> Resul...
random
[]
Rust
lexical-write-integer/src/write.rs
sjurajpuchky/rust-lexical
827dd8722967030bfe75cfbd786f0e160ffb9c0c
#![doc(hidden)] #[cfg(feature = "compact")] use crate::compact::Compact; #[cfg(not(feature = "compact"))] use crate::decimal::Decimal; #[cfg(all(not(feature = "compact"), feature = "power-of-two"))] use crate::radix::Radix; use lexical_util::format; macro_rules! write_mantissa { ($($t:tt)+) => ( ...
#![doc(hidden)] #[cfg(feature = "compact")] use crate::compact::Compact; #[cfg(not(feature = "compact"))] use crate::decimal::Decimal; #[cfg(all(not(feature = "compact"), feature = "power-of-two"))] use crate::radix::Radix; use lexical_util::format; macro_rules! write_mantissa { ($($t:tt)+) => ( ...
write_mantissa!(Decimal + Radix); write_exponent!(Decimal + Radix); } macro_rules! write_integer_impl { ($($t:ty)*) => ($( impl WriteInteger for $t {} )*) } write_integer_impl! { u8 u16 u32 u64 u128 usize }
unsafe fn write_integer<U, const FORMAT: u128, const MASK: u128, const SHIFT: i32>( self, buffer: &mut [u8], ) -> usize where U: Decimal + Radix, { let value = U::as_cast(self); if format::radix_from_flags(FORMAT, MASK, SHIFT) == 10 { unsafe { value.decima...
function_block-full_function
[ { "content": "#[inline]\n\npub fn is_special_eq<const FORMAT: u128>(mut byte: Bytes<FORMAT>, string: &'static [u8]) -> usize {\n\n let format = NumberFormat::<{ FORMAT }> {};\n\n if cfg!(feature = \"format\") && format.case_sensitive_special() {\n\n if shared::starts_with(byte.special_iter(), strin...
Rust
src/db.rs
hlb8122/keyserver-rust
783c542085657c5997741a542143f6ae0abf2af2
use std::{ sync::Arc, time::{SystemTime, UNIX_EPOCH}, }; use crate::{ crypto::Address, models::address_metadata::{AddressMetadata, Payload}, }; use prost::Message; use rocksdb::{CompactionDecision, Error, Options, DB}; use crate::net::errors::ValidationError; fn expired(payload: &Payload) -> bool { ...
use std::{ sync::Arc, time::{SystemTime, UNIX_EPOCH}, }; use crate::{ crypto::Address, models::address_metadata::{AddressMetadata, Payload}, }; use prost::Message; use rocksdb::{CompactionDecision, Error, Options, DB}; use crate::net::errors::ValidationError; fn expired(payload: &Payload) -> bool { ...
fn ttl_filter(_level: u32, _key: &[u8], value: &[u8]) -> CompactionDecision { let metadata = AddressMetadata::decode(value).unwrap(); let payload = Payload::decode(&metadata.serialized_payload[..]).unwrap(); if expired(&payload) { CompactionDecision::Remove } else { Compa...
temTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() as i64; payload.timestamp + payload.ttl < timestamp }
function_block-function_prefixed
[ { "content": "fn extract_pubkey_hash(raw_script: &[u8]) -> Option<Vec<u8>> {\n\n if raw_script.len() != 25 {\n\n return None;\n\n }\n\n\n\n if raw_script[0..3] != [118, 169, 20] {\n\n return None;\n\n }\n\n\n\n if raw_script[23..25] != [136, 172] {\n\n return None;\n\n }\n...
Rust
src/sys/pkg/tests/system-updater/src/writes_images.rs
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
use {super::*, pretty_assertions::assert_eq}; #[fasync::run_singlethreaded(test)] async fn fails_on_paver_connect_error() { let env = TestEnv::builder().unregister_protocol(Protocol::Paver).oneshot(true).build(); env.resolver .register_package("update", "upd4t3") .add_file("packages.json", m...
use {super::*, pretty_assertions::assert_eq}; #[fasync::run_singlethreaded(test)] async fn fails_on_paver_connect_error() { let env = TestEnv::builder().unregister_protocol(Protocol::Paver).oneshot(true).build(); env.resolver .register_package("update", "upd4t3") .add_file("packages.json", m...
#[fasync::run_singlethreaded(test)] async fn skip_recovery_does_not_write_recovery_or_vbmeta() { let env = TestEnv::builder().oneshot(true).build(); env.resolver .register_package("update", "upd4t3") .add_file("packages.json", make_packages_json([])) .add_file("zbi", "fake zbi") ...
async fn fails_on_image_write_error() { let env = TestEnv::builder() .paver_service(|builder| builder.call_hook(|_| Status::INTERNAL)) .oneshot(true) .build(); env.resolver .register_package("update", "upd4t3") .add_file("packages.json", make_packages_json([])) ....
function_block-full_function
[]
Rust
src/codegen/rust/mod.rs
dzamlo/svd
3ca6b8808ea2606b5673ff4edfec63fd7c9c8c93
use codegen::error::CodegenError; use device::Device; use field::{Field, FieldsGroup}; use is_similar::IsSimilarOptions; use peripheral::{Peripheral, PeripheralsGroup}; use register::Register; use register_or_cluster::RegisterOrCluster; use std::fmt::Display; use std::io; use std::io::Write; macro_rules! write_line { ...
use codegen::error::CodegenError; use device::Device; use field::{Field, FieldsGroup}; use is_similar::IsSimilarOptions; use peripheral::{Peripheral, PeripheralsGroup}; use register::Register; use register_or_cluster::RegisterOrCluster; use std::fmt::Display; use std::io; use std::io::Write; macro_rules! write_line { ...
fn indent(&mut self) { self.indentation_level += 1; } fn deindent(&mut self) { if self.indentation_level > 0 { self.indentation_level -= 1; } } pub fn generate_doc<D: Display>(&mut self, doc: &Option<D>) -> Result<(), CodegenError> { if self.with_doc {...
dentation(&mut self) -> Result<(), io::Error> { for _ in 0..self.indentation_level { try!(write!(self.out, " ")); } Ok(()) }
function_block-function_prefixed
[ { "content": "fn is_dim_index_str_valid(s: &str) -> bool {\n\n s.chars().all(is_dim_index_char_valid)\n\n}\n\n\n\nimpl FromStr for DimIndexType {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<DimIndexType> {\n\n if s.contains('-') {\n\n let mut splitted = s.split('-');\...
Rust
src/nucleo_f401re/bootloader.rs
ithinuel/usbd-dfu
cf8c55c4ceccc0d00cc69f519cd88732d2ef358b
use core::convert::TryFrom; use core::task::Poll; use usbd_dfu::Result; use super::MANIFEST_REGION_START; pub const APPLICATION_REGION_START: usize = 0x0800_8000; pub const APPLICATION_LENGTH: usize = MANIFEST_REGION_START - APPLICATION_REGION_START; const SECTORS: [(usize, usize); 8] = [ (0x0800_0000, 16 * 1024...
use core::convert::TryFrom; use core::task::Poll; use usbd_dfu::Result; use super::MANIFEST_REGION_START; pub const APPLICATION_REGION_START: usize = 0x0800_8000; pub const APPLICATION_LENGTH: usize = MANIFEST_REGION_START - APPLICATION_REGION_START; const SECTORS: [(usize, usize); 8] = [ (0x0800_0000, 16 * 1024...
Poll::Ready(res) } } MemoryState::Programming { addr, to_write, src, } => { let sr = self.flash.sr.read(); if sr.bsy().bit_is_set() { Poll::Pending ...
Some(Sector(self.0)) } else { None } } } #[derive(Debug)] enum MemoryState { Erasing(Sector), Programming { addr: usize, to_write: usize, src: [u8; 4], }, Idle, } pub struct Memory { flash: stm32f4xx_hal::pac::FLASH, state: MemorySt...
random
[ { "content": "pub fn consume_debug(_f: impl FnMut(&[u8])->usize) {\n\n\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! dbgprint {\n\n ($($arg:tt)*) => {{}};\n\n}\n\n\n\nmacro_rules! impl_capabilities {\n\n ($name:ty) => {\n\n impl usbd_dfu::Capabilities for $name {\n\n const CAN_UPLOAD: bool...
Rust
src/bin/perf.rs
tianenchen/trojan-lite
0238111dd4ad4f1cb64fff2f3db55d8a11d12c95
use std::{ io, net::SocketAddr, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, }; use futures::TryFutureExt; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}, }; use bytes::BufMut; use argh::FromArgs; use trojan_lite::hex_hash; use tokio_rustl...
use std::{ io, net::SocketAddr, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, }; use futures::TryFutureExt; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}, }; use bytes::BufMut; use argh::FromArgs; use trojan_lite::hex_hash; use tokio_rustl...
#[tokio::main] async fn main() { let opts: Options = argh::from_env(); let addr = "127.0.0.1:28078".parse().unwrap(); let amt = Arc::new(AtomicUsize::default()); let dummy = amt.clone(); if let Err(e) = perf( opts.thread, opts.trojan_server_addr, addr, &opts.user, ...
async fn perf( threads: u8, addr: SocketAddr, target_addr: SocketAddr, user: &str, amt: Arc<AtomicUsize>, ) -> io::Result<()> { let header = generate_trojan_header(target_addr, user); let do_recv = do_recv(target_addr, amt).map_err(|e| { eprint!("{}", e); std::process::exit(1...
function_block-full_function
[]
Rust
src/compare.rs
solarretrace/fcmp-rs
367eaec284b182f58cf7553d017d1a9481c0fd6d
use crate::ops::DiffOp; use anyhow::anyhow; use std::cmp::Ordering; use std::fs::File; use std::fs::Metadata; use std::io::ErrorKind; use std::path::Path; use std::path::PathBuf; use std::str::FromStr; use std::time::SystemTime; #[derive(Debug)] pub struct FileCmp { path: PathBuf, file: Option<Fi...
use crate::ops::DiffOp; use anyhow::anyhow; use std::cmp::Ordering; use std::fs::File; use std::fs::Metadata; use std::io::ErrorKind; use std::path::Path; use std::path::PathBuf; use std::str::FromStr; use std::time::SystemTime; #[derive(Debug)] pub struct FileCmp { path: PathBuf, file: Option<Fi...
} impl FileCmp { #[must_use] pub fn not_found(path: PathBuf) -> Self { Self { path, file: None, metadata: None, } } #[must_use] pub fn is_found(&self) -> bool { self.file.is_some() } #[must_use] ...
ptions() .read(true) .open(&path) { Ok(file) => Ok(Self { path, metadata: Some(file.metadata()?), file: Some(file), }), Err(e) => match e.kind() { ErrorKind::NotFound => Ok(Self::not_foun...
function_block-function_prefixed
[ { "content": "\tpub fn posix_cmp() -> Self {\n\n\t\tSelf::Subprocess {\n\n\t\t\tcommand: \"cmp\",\n\n\t\t\targs: vec![\"-s\"],\n\n\t\t}\n\n\t}\n\n\t\n\n\n\n\t/// Returns true if the files at the given paths are different.\n\n\tpub fn diff(&self, a: &Path, b: &Path) -> Result<bool, std::io::Error> {\n\n\t\tmatch...
Rust
src/fairings.rs
umpyre-code/turnstile
7821592ac8314468d75ab5c14fe94081e202e7b0
use std::time::Instant; use instrumented::{prometheus, register}; use rocket::fairing::{Fairing, Info, Kind}; use rocket::{Data, Request, Response}; lazy_static! { static ref REQUEST_COUNTER: prometheus::IntCounterVec = { let counter_opts = prometheus::Opts::new("http_requests_total", "HTTP Request counte...
use std::time::Instant; use instrumented::{prometheus, register}; use rocket::fairing::{Fairing, Info, Kind}; use rocket::{Data, Request, Response}; lazy_static! { static ref REQUEST_COUNTER: prometheus::IntCounterVec = { let counter_opts = prometheus::Opts::new("http_requests_total", "HTTP Request counte...
} pub struct RateLimitHeaders; impl Fairing for RateLimitHeaders { fn info(&self) -> Info { Info { name: "Rate limit response headers", kind: Kind::Response, } } fn on_response(&self, request: &Request, response: &mut Response) { use crate::guards; ...
fn on_response(&self, request: &Request, response: &mut Response) { let route = if let Some(route) = request.route() { route.uri.path() } else { "none" }; let (browser_name, browser_os, browser_version) = get_ua(request); RESPONSE_COUNTER .wi...
function_block-full_function
[ { "content": "#[post(\"/metrics/counter/<metric>/inc\")]\n\npub fn post_metrics_counter_inc(\n\n metric: String,\n\n _ratelimited: guards::RateLimited,\n\n) -> Result<(), ResponseError> {\n\n METRICS_COUNTER.with_label_values(&[metric.as_str()]).inc();\n\n Ok(())\n\n}\n\n\n", "file_path": "src/m...
Rust
src/transaction.rs
murki/arloader
c2ebfa40ae022c95cf155ab98b3a3583c9db8dd9
use crate::{ error::Error, merkle::{Node, Proof}, }; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; #[derive(Serialize, Deserialize, Debug, Default, PartialEq)] pub struct Transaction { pub format: u8, pub id: Base64, pub last_tx: Base64, pub owner: ...
use crate::{ error::Error, merkle::{Node, Proof}, }; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; #[derive(Serialize, Deserialize, Debug, Default, PartialEq)] pub struct Transaction { pub format: u8, pub id: Base64, pub last_tx: Base64, pub owner: ...
} } impl<'a> ToItems<'a, Tag<Base64>> for Tag<Base64> { fn to_deep_hash_item(&'a self) -> Result<DeepHashItem, Error> { Ok(DeepHashItem::List(vec![ DeepHashItem::Blob(self.name.0.to_vec()), DeepHashItem::Blob(self.value.0.to_vec()), ])) } } #[derive(Debug, Clone, P...
if self.len() > 0 { Ok(DeepHashItem::List( self.iter() .map(|t| t.to_deep_hash_item().unwrap()) .collect(), )) } else { Ok(DeepHashItem::Blob(Vec::<u8>::new())) }
if_condition
[ { "content": "/// Generates data chunks from which the calculation of root id starts.\n\npub fn generate_leaves(data: Vec<u8>, crypto: &Provider) -> Result<Vec<Node>, Error> {\n\n let mut data_chunks: Vec<&[u8]> = data.chunks(MAX_CHUNK_SIZE).collect();\n\n\n\n #[allow(unused_assignments)]\n\n let mut l...
Rust
src/printer.rs
DarthBenro008/gunfollower
57b6e0f2233426e27e0b55113be67c7556287024
use crate::models::followers::FollowersList; use console::style; pub fn print_error(action: &str, error: &std::boxed::Box<dyn std::error::Error>) { println!( "{} {}\n{}: {}", style("😭 Uh oh, somthing went wrong while") .for_stderr() .bold() .red(), style...
use crate::models::followers::FollowersList; use console::style; pub fn print_error(action: &str, error: &std::boxed::Box<dyn std::error::Error>) { println!( "{} {}\n{}: {}", style("😭 Uh oh, somthing went wrong while") .for_stderr() .bold() .red(), style...
pub fn print_heading(data: String) { println!("\n{}", style(data).cyan().underlined()) } pub fn print_followers_unfollowers(new_followers: FollowersList, unfollowers: FollowersList) { if new_followers.is_empty() && unfollowers.is_empty() { println!( "{}", style("😎 Chill! No o...
pub fn print_follwers_metric(data: String) { println!( "✅ {} {} {}", style("You currently have".to_string()).for_stdout().green(), style(data).for_stdout().green().bold().underlined(), style("followers!").for_stdout().green() ) }
function_block-full_function
[ { "content": "pub fn shell_handler() -> Result<(), Box<dyn Error>> {\n\n let script = String::from(\n\n \"function prompt_gunfollower() {\n\n result=$(gunfollower stats)\n\n if [[ \\\"$result\\\" == \\\"err\\\" ]]\n\n then\n\n p10k segment -f yellow -t \\\"logged out of gunfollower\\\"...
Rust
prellblock/src/peer/peer_inbox.rs
lpirl/Prellblock
7353160295df4e56a1c3eddc1e1195eb96ada050
use super::{message, Calculator, Pong}; use crate::{ consensus::{Consensus, ConsensusResponse}, data_storage::DataStorage, transaction_checker::TransactionChecker, BoxError, }; use pinxit::{verify_signed_batch_iter, Signed, VerifiedRef}; use prellblock_client_api::Transaction; use std::sync::{Arc, Mutex...
use super::{message, Calculator, Pong}; use crate::{ consensus::{Consensus, ConsensusResponse}, data_storage::DataStorage, transaction_checker::TransactionChecker, BoxError, }; use pinxit::{verify_signed_batch_iter, Signed, VerifiedRef}; use prellblock_client_api::Transaction; use std::sync::{Arc, Mutex...
ransaction.signer(), params)?; } Transaction::CreateAccount(params) => { log::debug!( "Client {} creates account {}: {:#?}", &transaction.signer(), params.id, params.permissions, ); ...
nbox { #[must_use] pub fn new( calculator: ArcMut<Calculator>, data_storage: Arc<DataStorage>, consensus: Arc<Consensus>, transaction_checker: TransactionChecker, ) -> Self { Self { calculator, data_storage, consensus, ...
random
[ { "content": "/// Verify a batch of `Signed<T>`.\n\n///\n\n/// This returns an `Iterator` over `Verified<T>` if and only if\n\n/// **all** signatures can be verified.\n\n///\n\n/// # Example\n\n/// ```\n\n/// use pinxit::{verify_signed_batch, Identity, Signable, Signed, VerifiedRef};\n\n///\n\n/// // define exa...
Rust
src/source/settings_loader.rs
IyesGames/bevy_kira_audio
f450d57885d1d4de4e403d97a4e9d115e8cac695
use std::time::Duration; use std::{io::Cursor, path::PathBuf}; use bevy::asset::{AssetLoader, LoadContext, LoadedAsset}; use bevy::utils::BoxedFuture; use kira::sound::static_sound::{StaticSoundData, StaticSoundSettings}; use kira::tween::Tween; use kira::{LoopBehavior, PlaybackRate, Volume}; use serde::Deserialize; ...
use std::time::Duration; use std::{io::Cursor, path::PathBuf}; use bevy::asset::{AssetLoader, LoadContext, LoadedAsset}; use bevy::utils::BoxedFuture; use kira::sound::static_sound::{StaticSoundData, StaticSoundSettings}; use kira::tween::Tween; use kira::{LoopBehavior, PlaybackRate, Volume}; use serde::Deserialize; ...
} impl AssetLoader for SettingsLoader { fn load<'a>( &'a self, bytes: &'a [u8], load_context: &'a mut LoadContext, ) -> BoxedFuture<'a, Result<(), anyhow::Error>> { Box::pin(async move { let sound_settings: SoundSettings = ron::de::from_bytes(bytes)?; le...
static_sound_settings.playback_rate = PlaybackRate::from(settings.playback_rate); static_sound_settings.panning = settings.panning; static_sound_settings.reverse = settings.reverse; static_sound_settings.loop_behavior = settings .loop_behavior .map(|start_position| LoopBe...
function_block-function_prefix_line
[ { "content": "#[derive(Default)]\n\nstruct LastAction(f64);\n\n\n\nimpl LastAction {\n\n fn action(&mut self, time: &Time) -> bool {\n\n if time.seconds_since_startup() - self.0 < 0.2 {\n\n return false;\n\n }\n\n self.0 = time.seconds_since_startup();\n\n\n\n true\n\n ...
Rust
ivy-graphics/src/animation/mod.rs
ten3roberts/ivy
fb5a7645c9f699c2aebf3d1b90c1d1f9e78355fa
use glam::{Quat, Vec3}; use gltf::animation::util::{ReadOutputs, Rotations, Scales, Translations}; use ivy_base::{Position, Rotation, Scale}; mod animations; mod animator; pub use animations::*; pub use animator::*; use crate::Skin; #[derive(Debug)] pub struct Animation { name: String, skin: usize, dura...
use glam::{Quat, Vec3}; use gltf::animation::util::{ReadOutputs, Rotations, Scales, Translations}; use ivy_base::{Position, Rotation, Scale}; mod animations; mod animator; pub use animations::*; pub use animator::*; use crate::Skin; #[derive(Debug)] pub struct Animation { name: String, skin: usize, dura...
pub fn duration(&self) -> f32 { self.duration } pub fn channels(&self) -> &[Channel] { self.channels.as_ref() } pub fn channel(&self, index: usize) -> &Channel { &self.channels[index] } pub fn skin(&self) -> usize { self.skin } ...
pub fn from_gltf( animation: gltf::Animation, skins: &[Skin], buffers: &[gltf::buffer::Data], ) -> Vec<Self> { let mut animations: Vec<Self> = Vec::new(); animation.channels().for_each(|channel| { let target = channel.target(); let joint = target.nod...
function_block-full_function
[ { "content": "/// Compute barycentric coordinates of p in relation to the triangle defined by (a, b, c).\n\npub fn barycentric_vector(point: Vec3, p1: Vec3, p2: Vec3, p3: Vec3) -> (f32, f32, f32) {\n\n let v0 = p2 - p1;\n\n let v1 = p3 - p1;\n\n let v2 = point - p1;\n\n let d00 = v0.dot(v0);\n\n ...
Rust
src/portfolio/repository/in_memory.rs
Uzaaft/barter-rs
08f1ddd9c622d4b7c4cddfc4520242e0c3360c6e
use crate::{Market, MarketId}; use crate::portfolio::{Balance, BalanceId}; use crate::portfolio::position::{determine_position_id, Position, PositionId}; use crate::portfolio::repository::error::RepositoryError; use crate::portfolio::repository::{BalanceHandler, determine_exited_positions_id, PositionHandler, Statistic...
use crate::{Market, MarketId}; use crate::portfolio::{Balance, BalanceId}; use crate::portfolio::position::{determine_position_id, Position, PositionId}; use crate::portfolio::repository::error::RepositoryError; use crate::portfolio::repository::{BalanceHandler, determine_exited_positions_id, PositionHandler, Statistic...
) .map(Position::clone) }) .collect()) } fn remove_position( &mut self, position_id: &String, ) -> Result<Option<Position>, RepositoryError> { Ok(self.open_positions.remove(position_id)) } fn set_exited_position( &mut self...
determine_position_id( engine_id, market.exchange, &market.symbol, )
call_expression
[]
Rust
src/handlers.rs
bbhh/attendance-tracker
8b5d499578674623994b4b799ddd9fd5a6a2d2ce
use actix_web::{HttpResponse, web, Error}; use crate::models::{AddPersonRequest, ListAttendancesRequest, UpsertAttendanceRequest, ListPersonsRequest}; use crate::{DbPool, actions}; use crate::responses::ErrorResponse; use chrono::NaiveDate; /***********/ /* PERSONS */ /***********/ #[get("/persons")] pub async fn li...
use actix_web::{HttpResponse, web, Error}; use crate::models::{AddPersonRequest, ListAttendancesRequest, UpsertAttendanceRequest, ListPersonsRequest}; use crate::{DbPool, actions}; use crate::responses::ErrorResponse; use chrono::NaiveDate; /***********/ /* PERSONS */ /***********/ #[get("/persons")] pub async fn li...
o_owned()))); } let present = form.present.to_owned(); let result = web::block(move || actions::upsert_attendance(&connection, date.as_str(), person_id, present)) .await .map_err(|e| { eprintln!("{}", e); HttpResponse::InternalServerError().finish() })?...
.await .map_err(|e| { eprintln!("{}", e); HttpResponse::InternalServerError().finish() })?; Ok(HttpResponse::Ok().json(persons)) } } #[post("/persons")] pub async fn add_person(pool: web::Data<DbPool>, form: web::Json<AddPersonRequest>) -> Result<Ht...
random
[ { "content": "pub fn get_person(connection: &SqliteConnection, id_: i32) -> Result<Option<Person>, diesel::result::Error> {\n\n use crate::schema::persons::dsl::*;\n\n\n\n let person = persons\n\n .filter(id.eq(id_))\n\n .first::<Person>(connection)\n\n .optional()?;\n\n\n\n Ok(per...
Rust
bee-snapshot/src/pruning/mod.rs
neumoxx/bee-p
2a68c3c6c17bd2c8dd36d8274ef0db3a04d50b16
mod config; pub use config::{PruningConfig, PruningConfigBuilder}; use crate::constants::{ADDITIONAL_PRUNING_THRESHOLD, SOLID_ENTRY_POINT_CHECK_THRESHOLD_PAST}; use bee_crypto::ternary::Hash; use bee_protocol::{ tangle::{helper, tangle}, MilestoneIndex, }; use bee_tangle::traversal; use dashmap::DashMap; ...
mod config; pub use config::{PruningConfig, PruningConfigBuilder}; use crate::constants::{ADDITIONAL_PRUNING_THRESHOLD, SOLID_ENTRY_POINT_CHECK_THRESHOLD_PAST}; use bee_crypto::ternary::Hash; use bee_protocol::{ tangle::{helper, tangle}, MilestoneIndex, }; use bee_tangle::traversal; use dashmap::DashMap; ...
pub fn get_new_solid_entry_points(target_index: MilestoneIndex) -> Result<DashMap<Hash, MilestoneIndex>, Error> { let solid_entry_points = DashMap::<Hash, MilestoneIndex>::new(); for index in *target_index - SOLID_ENTRY_POINT_CHECK_THRESHOLD_PAST..*target_index { let milestone_hash; ...
l::visit_children_follow_trunk( tangle(), *hash, |_, metadata| { if is_solid { return false; } is_solid = metadata.flags().is_confirmed() && metadata.milestone_index() > milestone_index; true }, |_, _, _...
function_block-function_prefixed
[ { "content": "pub fn on_all_tails<Apply: FnMut(&Hash, &TransactionRef, &TransactionMetadata)>(\n\n tangle: &Tangle<TransactionMetadata>,\n\n root: Hash,\n\n apply: Apply,\n\n) {\n\n traversal::visit_parents_depth_first(\n\n tangle,\n\n root,\n\n |_, _, metadata| !metadata.flags(...
Rust
cc13x0-pac/src/gpio/dout15_12.rs
jamesmunns/cc13x0-pac-example
adfe233d4fbefcd7c4c918270ce33b36f48f3830
#[doc = "Reader of register DOUT15_12"] pub type R = crate::R<u32, super::DOUT15_12>; #[doc = "Writer for register DOUT15_12"] pub type W = crate::W<u32, super::DOUT15_12>; #[doc = "Register DOUT15_12 `reset()`'s with value 0"] impl crate::ResetValue for super::DOUT15_12 { type Type = u32; #[inline(always)] ...
#[doc = "Reader of register DOUT15_12"] pub type R = crate::R<u32, super::DOUT15_12>; #[doc = "Writer for register DOUT15_12"] pub type W = crate::W<u32, super::DOUT15_12>; #[doc = "Register DOUT15_12 `reset()`'s with value 0"] impl crate::ResetValue for super::DOUT15_12 { type Type = u32; #[inline(always)] ...
ets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn ...
lways)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut ...
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
lib/libproc_macro/src/protocol.rs
emosenkis/mrustc
298fef8673ee80e594d86ab420e7e41c5cfdcf78
pub enum Token { Symbol(String), Ident(String), Lifetime(String), String(String), ByteString(Vec<u8>), Char(char), Unsigned(u128, u8), Signed(i128, u8), Float(f64, u8), } pub struct Reader<R> { inner: R, } impl<R: ::std::io::Read> Reader<R> { pub fn new(r: R) -> Reader<R> {...
pub enum Token { Symbol(String), Ident(String), Lifetime(String), String(String), ByteString(Vec<u8>), Char(char), Unsigned(u128, u8), Signed(i128, u8), Float(f64, u8), } pub struct Reader<R> { inner: R, } impl<R: ::std::io::Read> Reader<R> { pub fn new(r: R) -> Reader<R> {...
fn get_string(&mut self) -> String { let raw = self.get_byte_vec(); String::from_utf8(raw).expect("Invalid UTF-8 passed from compiler") } fn get_f64(&mut self) -> f64 { let mut buf = [0u8; 8]; match self.inner.read_exact(&mut buf) { Ok(_) => {}, Err(e...
Ok(_) => {}, Err(e) => panic!("Error reading from stdin get_byte_vec({}) - {}", size, e), } buf }
function_block-function_prefix_line
[ { "content": "pub fn dump_token_stream<R: ::std::io::Read>(reader: R)\n\n{\n\n let mut s = protocol::Reader::new(reader);\n\n while let Some(v) = s.read_ent()\n\n {\n\n match v\n\n {\n\n Token::Symbol(s) => println!(\"SYM {}\", s),\n\n Token::Ident(s) => println!(\"IDENT {}\...
Rust
webchordr/song-list/src/lib.rs
cundd/chordr
243a7dcfa1e619dad76de788338485c76c07b51c
use log::info; use web_sys::HtmlElement; use yew::prelude::*; use libchordr::models::song_list::SongList as SongListLibModel; use libchordr::prelude::*; use webchordr_events::setlist_events::SetlistEvent; use webchordr_events::{Event, SortingChange}; use crate::sortable_service::{SortableHandle, SortableOptions, Sort...
use log::info; use web_sys::HtmlElement; use yew::prelude::*; use libchordr::models::song_list::SongList as SongListLibModel; use libchordr::prelude::*; use webchordr_events::setlist_events::SetlistEvent; use webchordr_events::{Event, SortingChange}; use crate::sortable_service::{SortableHandle, SortableOptions, Sort...
fn change(&mut self, props: Self::Properties) -> ShouldRender { if self.props != props { self.props = props; if self.props.sortable { self.make_sortable(); } else { self.make_unsortable(); } true } else { ...
fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::SetlistChangeSorting(e) => { let sorting_change = self.patch_sorting_change(e); if sorting_change.new_index() != sorting_change.old_index() { self.props.on_setlist_change.e...
function_block-full_function
[ { "content": "type SortingChangeFn = dyn Fn(i32, i32);\n\n\n\n/// Service to make a HtmlElement sortable using [Shopify/draggable](https://github.com/Shopify/draggable)\n\npub struct SortableService {}\n\n\n\n#[must_use]\n\npub struct SortableHandle {\n\n sortable: SortableWrapper,\n\n _closure: Closure<S...
Rust
hotel/src/gpio.rs
phil-levis-google/tock-hotel
fd0fe18dc07a463f211618e2b90cf42dcdad781b
use self::Pin::*; use core::cell::Cell; use core::mem::transmute; use kernel::common::cells::VolatileCell; use kernel::hil; pub struct PortRegisters { pub data_in: VolatileCell<u32>, pub data_out: VolatileCell<u32>, _reserved: [u32; 2], pub output_enable: VolatileCell<u32>, pub output_disable: Vola...
use self::Pin::*; use core::cell::Cell; use core::mem::transmute; use kernel::common::cells::VolatileCell; use kernel::hil; pub struct PortRegisters { pub data_in: VolatileCell<u32>, pub data_out: VolatileCell<u32>, _reserved: [u32; 2], pub output_enable: VolatileCell<u32>, pub output_disable: Vola...
fn disable_interrupt(&self) { let port: &mut PortRegisters = unsafe { transmute(self.port) }; let mask = 1 << (self.pin as u32); port.interrupt_disable.set(mask); } } impl hil::gpio::PinCtl for GPIOPin { fn set_input_mode(&self, mode: hil::gpio::InputMode) { match mod...
fn enable_interrupt(&self, identifier: usize, mode: hil::gpio::InterruptMode) { self.client_data.set(identifier); let port: &mut PortRegisters = unsafe { transmute(self.port) }; let mask = 1 << (self.pin as u32); match mode { hil::gpio::InterruptMode::RisingEdge => { ...
function_block-full_function
[ { "content": "/// An [RNG](trait.RNG.html) client\n\n///\n\n/// Clients of an [RNG](trait.RNG.html) must implement this trait.\n\npub trait Client {\n\n /// Called by the (RNG)[trait.RNG.html] when there are one or more random\n\n /// numbers available\n\n ///\n\n /// `randomness` in an `Iterator` o...
Rust
src/packet/udp.rs
little-dude/libpnet
06d4ae9599efbc3454fd2488db093a58c90c1ed7
use packet::Packet; use packet::ip::IpNextHeaderProtocol; use pnet_macros_support::types::*; use std::net::{Ipv4Addr, Ipv6Addr}; #[packet] pub struct Udp { source: u16be, destination: u16be, length: u16be, checksum: u16be, #[payload] payload: Vec<u8>, } pub fn ipv4_checksum(packet: &UdpPac...
use packet::Packet; use packet::ip::IpNextHeaderProtocol; use pnet_macros_support::types::*; use std::net::{Ipv4Addr, Ipv6Addr}; #[packet] pub struct Udp { source: u16be, destination: u16be, length: u16be, checksum: u16be, #[payload] payload: Vec<u8>, } pub fn ipv4_checksum(packet: &UdpPac...
1); let ipv6_destination = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); { let mut ip_header = MutableIpv6Packet::new(&mut packet[..]).unwrap(); ip_header.set_next_header(next_header); ip_header.set_source(ipv6_source); ip_header.set_destination(ipv6_destination); } packet...
function_block-function_prefixed
[ { "content": "fn build_udp_header(packet: &mut [u8], offset: usize) {\n\n let mut udp_header = MutableUdpPacket::new(&mut packet[offset..]).unwrap();\n\n\n\n udp_header.set_source(1234); // Arbitary port number\n\n udp_header.set_destination(1234);\n\n udp_header.set_length((UDP_HEADER_LEN + TEST_DA...
Rust
libphoenix/src/syscall.rs
jeremydavis519/phoenix
0664ac66b3d0ed7104b41c57b8c598b1c73ebe48
/* Copyright (c) 2021 Jeremy Davis (jeremydavis519@gmail.com) * * 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, co...
/* Copyright (c) 2021 Jeremy Davis (jeremydavis519@gmail.com) * * 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, co...
pub fn memory_page_size() -> usize { let page_size: usize; unsafe { asm!( "svc 0x0380", lateout("x0") page_size, options(nomem, nostack, preserves_flags) ); } page_size } define_async_syscalls! { ...
svc 0x0100", in("x2") status as usize, options(nomem, nostack, preserves_flags, noreturn) ); } }
function_block-function_prefix_line
[ { "content": "// Blocks the thread until a system call it made is complete.\n\nfn thread_wait(thread: Option<&mut Thread<File>>, _future_addr: usize) -> Response {\n\n assert!(!thread.is_none(), \"attempted to block a kernel thread\");\n\n // FIXME: If the given address doesn't point to a future, terminat...
Rust
donut_2_in_rust/main.rs
joaocarvalhoopen/3D_Text_donut_demo_in_Rust
880f2dd31cf0d487d01b4a7e631700190b99cadb
use std::f32::consts::PI; use std::{thread, time}; use slice_fill::SliceExt; const THETA_SPACING: f32 = 0.07; const PHI_SPACING: f32 = 0.02; const R1: f32 = 1.0; const R2: f32 = 2.0; const K2: f32 = 10.0; const SCREEN_WIDTH: f32 = 80.0; const SCREEN_HEIGHT: f32 = 50.0; const K1: f32 = SCREEN_WIDTH * K2 * 2.0...
use std::f32::consts::PI; use std::{thread, time}; use slice_fill::SliceExt; const THETA_SPACING: f32 = 0.07; const PHI_SPACING: f32 = 0.02; const R1: f32 = 1.0; const R2: f32 = 2.0; const K2: f32 = 10.0; const SCREEN_WIDTH: f32 = 80.0; const SCREEN_HEIGHT: f32 = 50.0; const K1: f32 = SCREEN_WIDTH * K2 * 2.0...
let mut output: Vec<char> = vec![' '; (SCREEN_WIDTH * SCREEN_HEIGHT) as usize]; println!("\x1b[2J"); loop { render_frame(& a, & b, & mut zBuffer, & mut output); println!("donut_2_in_rust"); a += 0.04; b += 0.02; thread::sleep(time::Duration::from_millis(10)); } }
function_block-function_prefix_line
[ { "content": "#[warn(unstable_name_collisions)]\n\nfn main() {\n\n let lux = ['.', ',', '-', '~', ':', ';', '=', '!', '*', '#', '$', '@'];\n\n\n\n let mut A: f32 = 0.0_f32;\n\n let mut B: f32 = 0.0_f32;\n\n let mut i: f32;\n\n let mut j: f32;\n\n let mut z: Vec<f32> = vec![0.0; max_buf_size];...
Rust
src/lib.rs
jam1garner/hexlit
4f25811caf13304696eedd23105586114c2973bf
#![no_std] #[macro_export] macro_rules! hex { (@string $arg:expr) => {{ const NUM_SPACES: usize = { let data = $arg.as_bytes(); let mut space_count: usize = 0; let mut char_index: usize = 0; while char_index < data.len() { if data[char_index...
#![no_std] #[macro_export] macro_rules! hex { (@string $arg:expr) => {{ const NUM_SPACES: usize = { let data = $arg.as_bytes(); let mut space_count: usize = 0; let mut char_index: usize = 0; while char_index < data.len() { if data[char_index...
let mut char_index: usize = 0; let string_length = s.len(); while data_index < string_length && char_index + 1 < string_length { if s[char_index] != b' ' && s[char_index] != b'_' && s[char_index] != b'"' { data[data_index] = ...
UM_SKIPPED) % 2) as usize]; const ARRAY_LENGTH: usize = ($arg.len() - NUM_SKIPPED) / 2; const RESULT: [u8; ARRAY_LENGTH] = { const fn always_true() -> bool { true } const fn to_ordinal(input: u8) -> u8 { match...
random
[ { "content": "[![Current Crates.io Version](https://img.shields.io/crates/v/hexlit.svg)](https://crates.io/crates/hexlit)\n\n[![docs-rs](https://docs.rs/hexlit/badge.svg)](https://docs.rs/hexlit)\n\n![MSRV 1.46+](https://img.shields.io/badge/rustc-1.46+-blue.svg)\n\n\n\n# hexlit\n\nA zero-allocation no_std-comp...
Rust
src/service.rs
tdawson/bodhi-rs
522ff5da8d3b003b8a4ab39c415f3a451be44ffd
use std::fmt::{Debug, Formatter}; use std::time::Duration; use fedora::{AnonymousSessionBuilder, OpenIDSessionBuilder, Session}; use reqwest::blocking::Response; use url::Url; use crate::data::{FEDORA_BODHI_STG_URL, FEDORA_BODHI_URL}; use crate::error::{QueryError, ServiceError}; use crate::{Create, Edit, Query}; ...
use std::fmt::{Debug, Formatter}; use std::time::Duration; use fedora::{AnonymousSessionBuilder, OpenIDSessionBuilder, Session}; use reqwest::blockin
e); } Ok(response) } pub fn query<T>(&self, query: impl Query<T>) -> Result<T, QueryError> { Query::query(query, self) } pub fn create<T>(&self, creator: &dyn Create<T>) -> Result<T, QueryError> { Create::create(creator, self) } pub fn edit<T>(&...
g::Response; use url::Url; use crate::data::{FEDORA_BODHI_STG_URL, FEDORA_BODHI_URL}; use crate::error::{QueryError, ServiceError}; use crate::{Create, Edit, Query}; pub const DEFAULT_ROWS: u32 = 50; const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); const REQUEST_RETRIES: usize = 3; const USER_AGENT: &str...
random
[ { "content": "use std::cmp::PartialEq;\n\nuse std::convert::TryFrom;\n\nuse std::error::Error;\n\nuse std::fmt::{Display, Formatter};\n\nuse std::str::FromStr;\n\n\n\nuse serde::{Deserialize, Serialize};\n\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\n\n\n/// This error is returned when a string fails...
Rust
paddlers-frontend/src/game.rs
bjorn3/paddlers-browser-game
0d13e6c5ae99384f030a9e085798226eeda2a89d
pub(crate) mod abilities; pub(crate) mod attacks; pub(crate) mod buildings; pub(crate) mod components; #[cfg(feature = "dev_view")] pub(crate) mod dev_view; pub(crate) mod dialogue; pub(crate) mod fight; pub(crate) mod forestry; pub(crate) mod game_event_manager; pub(crate) mod leaderboard; pub(crate) mod level; pub(cr...
pub(crate) mod abilities; pub(crate) mod attacks; pub(crate) mod buildings; pub(crate) mod components; #[cfg(feature = "dev_view")] pub(crate) mod dev_view; pub(crate) mod dialogue; pub(crate) mod fight; pub(crate) mod forestry; pub(crate) mod game_event_manager; pub(crate) mod leaderboard; pub(crate) mod level; pub(cr...
pub fn check<R>(&self, res: PadlResult<R>) -> Option<R> { if let Err(e) = res { let mut q = self.world.write_resource::<ErrorQueue>(); q.push(e); None } else { Some(res.unwrap()) } } pub fn confirm_to_user(&mut self, msg: String) ...
fn worker_entity_by_net_id(&self, net_id: i64) -> PadlResult<Entity> { let net = self.world.read_storage::<NetObj>(); let ent = self.world.entities(); NetObj::lookup_worker(net_id, &net, &ent) }
function_block-function_prefix_line
[]
Rust
src/drawio_exporter/core/drawio/drawio_desktop.rs
rlespinasse/drawio-exporter
e694da9216322d8911bc232c103b5b78cfdecd93
use anyhow::{Context, Result}; use predicate::str::contains; use predicates::prelude::*; use std::path::PathBuf; use std::process::Command; pub struct DrawioDesktop<'a> { application: &'a str, is_headless: bool, } impl<'a> DrawioDesktop<'a> { pub fn new(application_path: Option<&'a str>, is_headless: bool...
use anyhow::{Context, Result}; use predicate::str::contains; use predicates::prelude::*; use std::path::PathBuf; use std::process::Command; pub struct DrawioDesktop<'a> { application: &'a str, is_headless: bool, } impl<'a> DrawioDesktop<'a> { pub fn new(application_path: Option<&'a str>, is_headless: bool...
sts", path); return None; } } application_path } pub struct ExportArguments<'a> { pub recursive: bool, pub output: Option<&'a str>, pub input: &'a str, pub format: &'a str, pub border: &'a str, pub scale: Option<&'a str>, pub width: Option<&'a str>, pub heigh...
io.app/Contents/MacOS/draw.io"), "windows" => Some("C:\\Program Files\\draw.io\\draw.io.exe"), "linux" => Some("/opt/drawio/drawio"), _ => None, }; if let Some(path) = application_path { if !PathBuf::from(path).exists() { println!("Draw.io Desktop default path '{}' do...
function_block-random_span
[ { "content": "fn is_drawio_file_has_been_updated(path: &Path, export_folder: &str) -> bool {\n\n match get_modified_date(path) {\n\n None => true, // If we can't access a modified date, we consider its have been updated\n\n Some(drawio_file_modified_date) => {\n\n is_drawio_file_olde...
Rust
benches/benches/bevy_reflect/struct.rs
thibaudio/bevy
dbd856de71a3a00bfd30bd3113147819b97688a6
use std::time::Duration; use bevy_reflect::{DynamicStruct, GetField, Reflect, Struct}; use criterion::{ black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput, }; criterion_group!( benches, concrete_struct_apply, concrete_struct_field, dynamic_struct_apply, d...
use std::time::Duration; use bevy_reflect::{DynamicStruct, GetField, Reflect, Struct}; use criterion::{ black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput, }; criterion_group!( benches, concrete_struct_apply, concrete_struct_field, dynamic_struct_apply, d...
let mut s = DynamicStruct::default(); for i in 0..*field_count { let field_name = format!("field_{}", i); s.insert(&field_name, ()); } let field = black_box("field_63"); bencher.iter(|| { blac...
group.throughput(Throughput::Elements(field_count as u64)); group.bench_with_input( BenchmarkId::from_parameter(field_count), &field_count, |bencher, field_count| {
function_block-random_span
[]
Rust
src/map/themes.rs
ndouglas/downdelving
17517214f1c423284c686b4bc9509e24daf3d260
use rltk::RGB; use super::{Map, TileType}; use crate::components::Renderable; pub fn get_tile_renderable(idx: usize, map: &Map) -> Renderable { let mut result = match map.depth { 9 => get_mushroom_tile_renderable(idx, map), 8 => get_mushroom_tile_renderable(idx, map), 7 => { le...
use rltk::RGB; use super::{Map, TileType}; use crate::components::Renderable; pub fn get_tile_renderable(idx: usize, map: &Map) -> Renderable { let mut result = match map.depth { 9 => get_mushroom_tile_renderable(idx, map), 8 => get_mushroom_tile_renderable(idx, map), 7 => { le...
fn get_mushroom_tile_renderable(idx: usize, map: &Map) -> Renderable { let glyph; let fg; let bg = RGB::from_f32(0., 0., 0.); match map.tiles[idx] { TileType::Wall => { glyph = rltk::to_cp437('♠'); fg = RGB::from_f32(1.0, 0.0, 1.0); } TileType::Bridge =...
s => { glyph = rltk::to_cp437('>'); fg = RGB::from_f32(0., 1.0, 1.0); } TileType::UpStairs => { glyph = rltk::to_cp437('<'); fg = RGB::from_f32(0., 1.0, 1.0); } _ => { glyph = rltk::to_cp437('"'); fg = RGB::from_f32(...
function_block-function_prefixed
[ { "content": "pub fn apply_vertical_tunnel(map: &mut Map, y1: i32, y2: i32, x: i32) -> Vec<usize> {\n\n let mut corridor = Vec::new();\n\n for y in min(y1, y2)..=max(y1, y2) {\n\n let idx = map.xy_idx(x, y);\n\n if idx > 0\n\n && idx < map.width as usize * map.height as usize\n\n ...
Rust
src/internal/gc/thread_garbage.rs
Avi-D-coder/swym
3ffedeb760902bcb83606d35ebe2b1b01d24f41e
use crate::internal::{ alloc::FVec, epoch::QuiesceEpoch, gc::{ queued::{FnOnceish, Queued}, quiesce::OwnedSynch, }, }; use core::mem::{self, ManuallyDrop}; const UNUSED_BAG_COUNT: usize = 64; dyn_vec_decl! {struct DynVecFnOnceish: FnOnceish;} struct Bag { queued: DynVecFnOnceish<'...
use crate::internal::{ alloc::FVec, epoch::QuiesceEpoch, gc::{ queued::{FnOnceish, Queued}, quiesce::OwnedSynch, }, }; use core::mem::{self, ManuallyDrop}; const UNUSED_BAG_COUNT: usize = 64; dyn_vec_decl! {struct DynVecFnOnceish: FnOnceish;} struct Bag { queued: DynVecFnOnceish<'...
#[inline] fn collect(&mut self) { unsafe { for mut closure in self.queued.drain() { closure.call() } } } } #[repr(C)] struct SealedBag { quiesce_epoch: QuiesceEpoch, bag: Bag, } struct UnusedBags { bags: FVec<Bag>, } ...
fn seal(self, quiesce_epoch: QuiesceEpoch) -> SealedBag { debug_assert!(!self.queued.is_empty(), "attempt to seal an empty `Bag`"); SealedBag { bag: self, quiesce_epoch, } }
function_block-full_function
[ { "content": "/// An in place FnOnce\n\npub trait FnOnceish {\n\n /// Unsafe to call more than once\n\n unsafe fn call(&mut self);\n\n}\n\n\n\nimpl<T: 'static + Send> FnOnceish for Queued<T> {\n\n #[inline]\n\n unsafe fn call(&mut self) {\n\n // if T's actual alignment is greater than the ali...
Rust
src/game.rs
afaber999/rust_breakout
367fdc05fc479d729a0f762ae37098f1dee4549d
use std::{borrow::{Borrow, BorrowMut}, rc::Rc}; use glutin::event::VirtualKeyCode; use crate::game_object::GameObject; use crate::sprite_renderer::SpriteRenderer; use crate::resource_manager::ResourceManager; use crate::texture::Texture; use crate::game_level::GameLevel; use crate::ball_object::BallObject; ...
use std::{borrow::{Borrow, BorrowMut}, rc::Rc}; use glutin::event::VirtualKeyCode; use crate::game_object::GameObject; use crate::sprite_renderer::SpriteRenderer; use crate::resource_manager::ResourceManager; use crate::texture::Texture; use crate::game_level::GameLevel; use crate::ball_object::BallObject; ...
pub fn update(&mut self, dt: f32) { if let Some(objs) = self.globjs.borrow_mut() { objs.ball.do_move(dt, self.width as u32); } self.do_collisions(); } pub fn render( &mut self, _dt: f32) { if let Some(objs) = &self.globjs { o...
objs.player.set_position(position); }, VirtualKeyCode::Space => { objs.ball.un_stuck(); }, _ => (), } } }
function_block-function_prefix_line
[ { "content": "pub fn main() {\n\n unsafe \n\n {\n\n let event_loop = glutin::event_loop::EventLoop::new();\n\n let window_builder = glutin::window::WindowBuilder::new()\n\n .with_title(\"learn-opengl-glow => BREAKOUT\")\n\n .with_inner_size(glutin::dpi::LogicalSize::new...
Rust
src/statistics/lookups.rs
lukaspustina/mhost
238f4d70e8708deccdfcb665d84dda99a989c519
use std::collections::{BTreeMap, HashSet}; use std::fmt; use std::marker::PhantomData; use crate::resolver::lookup::LookupResult; use crate::resolver::{Error, Lookups}; use crate::RecordType; use super::*; #[derive(Debug)] pub struct LookupsStats<'a> { pub responses: usize, pub nxdomains: usize, pub ti...
use std::collections::{BTreeMap, HashSet}; use std::fmt; use std::marker::PhantomData; use crate::resolver::lookup::LookupResult; use crate::resolver::{Error, Lookups}; use crate::RecordType; use super::*; #[derive(Debug)] pub struct LookupsStats<'a> { pub responses: usize, pub nxdomains: usize, pub ti...
let rr_types = rr_types_as_str(&self.rr_type_counts); let num_rr = count_rrs(&self.rr_type_counts); let str = format!("{num_resp} responses with {num_rr} RR [{rr_types}], {num_nx} Nx, {errs} in (min {min_time}, max {max_time}) ms from {num_srvs} server{servers}", num_...
0 { styles::ERR.paint(refuses) } else { styles::NORMAL.paint(refuses) }, num_sf = if servfails > 0 { styles::ERR.paint(servfails) } else { styles::NORMAL.paint(servfails) ...
function_block-function_prefixed
[ { "content": "fn create_breaker(on_error: bool, on_timeout: bool) -> Box<dyn Fn(&Lookup) -> bool + Send> {\n\n Box::new(move |l: &Lookup| match l.result.err() {\n\n Some(Error::Timeout) if on_timeout => true,\n\n Some(Error::Timeout) if !on_timeout => false,\n\n Some(_) if on_error => tr...
Rust
src/game/shared/resource_manager.rs
deadshot465/demo_game
00a674a0a528f3a5c7c8284be36bf826998b139d
use ash::vk::CommandBuffer; use crossbeam::sync::ShardedLock; use parking_lot::Mutex; use std::collections::HashMap; use std::sync::Arc; use crate::game::enums::SceneType; use crate::game::graphics::vk::{Buffer, Graphics, Image}; use crate::game::shared::traits::disposable::Disposable; use crate::game::shared::traits:...
use ash::vk::CommandBuffer; use crossbeam::sync::ShardedLock; use parking_lot::Mutex; use std::collections::HashMap; use std::sync::Arc; use crate::game::enums::SceneType; use crate::game::graphics::vk::{Buffer, Graphics, Image}; use crate::game::shared::traits::disposable::Disposable; use crate::game::shared::traits:...
pub fn add_texture(&mut self, texture: TextureType) -> Arc<ShardedLock<TextureType>> { let texture_wrapped = Arc::new(ShardedLock::new(texture)); self.textures.push(texture_wrapped.clone()); texture_wrapped } pub fn get_model_count(&self) -> usize { let mut count = 0; ...
where U: Disposable, { self.resource.push(Arc::new(Mutex::new(Box::new(resource)))); let mutable = self.resource.last_mut().cloned().unwrap(); let mut boxed = mutable.lock(); boxed.set_name(name); let ptr = boxed.as_mut() as *mut _ as *mut U; ptr }
function_block-function_prefix_line
[ { "content": " #[doc = \"Generated trait containing gRPC methods that should be implemented for use with GrpcServiceServer.\"]\n\n #[async_trait]\n\n pub trait GrpcService: Send + Sync + 'static {\n\n #[doc = \" Register player to the database.\"]\n\n async fn register(\n\n &se...
Rust
src/archive.rs
shreyashsaitwal/aix-jetifier
bbd3d1e4f8c9cda1b751a6f929e95c9c9aaa7a21
use std::{fs, process}; use std::error::Error; use std::fs::File; use std::io::{ErrorKind, Read, Write}; use std::path::{Path, PathBuf}; use ansi_term::Color::Red; use zip::{ZipArchive, ZipWriter}; use zip::write::FileOptions; use crate::util; #[derive(PartialEq)] pub enum ArchiveType { Aia, Aix, } pub fn e...
use std::{fs, process}; use std::error::Error; use std::fs::File; use std::io::{ErrorKind, Read, Write}; use std::path::{Path, PathBuf}; use ansi_term::Color::Red; use zip::{ZipArchive, ZipWriter}; use zip::write::FileOptions; use crate::util; #[derive(PartialEq)] pub enum ArchiveType { Aia, Aix, } pub fn e...
pub fn pack_dir(dir_path: &Path, output_dir: &Path, prefix: &str) { let archive_basename = if prefix.eq(".x.aix") { dir_path.file_name().unwrap().to_str().unwrap() } else { dir_path.file_stem().unwrap().to_str().unwrap() }; let out_path = output_dir.join(format!("{}{}", archive_basena...
n!( " {} Unable to open {}. Reason: {}", Red.paint("error"), path.to_str().unwrap(), err.to_string() ); process::exit(1); } }; if let Err(err) = archive.extract(&output_dir) { eprintln!( ...
function_block-function_prefixed
[ { "content": "/// Returns the Recast's data directory.\n\npub fn data_dir() -> PathBuf {\n\n let home = if cfg!(windows) { \"UserProfile\" } else { \"HOME\" };\n\n Path::new(&env::var(home).unwrap()).join(\".recast\")\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 5, "score": 76507.530428388...
Rust
pnm2flif/src/verify.rs
SkoltechRobotics/oscar-cli
267f763dd7b6f0e5a3eb9ad6d04262fb834a5f00
use std::process::{Command, Stdio}; use std::path::Path; use std::io; use indicatif::{ProgressBar, ProgressStyle, ParallelProgressIterator}; use rayon::iter::{ParallelIterator, IntoParallelRefIterator}; use oscar_utils::{PBAR_TEMPLATE, WIDTH, HEIGHT}; use oscar_utils::conversions::{raw_flip, rgba2raw}; use oscar_util...
use std::process::{Command, Stdio}; use std::path::Path; use std::io; use indicatif::{ProgressBar, ProgressStyle, ParallelProgressIterator}; use rayon::iter::{ParallelIterator, IntoParallelRefIterator}; use oscar_utils::{PBAR_TEMPLATE, WIDTH, HEIGHT}; use oscar_utils::conversions::{raw_flip, rgba2raw}; use oscar_util...
fn cpp_flif_load(path: &Path) -> io::Result<Box<[u8]>> { let f = tempfile::Builder::new() .suffix(".pam") .tempfile()?; let status = Command::new("flif") .arg("-d") .arg("--overwrite") .arg(path) .arg(f.path()) .stderr(Stdio::null()) .stdout(Std...
fn get_filenames(dir: &Path, ext: &str) -> io::Result<Vec<String>> { let ext = std::ffi::OsStr::new(ext); let mut fnames = Vec::new(); for entry in std::fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); let ft = entry.file_type()?; if !ft.is_file() || path.ext...
function_block-full_function
[ { "content": "/// Demosaic image using bi-linear approach assuming BGGR pattern\n\npub fn bggr_bayer(data: &[u8], width: usize, height: usize) -> Box<[u8]> {\n\n assert_eq!(data.len(), width*height);\n\n assert_eq!(width % 2, 0);\n\n assert_eq!(height % 2, 0);\n\n let buf = vec![0u8; 3*width*height]...
Rust
src/swirlr.rs
willdady/swirlr-wasm
ffefb6d039588a4b25eeeffb77d0cd0f8f5545cd
extern crate image; use std::f64::consts::PI; use image::*; #[derive(Debug)] pub struct Point { x: f64, y: f64 } impl Point { fn dist(&self, point: &Point) -> f64 { ((point.x - self.x).powi(2) + (point.y - self.y).powi(2)).sqrt() } fn angle(&self, point: &Point) -> f64 { let del...
extern crate image; use std::f64::consts::PI; use image::*; #[derive(Debug)] pub struct Point { x: f64, y: f64 } impl Point { fn dist(&self, point: &Point) -> f64 { ((point.x - self.x).powi(2) + (point.y - self.y).powi(2)).sqrt() } fn angle(&self, point: &Point) -> f64 { let del...
fn get_average_rgba_between_points(source: &RgbaImage, p1: &Point, p2: &Point) -> Rgba<u8> { let dist = p1.dist(&p2) as u32; let theta = p1.angle(&p2); let (width, height) = source.dimensions(); let mut pixels = vec!(); for i in 0..dist { let sx = (p1.x + i as f64 * theta.cos()).round() as...
count += 1.0; } r = r / count; g = g / count; b = b / count; a = a / count; return Rgba([r.round() as u8, g.round() as u8, b.round() as u8, a.round() as u8]) }
function_block-function_prefix_line
[ { "content": "#[wasm_bindgen]\n\npub fn render() {\n\n let document = web_sys::window().unwrap().document().unwrap();\n\n let canvas = document.get_element_by_id(\"canvas\").unwrap();\n\n let canvas: web_sys::HtmlCanvasElement = canvas\n\n .dyn_into::<web_sys::HtmlCanvasElement>()\n\n .ma...
Rust
src/blocks.rs
rdrmic/color-columns
197a7a46ba314b93401a7882e764c85c844ec967
#![allow( clippy::float_cmp, clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_precision_loss, clippy::cast_sign_loss, clippy::missing_const_for_fn )] use std::fmt::{Display, Formatter, Result}; use rand::prelude::SliceRandom; use rand::rngs::ThreadRng; use rand::Rng; ...
#![allow( clippy::float_cmp, clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_precision_loss, clippy::cast_sign_loss, clippy::missing_const_for_fn )] use std::fmt::{Display, Formatter, Result}; use rand::prelude::SliceRandom; use rand::rngs::ThreadRng; use rand::Rng; ...
) -> Result { write!( f, "{} ({},{})", self.color.code, position_to_idx(self.rect.x, 'x'), position_to_idx(self.rect.y, 'y') ) } } #[derive(Debug, Copy, Clone)] pub struct BlockColor { pub code: char, pub color: Color, } /********...
A_RECT, }; use self::cargo::Cargo; pub mod cargo; pub mod matches; pub mod pile; pub fn position_to_idx(pos: f32, axis: char) -> usize { let idx: usize; if axis == 'x' { idx = ((pos - GAME_ARENA_RECT.left()) / BLOCK_SIZE) as usize; } else if axis == 'y' { idx = ((GAME_ARENA_RECT.bottom() ...
random
[ { "content": "# Color Columns\n\nA falling-blocks-type 2D game with a simple but addictive gameplay\n\n\n\n![Gameplay screenshot](github-resources/cc_gameplay.png)\n\n\n\n## About\n\nThe game is a remake of various old, \"classic\", columns-type games.\n\nAnd it's made in an attempt to learn [Rust programming l...
Rust
sudograph-generate/src/settings/generate_settings.rs
Sudograph/sudograph
a9c7e929c7413347bd925d15bd001d6a9399ef8d
use crate::get_graphql_type_name; use graphql_parser::schema::ObjectType; use proc_macro2::TokenStream; use quote::quote; pub fn generate_export_generated_query_function_attribute( sudograph_settings_option: Option<&ObjectType<String>> ) -> TokenStream { let export_generated_query_function_setting = get_settin...
use crate::get_graphql_type_name; use graphql_parser::schema::ObjectType; use proc_macro2::TokenStream; use quote::quote; pub fn generate_ex
{ let object_store = storage::get_mut::<ObjectTypeStore>(); sudograph::sudodb::clear(object_store); return Ok(true); } }; }, false => { return quote! {}; } }; } fn get_setting_boolean( ...
port_generated_query_function_attribute( sudograph_settings_option: Option<&ObjectType<String>> ) -> TokenStream { let export_generated_query_function_setting = get_setting_boolean( sudograph_settings_option, "exportGeneratedQueryFunction", true ); match export_generated_query_f...
random
[ { "content": "pub fn delete(\n\n object_type_store: &mut ObjectTypeStore,\n\n object_type_name: &str,\n\n id_option: Option<String>,\n\n ids_option: Option<Vec<String>>,\n\n selection_set: &SelectionSet\n\n) -> Result<Vec<String>, Box<dyn Error>> {\n\n // TODO playing around with where to plac...
Rust
src/backend/board_representation/movement.rs
SteinarSi/Chessbot5
ca241c4a74bb4cf89384f551b7a52f1a15f4b29b
use std::fmt; use std::char; use std::io::{Error, ErrorKind}; use std::iter::FromIterator; use std::ops::Index; use rand::thread_rng; use rand::prelude::SliceRandom; use super::piece::{Piece, Color, Color::*}; #[derive(Copy, Clone, Hash, Eq)] pub struct Move{ pub from: Position, pub to: Position, heur...
use std::fmt; use std::char; use std::io::{Error, ErrorKind}; use std::iter::FromIterator; use std::ops::Index; use rand::thread_rng; use rand::prelude::SliceRandom; use super::piece::{Piece, Color, Color::*}; #[derive(Copy, Clone, Hash, Eq)] pub struct Move{ pub from: Position, pub to: Position, heur...
}
e, -10), Move::new(0, 0, 0, 0, None, 100)]); let expected_white = Moves(vec![Move::new(0, 0, 0, 0, None, 100), Move::new(0, 0, 0, 0, None, 50), Move::new(0, 0, 0, 0, None, 25), Move::new(0, 0, 0, 0, None, -10)]); moves.sort_by_heuristic(White); assert_eq!(moves, expected_white); let expected_black = Mov...
function_block-function_prefixed
[ { "content": "fn solve_position(s: &str, c: Color) -> Moves{\n\n let mut bot = Omikron::new();\n\n let b = Board::custom(s, c);\n\n bot.set_time(30);\n\n bot.search(b.clone());\n\n\n\n bot.principal_variation(b)\n\n}\n", "file_path": "src/backend/bot_testing.rs", "rank": 0, "score": 2...
Rust
crates/pill_engine/src/ecs/components/mesh_rendering_component.rs
MattSzymonski/Pill-Engine
a7d1584896b5edd4ac7db258db4406e1bb7f4135
use crate::{ engine::Engine, graphics::{ RenderQueueKey, compose_render_queue_key }, resources::{ Material, MaterialHandle, Mesh, MeshHandle, ResourceManager }, ecs::{ EntityHandle, ComponentStorage, Component, SceneHandle, DeferredUpdateComponentRequest, DeferredUpdateManagerPointer, DeferredUpdateCom...
use crate::{ engine::Engine, graphics::{ RenderQueueKey, compose_render_queue_key }, resources::{ Material, MaterialHandle, Mesh, MeshHandle, ResourceManager }, ecs::{ EntityHandle, ComponentStorage, Component, SceneHandle, DeferredUpdateComponentRequest, DeferredUpdateManagerPointer, DeferredUpdateCom...
} } } impl PillTypeMapKey for MeshRenderingComponent { type Storage = ComponentStorage<MeshRenderingComponent>; } impl Component for MeshRenderingComponent { fn initialize(&mut self, engine: &mut Engine) -> Result<()> { let deferred_update_component = engine.get_global_component_mut:...
lf.post_deferred_update_request(DEFERRED_REQUEST_VARIANT_UPDATE_RENDER_QUEUE); } pub fn remove_mesh(&mut self) { self.mesh_handle = None; self.post_deferred_update_request(DEFERRED_REQUEST_VARIANT_UPDATE_RENDER_QUEUE); } pub(crate) fn set_material_handle(&mut self, material_handle: Opt...
random
[ { "content": "// Creates pill engine render queue composed from order, material index, material version, mesh index, mesh version\n\npub fn compose_render_queue_key(resource_manager: &ResourceManager, material_handle: &MaterialHandle, mesh_handle: &MeshHandle) -> Result<RenderQueueKey> { \n\n let material = ...
Rust
src/lib.rs
dmulholl/arguably
9c08f7d84cc7b71bff440b091e0700b7cee4b810
use std::collections::HashMap; use std::fmt; use std::error; #[derive(Debug)] pub enum Error { InvalidName(String), MissingValue(String), MissingHelpArg, InvalidUnicode, } impl error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -...
use std::collections::HashMap; use std::fmt; use std::error; #[derive(Debug)] pub enum Error { InvalidName(String), MissingValue(String), MissingHelpArg, InvalidUnicode, } impl error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -...
fn handle_short_opt(&mut self, arg: &str, argstream: &mut ArgStream) -> Result<(), Error> { for c in arg.chars().skip(1) { if let Some(index) = self.flag_map.get(&c.to_string()) { self.flags[*index].count += 1; } else if let Some(index) = self.option_map.get(&c.to_s...
fn handle_long_opt(&mut self, arg: &str, argstream: &mut ArgStream) -> Result<(), Error> { if let Some(index) = self.flag_map.get(&arg[2..]) { self.flags[*index].count += 1; } else if let Some(index) = self.option_map.get(&arg[2..]) { if argstream.has_next() { sel...
function_block-full_function
[ { "content": "fn cmd_boo(_cmd_name: &str, _cmd_parser: &ArgParser) {\n\n println!(\"boo!\");\n\n}\n", "file_path": "examples/command.rs", "rank": 1, "score": 70111.62751531908 }, { "content": "#[test]\n\nfn command_missing() {\n\n let mut parser = ArgParser::new().command(\"cmd\", ArgP...
Rust
src/utilities.rs
Seifayachi001/PayScale-API
637b937dd0350f8eca23525781a41a51c56980bf
use std::fs::File; use std::error::Error; use std::io::{BufReader}; use std::cmp; use chrono::prelude::*; use crate::models::{Group, PayScale, RateOfPay, ActiveRateOfPay}; pub fn load_group_data() -> Result<Vec<Group>, Box<dyn Error>> { let file = File::open("./data/groups_data.json").expect("could not open file...
use std::fs::File; use std::error::Error; use std::io::{BufReader}; use std::cmp; use chrono::prelude::*; use crate::models::{Group, PayScale, RateOfPay, ActiveRateOfPay}; pub fn load_group_data() -> Result<Vec<Group>, Box<dyn Error>> { let file = File::open("./data/groups_data.json").expect("could not open file...
if sd >= convert_string_to_naive_date(&rates[next_rate_index].date_time) { rate_index += 1; } }; active_rates_of_pay }
veDate, ) -> Vec<ActiveRateOfPay> { let rates = &payscale.rates_of_pay; let mut step = 0; let max_step = payscale.steps as usize - 1; let max_rate = payscale.rates_of_pay.len() - 1; let mut active_rates_of_pay = Vec::new(); for (i, (s, e)) in steps.iter().enumerate() { if start...
random
[ { "content": "pub fn create_schema() -> Schema {\n\n Schema::new(QueryRoot, EmptyMutation::new())\n\n}\n\n\n", "file_path": "src/graphql_schema.rs", "rank": 6, "score": 66767.92777064219 }, { "content": "", "file_path": "src/errors/errors.rs", "rank": 7, "score": 32743.7923918...
Rust
src/spi/peripheral.rs
c-rustacean/lpc8xx-hal
cee8a0047ff38ec909c87b30b7435a225e3a29a1
use core::convert::Infallible; use embedded_hal::spi::{FullDuplex, Mode, Phase, Polarity}; use crate::{ dma::{self, transfer::state::Ready}, init_state::{Disabled, Enabled}, pac::spi0::cfg::MASTER_A, swm, syscon, }; use super::{Clock, ClockSource, Instance, Interrupts, SlaveSelect, Transfer}; pub st...
use core::convert::Infallible; use embedded_hal::spi::{FullDuplex, Mode, Phase, Polarity}; use crate::{ dma::{self, transfer::state::Ready}, init_state::{Disabled, Enabled}, pac::spi0::cfg::MASTER_A, swm, syscon, }; use super::{Clock, ClockSource, Instance, Interrupts, SlaveSelect, Transfer}; pub st...
} impl<I, Mode> SPI<I, Enabled<Mode>> where I: Instance, { pub fn enable_interrupts(&mut self, interrupts: Interrupts) { interrupts.enable(&self.spi); } pub fn disable_interrupts(&mut self, interrupts: Interrupts) { interrupts.disable(&self.spi)...
e.phase { Phase::CaptureOnFirstTransition => { w.cpha().clear_bit(); } Phase::CaptureOnSecondTransition => { w.cpha().set_bit(); } } w.master().variant(master); w.enable().enabled(...
function_block-function_prefixed
[ { "content": "/// Implemented by types that indicate the state of SWM functions\n\n///\n\n/// This trait is implemented by types that indicate the state of SWM functions.\n\n/// It exists only to document which types those are. Users should not need to\n\n/// implement this trait, nor use it directly.\n\npub tr...
Rust
src/gtk_app/app.rs
svenslaggare/imageeditor
bd86b504c92f79e740ff2dbcfa835fab2e11a1ee
use std::rc::Rc; use std::cell::RefCell; use std::ops::{Deref, DerefMut}; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use gtk::prelude::*; use gtk::{Application, ApplicationWindow, GLArea, Orientation, EventBox, gdk, gdk_pixbuf}; use gtk::gio::ApplicationFlags; use gtk::gdk_...
use std::rc::Rc; use std::cell::RefCell; use std::ops::{Deref, DerefMut}; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use gtk::prelude::*; use gtk::{Application, ApplicationWindow, GLArea, Orientation, EventBox, gdk, gdk_pixbuf}; use gtk::gio::ApplicationFlags; use gtk::gdk_...
.width() { let pixel = image.get_pixel(x, y); gtk_image.put_pixel(x, y, pixel[0], pixel[1], pixel[2], pixel[3]); } } self_change.store(true, Ordering::SeqCst); clipboard_clone.set...
:new(GTKProgram::new()); let clipboard = Rc::new(gtk::Clipboard::get(&gdk::SELECTION_CLIPBOARD)); let layout = gtk::Box::new(Orientation::Vertical, 6); window.add(&layout); let gl_area = Rc::new(GLArea::new()); gl_loader::init_gl(); gl::load_with(|symbol| gl_loader::get...
random
[ { "content": "fn create_resize_dialog(window: &ApplicationWindow,\n\n gtk_program: GTKProgramRef,\n\n title: &str) -> (gtk::Dialog, (gtk::SpinButton, gtk::SpinButton, gtk::SpinButton)) {\n\n let resize_dialog = create_dialog(window, title);\n\n resize_dialog.s...
Rust
src/main.rs
Riku32/kawaii.sh
2ec4b697f4ea7357d844203e168c189561dde183
use config::StorageConfig; use models::MessageResponse; use tokio::fs; use std::{ panic, path::{Path, PathBuf}, }; use actix_web::{ dev::{ServiceRequest, ServiceResponse}, http::StatusCode, middleware::Logger, web::{self, Data}, App, HttpRequest, HttpServer, }; use actix_files::{Files, Na...
use config::StorageConfig; use models::MessageResponse; use tokio::fs; use std::{ panic, path::{Path, PathBuf}, }; use actix_web::{ dev::{ServiceRequest, ServiceResponse}, http::StatusCode, middleware::Logger, web::{self, Data}, App, HttpRequest, HttpServer, }; use actix_files::{Files, Na...
ne, }; HttpServer::new(move || { let mut app = App::new() .wrap(Logger::default()) .app_data(api_state.clone()) .service( web::scope("/api/") .service(routes::user::get_routes(smtp_enabled)) .service(routes::aut...
function_block-function_prefixed
[ { "content": "// Sign a JWT token and get a string\n\npub fn create_jwt_string(\n\n user_id: &str,\n\n application_id: Option<String>,\n\n issuer: &str,\n\n expiration: Option<i64>,\n\n key: &str,\n\n) -> Result<String, jsonwebtoken::errors::Error> {\n\n let claims = JWTClaims {\n\n iss...
Rust
src/lib.rs
Joylei/plctag-rs
23f515b893299229ca8acc2422c47e87fe6fa11d
/*! # plctag-rs a rust wrapper of [libplctag](https://github.com/libplctag/libplctag), with rust style APIs and useful extensions. [![crates.io](https://img.shields.io/crates/v/plctag.svg)](https://crates.io/crates/plctag) [![docs](https://docs.rs/plctag/badge.svg)](https://docs.rs/plctag) [![build](https:...
/*! # plctag-rs a rust wrapper of [libplctag](https://github.com/libplctag/libplctag), with rust style APIs and useful extensions. [![crates.io](https://img.shields.io/crates/v/plctag.svg)](https://crates.io/crates/plctag) [![docs](https://docs.rs/plctag/badge.svg)](https://docs.rs/plctag) [![build](https:...
.element_size(16) .element_count(1) .path("1,0") .read_cache_ms(0) .build() .unwrap(); let tag = RawTag::new(path, timeout).unwrap(); let status = tag.status(); assert!(status.is_ok()); } ``` ### Logging adapter for `libplctag` ```rust,ignore us...
) log adapter for `libplctag` - [plctag-derive](https://crates.io/crates/plctag-derive) macros for `plctag` - [plctag-sys](https://crates.io/crates/plctag-sys) native libplctag binding ## Examples ### read/write tag ```rust,ignore use plctag::{Encode, Decode, RawTag}; let timeout = 100;//ms let path="prot...
random
[ { "content": "#[derive(Debug)]\n\nstruct Wrapper<T>(Arc<Shared<T>>);\n\n\n\nimpl<T> Deref for Wrapper<T> {\n\n type Target = Shared<T>;\n\n #[inline(always)]\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\n\n\n/// Tag Entry State\n", "file_path": "crates/async/src/pool.rs...
Rust
rustfst/src/algorithms/rm_epsilon/rm_epsilon_static.rs
llogiq/rustfst
3172547ad57c5ae7e1c0474fd49187a81555b516
use anyhow::Result; use crate::algorithms::dfs_visit::dfs_visit; use crate::algorithms::queues::AutoQueue; use crate::algorithms::rm_epsilon::{RmEpsilonInternalConfig, RmEpsilonState}; use crate::algorithms::top_sort::TopOrderVisitor; use crate::algorithms::tr_filters::EpsilonTrFilter; use crate::algorithms::visitors:...
use anyhow::Result; use crate::algorithms::dfs_visit::dfs_visit; use crate::algorithms::queues::AutoQueue; use crate::algorithms::rm_epsilon::{RmEpsilonInternalConfig, RmEpsilonState}; use crate::algorithms::top_sort::TopOrderVisitor; use crate::algorithms::tr_filters::EpsilonTrFilter; use crate::algorithms::visitors:...
pub(crate) fn rm_epsilon_with_internal_config<W: Semiring, F: MutableFst<W>, Q: Queue>( fst: &mut F, opts: RmEpsilonInternalConfig<W, Q>, ) -> Result<()> { let connect = opts.connect; let weight_threshold = opts.weight_threshold.clone(); let state_threshold = opts.state_threshold; let start_st...
pub fn rm_epsilon<W: Semiring, F: MutableFst<W>>(fst: &mut F) -> Result<()> { let tr_filter = EpsilonTrFilter {}; let queue = AutoQueue::new(fst, None, &tr_filter)?; let opts = RmEpsilonInternalConfig::new_with_default(queue); rm_epsilon_with_internal_config(fst, opts) }
function_block-full_function
[ { "content": "/// Compare trs in the order input label, output label, weight and nextstate.\n\npub fn tr_compare<W: Semiring>(tr_1: &Tr<W>, tr_2: &Tr<W>) -> Ordering {\n\n if tr_1.ilabel < tr_2.ilabel {\n\n return Ordering::Less;\n\n }\n\n if tr_1.ilabel > tr_2.ilabel {\n\n return Orderin...
Rust
crates/tm4c129x/src/usb0/csrl0.rs
m-labs/ti2svd
30145706b658136c35c90290701de3f02a4b8ef2
#[doc = "Writer for register CSRL0"] pub type W = crate::W<u8, super::CSRL0>; #[doc = "Register CSRL0 `reset()`'s with value 0"] impl crate::ResetValue for super::CSRL0 { type Type = u8; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `RXRDY`"] pub struct ...
#[doc = "Writer for register CSRL0"] pub type W = crate::W<u8, super::CSRL0>; #[doc = "Register CSRL0 `reset()`'s with value 0"] impl crate::ResetValue for super::CSRL0 { type Type = u8; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `RXRDY`"] pub struct ...
<< 6); self.w } } #[doc = "Write proxy for field `NAKTO`"] pub struct NAKTO_W<'a> { w: &'a mut W, } impl<'a> NAKTO_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(alway...
fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u8) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `...
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
advanced_features/src/unsafe_rust.rs
monadplus/learning-rust
edf05c24b4f79a5e77819189d1283419b7c36a19
extern "C" { fn abs(input: i32) -> i32; } #[no_mangle] pub extern "C" fn call_from_c() { println!("Just called a Rust function from C!"); } static HELLO_WORLD: &str = "Hello, world!"; static mut COUNTER: u32 = 0; fn add_to_count(inc: u32) { unsafe { COUNTER += inc; } } pub fn main() { ...
extern "C" { fn abs(input: i32) -> i32; } #[no_mangle] pub extern "C" fn call_from_c() { println!("Just called a Rust function from C!"); } static HELLO_WORLD: &str = "Hello, world!"; static mut COUNTER: u32 = 0; fn add_to_count(inc: u32) { unsafe { COUNTER += inc; } } pub fn main() { ...
t_at_mut as safe rust code. fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { let len = slice.len(); assert!(mid <= len); // two mutable borrows (&mut slice[..mid], &mut slice[mid..]) } Rust’s borrow checker can’t understand that we’re borrowing d...
function_block-function_prefixed
[]
Rust
sardine/src/srd_errors.rs
bryanmccollaum1/sardine-rs
19f4fbe165542b024d702c51da9481356c21ce39
use hmac::crypto_mac::InvalidKeyLength; use std; use std::ffi::NulError; use std::fmt; use std::io::Error; use std::string::FromUtf8Error; use chacha; use rand; #[derive(Debug)] pub enum SrdError { Io(Error), Ffi(NulError), BadSequence, Crypto, MissingBlob, BlobFormatError, Cipher, Rn...
use hmac::crypto_mac::InvalidKeyLength; use std; use std::ffi::NulError; use std::fmt; use std::io::Error; use std::string::FromUtf8Error; use chacha; use rand; #[derive(Debug)] pub enum SrdError { Io(Error), Ffi(NulError), BadSequence, Crypto, MissingBlob, BlobFormatError, Cipher, Rn...
or: rand::Error) -> SrdError { SrdError::Rng } } cfg_if! { if #[cfg(feature = "aes")] { use block_modes::{InvalidKeyIvLength, BlockModeError}; impl From<InvalidKeyIvLength> for SrdError { fn from(_error: InvalidKeyIvLength) -> SrdError{ SrdError::Crypto ...
manipulating null-terminated strings", SrdError::BadSequence => "Unexpected packet received", SrdError::Crypto => "There was a cryptographic error", SrdError::MissingBlob => "No blob specified", SrdError::BlobFormatError => "Blob format error", SrdError::Ciphe...
random
[ { "content": "#[cfg(not(feature = \"wasm\"))]\n\npub fn fill_random(data: &mut [u8]) -> Result<()> {\n\n OsRng.try_fill_bytes(data)?;\n\n Ok(())\n\n}\n\n\n\n#[cfg(feature = \"wasm\")]\n\n#[wasm_bindgen]\n\nextern \"C\" {\n\n // For WebAssembly, you must bind your own rng or else it will fail. This will...
Rust
pkg/integer/src/lib.rs
babygau/projecteuler-rust
0e9adcc4ef2d084b6520a63f41110c91c7165309
#![warn(bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] extern crate num; use std::cmp::Ordering; use num::{One, Zero, FromPrimitive, ToPrimitive}; pub trait Integer: num::Integer + Clone + FromPrimitive + ToPrimitive { ...
#![warn(bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] extern crate num; use std::cmp::Ordering; use num::{One, Zero, FromPrimitive, ToPrimitive}; pub trait Integer: num::Integer + Clone + FromPrimitive + ToPrimitive { ...
(&3)); assert_eq!(2, 5.div_round(&3)); assert_eq!(2, 5.div_ceil(&3)); assert_eq!(3, 5.div_round(&2)); } #[test] fn digits() { fn check(n: u32, v: &[u32], radix: u32) { assert_eq!(v, &n.into_digits(radix).collect::<Vec<_>>()[..]); let mut rev = n.into...
#[inline] fn from_digits<T: Iterator<Item = Self>>(digits: T, radix: Self) -> Self { let mut result: Self = Zero::zero(); let mut order: Self = One::one(); for d in digits { result = result + order.clone() * d; order = order * radix.clone(); } result ...
random
[ { "content": "/// Numbers which can be factorized.\n\npub trait Factorize: Integer + FromPrimitive + Clone {\n\n /// An iterator visiting all factors in ascending order.\n\n fn factorize(&self, ps: &PrimeSet) -> Factors<Self>;\n\n\n\n /// Calculates the number of all positive divisors.\n\n fn num_of...
Rust
leaf/src/proxy/tls/stream.rs
gaoxiaowei/leaf
ecce10a7100f145a1f66d7b1440ee1ca4ebcc6b1
use anyhow::{anyhow, Result}; use futures::TryFutureExt; use tokio::io::{AsyncRead, AsyncWrite}; use crate::proxy::{ProxyStream, SimpleProxyStream}; use log::*; #[cfg(feature = "rustls-tls")] pub mod wrapper { use std::sync::Arc; use tokio_rustls::{rustls::ClientConfig, webpki::DNSNameRef, TlsConnector}; ...
use anyhow::{anyhow, Result}; use futures::TryFutureExt; use tokio::io::{AsyncRead, AsyncWrite}; use crate::proxy::{ProxyStream, SimpleProxyStream}; use log::*; #[cfg(feature = "rustls-tls")] pub mod wrapper { use std::sync::Arc; use tokio_rustls::{rustls::ClientConfig, webpki::DNSNameRef, TlsConnector}; ...
trace!("stream openssl-tls:wrap_tls option {}", insecure); let connector = builder.build(); let mut ssl = Ssl::new(connector.context()).map_err(|_| anyhow!(format!("new tls stream failed")))?; ssl.set_hostname(domain) .map_err(|_| anyhow!(format!("set tls hostna...
if alpns.len() > 0 { let wire = alpns .into_iter() .map(|a| [&[a.len() as u8], a.as_bytes()].concat()) .collect::<Vec<Vec<u8>>>() .concat(); builder .set_alpn_protos(&wire) .map_err(|e| anyhow!(format...
if_condition
[ { "content": "/// A reliable transport for both inbound and outbound handlers.\n\npub trait ProxyStream: AsyncRead + AsyncWrite + Send + Sync + Unpin {}\n\n\n", "file_path": "leaf/src/proxy/mod.rs", "rank": 0, "score": 415717.8247347756 }, { "content": "pub fn from_file(path: &str) -> Result...
Rust
src/expectation.rs
dyedgreen/uncertain
579d9c368bbae7c19661c599a349b8db8d271a8a
use crate::Uncertain; use num_traits::{identities, Float}; use rand_pcg::Pcg32; use std::error::Error; use std::fmt; const STEP: usize = 10; const MAXS: usize = 1000; #[derive(Debug, Clone)] pub struct ConvergenceError<F> where F: Float, { sample_mean: F, diff_sum: F, steps: F, precision: F, } im...
use crate::Uncertain; use num_traits::{identities, Float}; use rand_pcg::Pcg32; use std::error::Error; use std::fmt; const STEP: usize = 10; const MAXS: usize = 1000; #[derive(Debug, Clone)] pub struct ConvergenceError<F> where F: Float, { sample_mean: F, diff_sum: F, steps: F, precision: F, } im...
} impl<F: Float + fmt::Debug + fmt::Display> Error for ConvergenceError<F> {} fn mean_standard_deviation<F: Float>(diff_sum: F, steps: F) -> F { diff_sum.sqrt() / steps } pub fn compute<U>(src: &U, precision: U::Value) -> Result<U::Value, ConvergenceError<U::Value>> where U: Uncertain + ?Sized, U::Valu...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Expected value {} +/- {} did not converge to desired precision {}", self.non_converged_value(), self.two_sigma_error(), self.desired_precision() ) }
function_block-full_function
[ { "content": "/// Compute the sequential probability ration test.\n\npub fn compute<U>(src: &U, prob: f32) -> bool\n\nwhere\n\n U: Uncertain + ?Sized,\n\n U::Value: Into<bool>,\n\n{\n\n let mut rng = Pcg32::new(0xcafef00dd15ea5e5, 0xa02bdbf7bb3c0a7);\n\n\n\n let upper_ln = (D1 / (1.0 - D1)).ln();\n\...
Rust
src/main.rs
Niniib/anime4you-dl
ba56344a8a6853309a3d852f0ff8a9cb23acd7a5
use std::{ collections::HashMap, fs::File, path::Path, process::{exit, Command}, }; use anime4you::{Host, Language, Resolver, Series}; use anyhow::{anyhow, Error}; use clap::{App, Arg}; use colorful::Color; use colorful::Colorful; use downloader::Downloader; use dssim_core::{Dssim, ToRGBAPLU}; use imgr...
use std::{ collections::HashMap, fs::File, path::Path, process::{exit, Command}, }; use anime4you::{Host, Language, Resolver, Series}; use anyhow::{anyhow, Error}; use clap::{App, Arg}; use colorful::Color; use colorful::Colorful; use downloader::Downloader; use dssim_core::{Dssim, ToRGBAPLU}; use imgr...
async fn download( episode: u32, link: &str, output: &str, pattern: String, title: &str, use_youtube_dl: bool, ) -> Result<(), Error> { let pattern = pattern.replace("(%series_name)", sanitize_filename(title).as_str()); let pattern = pattern.replace("(%episode)", episode.to_string().as...
async fn get_downloader(link: &str) -> Result<Downloader, Error> { let hoster = Host::get_from_url(link); match hoster { Host::Vivo => downloader::vivo::new(link).await, Host::Vidoza => downloader::vidoza::new(link).await, Host::GoUnlimited => downloader::gounlimited::new(link).await, ...
function_block-full_function
[ { "content": "fn rot47(input: String) -> String {\n\n caesar(input, \"!\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\", 47)\n\n}\n\n\n\npub async fn new(url: &str) -> Result<Downloader, Error> {\n\n let url = url.replace(\"embed/\", \"\");\n\n let r...
Rust
src/io.rs
parallel-programming-hwr/bdflib-rs
f346eeb0cc661a30c8b9560db8e17840538164ac
use super::chunks::*; use byteorder::{BigEndian, ByteOrder}; use std::collections::HashMap; use std::convert::TryInto; use std::fs::File; use std::io::Error; use std::io::{BufReader, BufWriter, ErrorKind, Read, Write}; use std::thread; use crossbeam_channel::{bounded, Sender, Receiver}; use crossbeam_utils::sync::WaitG...
use super::chunks::*; use byteorder::{BigEndian, ByteOrder}; use std::collections::HashMap; use std::convert::TryInto; use std::fs::File; use std::io::Error; use std::io::{BufReader, BufWriter, ErrorKind, Read, Write}; use std::thread; use crossbeam_channel::{bounded, Sender, Receiver}; use crossbeam_utils::sync::WaitG...
pub fn next_chunk(&mut self) -> Result<GenericChunk, Error> { if self.compressed { if let Err(_) = self.add_compression_chunk() { self.thread_manager.drop_sender(); } if let Ok(chunk) = self.thread_manager.receiver_result.recv() { Ok...
l { let mut header = [0u8; 11]; let _ = self.reader.read(&mut header); header == BDF_HDR.as_ref() }
function_block-function_prefixed
[ { "content": " data: serialized_data,\n\n crc: crc_sum,\n\n }\n\n }\n\n\n\n /// Compresses the data of the chunk using lzma with a level of 6\n\n pub fn compress(&mut self, level: u32) -> Result<(), Error> {\n\n let data = self.data.as_slice();\n\n let mut com...
Rust
src/modal.rs
aleksey-r/rust-crud
424e688ca96ec6c895ce1e6ebb1b5ac54ea95cba
use yew::prelude::*; use yew::{html, Component, ComponentLink, Html, ShouldRender}; use stdweb::unstable::TryInto; use stdweb::web::{event::IEvent, Element, FormData}; use crate::item::Item; use crate::item::ItemFormData; use crate::item::ItemValidationErr; use yew::services::{ ConsoleService }; #[derive(Propertie...
use yew::prelude::*; use yew::{html, Component, ComponentLink, Html, ShouldRender}; use stdweb::unstable::TryInto; use stdweb::web::{event::IEvent, Element, FormData}; use crate::item::Item; use crate::item::ItemFormData; use crate::item::ItemValidationErr; use yew::services::{ ConsoleService }; #[derive(Propertie...
fn change(&mut self, props: Self::Properties) -> ShouldRender { self.item = props.item; self.visible = props.visible; true } fn view(&self) -> Html { let visible = if self.visible { "is-active" } else { "" }; let error = |e: &ItemValidationErr| { match e { ItemValidationErr:...
alMsg::HideModal => { self.visible = false; self.on_close.emit(true); true } ModalMsg::Save(form_data) => { let form_data: ItemFormData = form_data.into(); let valid = ItemFormData::validate(&form_data); match valid { Ok(_v) => { self....
function_block-function_prefixed
[ { "content": "fn main() {\n\n yew::start_app::<Model>();\n\n}\n", "file_path": "src/main.rs", "rank": 0, "score": 20636.372588662816 }, { "content": " price: String\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum ItemValidationErr {\n\n InvalidName,\n\n InvalidPrice\n\n}\n\n\n\nimpl ...
Rust
src/lib.rs
xoac/futures-test-sink
5311a922f19446538b4943252456ef9b03e4afe3
#![deny(missing_docs)] pub mod fuse_last; mod mock_sink; pub use mock_sink::SinkMock; use futures::never::Never; use futures::sink::Sink; use std::iter::{repeat, successors, Repeat}; use std::marker::PhantomData; use std::{ pin::Pin, task::{Context, Poll}, }; fn reverse<E>(poll: &Poll<Result<(), E>>) -> O...
#![deny(missing_docs)] pub mod fuse_last; mod mock_sink; pub use mock_sink::SinkMock; use fu
let r3 = Pin::new(&mut s).poll_ready(&mut cx); assert_eq!(r3, Poll::Pending); assert_eq!(1, cnt.load(atomic::Ordering::SeqCst)); let r4 = Pin::new(&mut s).poll_ready(&mut cx); assert_eq!(r4, Poll::Ready(Err(12))); assert_eq!(1, cnt.load(atomic::Ordering::SeqCst)); ...
tures::never::Never; use futures::sink::Sink; use std::iter::{repeat, successors, Repeat}; use std::marker::PhantomData; use std::{ pin::Pin, task::{Context, Poll}, }; fn reverse<E>(poll: &Poll<Result<(), E>>) -> Option<Poll<Result<(), E>>> { match poll { Poll::Pending => Some(Poll::Ready(Ok(()))),...
random
[ { "content": "/// Extension trait for Iterator that allow use `FuseLast` in chain-like manner.\n\npub trait IteratorExt: Iterator {\n\n /// Creates an iterator that will be fused on last element forever.\n\n ///\n\n /// After an iterator returns `None`, future calls may or may not yield `Some(T)` again...
Rust
ronvoy-proxy/src/route.rs
bpowers/ronvoy
e04b9081ee3cc0d3043154831721382ae3212242
use axum::http::Uri; use std::error::Error as StdError; use std::fmt::{Display, Formatter}; use envoy_control_plane::envoy::config::route::v3::{ route::Action as V3Action, route_action::ClusterSpecifier as V3ClusterSpecifier, route_match::PathSpecifier as V3PathSpecifier, Route as V3Route, RouteAction as V3R...
use axum::http::Uri; use std::error::Error as StdError; use std::fmt::{Display,
Error> { match value.cluster_specifier { Some(V3ClusterSpecifier::Cluster(name)) => Ok(RouteAction { cluster: ClusterSpecifier::Name(name), }), _ => Err(Error::UnsupportedClusterSpecifier), } } } #[derive(Debug, Clone, PartialEq)] pub enum Action ...
Formatter}; use envoy_control_plane::envoy::config::route::v3::{ route::Action as V3Action, route_action::ClusterSpecifier as V3ClusterSpecifier, route_match::PathSpecifier as V3PathSpecifier, Route as V3Route, RouteAction as V3RouteAction, RouteMatch as V3RouteMatch, }; #[derive(Debug, Clone, PartialEq)]...
random
[ { "content": "pub fn load_config_sync(path: &Path) -> Result<V3Bootstrap, Box<dyn StdError>> {\n\n let config_contents = file::read_all_utf8_sync(path)?;\n\n let config_ext = path.extension().unwrap_or_default();\n\n let bootstrap = if config_ext == \"yaml\" || config_ext == \"yml\" {\n\n eprint...
Rust
src/main.rs
mfep/genee
c303f4ab56570acab85f8e852b570e30648866ef
use anyhow::{bail, Context, Result}; use chrono::Duration; use chrono::Local; use chrono::NaiveDate; use dialoguer::MultiSelect; use genee::configuration; use genee::datafile; use genee::datafile::DiaryData; use genee::graphing; use std::path::{Path, PathBuf}; use structopt::StructOpt; #[derive(StructOpt)] #[structopt...
use anyhow::{bail, Context, Result}; use chrono::Duration; use chrono::Local; use chrono::NaiveDate; use dialoguer::MultiSelect; use genee::configuration; use genee::datafile; use genee::datafile::DiaryData; use genee::graphing; use std::path::{Path, PathBuf}; use structopt::StructOpt; #[derive(StructOpt)] #[structopt...
fn handle_config() -> Result<CliOptions> { let opt = CliOptions::from_args(); let persistent_config = configuration::load_config()?; let opt = merge_cli_and_persistent_options(opt, &persistent_config); Ok(opt) } fn parse_from_date(input_date: &Option<String>) -> Result<Option<NaiveDate>> { match ...
y(), &persistent_config ); } Command::New { ref category_list } => { create_new(datafile_path, category_list)?; } Command::SaveConfig => { save_config(&opt)?; } } Ok(()) }
function_block-function_prefixed
[ { "content": "fn pretty_print_row(date: &NaiveDate, data: &[bool]) -> String {\n\n let mut ret = String::new();\n\n ret += &date.format(datafile::DATE_FORMAT).to_string();\n\n for &val in data {\n\n ret += if val { \" ✓ \" } else { \" \" };\n\n }\n\n ret += \"\\n\";\n\n ret\n\n}\n\n...
Rust
hom_nand/src/tlwe.rs
hideki1217/rusTfhe
a5a910dedc09916b3aa849e54de8b1aacb099bdd
use super::digest::{Crypto, Cryptor, Encryptable, Encrypted}; use num::Zero; use std::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign}; use utils::{ math::{Binary, ModDistribution, Random, Torus32}, mem, torus, traits::AsLogic, }; pub struct TLWE<const N: usize>; macro_rules! tlwe_encryptable { ($t:ty) ...
use super::digest::{Crypto, Cryptor, Encryptable, Encrypted}; use num::Zero; use std::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign}; use utils::{ math::{Binary, ModDistribution, Random, Torus32}, mem, torus, traits::AsLogic, }; pub struct TLWE<const N: usize>; macro_rules! tlwe_encryptable { ($t:ty) ...
, "Part1.keyを変えてもidenitity, item={}", item); }; test(Binary::One); test(Binary::Zero); } { const N: usize = 256; const M: usize = 60; let mut b_uniform = BinaryDistribution::uniform(); let s_key_tlwelv1 = b_uniform.gen_...
type Output = Self; fn mul(self, rhs: Int) -> Self::Output { let (b, mut a) = self.get_and_drop(); a.iter_mut().for_each(|a_| *a_ = *a_ * rhs); TLWERep::new(b * rhs, a) } } impl<const N: usize> Zero for TLWERep<N> { fn zero() -> Self { TLWERep::new(Torus32::zero(), [Toru...
random
[ { "content": "/// # Caution\n\n/// ## item_iter's length must be more than N\n\npub fn array_create_enumerate<T, F, const N: usize>(init: F) -> [T; N]\n\nwhere\n\n F: FnMut(usize) -> T,\n\n{\n\n let mut arr: [MaybeUninit<T>; N] = unsafe { MaybeUninit::uninit().assume_init() };\n\n arr.iter_mut()\n\n ...
Rust
src/platform/quickcheck.rs
Whiley/WhileyBuildTool
c582b6c7b5df31c62648818a202e1d8e8ea41c28
use std::error::Error; use std::path::{Path,PathBuf}; use glob::glob; use crate::config; use crate::config::{Config,Key}; use crate::build; use crate::build::{PACKAGE_NAME,Artifact}; use crate::platform; use crate::platform::{PluginError,whiley}; use crate::jvm; static BUILD_CHECK_MIN : Key = Key::new(&["build","check...
use std::error::Error; use std::path::{Path,PathBuf}; use glob::glob; use crate::config; use crate::config::{Config,Key}; use crate::build; use crate::build::{PACKAGE_NAME,Artifact}; use crate::platform; use crate::platform::{PluginError,whiley}; use crate::jvm; static BUILD_CHECK_MIN : Key = Key::new(&["build","check...
} pub const DESCRIPTOR : Descriptor = Descriptor{};
y::TARGET_DEFAULT.to_string()); let min = config.get_int(&BUILD_CHECK_MIN).unwrap_or(MIN_DEFAULT); let max = config.get_int(&BUILD_CHECK_MAX).unwrap_or(MAX_DEFAULT); let length = config.get_int(&BUILD_CHECK_LENGTH).unwrap_or(LENGTH_DEFAULT); let depth = config.get_int(&BUILD_CHECK_DEPTH).unwrap_or(DEPTH_DEFAULT); ...
function_block-function_prefixed
[ { "content": "fn get_pkg_path(whileyhome: &Path, name: &String) -> PathBuf {\n\n let mut buf = PathBuf::new();\n\n buf.push(whileyhome);\n\n buf.push(REPOSITORY_NAME);\n\n buf.push(name);\n\n return buf;\n\n}\n", "file_path": "src/command/install.rs", "rank": 0, "score": 159043.052696...
Rust
canvas_animation/src/path/region_path.rs
Logicalshift/flowbetween
06836dd6b90e2542599214d5fff5bb056cfbb97f
use flo_canvas::*; use flo_curves::bezier::path::*; #[derive(Clone, Copy, PartialEq, Eq)] pub enum PathRegionType { OutsideRegion, EnclosesRegion, IntersectsRegion, InsideRegion, } #[derive(Copy, Clone, PartialEq, Eq)] enum RegionExteriorEdgeKind { Intersection, ...
use flo_canvas::*; use flo_curves::bezier::path::*; #[derive(Clone, Copy, PartialEq, Eq)] pub enum PathRegionType { OutsideRegion, EnclosesRegion, IntersectsRegion, InsideRegion, } #[derive(Copy, Clone, PartialEq, Eq)] enum RegionExteriorEdgeKind { Intersection, ...
fn to_path_intersection(&mut self) { self.graph.reset_edge_kinds(); self.graph.set_exterior_by_intersecting(); self.graph.heal_exterior_gaps(); self.exterior_edges = RegionExteriorEdgeKind::Intersection; } fn to_path_subtraction(&mut self) { ...
pub (crate) fn new(path: GraphPath<Coord2, PathLabel>) -> RegionPath { RegionPath { graph: path, exterior_edges: RegionExteriorEdgeKind::Intersection } }
function_block-full_function
[ { "content": "///\n\n/// Trait implemented by tree structures that can describe how they\n\n/// differ from another structure.\n\n///\n\npub trait DiffableTree where Self: Clone {\n\n ///\n\n /// Retrieves the child nodes of this item\n\n ///\n\n fn child_nodes<'a>(&'a self) -> Vec<&'a Self>;\n\n\n\...
Rust
src/coord.rs
rosm-project/rosm_geo
d824ca6208c21859a8fd9635a5fb4c07cb0397cd
use std::error; use std::fmt; #[derive(Clone, Copy, Debug)] pub struct GeoCoord { lon: f64, lat: f64, } impl GeoCoord { pub fn from_degrees(lon: f64, lat: f64) -> Result<Self, InvalidGeoCoord> { if (-180.0..=180.0).contains(&lon) && (-90.0..=90.0).contains(&lat) { Ok(Self { lon, lat })...
use std::error; use std::fmt; #[derive(Clone, Copy, Debug)] pub struct GeoCoord { lon: f64, lat: f64, } impl GeoCoord { pub fn from_degrees(lon: f64, lat: f64) -> Result<Self, InvalidGeoCoord> { if (-180.0..=180.0).contains(&lon) && (-90.0..=90.0).contains(&lat) { Ok(Self { lon, lat })...
} fn interleave(x: i64, y: i64) -> i64 { let mut morton: i64 = 0; for i in 0..32 { morton |= (x & 1i64 << i) << i | (y & 1i64 << i) << (i + 1); } morton } impl CompactGeoCoord { pub fn morton_code(&self) -> i64 { interleave(self.lon as i64, self.lat as i64) } } #[derive(...
f { lon: coord.lon as f64 * 180.0 / (1u64 << 31) as f64, lat: coord.lat as f64 * 90.0 / (1 << 30) as f64, } }
function_block-function_prefixed
[ { "content": "use crate::rect::{GeoRect, Edge};\n\nuse crate::coord::{GeoCoord, TileCoord};\n\n\n\nuse std::error;\n\nuse std::f64::consts::PI;\n\nuse std::fmt;\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\npub struct TileId {\n\n x: u32,\n\n y: u32,\n\n z: u32,\n\n}\n\n\n\nimpl TileId {\n\n ...
Rust
src/transformations/src/transformer.rs
mrrabbitte/buttercup
19cddc486d539ab899cff587befc1cb8f5c6bc52
use std::collections::HashMap; use buttercup_values::{ValueHolder, ValuesPayload}; use buttercup_values::geolocation::GeoCoordinates; use serde::{Deserialize, Serialize}; use crate::di::DiInputTransformation; use crate::mono::MonoInputTransformation; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum InputOrde...
use std::collections::HashMap; use buttercup_values::{ValueHolder, ValuesPayload}; use buttercup_values::geolocation::GeoCoordinates; use serde::{Deserialize, Serialize}; use crate::di::DiInputTransformation; use crate::mono::MonoInputTransformation; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum InputOrde...
Serialize, Deserialize)] pub struct TransformationRequest { definition: TransformationDefinition, transformation: Transformation } impl TransformationRequest { pub fn new(definition: TransformationDefinition, transformation: Transformation) -> TransformationRequest { Transformatio...
InputTransformationDefinition { SingleInputTransformationDefinition { transformation_definition_id, input_name, transformation } } } #[derive(Serialize, Deserialize)] pub struct DoubleInputTransformationDefinition { transformation_definition_id: i32, fi...
random
[ { "content": "pub fn one_off_root_tree_with_id(child_id: i32,\n\n definitions: Vec<Arc<dyn BehaviorTreeNodeDefinition>>,\n\n id: i32)\n\n -> BehaviorTreeDefinition {\n\n BehaviorTreeDefinition::new(id,\n\n ...
Rust
src/eapi.rs
pkgcraft/pkgcraft
fcab7a5115bce731a86484947986252648a1ba51
use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::fmt; use std::hash::{Hash, Hasher}; use indexmap::IndexMap; use once_cell::sync::Lazy; use regex::Regex; use crate::atom::Atom; use crate::error::Error; static VALID_EAPI_RE: Lazy<Regex> = Lazy::new(|| Regex::new("^[A-Za-z0-9_][A-Za-z0-9+...
use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::fmt; use std::hash::{Hash, Hasher}; use indexmap::IndexMap; use once_cell::sync::Lazy; use regex::Regex; use crate::atom::Atom; use crate::error::Error; static VALID_EAPI_RE: Lazy<Regex> = Lazy::new(|| Regex::new("^[A-Za-z0-9_][A-Za-z0-9+...
#[inline] pub fn atom<S: AsRef<str>>(&'static self, s: S) -> crate::Result<Atom> { Atom::new(s.as_ref(), self) } fn new( id: &'static str, parent: Option<&'static Eapi>, eapi_options: Option<&EapiOptions>, eapi_incremental_keys: Option<&EapiKeys>, ) ->...
pub fn has(&self, opt: &str) -> bool { match self.options.get(opt) { Some(value) => *value, None => panic!("unknown EAPI option {:?}", opt), } }
function_block-function_prefix_line
[ { "content": "#[allow(unused_must_use)]\n\npub fn bench_parse_required_use(c: &mut Criterion) {\n\n c.bench_function(\"required-use-conditional\", |b| {\n\n b.iter(|| {\n\n required_use::parse(\"u1? ( u2 )\", EAPI_LATEST);\n\n })\n\n });\n\n}\n", "file_path": "benches/required...
Rust
src/main.rs
poteto/monkers
ac91a7a50545c0b88dfe44f06bd17b6aa7c82398
use clap::{App, Arg}; use monkers::{ ast::Program, compiler::{Bytecode, Compiler, CompilerState}, eval::{Env, Interpreter}, ir::IR, vm::{VMState, VM}, {lexer::Lexer, parser::Parser}, }; use rustyline::{error::ReadlineError, Editor}; use string_interner::StringInterner; use std::{cell::RefCell, ...
use clap::{App, Arg}; use monkers::{ ast::Program, compiler::{Bytecode, Compiler, CompilerState}, eval::{Env, Interpreter}, ir::IR, vm::{VMState, VM}, {lexer::Lexer, parser::Parser}, }; use rustyline::{error::ReadlineError, Editor}; use string_interner::StringInterner; use std::{cell::RefCell, ...
let bytecode = self.compile(&program); if self.options.debug { dbg!(&bytecode); } let vm_state = VMState::new(Some(Rc::clone(&self.state.vm_state.globals))); let mut vm = VM::new(bytecode, vm_state); if l...
input: &str) -> Option<IR> { let program = self.parse(input); match self.options.strategy { EvalStrategy::Compiled => {
random
[ { "content": "fn lookup_identifier(interner: Rc<RefCell<StringInterner>>, identifier: &str) -> Token {\n\n match identifier {\n\n \"fn\" => Token::Function,\n\n \"let\" => Token::Let,\n\n \"true\" => Token::Boolean(true),\n\n \"false\" => Token::Boolean(false),\n\n \"if\" =...
Rust
src/guest/call/syscall/types/sockaddr.rs
platten/sallyport
735a051234b468096df2337e2a7182339f65ddba
use crate::guest::alloc::{ Allocator, Collect, Collector, Commit, Committer, InOut, Input, Output, Stage, }; use crate::Result; use core::alloc::Layout; use core::mem::{align_of, size_of}; use core::slice; use libc::{sockaddr_storage, socklen_t, EOVERFLOW}; pub struct SockaddrInput<'a>(pub &'a [u8]); pub type ...
use crate::guest::alloc::{ Allocator, Collect, Collector, Commit, Committer, InOut, Input, Output, Stage, }; use crate::Result; use core::alloc::Layout; use core::mem::{align_of, size_of}; use core::slice; use libc::{sockaddr_storage, socklen_t, EOVERFLOW}; pub struct SockaddrInput<'a>(pub &'a [u8]); pub type ...
} impl<'a> Commit for StagedSockaddrOutput<'a> { type Item = CommittedSockaddrOutput<'a>; #[inline] fn commit(self, com: &impl Committer) -> Self::Item { Self::Item { addr: self.addr, addrlen: self.addrlen.commit(com), } } } impl<'a> Collect for CommittedSocka...
fn stage(self, alloc: &mut impl Allocator) -> Result<Self::Item> { let layout = Layout::from_size_align(self.addr.len(), align_of::<sockaddr_storage>()) .map_err(|_| EOVERFLOW)?; let addr = alloc.allocate_output_layout(layout)?; let addrlen = InOut::stage(alloc, self.addrlen)?; ...
function_block-full_function
[ { "content": "#[inline]\n\nfn deref_sockaddr_input(data: &mut [u8], addr_offset: usize, addrlen: usize) -> Result<*const u8> {\n\n let addr = unsafe { deref::<u8>(data, addr_offset, addrlen) }?;\n\n if addr.align_offset(align_of::<sockaddr_storage>()) != 0 {\n\n Err(EFAULT)\n\n } else {\n\n ...
Rust
src/librustc_mir/def_use.rs
nickdesaulniers/rust
86a686c4f71d208ecf8f7ee5a035b17a545d8b62
use rustc::mir::repr::{Local, Location, Lvalue, Mir}; use rustc::mir::visit::{LvalueContext, MutVisitor, Visitor}; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; use std::marker::PhantomData; use std::mem; pub struct DefUseAnalysis<'tcx> { info: IndexVec<Local, Info<'tcx>>, mir_summary: MirSummary,...
use rustc::mir::repr::{Local, Location, Lvalue, Mir}; use rustc::mir::visit::{LvalueContext, MutVisitor, Visitor}; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; use std::marker::PhantomData; use std::mem; pub struct DefUseAnalysis<'tcx> { info: IndexVec<Local, Info<'tcx>>, mir_summary: MirSummary,...
value<'tcx>, context: LvalueContext<'tcx>, location: Location) { if self.mir_summary.local_index(lvalue) == Some(self.query) { (self.callback)(lvalue, context, location) } self.super_lvalue(lvalue, context, location) } } #[derive(Clone, Co...
Location) { for lvalue_use in &self.info[local].defs_and_uses { MutateUseVisitor::new(local, &mut callback, self.mir_summary, mir).visit_location(mir, lval...
random
[ { "content": "pub fn walk_local<V: Visitor>(visitor: &mut V, local: &Local) {\n\n for attr in local.attrs.iter() {\n\n visitor.visit_attribute(attr);\n\n }\n\n visitor.visit_pat(&local.pat);\n\n walk_list!(visitor, visit_ty, &local.ty);\n\n walk_list!(visitor, visit_expr, &local.init);\n\n...
Rust
dapptools/src/utils.rs
guanqun/dapptools-rs
8dd1d8504112d4d561286e9296d5321526828ff3
use dapp::Contract; use eyre::{ContextCompat, WrapErr}; use std::{ env::VarError, fs::{File, OpenOptions}, path::PathBuf, }; const DEFAULT_OUT_FILE: &str = "dapp.sol.json"; const LOCAL_RPC_URL: &str = "http://127.0.0.1:8545"; pub const DAPP_JSON: &str = "./out/dapp.sol.json"; pub fn subscriber() { ...
use dapp::Contract; use eyre::{ContextCompat, WrapErr}; use std::{ env::VarError, fs::{File, OpenOptions}, path::PathBuf, }; const DEFAULT_OUT_FILE: &str = "dapp.sol.json"; const LOCAL_RPC_URL: &str = "http://127.0.0.1:8545"; pub const DAPP_JSON: &str = "./out/dapp.sol.json"; pub fn subscriber() { ...
g(), path: format!("{}/", dir2.into_os_string().into_string().unwrap()), }, ]; expected.sort_unstable(); assert_eq!(remappings, expected); } }
find_many_str(path: &str) -> eyre::Result<Vec<String>> { let remappings = Self::find_many(path)?; Ok(remappings.iter().map(|mapping| format!("{}={}", mapping.name, mapping.path)).collect()) } pub fn find_many(path: &str) -> eyre::Result<Vec<Self>> { let path = std::path::Path::new...
random
[ { "content": "pub fn encode_args(func: &Function, args: &[impl AsRef<str>]) -> Result<Vec<u8>> {\n\n let params = func\n\n .inputs\n\n .iter()\n\n .zip(args)\n\n .map(|(input, arg)| (&input.kind, arg.as_ref()))\n\n .collect::<Vec<_>>();\n\n let tokens = parse_tokens(para...
Rust
src/server_state.rs
zamazan4ik/aws-gamelift-server-sdk-rs
c1eba41df576feddf88104816aef25e48bc5185e
use crate::{entity::GetInstanceCertificateResult, error::GameLiftErrorType}; use tokio::task::JoinHandle; const HEALTHCHECK_TIMEOUT_SECONDS: u64 = 60; #[derive(Default)] struct SessionState { is_process_ready: bool, game_session_id: Option<crate::entity::GameSessionId>, termination_time: Option<crate::ent...
use crate::{entity::GetInstanceCertificateResult, error::GameLiftErrorType}; use tokio::task::JoinHandle; const HEALTHCHECK_TIMEOUT_SECONDS: u64 = 60; #[derive(Default)] struct SessionState { is_process_ready: bool, game_session_id: Option<crate::entity::GameSessionId>, termination_time: Option<crate::ent...
pub async fn stop_matchmaking( &self, request: crate::entity::StopMatchBackfillRequest, ) -> Result<(), GameLiftErrorType> { self.inner.read().await.http_client.stop_matchmaking(request).await } async fn start_health_check(&mut self) { log::debug!("Health check started...
t: crate::entity::StartMatchBackfillRequest, ) -> Result<crate::entity::StartMatchBackfillResult, GameLiftErrorType> { self.inner.read().await.http_client.backfill_matchmaking(request).await }
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn update_game_session_mapper(\n\n source: crate::protos::generated_with_pure::sdk::UpdateGameSession,\n\n) -> crate::entity::UpdateGameSession {\n\n use std::str::FromStr;\n\n crate::entity::UpdateGameSession {\n\n game_session: Some(game_session_mapper(...
Rust
src/executor/executor.rs
hephex/rabble
09068f45283b575419b88f96d5f69a49b8cd8d57
use serde::{Serialize, Deserialize}; use std::mem; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::collections::HashMap; use amy; use slog; use time::Duration; use ferris::{Wheel, CopyWheel, Resolution}; use envelope::Envelope; use pid::Pid; use process::Process; use node_id::NodeId; use msg::Msg...
use serde::{Serialize, Deserialize}; use std::mem; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::collections::HashMap; use amy; use slog; use time::Duration; use ferris::{Wheel, CopyWheel, Resolution}; use envelope::Envelope; use pid::Pid; use process::Process; use node_id::NodeId; use msg::Msg...
fn get_status(&self, correlation_id: CorrelationId) { let status = ExecutorStatus { total_processes: self.processes.len(), services: self.service_senders.keys().cloned().collect() }; let envelope = Envelope { to: correlation_id.pid.clone(), f...
ecutorMsg::RegisterService(pid, tx) => { self.service_senders.insert(pid, tx); }, ExecutorMsg::GetStatus(correlation_id) => self.get_status(correlation_id), ExecutorMsg::Tick => self.tick(), ExecutorMsg::Shutdown => re...
function_block-function_prefixed
[ { "content": "// A container type for status information for a given component\n\npub trait Metrics<'de>: Serialize + Deserialize<'de> + Debug + Clone {\n\n fn data(&self) -> Vec<(String, Metric)>;\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\npub enum Metric {\n\n Gauge(i64),\...
Rust
src/backends/dialog.rs
ssokolow/dialog-rs
e6666665fb55878df74f2732dca9bfb97d38ce17
use std::process; use crate::{Choice, Error, Input, Message, Password, Question, Result}; #[derive(Debug)] pub struct Dialog { backtitle: Option<String>, width: String, height: String, } impl Dialog { pub fn new() -> Dialog { Dialog { backtitle: None, height: "0...
use std::process; use crate::{Choice, Error, Input, Message, Password, Question, Result}; #[derive(Debug)] pub struct Dialog { backtitle: Option<String>, width: String, height: String, } impl Dialog { pub fn new() -> Dialog { Dialog { backtitle: None, height: "0...
fn show_password(&self, password: &Password) -> Result<Option<String>> { let args = vec!["--passwordbox", &password.text]; self.execute(args, vec![], &password.title) .and_then(get_stderr) } fn show_question(&self, question: &Question) -> Result<Choice> { let args = ve...
sage) -> Result<()> { let args = vec!["--msgbox", &message.text]; self.execute(args, vec![], &message.title) .and_then(|output| require_success(output.status)) .map(|_| ()) }
function_block-function_prefixed
[ { "content": "fn main() -> dialog::Result<()> {\n\n dialog::Message::new(\"This is a message.\").show()?;\n\n\n\n dialog::Message::new(\"This is a message.\")\n\n .title(\"And this is a title:\")\n\n .show()\n\n}\n", "file_path": "examples/message.rs", "rank": 0, "score": 119906....
Rust
src/main.rs
kanru/davif
2fe07a4c208376685d40fdaee1f4ee68095ba7e7
use clap::{App, Arg}; use libavif_sys::{ avifDecoderCreate, avifDecoderRead, avifImage, avifImageCreateEmpty, avifImageYUVToRGB, avifROData, AVIF_RESULT_OK, }; use std::{ convert::TryFrom, fs::File, io::{self, BufWriter, Read}, path::Path, ptr, }; fn main() { let matches = App::new("dav...
use clap::{App, Arg}; use libavif_sys::{ avifDecoderCreate, avifDecoderRead, avifImage, avifImageCreateEmpty, avifImageYUVToRGB, avifROData, AVIF_RESULT_OK, }; use std::{ convert::TryFrom, fs::File, io::{self, BufWriter, Read}, path::Path, ptr, }; fn main() { let matches = App::new("dav...
fn open_avif<T: AsRef<Path>>(path: T) -> io::Result<Vec<u8>> { let mut file = File::open(path)?; let mut buf = Vec::new(); file.read_to_end(&mut buf)?; Ok(buf) } fn as_avif(buf: &[u8]) -> avifROData { avifROData { data: buf.as_ptr(), size: buf.len(), } }
image = RgbImage::try_from(avif_image)?; rgb_image.resize(width, height); rgb_image.save_as_png(output_file)?; Ok(()) }
function_block-function_prefixed
[ { "content": "## DAVIF\n\n\n\nDecompress an [AVIF][] file to an image file.\n\nAs of 2020-05-31 only PNG format output is implemented.\n\n\n\nI wrote this program to use it as a thumbnailer for Gnome desktop.\n\nThe commandline switch is compatiable with the `dwebp` utility for webp.\n\n\n\n[AVIF]: https://aome...
Rust
src/nes/cartridge.rs
danijoo/jane
e054472e65273748c8b48d15ef44502451c24f9b
use crate::nes::mappers::*; use failure::Error; use std::io::prelude::*; use std::fs::File; use crate::nes::types::*; use std::path::Path; use std::io::SeekFrom; #[derive(Debug)] struct Header { prg_rom_chunks: Byte, chr_rom_chunks: Byte, mapper1: Byte, mapper2: Byte, prg_ram_size: Byte, tv...
use crate::nes::mappers::*; use failure::Error; use std::io::prelude::*; use std::fs::File; use crate::nes::types::*; use std::path::Path; use std::io::SeekFrom; #[derive(Debug)] struct Header { prg_rom_chunks: Byte, chr_rom_chunks: Byte, mapper1: Byte, mapper2: Byte, prg_ram_size: Byte, tv...
#[test] fn test_cartridge_new() { let path = Path::new("test_roms/nestest.nes"); Cartridge::new(&path).unwrap(); } }
fn test_header_has_trainer() { let header = Header { prg_rom_chunks: 1, chr_rom_chunks: 1, mapper1: (1 << 2), mapper2: 0x00, prg_ram_size: 0x00, tv1: 0x00, tv2: 0x00 }; assert!(header....
function_block-full_function
[ { "content": "pub trait Mapper {\n\n fn map_read_addr(&self, addr: Addr) -> Option<Addr>;\n\n fn map_write_addr(&self, addr: Addr) -> Option<Addr>;\n\n fn map_read_addr_ppu(&self, addr: Addr) -> Option<Addr>;\n\n fn map_write_addr_ppu(&self, addr: Addr) -> Option<Addr>;\n\n}\n\n\n\n// Mapper 0\n\n//...
Rust
src/sys/pkg/bin/system-update-configurator/src/bridge/vx_ta/mod.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
mod tee_client_api; use self::tee_client_api::*; use std::fmt; use std::fmt::Debug; use std::mem; use std::ptr; use thiserror::Error; use tracing::debug; use self::tee_client_api::{ teec_operation_impl, TEEC_Operation as TeecOperation, TEEC_Value as TeecValue, }; use self::tee_client_api::{ TEEC_Parameter ...
mod tee_client_api; use self::tee_client_api::*; use std::fmt; use std::fmt::Debug; use std::mem; use std::ptr; use thiserror::Error; use tracing::debug; use self::tee_client_api::{ teec_operation_impl, TEEC_Operation as TeecOperation, TEEC_Value as TeecValue, }; use self::tee_client_api::{ TEEC_Parameter ...
}
t() { let rc = ota_config_get(0); assert_matches!(rc, Err(TeeError::General(TEEC_ERROR_NOT_SUPPORTED))); let rc = ota_config_set(0); assert_matches!(rc, Err(TeeError::General(TEEC_ERROR_NOT_SUPPORTED))); }
function_block-function_prefixed
[]
Rust
packages/native/native/src/entries.rs
emeraldpay/emerald-vault-node
79fefc57f89cf57f967dd58a6cadd80dbf33e7b4
use std::convert::TryFrom; use std::str::FromStr; use neon::prelude::*; use uuid::Uuid; use access::{args_get_str, VaultConfig, WrappedVault}; use emerald_vault::{ convert::json::keyfile::EthereumJsonV3File, storage::error::VaultError, EthereumAddress, EthereumPrivateKey, }; use json::StatusResult; use emeral...
use std::convert::TryFrom; use std::str::FromStr; use neon::prelude::*; use uuid::Uuid; use access::{args_get_str, VaultConfig, WrappedVault}; use emerald_vault::{ convert::json::keyfile::EthereumJsonV3File, storage::error::VaultError, EthereumAddress, EthereumPrivateKey, }; use json::StatusResult; use emeral...
pub fn export_pk(mut cx: FunctionContext) -> JsResult<JsObject> { let cfg = VaultConfig::get_config(&mut cx); let vault = WrappedVault::new(cfg); let wallet_id = cx .argument::<JsString>(1) .expect("wallet_id not provided") .value(); let wallet_id = Uuid::from_str(wallet_id.as...
o_string_pretty(&pk).expect("Failed to convert to JSON"); let status = StatusResult::Ok(result).as_json(); let js_value = neon_serde::to_value(&mut cx, &status).expect("Invalid Value"); Ok(js_value.downcast().unwrap()) }
function_block-function_prefixed
[ { "content": "fn read_wallet_and_entry_ids(cx: &mut FunctionContext, pos: i32) -> (Uuid, usize) {\n\n let wallet_id = cx\n\n .argument::<JsString>(pos)\n\n .expect(\"wallet_id is not provided\")\n\n .value();\n\n let wallet_id = Uuid::parse_str(wallet_id.as_str()).expect(\"Invalid UUI...
Rust
src/color_space/spaced_color.rs
tylerreisinger/prisma
0c886242ac0299bfc6863db9214dd9cbba19eda7
use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use crate::alpha::{Rgba, Xyza}; use crate::channel::{ AngularChannelScalar, ChannelFormatCast, FreeChannelScalar, PosNormalChannelScalar, }; use crate::color_space::{ColorSpace, ConvertFromXyz, ConvertToXyz}; use crate::convert::{FromColor, FromHsi, ...
use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use crate::alpha::{Rgba, Xyza}; use crate::channel::{ AngularChannelScalar, ChannelFormatCast, FreeChannelScalar, PosNormalChannelScalar, }; use crate::color_space::{ColorSpace, ConvertFromXyz, ConvertToXyz}; use crate::convert::{FromColor, FromHsi, ...
fEq, S: ColorSpace<T> + PartialEq, E: ColorEncoding + PartialEq, T: num_traits::Float, { type Epsilon = C::Epsilon; fn default_epsilon() -> Self::Epsilon { C::default_epsilon() } fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool { (self.space == other.space...
Encoding = E> + PartialEq + Clone + ConvertFromXyz<T, Xyza<T>, OutputColor = Rgba<T>>, E: ColorEncoding + PartialEq, T: PartialEq + Clone + num_traits::Float + FreeChannelScalar + PosNormalChannelScalar + ChannelFormatCast<f64>, f64: ChannelFor...
random
[ { "content": "/// The base color trait, representing any color\n\n///\n\n/// The main use of `Color` is to manipulate and act on colors in a generic context. It is used\n\n/// extensively internally.\n\npub trait Color: Clone + PartialEq {\n\n /// The unique tag unit struct identifying the color type\n\n ...
Rust
src/main.rs
hrolfurgylfa/vrchat-light-sync
2a6dee78836ecdb0f823020204d1e91d2515fc31
use nannou_osc::Type; use serde::Deserialize; use std::fs::File; use std::path::Path; use std::{thread, time}; #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] enum BulbService { HomeAssistant, } #[derive(Debug, Deserialize)] struct HomeAssistantConfig { entity_id: String, server_ip: Stri...
use nannou_osc::Type; use serde::Deserialize; use std::fs::File; use std::path::Path; use std::{thread, time}; #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] enum BulbService { HomeAssistant, } #[derive(Debug, Deserialize)] struct HomeAssistantConfig { entity_id: String, server_ip: Stri...
; } fn update_vrchat(sender: &nannou_osc::Sender<nannou_osc::Connected>, state: &BulbState) -> () { sender .send(("/avatar/parameters/on", vec![Type::Bool(state.on)])) .ok(); sender .send(("/avatar/parameters/Color", vec![Type::Float(state.hue)])) .ok(); sender .send...
match config.bulb_service { BulbService::HomeAssistant => match get_home_assistant_state(&config.home_assistant) { Ok(res) => res, Err(err) => panic!("Failed to get status from home assistant: {}", err), }, }
if_condition
[ { "content": "# VRChat Light Sync\n\nA program that sends your smart lights status to VRChat's OSC API\n", "file_path": "README.md", "rank": 10, "score": 7979.259204942369 } ]
Rust
std/src/exec.rs
Protowalker/endbasic
29f4bed8a1eb422c787ae8be58c86e3141b0afe8
use async_trait::async_trait; use endbasic_core::ast::{ArgSep, Expr, Value, VarType}; use endbasic_core::exec::Machine; use endbasic_core::syms::{ CallError, CallableMetadata, CallableMetadataBuilder, Command, CommandResult, }; use futures_lite::future::{BoxedLocal, FutureExt}; use std::rc::Rc; use std::thread; u...
use async_trait::async_trait; use endbasic_core::ast::{ArgSep, Expr, Value, VarType}; use endbasic_core::exec::Machine; use endbasic_core::syms::{ CallError, CallableMetadata, CallableMetadataBuilder, Command, CommandResult, }; use futures_lite::future::{BoxedLocal, FutureExt}; use std::rc::Rc; use std::thread; u...
} #[async_trait(?Send)] impl Command for ClearCommand { fn metadata(&self) -> &CallableMetadata { &self.metadata } async fn exec(&self, args: &[(Option<Expr>, ArgSep)], machine: &mut Machine) -> CommandResult { if !args.is_empty() { return Err(CallError::ArgumentError("CLEAR t...
pub fn new() -> Rc<Self> { Rc::from(Self { metadata: CallableMetadataBuilder::new("CLEAR", VarType::Void) .with_syntax("") .with_category(CATEGORY) .with_description( "Restores initial machine state but keeps the stored program. Thi...
function_block-full_function
[ { "content": "/// Executes `expr` on a scripting interpreter and ensures that the result is `exp_value`.\n\npub fn check_expr_ok<V: Into<Value>>(exp_value: V, expr: &str) {\n\n Tester::default()\n\n .run(format!(\"result = {}\", expr))\n\n .expect_var(\"result\", exp_value.into())\n\n .c...
Rust
src/efi/init.rs
xiaoyuxlu/rust-hypervisor-firmware
70247fd6d0eeeec56e8d8aa0926feef8cad5f5f2
#![allow(unused)] use r_efi::efi; use r_efi::efi::{ AllocateType, Boolean, CapsuleHeader, Char16, Event, EventNotify, Guid, Handle, InterfaceType, LocateSearchType, MemoryDescriptor, MemoryType, OpenProtocolInformationEntry, PhysicalAddress, ResetType, Status, Time, TimeCapabilities, TimerDelay, Tpl, MEM...
#![allow(unused)] use r_efi::efi; use r_efi::efi::{ AllocateType, Boolean, CapsuleHeader, Char16, Event, EventNotify, Guid, Handle, InterfaceType, LocateSearchType, MemoryDescriptor, MemoryType, OpenProtocolInformationEntry, PhysicalAddress, ResetType, Status, Time, TimeCapabilities, TimerDelay, Tpl, MEM...
&mut (*system_table).standard_error_handle as *mut Handle, &mut r_efi::protocols::simple_text_output::PROTOCOL_GUID as *mut Guid, InterfaceType::NativeInterface, (*system_table).std_err as *mut c_void ); } } #[c...
*system_table).console_out_handle as *mut Handle, &mut r_efi::protocols::simple_text_output::PROTOCOL_GUID as *mut Guid, InterfaceType::NativeInterface, (*system_table).con_out as *mut c_void ); let status = crate::efi::inst...
random
[ { "content": "pub fn find_image_in_fv (hob: *const c_void) -> (*const c_void, usize) {\n\n let mut hob_header : *const Header = hob as *const Header;\n\n\n\n loop {\n\n let header = unsafe {transmute::<*const Header, &Header>(hob_header)};\n\n match header.r#type {\n\n HOB_TYPE_FV => {\n\n l...