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
examples/rand-extension/lib.rs
KaiserKarel/ink
3c8b103075c9df208370c2423d124c81ebaff5d6
#![cfg_attr(not(feature = "std"), no_std)] use ink_env::Environment; use ink_lang as ink; #[ink::chain_extension] pub trait FetchRandom { type ErrorCode = RandomReadErr; #[ink(extension = 1101, returns_result = false)] fn fetch_random() -> [u8; 32]; } #[derive(Debug, Copy, Clone, PartialEq, ...
#![cfg_attr(not(feature = "std"), no_std)] use ink_env::Environment; use ink_lang as ink; #[ink::chain_extension] pub trait FetchRandom { type ErrorCode = RandomReadErr; #[ink(extension = 1101, returns_result = false)] fn fetch_random() -> [u8; 32]; } #[derive(Debug, Copy, Clone, PartialEq, ...
} } #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum CustomEnvironment {} impl Environment for CustomEnvironment { const MAX_EVENT_TOPICS: usize = <ink_env::DefaultEnvironment as Environment>::MAX_EVENT_TOPICS; type AccountId = <ink_env::...
match status_code { 0 => Ok(()), 1 => Err(Self::FailGetRandomSource), _ => panic!("encountered unknown status code"), }
if_condition
[ { "content": "pub fn transfer(account_id: &[u8], value: &[u8]) -> Result {\n\n let ret_code = unsafe {\n\n sys::seal_transfer(\n\n Ptr32::from_slice(account_id),\n\n account_id.len() as u32,\n\n Ptr32::from_slice(value),\n\n value.len() as u32,\n\n )\...
Rust
examples/day-12.rs
leandrobbraga/aoc-2020
1b52cf1485082ee861799d3d69b5181723090da1
use crate::Direction::{East, Forward, Left, North, Right, South, West}; use std::fs; use std::ops::Add; #[derive(Debug, Copy, Clone)] enum Direction { North, South, East, West, Left, Right, Forward, } #[derive(Debug)] struct Instruction { direction: Direction, value: u32, } #[deri...
use crate::Direction::{East, Forward, Left, North, Right, South, West}; use std::fs; use std::ops::Add; #[derive(Debug, Copy, Clone)] enum Direction { North, South, East, West, Left, Right, Forward, } #[derive(Debug)] struct Instruction { direction: Direction, value: u32, } #[deri...
position: (-(instruction.value as i32), 0), direction: original_direction, }, Forward => make_position( &Instruction { direction: original_direction, value: instruction.value, }, original_direction, ), _...
wp = rotate_waypoint(wp, -(instruction.value as i32)), Forward => { ship = ship + Position { position: ( wp.position.0 * instruction.value as i32, wp.position.1 * instruction.value as i32, ...
random
[]
Rust
src/portable.rs
oconnor663/baokeshed
aadfee0a5cf11ec6d0ee61037aaa873854cbf2a6
use crate::{offset_high, offset_low, Word, BLOCK_LEN, IV, MSG_SCHEDULE, OUT_LEN}; use arrayref::{array_mut_ref, array_ref, array_refs}; #[inline(always)] fn words_from_block(bytes: &[u8; BLOCK_LEN]) -> [Word; 16] { let refs = array_refs!(bytes, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4); [ Word::f...
use crate::{offset_high, offset_low, Word, BLOCK_LEN, IV, MSG_SCHEDULE, OUT_LEN}; use arrayref::{array_mut_ref, array_ref, array_refs}; #[inline(always)] fn words_from_block(bytes: &[u8; BLOCK_LEN]) -> [Word; 16] { let refs = array_refs!(bytes, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4); [ Word::f...
; assert_eq!(expected_out, test_out); } #[test] fn test_hash_many() { let mut input_buf = [0; BLOCK_LEN * 9]; crate::test::paint_test_input(&mut input_buf); let inputs = [ array_ref!(input_buf, 0 * BLOCK_LEN, 3 * BLOCK_LEN), array_ref!(input_buf, 3 *...
hash1( &blocks, &key, offset, flags, flags_start, flags_end, &mut test_out, )
call_expression
[ { "content": "#[inline(always)]\n\nfn round(state: &mut [Word; 16], msg: &[Word; 16], round: usize) {\n\n // Select the message schedule based on the round.\n\n let schedule = MSG_SCHEDULE[round];\n\n\n\n // Mix the columns.\n\n g(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]);\n\n g(sta...
Rust
src/lib.rs
HFQR/ipc-watcher
bf23b8c36efb2bb8c72e0440c9f46a1f0a092e97
mod error; mod shared; mod tick; use std::{mem, path::Path}; use shared_memory::{Shmem, ShmemConf}; use crate::{error::Error, shared::Shared}; pub fn shared_memory_create(path: impl AsRef<Path>, size: usize) -> Result<Shmem, Error> { let mut mem = ShmemConf::new() .size(size) .force_create_fli...
mod error; mod shared; mod tick; use std::{mem, path::Path}; use shared_memory::{Shmem, ShmemConf}; use crate::{error::Error, shared::Shared}; pub fn shared_memory_create(path: impl AsRef<Path>, size: usize) -> Result<Shmem, Error> { let mut mem = ShmemConf::new() .size(size) .force_create_fli...
} #[cfg(test)] mod test { use super::*; #[repr(C)] #[derive(Clone, Copy, Debug)] struct Foo([u8; 512]); #[test] fn works() { let mut mem = shared_memory_create("./test_file", 24).unwrap(); let watched = Watched::<Foo>::new_from_mem(&mut mem); watched.write(Foo([123;...
e"); if tick_new != self.tick { self.tick = tick_new; true } else { false } }
function_block-function_prefixed
[ { "content": "#[derive(Clone, Copy)]\n\nstruct State([u8; 8]);\n\n\n", "file_path": "examples/watcher.rs", "rank": 2, "score": 61034.29989680919 }, { "content": "#[derive(Clone, Copy)]\n\nstruct State([u8; 8]);\n\n\n", "file_path": "examples/watched.rs", "rank": 3, "score": 47039...
Rust
src/server.rs
lowquark/uflow
cdd9d6501b2954a647850282f594ea02e60249dc
use crate::MAX_FRAME_SIZE; use crate::frame; use super::endpoint; use super::peer; use super::udp_frame_sink::UdpFrameSink; use std::collections::HashMap; use std::net; use std::sync::Arc; use std::sync::RwLock; pub struct Server { socket: net::UdpSocket, max_peer_count: usize, peer_config: endpoint::C...
use crate::MAX_FRAME_SIZE; use crate::frame; use super::endpoint; use super::peer; use super::udp_frame_sink::UdpFrameSink; use std::collections::HashMap; use std::net; use std::sync::Arc; use std::sync::RwLock; pub struct Server { socket: net::UdpSocket, max_peer_count: usize, peer_config: endpoint::C...
ind(addr)?; socket.set_nonblocking(true)?; Ok(Self { socket, endpoints: HashMap::new(), incoming_peers: Vec::new(), max_peer_count, peer_config, }) } pub fn bind_any_ipv4(max_peer_count: usize, peer_config: endpoi...
eer_count: usize, peer_config: endpoint::Config) -> Result<Self, std::io::Error> { assert!(peer_config.is_valid(), "invalid endpoint config"); let socket = net::UdpSocket::b
function_block-random_span
[ { "content": "// Size of the buffer that the receiver will allocate for a packet in bytes\n\nfn alloc_size(packet_size: usize) -> usize {\n\n if packet_size > MAX_FRAGMENT_SIZE {\n\n ((packet_size + MAX_FRAGMENT_SIZE - 1) / MAX_FRAGMENT_SIZE) * MAX_FRAGMENT_SIZE\n\n } else {\n\n packet_size\...
Rust
esp-idf-sys/src/error.rs
trigovision/esp-idf-sys
a7bb1a7b3a6ea1f83649827fe4774964f260037f
use cstr_core::CStr; use crate::esp_err_t; use core::fmt::Write; use core::{ fmt::{Debug, Display}, ops::Try, }; #[derive(Debug)] pub enum EspError { NoMem, InvalidArg, InvalidState, InvalidSize, NotFound, NotSupported, Timeout, InvalidResponse, InvalidCrc, InvalidVersi...
use cstr_core::CStr; use crate::esp_err_t; use core::fmt::Write; use core::{ fmt::{Debug, Display}, ops::Try, }; #[derive(Debug)] pub enum EspError { NoMem, InvalidArg, InvalidState, InvalidSize, NotFound, NotSupported, Timeout, InvalidResponse, InvalidCrc, InvalidVersi...
fn from_error(v: Self::Error) -> Self { v.into() } fn from_ok(_v: Self::Ok) -> Self { Self(0) } } impl Display for EspError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { EspError::Unknown(code) => { let e...
fn into_result(self) -> Result<Self::Ok, Self::Error> { if self.0 == 0 { Ok(()) } else { Err(self.into()) } }
function_block-full_function
[ { "content": "#define CONFIG_SPIFFS_USE_MAGIC 1\n", "file_path": "sdkconfig.h", "rank": 6, "score": 31052.729848677303 }, { "content": "#define CONFIG_FATFS_TIMEOUT_MS 10000\n", "file_path": "sdkconfig.h", "rank": 7, "score": 31052.729848677303 }, { "content": "#define CO...
Rust
src/embeds/osu/medal_stats.rs
JoshiDhima/Bathbot
7a8dd8a768caede285df4f8ea5aead27bdbbf660
use crate::{ custom_client::{groups::*, OsekaiMedal}, embeds::{attachment, Author, EmbedFields, Footer}, util::{constants::OSU_BASE, numbers::round, osu::flag_url}, }; use hashbrown::HashMap; use rosu_v2::model::user::User; pub struct MedalStatsEmbed { author: Author, fields: EmbedFields, foot...
use crate::{ custom_client::{groups::*, OsekaiMedal}, embeds::{attachment, Author, EmbedFields, Footer}, util::{constants::OSU_BASE, numbers::round, osu::flag_url}, }; use hashbrown::HashMap; use rosu_v2::model::user::User; pub struct MedalStatsEmbed { author: Author, fields: EmbedFields, foot...
} impl_builder!(MedalStatsEmbed { author, fields, footer, image, thumbnail, });
for medal in owned.iter() { let entry = medals .get(&medal.medal_id) .and_then(|medal| counts.get_mut(medal.grouping.as_str())); if let Some((_, owned)) = entry { *owned += 1; } } ...
function_block-function_prefix_line
[ { "content": "fn main_fields(user: &User, stats: &UserStatistics, bonus_pp: f32) -> Vec<EmbedField> {\n\n let level = stats.level.float();\n\n\n\n vec![\n\n field!(\n\n \"Ranked score\",\n\n with_comma_int(stats.ranked_score).to_string(),\n\n true\n\n ),\n\n ...
Rust
serde-diff-derive/src/serde_diff/mod.rs
Boscop/serde-diff
e16c4df5df6d679c0086365cbbbb30a320cd1367
extern crate proc_macro; mod args; use quote::quote; pub fn macro_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { use darling::FromDeriveInput; let input = syn::parse_macro_input!(input as syn::DeriveInput); let struct_args = args::SerdeDiffStructArgs::from_derive_input(&input)....
extern crate proc_macro; mod args; use quote::quote; pub fn macro_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { use darling::FromDeriveInput; let input = syn::parse_macro_input!(input as syn::DeriveInput); let struct_args = args::SerdeDiffStructArgs::from_derive_input(&input)....
e! { fn apply<'de, A>( &mut self, seq: &mut A, ctx: &mut serde_diff::ApplyContext, ) -> Result<bool, <A as serde_diff::_serde::de::SeqAccess<'de>>::Error> where A: serde_diff::_serde::de::SeqAccess<'de>, { let mut __changed__ = false; ...
} ctx.pop_path_element()?; } }); } else { diff_fn_field_handlers.push(quote! { { { ctx.push_field(#ident_as_str); __changed__ |= <#ty as serde_diff::SerdeDiff>::diff...
random
[ { "content": "#[proc_macro_derive(SerdeDiff, attributes(serde_diff))]\n\npub fn serde_diff_macro_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n serde_diff::macro_derive(input)\n\n}\n", "file_path": "serde-diff-derive/src/lib.rs", "rank": 4, "score": 61432.704635666276 }...
Rust
novus/src/commands/info.rs
novus-package-manager/novus
3da1bda3761c65d792c07daac7e293ce96e635db
use colored::Colorize; use utils::classes::local_package_info::LocalPackageInfo; use utils::classes::package::Package; use utils::classes::package_info::PackageInfo; use utils::constants::help_menu::info_wrong_package_error; use utils::constants::version::__VERSION__; use utils::get_package::get_package; use utils::reg...
use colored::Colorize; use utils::classes::local_package_info::LocalPackageInfo; use utils::classes::package::Package; use utils::classes::package_info::PackageInfo; use utils::constants::help_menu::info_wrong_package_error; use utils::constants::version::__VERSION__; use utils::get_package::get_package; use utils::reg...
fn verify_args(args: Vec<String>, packages: Vec<&str>) -> (String, Vec<String>) { let mut flags = vec![]; let mut package = String::new(); for arg in args { if arg.starts_with("-") { flags.push(arg); } else { package = arg; } } if !flags.contains(&"...
rsions[&package.latest_version].checksum.clone(), file_type: package.versions[&package.latest_version].file_type.clone(), } }
function_block-function_prefixed
[ { "content": "pub fn get_local_info(package_name: String) -> LocalPackageInfo {\n\n use winreg::enums::*;\n\n use winreg::RegKey;\n\n\n\n let mut regkey = RegKey::predef(HKEY_LOCAL_MACHINE);\n\n\n\n let mut local_package_info_global: LocalPackageInfo = LocalPackageInfo {\n\n comments: String:...
Rust
ajars_actix_web/src/lib.rs
ufoscout/AjaRS
5081d2e1d43c6934196fadf1c1c5178f04098436
use std::future::Future; use ::actix_web::{ web::{self, Json, Query}, FromRequest, Resource, ResponseError, }; use ajars_core::{HttpMethod, RestType}; use futures_util::future::FutureExt; use serde::{de::DeserializeOwned, Serialize}; pub mod actix_web { pub use actix_web::*; } pub trait ActixWebHandler<I...
use std::future::Future; use ::actix_web::{ web::{self, Json, Query}, FromRequest, Resource, ResponseError, }; use ajars_core::{HttpMethod, RestType}; use futures_util::future::FutureExt; use serde::{de::DeserializeOwned, Serialize}; pub mod actix_web { pub use actix_web::*; } pub trait ActixWebHandler<I...
sponse = test::read_body_json(resp).await; assert_eq!(resp.message, payload.message); } #[actix_rt::test] async fn should_create_a_post_endpoint() { let rest = RestFluent::<PingRequest, PingResponse>::post(format!("/api/something/{}", rand::random::<usize>())); let app = t...
[derive(Debug, Clone)] struct ServerError {} impl Display for ServerError { fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Ok(()) } } impl ResponseError for ServerError {} #[actix_rt::test] async fn should_create_a_delete_endpoint() { ...
random
[ { "content": "/// spanws an actix server and returns the server port\n\npub fn spawn_actix_web<REST: 'static + Clone + Send + RestType<Simple<String>, Simple<String>>>(\n\n echo_rest: REST,\n\n) -> u16 {\n\n let free_port = port_check::free_local_port().unwrap();\n\n let address = format!(\"127.0.0.1:{...
Rust
src/response.rs
aleksandrpak/iron
f9f174322133249120920149c1752341fd9dfe03
use std::old_io::{self, IoResult}; use std::fmt::{self, Debug}; use typemap::TypeMap; use plugin::Extensible; use modifier::{Set, Modifier}; use hyper::header::Headers; use status::{self, Status}; use {Plugin, headers}; pub use hyper::server::response::Response as HttpResponse; use hyper::net::Fresh; pub struct ...
use std::old_io::{self, IoResult}; use std::fmt::{self, Debug}; use typemap::TypeMap; use plugin::Extensible; use modifier::{Set, Modifier}; use hyper::header::Headers; use status::{self, Status}; use {Plugin, headers}; pub use hyper::server::response::Response as HttpResponse; use hyper::net::Fresh; pub struct ...
} fn write_with_body(mut res: HttpResponse<Fresh>, mut body: Box<Reader + Send>) -> IoResult<()> { let content_type = res.headers().get::<headers::ContentType>() .map(|cx| cx.clone()) .unwrap_or_else(|| headers::ContentType("text/plain".parse().unwrap())); ...
pub fn write_back(self, mut http_res: HttpResponse<Fresh>) { *http_res.headers_mut() = self.headers; *http_res.status_mut() = self.status.clone().unwrap_or(status::NotFound); let out = match self.body { Some(body) => write_with_body(http_res, body), None => { ...
function_block-full_function
[ { "content": "/// `BeforeMiddleware` are fired before a `Handler` is called inside of a Chain.\n\n///\n\n/// `BeforeMiddleware` are responsible for doing request pre-processing that requires\n\n/// the ability to change control-flow, such as authorization middleware, or for editing\n\n/// the request by modifyi...
Rust
src/cmos.rs
TheKernelCorp/Hydroxide
4a579875006207765b5367efc76fa84f3c48177f
use bitflags::bitflags; use lazy_static::lazy_static; use spin::Mutex; use x86_64::instructions::port::Port; const CMOS_ADDR: u16 = 0x70; const CMOS_DATA: u16 = 0x71; lazy_static! { static ref CMOS_PORT_ADDR: Mutex<Port<u8>> = Mutex::new(Port::new(CMOS_ADDR)); static ref CMOS_PORT_DATA: Mutex<Port<u8>> = Mute...
use bitflags::bitflags; use lazy_static::lazy_static; use spin::Mutex; use x86_64::instructions::port::Port; const CMOS_ADDR: u16 = 0x70; const CMOS_DATA: u16 = 0x71; lazy_static! { static ref CMOS_PORT_ADDR: Mutex<Port<u8>> = Mutex::new(Port::new(CMOS_ADDR)); static ref CMOS_PORT_DATA: Mutex<Port<u8>> = Mute...
}
F: FnMut(&mut Port<u8>, &mut Port<u8>) -> R, { let addr_port = &mut *CMOS_PORT_ADDR.lock(); let data_port = &mut *CMOS_PORT_DATA.lock(); f(addr_port, data_port) }
function_block-function_prefix_line
[ { "content": "/// Find a memory region suitable for the heap\n\npub fn find_heap_space(bootinfo: &BootInfo) -> (u64, u64) {\n\n // Initialize the memory region to None\n\n let mut found_region: Option<&MemoryRegion> = None;\n\n\n\n let size =\n\n |region: &MemoryRegion| (region.range.end_addr() ...
Rust
src/handshake.rs
Alex6323/goshimmer_network
18a81764bf65546136233de35453d4c04eae9c00
use crate::{ config::{ManualPeerConfig, ManualPeerInfo}, conn::Direction, consts::{HANDSHAKE_TIMEOUT_SECS, MAX_HANDSHAKE_PACKET_SIZE, VERSION}, identity::{Identity, LocalIdentity}, packet::{packet_hash, Packet, PacketType}, proto, }; use crypto::signatures::ed25519; use prost::{bytes::BytesMut,...
use crate::{ config::{ManualPeerConfig, ManualPeerInfo}, conn::Direction, consts::{HANDSHAKE_TIMEOUT_SECS, MAX_HANDSHAKE_PACKET_SIZE, VERSION}, identity::{Identity, LocalIdentity}, packet::{packet_hash, Packet, PacketType}, proto, }; use crypto::signatures::ed25519; use prost::{bytes::BytesMut,...
pub fn from_protobuf(bytes: &[u8]) -> Result<Self, HandshakeError> { let inner = proto::HandshakeResponse::decode(bytes).map_err(|e| HandshakeError::Decode(e))?; Ok(Self { inner }) } pub fn req_hash(&self) -> &Vec<u8> { &self.inner.req_hash } pub fn protobuf(&self) -> Re...
pub fn new(req_data: &[u8]) -> Self { let inner = proto::HandshakeResponse { req_hash: packet_hash(req_data), }; Self { inner } }
function_block-full_function
[ { "content": "pub fn packet_hash(packet_bytes: &[u8]) -> Vec<u8> {\n\n digest::digest(&digest::SHA256, packet_bytes).as_ref().to_vec()\n\n}\n\n\n\npub struct Packet(proto::Packet);\n\n\n\nimpl Packet {\n\n pub fn new(ty: PacketType, data: &[u8], public_key: &[u8], signature: &[u8]) -> Self {\n\n Se...
Rust
default-plugins/status-bar/src/first_line.rs
herbygillot/zellij
f2fa8839d414ff4cdaeeb7aedfc5cbccba0dc920
use ansi_term::{ANSIStrings, Style}; use zellij_tile::prelude::*; use crate::colors::{BLACK, BRIGHT_GRAY, GRAY, GREEN, RED, WHITE}; use crate::{LinePart, ARROW_SEPARATOR}; struct CtrlKeyShortcut { mode: CtrlKeyMode, action: CtrlKeyAction, } impl CtrlKeyShortcut { pub fn new(mode: CtrlKeyMode, action: Ctr...
use ansi_term::{ANSIStrings, Style}; use zellij_tile::prelude::*; use crate::colors::{BLACK, BRIGHT_GRAY, GRAY, GREEN, RED, WHITE}; use crate::{LinePart, ARROW_SEPARATOR}; struct CtrlKeyShortcut { mode: CtrlKeyMode, action: CtrlKeyAction, } impl CtrlKeyShortcut { pub fn new(mode: CtrlKeyMode, action: Ctr...
).to_string(), len, } } fn unselected_mode_shortcut_single_letter(letter: char) -> LinePart { let char_shortcut_text = format!(" {} ", letter); let len = char_shortcut_text.chars().count() + 4; let prefix_separator = Style::new().fg(GRAY).on(BRIGHT_GRAY).paint(ARROW_SEPARATOR); let char_sh...
.paint(letter.to_string()); let char_right_separator = Style::new() .bold() .fg(BLACK) .on(BRIGHT_GRAY) .bold() .paint(">"); let styled_text = Style::new() .fg(BLACK) .on(BRIGHT_GRAY) .bold() .paint(format!("{} ", text)); let suffix_...
random
[ { "content": "pub fn active_tab(text: String) -> LinePart {\n\n let left_separator = Style::new().fg(GRAY).on(GREEN).paint(ARROW_SEPARATOR);\n\n let tab_text_len = text.chars().count() + 4; // 2 for left and right separators, 2 for the text padding\n\n let tab_styled_text = Style::new()\n\n .fg(...
Rust
src/lib.rs
Anexen/pyxirr
6b91c10d3ae5a5b083f1d2d90a34e575065ab157
use pyo3::prelude::*; use pyo3::{create_exception, exceptions, wrap_pyfunction}; mod conversions; mod core; create_exception!(pyxirr, InvalidPaymentsError, exceptions::PyException); impl From<core::InvalidPaymentsError> for PyErr { fn from(value: core::InvalidPaymentsError) -> Self { InvalidPaymentsError...
use pyo3::prelude::*; use pyo3::{create_exception, exceptions, wrap_pyfunction}; mod conversions; mod core; create_exception!(pyxirr, InvalidPaymentsError, exceptions::PyException); impl From<core::InvalidPaymentsError> for PyErr { fn from(value: core::InvalidPaymentsError) -> Self { InvalidPaymentsError...
) }) } #[pyfunction(amounts = "None")] #[pyo3(text_signature = "(rate, dates, amounts)")] fn xnfv(py: Python, rate: f64, dates: &PyAny, amounts: Option<&PyAny>) -> PyResult<Option<f64>> { let (dates, amounts) = conversions::extract_payments(dates, amounts)?; py.allow_threads(move || Ok(float_or_none(core::...
float_or_none(core::xfv( &start_date, &cash_flow_date, &end_date, cash_flow_rate, end_rate, cash_flow, ))
call_expression
[ { "content": "pub fn fv(rate: f64, nper: f64, pmt: f64, pv: f64, pmt_at_begining: Option<bool>) -> f64 {\n\n if rate == 0.0 {\n\n return -(pv + pmt * nper);\n\n }\n\n\n\n let pmt_at_begining = convert_pmt_at_begining(pmt_at_begining);\n\n let factor = f64::powf(1.0 + rate, nper);\n\n\n\n -...
Rust
src/handlers/util.rs
jsvana/uwiki
d00c93d75b8803814e104cf20ad98976f272c0f1
use std::fmt; use handlebars::Handlebars; use log::debug; use serde_derive::Serialize; use serde_json::json; use sqlx::{Pool, Postgres}; use warp::http::{StatusCode, Uri}; use warp_sessions::{MemoryStore, SessionWithStore}; pub type HandlerReturn = (Box<dyn warp::Reply>, SessionWithStore<MemoryStore>); pub fn error_...
use std::fmt; use handlebars::Handlebars; use log::debug; use serde_derive::Serialize; use serde_json::json; use sqlx::{Pool, Postgres}; use warp::http::{StatusCode, Uri}; use warp_sessions::{MemoryStore, SessionWithStore}; pub type HandlerReturn = (Box<dyn warp::Reply>, SessionWithStore<MemoryStore>); pub fn error_...
; match sqlx::query!( "SELECT users.username AS username \ FROM tokens \ LEFT JOIN users \ ON users.id = tokens.user_id \ WHERE token = $1 \ AND expiration >= CAST(EXTRACT(epoch FROM CURRENT_TIMESTAMP) AS INTEGER)", token, ) .fetch_one(db) .await ...
match session_with_store.session.get::<String>("sid") { Some(token) => token, None => { return None; } }
if_condition
[ { "content": "pub fn with_db(\n\n db: Pool<Postgres>,\n\n) -> impl Filter<Extract = (Pool<Postgres>,), Error = std::convert::Infallible> + Clone {\n\n warp::any().map(move || db.clone())\n\n}\n\n\n", "file_path": "src/handlers/handlers.rs", "rank": 1, "score": 76223.27681977108 }, { "c...
Rust
rust/strprintf/src/lib.rs
nickwynja/newsboat
e6105033129a3dd853bde8fd11a1e2a9fd574f38
#![allow(clippy::unreadable_literal)] pub mod specifiers_iterator; pub use crate::specifiers_iterator::SpecifiersIterator; pub mod traits; use crate::traits::*; use std::ffi::{CStr, CString}; use std::mem; use std::vec::Vec; #[cfg(target_pointer_width = "32")] mod format_specifiers_32bit; #[cfg(target_pointer_wi...
#![allow(clippy::unreadable_literal)] pub mod specifiers_iterator; pub use crate::specifiers_iterator::SpecifiersIterator; pub mod traits; use crate::traits::*; use std::ffi::{CStr, CString}; use std::mem; use std::vec::Vec; #[cfg(target_pointer_width = "32")] mod format_specifiers_32bit; #[cfg(target_pointer_wi...
assert_eq!(fmt!(&format!("%{}", PRId32), std::i32::MIN), "-2147483648"); assert_eq!(fmt!(&format!("%{}", PRIi32), std::i32::MAX), "2147483647"); assert_eq!(fmt!(&format!("%{}", PRId32), std::i32::MAX), "2147483647"); } #[test] fn formats_u32() { assert_eq!(fmt!(&format!("%{...
"100500 -191"); } #[test] fn formats_i32() { assert_eq!(fmt!(&format!("%{}", PRIi32), 42i32), "42"); assert_eq!(fmt!(&format!("%{}", PRId32), 42i32), "42"); assert_eq!(fmt!(&format!("%{}", PRIi32), std::i32::MIN), "-2147483648");
random
[ { "content": "fn padded_format(input: &str) -> IResult<&str, Specifier> {\n\n let (input, _) = tag(\"%\")(input)?;\n\n let (input, width) =\n\n take_while(|chr: char| chr.is_ascii() && (chr.is_numeric() || chr == '-'))(input)?;\n\n let (input, format) = take(1usize)(input)?;\n\n\n\n // unwrap...
Rust
daemon/src/db.rs
comit-network/hermes
74e939c4c9784a07c3bf6d9d4e1ed69ef4cf3831
use crate::model; use crate::model::cfd::CfdEvent; use crate::model::cfd::Event; use crate::model::cfd::OrderId; use crate::model::cfd::Role; use crate::model::Identity; use crate::model::Leverage; use crate::model::Position; use crate::model::Price; use crate::model::Usd; use anyhow::Context; use anyhow::Result; use f...
use crate::model; use crate::model::cfd::CfdEvent; use crate::model::cfd::Event; use crate::model::cfd::OrderId; use crate::model::cfd::Role; use crate::model::Identity; use crate::model::Leverage; use crate::model::Position; use crate::model::Price; use crate::model::Usd; use anyhow::Context; use anyhow::Result; use f...
append_event(event1.clone(), &mut conn).await.unwrap(); let (_, events) = load_cfd(cfd.id(), &mut conn).await.unwrap(); assert_eq!(events, vec![event1.clone()]); let event2 = Event { timestamp, id: cfd.id(), event: CfdEvent::RevokeConfirmed, ...
let event1 = Event { timestamp, id: cfd.id(), event: CfdEvent::OfferRejected, };
assignment_statement
[ { "content": "pub fn dummy_new_order() -> maker_cfd::NewOrder {\n\n maker_cfd::NewOrder {\n\n price: dummy_price(),\n\n min_quantity: Usd::new(dec!(5)),\n\n max_quantity: Usd::new(dec!(100)),\n\n tx_fee_rate: 1,\n\n funding_rate: FundingRate::default(),\n\n }\n\n}\n\n\n"...
Rust
rustybeer-util/src/conversions.rs
rogercyyu/rustybeer
d4979bb68904704af3aaa550a78ce99c406513fa
use regex::Regex; use std::num::ParseFloatError; use measurements::{Mass, Temperature, Volume}; pub struct TemperatureBuilder; impl TemperatureBuilder { pub fn new(val: &str) -> Result<measurements::Temperature, ParseFloatError> { if val.is_empty() { return Ok(Tempera...
use regex::Regex; use std::num::ParseFloatError; use measurements::{Mass, Temperature, Volume}; pub struct TemperatureBuilder; impl TemperatureBuilder { pub fn new(val: &str) -> Result<measurements::Temperature, ParseFloatError> { if val.is_empty() { return Ok(Tempera...
} pub struct VolumeBuilder; impl VolumeBuilder { pub fn new(val: &str) -> Result<measurements::Volume, ParseFloatError> { if val.is_empty() { return Ok(Volume::from_litres(0.0)); } let re = Regex::new(r"([0-9.]*)\s?([a-zA-Z]{1,3}[0-9]{0,1})$").unwrap(...
let re = Regex::new(r"([0-9.]*)\s?([a-zA-Z]{1})$").unwrap(); if let Some(caps) = re.captures(val) { let float_val = caps.get(1).unwrap().as_str(); return Ok( match caps.get(2).unwrap().as_str().to_uppercase().as_str() { "F" => Temperature::from_fahrenh...
function_block-function_prefix_line
[ { "content": "/// Calculates the new volume based off a current\n\n/// gravity, a current volume, and a target gravity\n\npub fn calculate_new_volume(current_gravity: f32, current_volume: f32, target_gravity: f32) -> f32 {\n\n current_volume * (current_gravity - 1.) / (target_gravity - 1.)\n\n}\n", "file...
Rust
tokenizers/tests/added_tokens.rs
KappaDistributive/tokenizers
14b12b47a3b57237f267b46e776cd9fa1582a3fb
mod common; use common::*; use tokenizers::tokenizer::AddedToken; #[test] fn add_tokens() { let mut tokenizer = get_empty(); assert_eq!( tokenizer.add_special_tokens(&[ AddedToken::from("<cls>".into()), AddedToken::from("<sep>".into()) ]), 2 ); assert_e...
mod common; use common::*; use tokenizers::tokenizer::AddedToken; #[test] fn add_tokens() { let mut tokenizer = get_empty(); assert_eq!( tokenizer.add_special_tokens(&[ AddedToken::from("<cls>".into()), AddedToken::from("<sep>".into()) ]), 2 ); assert_e...
_tokens(&[AddedToken::from("ing".into())]); tokenizer.add_special_tokens(&[AddedToken::from("ike".into())]); let output = tokenizer.encode(input, false).unwrap(); assert_eq!(output.get_tokens(), &["I", "Ġl", "ike", "Ġda", "nci", "ng"]); }
ial_tokens(&[AddedToken::from("ing".into()).single_word(false)]); let input = "I like dancing"; let output = tokenizer.encode(input, false).unwrap(); assert_eq!(output.get_tokens(), &["I", "Ġlike", "Ġd", "anc", "ing"]); } #[test] fn overlapping_tokens() { let mut tokenizer = get_byte_level(false, fal...
random
[ { "content": "#[allow(dead_code)]\n\npub fn get_bert() -> Tokenizer {\n\n let mut tokenizer = Tokenizer::new(Box::new(get_bert_wordpiece()));\n\n tokenizer.with_normalizer(Box::new(BertNormalizer::default()));\n\n tokenizer.with_pre_tokenizer(Box::new(BertPreTokenizer));\n\n tokenizer.with_decoder(B...
Rust
src/ui_app/zip_archiver.rs
Lastryo/Archiver
2e8a0cc23f3e1415f1c17ebb5b50a40e8a82b085
use std::io::{self, prelude::*}; use std::io::{Seek, Write}; use std::iter::Iterator; use std::ops::Add; use zip::result::ZipError; use zip::write::FileOptions; use std::fs::{self, File}; use std::path::Path; use walkdir::{DirEntry, WalkDir}; const METHOD_STORED: Option<zip::CompressionMethod> = Some(zip::Compressio...
use std::io::{self, prelude::*}; use std::io::{Seek, Write}; use std::iter::Iterator; use std::ops::Add; use zip::result::ZipError; use zip::write::FileOptions; use std::fs::{self, File}; use std::path::Path; use walkdir::{DirEntry, WalkDir}; const METHOD_STORED: Option<zip::CompressionMethod> = Some(zip::Compressio...
zipfile>", directory, directory ); for &method in [METHOD_STORED, METHOD_DEFLATED, METHOD_BZIP2, METHOD_ZSTD].iter() { if method.is_none() { continue; } match doit_dir(directory, &extension, method.unwrap()) { Ok(_) => println!("done: {} written to {}", d...
irectory, &dst_file, method.unwrap()) { Ok(_) => println!("done: {} written to {}", directory, dst_file), Err(e) => println!("Error: {:?}", e), } } 0 } pub fn create_archives(directory: &String, extension: &str) -> i32 { println!( "Usage: {} <source_directory> {} <de...
random
[ { "content": "fn get_extention(ext: &Extension) -> String {\n\n match ext {\n\n Extension::Zip => \".zip\".to_string(),\n\n Extension::Cbz => \".cbz\".to_string(),\n\n }\n\n}\n\n\n\n#[derive(PartialEq)]\n\npub enum Extension {\n\n Zip,\n\n Cbz,\n\n}\n", "file_path": "src/ui_app.rs"...
Rust
third_party/hexagon/src/object_pool.rs
bradyjoestar/rust-sgx-sdk
2e4263693e979c7273bfe844a28ba861b56ce185
use std::prelude::v1::*; use std::collections::HashMap; use errors::VMError; use value::Value; use object::Object; use object_info::{ObjectInfo, ObjectHandle, TypedObjectHandle}; use static_root::StaticRoot; use call_stack::CallStack; use errors; pub struct ObjectPool { objects: Vec<Option<ObjectInfo>>, object...
use std::prelude::v1::*; use std::collections::HashMap; use errors::VMError; use value::Value; use object::Object; use object_info::{ObjectInfo, ObjectHandle, TypedObjectHandle}; use static_root::StaticRoot; use call_stack::CallStack; use errors; pub struct ObjectPool { objects: Vec<Op
b fn set_static_object<K: ToString>(&mut self, key: K, obj: Value) { let key = key.to_string(); if self.static_objects.get(key.as_str()).is_some() { panic!(VMError::from("A static object with the same key already exists")); } if let Value::Object(id) = obj...
tion<ObjectInfo>>, object_idx_pool: Vec<usize>, static_objects: HashMap<String, Value>, alloc_count: usize } impl ObjectPool { pub fn new() -> ObjectPool { ObjectPool { objects: vec![ Some(ObjectInfo::new(Box::new(StaticRoot::new()))) ], objec...
random
[ { "content": "/// A heap-allocated object.\n\n///\n\n/// This is the core abstraction in the Hexagon VM type system.\n\n/// After creating, an object must be pinned to the object pool\n\n/// for use in the virtual environment.\n\n///\n\n/// If any initialization is required before the object is pinned\n\n/// to...
Rust
src/lib.rs
madeindjs/rawsql
108c6babf821707350f2792367d2429243a2096f
#![doc(html_root_url="https://manute.github.io/rawsql")] #![warn(missing_docs)] use std::io::{Read, Result}; use std::fs::File; use std::collections::HashMap; struct Parser { name: String, query: String, } impl Parser { fn init() -> Parser { Parser { name: String::new(), ...
#![doc(html_root_url="https://manute.github.io/rawsql")] #![warn(missing_docs)] use std::io::{Read, Result}; use std::fs::File; use std::collections::HashMap; struct Parser { name: String, query: String, } impl Parser { fn init() -> Parser { Parser { name: String::new(), ...
fn is_starting_query(&mut self) -> bool { !self.name.is_empty() } fn is_finishing_query(&mut self, line: &str) -> bool { !self.query.is_empty() && line.ends_with(";") } fn is_tagged_name(&mut self, line: &str) -> bool { line.starts_with("--") && line.contains("name") ...
y(&mut self, line: &str) { let q = line.trim_left(); if self.query.is_empty() { self.query = q.to_string(); } else { self.query = self.query.to_string() + " " + &q; } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let conn = Connection::connect(\"postgres://postgres:local@localhost\", &SslMode::None).unwrap();\n\n\n\n let queries = Loader::get_queries_from(\"examples/postgre.sql\").unwrap().queries;\n\n\n\n // Drop table\n\n conn.execute(queries.get(\"drop-table-person\").unwrap(...
Rust
crates/dprint/src/configuration/get_init_config_file_text.rs
joscha/dprint
f0a9eed2c9f574d8c6c2bb11aa01627b1ffd4008
use dprint_core::plugins::wasm::{self}; use dprint_core::types::ErrBox; use crate::environment::Environment; use crate::plugins::read_info_file; pub fn get_init_config_file_text(environment: &impl Environment) -> Result<String, ErrBox> { let info = match read_info_file(environment) { Ok(info) => { ...
use dprint_core::plugins::wasm::{self}; use dprint_core::types::ErrBox; use crate::environment::Environment; use crate::plugins::read_info_file; pub fn get_init_config_file_text(environment: &impl Environment) -> Result<String, ErrBox> { let info = match read_info_file(environment) { Ok(info) => { ...
(concat!( "You are using an old version of dprint so the created config file may not be as helpful of a starting point. ", "Consider upgrading to support new plugins. ", "Plugin system schema version is 3, latest is 9." )); assert_eq!(environment.take_logged_errors(), expected_messages); } ...
#[test] fn should_get_initialization_text_when_old_plugin_system() { let environment = TestEnvironment::new(); environment.add_remote_file( REMOTE_INFO_URL, r#"{ "schemaVersion": 3, "pluginSystemSchemaVersion": 9, // this is 9 instead of 3 "latest": [{ "name": "dprint-plugi...
random
[ { "content": "pub fn get_and_resolve_file_paths(config: &ResolvedConfig, args: &CliArgs, environment: &impl Environment) -> Result<Vec<PathBuf>, ErrBox> {\n\n let (file_patterns, absolute_paths) = get_config_file_paths(config, args, environment)?;\n\n return resolve_file_paths(&file_patterns, &absolute_paths,...
Rust
flowr/src/lib/flowruntime/image/image_buffer.rs
andrewdavidmackenzie/flow
484de720caa19684f0d96e9cbc925254ed4168e3
use std::sync::{Arc, Mutex}; use serde_json::Value; use flowcore::{Implementation, RunAgain, RUN_AGAIN}; use crate::client_server::ServerConnection; use crate::errors::*; use crate::runtime_messages::{ClientMessage, ServerMessage}; pub struct ImageBuffer { pub server_connection: Arc<Mutex<ServerConnection<...
use std::sync::{Arc, Mutex}; use serde_json::Value; use flowcore::{Implementation, RunAgain, RUN_AGAIN}; use crate::client_server::ServerConnection; use crate::errors::*; use crate::runtime_messages::{ClientMessage, ServerMessage}; pub struct ImageBuffer { pub server_connection: Arc<Mutex<ServerConnection<...
l, ClientMessage::Ack); let buffer = &ImageBuffer { server_connection } as &dyn Implementation; let (value, run_again) = buffer.run(&inputs); assert_eq!(run_again, RUN_AGAIN); assert_eq!(value, None); } }
g as u8, b as u8), (w as u32, h as u32), filename.to_string(), )); } } } (None, RUN_AGAIN) } } #[cfg(test)] mod test { use serde_json::json; use serial_test::serial; use flowcor...
random
[ { "content": "/// Implement the `FlowImpl` derive macro\n\npub fn flow_impl_derive(input: TokenStream) -> TokenStream {\n\n // Construct a representation of Rust code as a syntax tree that we can manipulate\n\n let ast = syn::parse(input).unwrap();\n\n\n\n // Build the trait implementation\n\n impl_...
Rust
lang-interp/src/ngram.rs
Emilgardis/problems
9d1e8f917f78621b66816d624009bbd12861f075
use std::collections::BTreeMap; use std::string::String; use std::fmt; #[derive(Serialize, Deserialize, Clone)] pub struct NGram<Data> where Data: Ord + Clone { source: BTreeMap<Data, u64>, total_entries: u64, n: u8, } impl<Data> NGram<Data> where Data: Ord + Clone { pub fn new(source: BTreeMap<Data, ...
use std::collections::BTreeMap; use std::string::String; use std::fmt; #[derive(Serialize, Deserialize, Clone)] pub struct NGram<Data> where Data: Ord + Clone { source: BTreeMap<Data, u64>, total_entries: u64, n: u8, } impl<Data> NGram<Data> where Data: Ord + Clone { pub fn new(source: BTreeMap<Data, ...
pub fn cos_simularity_with_0(&self, other: NGram<Data>) -> f64 { unimplemented!() } } impl<Data> fmt::Debug for NGram<Data> where Data: Ord + fmt::Debug + Clone { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.source) } } #[derive(Debug, Seriali...
4> { let mut A = Vec::new(); let mut B = Vec::new(); for (cA, countA) in self.source.iter() { match other.source.get(cA) { Some(countB) => { A.push(countA); B.push(countB); }, None => (), ...
function_block-function_prefixed
[ { "content": "// TODO: Better name.\n\npub fn get_sum_(multipliers: &[u64], max: u64) -> u64 {\n\n let mut sum = 0;\n\n for mult in multipliers {\n\n sum += (max-1)/mult * (mult + max) / 2;\n\n println!(\"{}\", mult)\n\n }\n\n \n\n sum\n\n}\n\n\n\n#[cfg(test)]\n\nmod multiplier_test...
Rust
src/fruits/mod.rs
kittsun/akatsuki-pp
6c39751ce82c4a88e8358e36b05fac1980fce705
#![cfg(feature = "fruits")] mod catch_object; mod difficulty_object; mod fruit_or_juice; mod gradual_difficulty; mod gradual_performance; mod movement; mod pp; mod slider_state; use catch_object::CatchObject; use difficulty_object::DifficultyObject; use fruit_or_juice::FruitOrJuice; pub use gradual_difficulty::*; pub...
#![cfg(feature = "fruits")] mod catch_object; mod difficulty_object; mod fruit_or_juice; mod gradual_difficulty; mod gradual_performance; mod movement; mod pp; mod slider_state; use catch_object::CatchObject; use difficulty_object::DifficultyObject; use fruit_or_juice::FruitOrJuice; pub use gradual_difficulty::*; pub...
pub fn strains(map: &Beatmap, mods: impl Mods) -> Strains { let (movement, _) = calculate_movement(map, mods, None); Strains { section_length: SECTION_LENGTH * mods.speed(), strains: movement.strain_peaks, } } fn calculate_movement( map: &Beatmap, mods: impl Mods, passed_obje...
pub fn stars( map: &Beatmap, mods: impl Mods, passed_objects: Option<usize>, ) -> FruitsDifficultyAttributes { let (mut movement, mut attributes) = calculate_movement(map, mods, passed_objects); attributes.stars = Movement::difficulty_value(&mut movement.strain_peaks).sqrt() * STAR_SCALING_F...
function_block-full_function
[ { "content": "/// Essentially the same as the [`stars`] function but instead of\n\n/// evaluating the final strains, it just returns them as is.\n\n///\n\n/// Suitable to plot the difficulty of a map over time.\n\npub fn strains(map: &Beatmap, mods: impl Mods) -> Strains {\n\n let (skills, _) = calculate_ski...
Rust
phase2/src/polynomial.rs
sarawut11/snark-setup
47f8c00dbf1246dbabc80bec83befab91b313969
use rayon::prelude::*; use zexe_algebra::{AffineCurve, PairingEngine, ProjectiveCurve, Zero}; use zexe_r1cs_core::Index; #[allow(clippy::too_many_arguments)] #[allow(clippy::type_complexity)] pub fn eval<E: PairingEngine>( coeffs_g1: &[E::G1Affine], coeffs_g2: &[E::G2Affine], alpha_coeffs_g1: &[E::G1A...
use rayon::prelude::*; use zexe_algebra::{AffineCurve, PairingEngine, ProjectiveCurve, Zero}; use zexe_r1cs_core::Index; #[allow(clippy::too_many_arguments)] #[allow(clippy::type_complexity)] pub fn eval<E: PairingEngine>( coeffs_g1: &[E::G1Affine], coeffs_g2: &[E::G2Affine], alpha_coeffs_g1: &[E::G1A...
#[test] fn test_dot_product() { let mut rng = thread_rng(); let num_inputs = 3; let input = gen_input(&mut rng); let scalar = input.iter().map(|i| i.0).collect::<Vec<_>>(); let elements: Vec<G1Affine> = random_point_vec(6, &mut rng); let expected = get...
1]) + elements[2].mul(scalar[5]) + elements[num_inputs].mul(scalar[2]) + elements[num_inputs + 2].mul(scalar[3]) + elements[num_inputs + 1].mul(scalar[4]) }
function_block-function_prefixed
[ { "content": "/// returns a random affine curve point vector from the provided rng\n\npub fn random_point_vec<C: AffineCurve>(size: usize, rng: &mut impl Rng) -> Vec<C> {\n\n (0..size).map(|_| random_point(rng)).collect()\n\n}\n\n\n", "file_path": "test-helpers/src/lib.rs", "rank": 0, "score": 38...
Rust
bot/src/db/macros.rs
osurce/setmod
397d252bc61f62fee399920c44868ab723f4102f
macro_rules! database_group_fns { ($thing:ty, $key:ty) => { pub fn edit_group( &self, channel: &str, name: &str, group: Option<String>, ) -> Result<bool, failure::Error> { let key = <$key>::new(channel, name); ...
macro_rules! database_group_fns { ($thing:ty, $key:ty) => { pub fn edit_group( &self, channel: &str, name: &str, group: Option<String>, ) -> Result<bool, failure::Error> { let key = <$key>::new(channel, name); ...
ock(); Ok(dsl::$module .filter(dsl::channel.eq(channel)) .load::<db::models::$thing>(&*c)?) } fn list_group( &self, channel: &str, group: &str, ) -> Result<Vec<db::models::$thing>, failure::Error>...
urn Some(Arc::clone(thing)); } None } pub fn get_any<'a>(&'a self, channel: &str, name: &str) -> Result<Option<$thing>, failure::Error> { let key = <$key>::new(channel, name); let thing = match self.db.fetch(&key)? { Som...
random
[ { "content": "/// Extract a settings key from the context.\n\nfn key<'a>(ctx: &mut command::Context<'a, '_>, prefix: &str) -> Option<&'a str> {\n\n let key = match ctx.next() {\n\n Some(key) => key,\n\n None => {\n\n ctx.respond(format!(\n\n \"Expected: {p} <key>\",\n\...
Rust
src/sam.rs
mosmeh/maguro
a6572410a579ae2540a67d63a136c1ee7a99071b
#![allow(clippy::write_with_newline)] use crate::{ index::{Index, SequenceId}, mapper::{pair::PairMapping, single::SingleMapping}, }; use std::io; pub fn write_header<W: io::Write>(mut out: W, pg: &str, index: &Index) -> io::Result<()> { out.write_all(b"@HD\tVN:1.0\tSO:unknown\n")?; for i in 0..index...
#![allow(clippy::write_with_newline)] use crate::{ index::{Index, SequenceId}, mapper::{pair::PairMapping, single::SingleMapping}, }; use std::io; pub fn write_header<W: io::Write>(mut out: W, pg: &str, index: &Index) -> io::Result<()> { out.write_all(b"@HD\tVN:1.0\tSO:unknown\n")?; for i in 0..index...
en(), mapping.pos2 + 1, if mapping.pos1 < mapping.pos2 { fragment_len } else { -fragment_len } )?; out.write_all(seq1)?; write!(out, "\t*\tAS:i:{}\n", mapping.score1)?; out.write_all(qname)?; write!(out, "\t{}\t", flag2)?; out.write_all(rn...
g.strand.is_reverse() { seq2 } else if let Some(rc) = rc_seq_cache2 { rc } else { *rc_seq_cache2 = Some(reverse_complement(seq2)); &rc_seq_cache2.as_ref().unwrap() }; let min_pos = mapping.pos1.min(mapping.pos2); let ref_len = index.seq_range(mapping.seq_id).len(); ...
random
[ { "content": "pub fn decode_in_place(seq: &mut [u8]) {\n\n for x in seq.iter_mut() {\n\n *x = DECODE_TABLE[*x as usize];\n\n }\n\n}\n\n\n", "file_path": "src/sequence.rs", "rank": 2, "score": 151939.37199802074 }, { "content": "pub fn complement_in_place(seq: &mut [u8]) {\n\n ...
Rust
core/mempool/src/map.rs
cosinlink/muta
b19502f48e6d314717a8a2286ada58f6097c6f31
use std::collections::HashMap; use parking_lot::RwLock; use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use protocol::types::Hash; pub struct Map<V> { buckets: Vec<Bucket<V>>, } impl<V> Map<V> where V: Send + Sync + Clone, { pub fn new(cache_size: usize) -> Self { let mut buckets =...
use std::collections::HashMap; use parking_lot::RwLock; use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use protocol::types::Hash; pub struct Map<V> { buckets: Vec<Bucket<V>>, } impl<V> Map<V> where V: Send + Sync + Clone, { pub fn new(cache_size: usize) -> Self { let mut buckets =...
#[bench] fn bench_chashmap_insert(b: &mut Bencher) { let txs = mock_txs(GEN_TX_SIZE); b.iter(move || { let cache = CHashMap::new(); txs.par_iter().for_each(|(hash, tx)| { cache.insert(hash, tx); }); }); } fn mock_txs(size: u...
b.iter(move || { let cache = Arc::new(RwLock::new(HashMap::new())); txs.par_iter().for_each(|(hash, tx)| { cache.write().unwrap().insert(hash, tx); }); }); }
function_block-function_prefix_line
[ { "content": "#[bench]\n\nfn bench_signed_tx_deserialize(b: &mut Bencher) {\n\n let txs: Vec<Bytes> = (0..50_000)\n\n .map(|_| mock_sign_tx().encode_sync().unwrap())\n\n .collect();\n\n\n\n b.iter(|| {\n\n txs.iter().for_each(|signed_tx| {\n\n SignedTransaction::decode_sync...
Rust
pusoy/src/play/finder.rs
EtomicBomb/ethan_ws
8fa01ccd0a91e6c1356dd7fd3ef63ed5485ad6ec
use crate::play::{Play, PlayKind}; use crate::cards::Card; use crate::Cards; pub fn all_plays(cards: Cards) -> Vec<Play> { let mut plays = Vec::new(); let mut rank_blocks = RankBlocks::new(cards); plays.push(Play::pass()); plays.append(&mut rank_blocks.strait_flushes()); plays.append(&mut r...
use crate::play::{Play, PlayKind}; use crate::cards::Card; use crate::Cards; pub fn all_plays(cards: Cards) -> Vec<Play> { let mut plays = Vec::new(); let mut rank_blocks = RankBlocks::new(cards); plays.push(Play::pass()); plays.append(&mut rank_blocks.strait_flushes()); plays.append(&mut r...
of_a_kind.is_disjoint(pair) { let mut collection = pair; collection.insert_all(three_of_a_kind); let play = Play::new(PlayKind::FullHouse, three_of_a_kind.max_card().unwrap(), collection); full_houses.push(play); } ...
let pairs = self.n_of_a_kinds(2); for three_of_a_kind in self.n_of_a_kinds(3) { for &pair in pairs.iter() { if three_
function_block-random_span
[ { "content": "fn get_payload_len(reader: &mut impl Read) -> io::Result<usize> {\n\n let mut heuristic_byte = [0u8; 1];\n\n reader.read_exact(&mut heuristic_byte)?;\n\n let [heuristic_byte] = heuristic_byte;\n\n\n\n match heuristic_byte & 0b_0111_1111 {\n\n n @ 0..=125 => Ok(n as usize),\n\n ...
Rust
crates/sdp-types/src/lib.rs
kbalt/ezk
6886981a5d13954fb8536cf69d83b147551fd55c
use bytes::Bytes; use bytesstr::BytesStr; use internal::IResult; use nom::branch::alt; use nom::bytes::complete::{tag, take_while}; use nom::character::complete::{char, digit1}; use nom::combinator::{map, map_res}; use nom::sequence::preceded; use std::fmt; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::From...
use bytes::Bytes; use bytesstr::BytesStr; use internal::IResult; use nom::branch::alt; use nom::bytes::complete::{tag, take_while}; use nom::character::complete::{char, digit1}; use nom::combinator::{map, map_res}; use nom::sequence::preceded; use std::fmt; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::From...
} fn slash_num(i: &str) -> IResult<&str, u32> { preceded(char('/'), map_res(digit1, FromStr::from_str))(i) } fn token(c: char) -> bool { matches!(c, '\x21' | '\x23'..='\x27' | '\x2A'..='\x2B' | '\x2D'..='\x2E' | '\x30'..='\x39' | '\x41'..='\x5A' | '\x5E'..='\x7E') } fn not_whitespace(c: char) -> bool { ...
r) } TaggedAddress::IP6FQDN(fqdn) => { write!(f, "IN IP6 {}", fqdn) } } }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn ws<I, O, E, L>(mut l: L) -> impl FnMut(I) -> IResult<I, O, E>\n\nwhere\n\n I: InputLength + InputIter + InputTakeAtPosition,\n\n <I as InputTakeAtPosition>::Item: Into<char>,\n\n E: ParseError<I>,\n\n L: WsTuple<I, O, E>,\n\n{\n\n move |i: I| l.parse(i)\n\n}\n\n\...
Rust
lib/vis-rs/src/parser.rs
luteberget/railplot
c960966a0969fa9a6b975dda4d489f6b3ec18bc6
use parser_utils::*; use std::path::Path; use failure; type Position = f64; type Id = String; #[derive(Debug, Copy, Clone)] pub enum Side { Left, Right } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Dir { Up, Down } #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum Port { In, Out, Left, Right...
use parser_utils::*; use std::path::Path; use failure; type Position = f64; type Id = String; #[derive(Debug, Copy, Clone)] pub enum Side { Left, Right } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Dir { Up, Down } #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum Port { In, Out, Left, Right...
} fn identifier(i: &mut usize, tokens: &[Token]) -> Result<String, ParseError> { let r = match tokens[*i] { Token::Id(ref s) => s.clone(), ref x => return Err(ParseError::UnexpectedToken(*i, format!("{:?}", x.clone()))), }; *i += 1; Ok(r) } fn number(i: &mut usize, tokens: &[Token]) -...
if identifier(i, t)? != s { Err(ParseError::UnexpectedToken(*i, format!("{:?}", s))) } else { Ok(()) }
if_condition
[ { "content": "pub fn matches<Token: PartialEq + Debug + Clone>(i: &mut usize,\n\n tokens: &[Token],\n\n tok: Token)\n\n -> bool {\n\n let r = tokens[*i] == tok;\n\n ...
Rust
src/api.rs
sacovo/public-transport-cli
d4bea6f4f364c36aaefe5ad50587c87fe05c37e2
use std::fmt::{Display, Write}; use chrono::{DateTime, Duration, Local}; use pad::PadStr; use serde::{Deserialize, Serialize}; use colored::{ColoredString, Colorize}; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Location { id: String, name: String, } #[derive(Debug,...
use std::fmt::{Display, Write}; use chrono::{DateTime, Duration, Local}; use pad::PadStr; use serde::{Deserialize, Serialize}; use colored::{ColoredString, Colorize}; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Location { id: String, name: String, } #[derive(Debug,...
} impl Display for Connection { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let duration = self.time_until(); write!( f, "{} - {}, Leaves in {:02}:{:02}\n\n", self.from.departure.as_ref().unwrap().format("%H:%M"), self.to.ar...
ture))?; }; write!(f, "{}", " ┃ \n".cyan())?; if let Some(arrival) = &self.arrival { write!(f, "{}\n", print_checkpoint(&arrival))?; } write!(f, "\n") }
function_block-function_prefixed
[ { "content": "pub fn load_config() -> Result<()> {\n\n CONFIG\n\n .set(if_chain! {\n\n if let Some(config_dir) = dirs::config_dir();\n\n let config_path = config_dir.join(\"spt_cli.json\");\n\n if config_path.exists();\n\n then {\n\n serde_jso...
Rust
vendor/backtrace/src/symbolize/libbacktrace.rs
raspbian-packages/cargo
3b1b88e08c83b03469c9a98c3237317c7eb5c330
#![allow(bad_style)] extern crate backtrace_sys as bt; use core::{ptr, slice}; use libc::{self, c_char, c_int, c_void, uintptr_t}; use SymbolName; use symbolize::ResolveWhat; use types::BytesOrWideString; pub enum Symbol { Syminfo { pc: uintptr_t, symname: *const c_char, }, Pcinfo { ...
#![allow(bad_style)] extern crate backtrace_sys as bt; use core::{ptr, slice}; use libc::{self, c_char, c_int, c_void, uintptr_t}; use SymbolName; use symbolize::ResolveWhat; use types::BytesOrWideString; pub enum Symbol { Syminfo { pc: uintptr_t, symname: *const c_char, }, Pcinfo { ...
pub fn filename_raw(&self) -> Option<BytesOrWideString> { self.filename_bytes().map(BytesOrWideString::Bytes) } #[cfg(feature = "std")] pub fn filename(&self) -> Option<&::std::path::Path> { use std::path::Path; #[cfg(unix)] fn bytes2path(bytes: &[u8]) -> Option<&Path...
fn filename_bytes(&self) -> Option<&[u8]> { match *self { Symbol::Syminfo { .. } => None, Symbol::Pcinfo { filename, .. } => { let ptr = filename as *const u8; unsafe { let len = libc::strlen(filename); Some(slice::f...
function_block-full_function
[ { "content": "fn handle(handle: &mut Easy, read: &mut dyn FnMut(&mut [u8]) -> usize) -> Result<String> {\n\n let mut headers = Vec::new();\n\n let mut body = Vec::new();\n\n {\n\n let mut handle = handle.transfer();\n\n handle.read_function(|buf| Ok(read(buf)))?;\n\n handle.write_f...
Rust
matrix/src/mat_impl.rs
Camotubi/basic_dsp
38a380439cc8936c64febbc12227df78d95fce7f
use super::*; pub trait Matrix<V, T>: MetaData + ResizeOps where V: Vector<T>, T: RealNumber, { fn delta(&self) -> T; fn set_delta(&mut self, delta: T); fn row_len(&self) -> usize; fn row_points(&self) -> usize; fn col_len(&self) -> usiz...
use super::*; pub trait Matrix<V, T>: MetaData + ResizeOps where V: Vector<T>, T: RealNumber, { fn delta(&self) -> T; fn set_delta(&mut self, delta: T); fn row_len(&self) -> usize; fn row_points(&self) -> usize; fn col_len(&self) -> usiz...
} fn row_points(&self) -> usize { if self.rows.len() == 0 { return 0; } self.rows[0].points() } fn col_len(&self) -> usize { self.rows.len() } fn rows(&self) -> &[V] { &self.rows[..] ...
where T: RealNumber, S: ToSlice<T>, V: Vector<T> { fn resize(&mut self, len: usize) -> VoidResult { for v in &mut self.rows[..] { r#try!(v.resize(len)); } Ok(()) } } impl<V, S, T> Matrix<V, T> for $matrix<V, S, T> ...
random
[ { "content": "pub fn create_delta(seed: usize, iteration: usize) -> f32 {\n\n let mut rng: StdRng = SeedableRng::seed_from_u64((seed + iteration) as u64);\n\n rng.gen_range(-10.0, 10.0)\n\n}\n\n\n", "file_path": "tests/tools/mod.rs", "rank": 1, "score": 189580.66460140707 }, { "content...
Rust
Rust/src/lib.rs
MadhavJivrajani/baesik_dfa
8932ea6c722684591d8b685ca4e23a17a25520ca
use std::cmp::Eq; use std::collections::HashMap; use std::hash::Hash; #[derive(Debug, Default, Copy, Eq, PartialEq, Hash, Clone)] pub struct State { is_start: bool, is_final: bool, name: char, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Transition { from_state: State, to_state...
use std::cmp::Eq; use std::collections::HashMap; use std::hash::Hash; #[derive(Debug, Default, Copy, Eq, PartialEq, Hash, Clone)] pub struct State { is_start: bool, is_final: bool, name: char, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Transition { from_state: State, to_state...
pub fn evaluate_string(&mut self, input_string: String) -> Result<String, String> { if self.num_of_start_states > 1 { return Err("More than one start state detected. Exiting".to_string()); } for input in input_string.chars() { if self.alphabet.contains(&input) == f...
self.current_state = applicable_transitions.remove(0).0.to_state; } else { self.current_state = current_state; self.reject = true; } }
function_block-function_prefix_line
[ { "content": " String name;\n", "file_path": "Java/State.java", "rank": 0, "score": 81874.61694319305 }, { "content": " public State(int is_start, int is_final, String name){\n\n this.is_start = is_start;\n\n this.is_final = is_final;\n\n this.name = name;\n", ...
Rust
src/fcs/envelop.rs
qiuchengxuan/rs-flight
66a09afe4e24f8b49c6445f9048172e46e6a0f03
#[cfg(not(any(test, feature = "std")))] use micromath::F32Ext; use nalgebra::Vector3; use crate::types::measurement::Attitude; pub struct Envelop { max_roll: f32, min_pitch: f32, max_pitch: f32, prev_roll_command: f32, hold_bank_angle: f32, } type Control = Vector3<f32>; impl Envelop { pub f...
#[cfg(not(any(test, feature = "std")))] use micromath::F32Ext; use nalgebra::Vector3; use crate::types::measurement::Attitude; pub struct Envelop { max_roll: f32, min_pitch: f32, max_pitch: f32, prev_roll_command: f32, hold_bank_angle: f32, } type Control = Vector3<f32>; impl Envelop { pub f...
else if input.x.abs() < 0.1 { if atti.roll.abs() < 33.0 { output.x = (self.hold_bank_angle - atti.roll).clamp(-25.0, 25.0); } else if input.y.abs() < 0.1 { output.x = -f32::min(atti.roll.abs() - 33.0, 25.0).copysign(atti.roll); } } out...
e, g: f32) -> Control { let mut output = input; if input.x.abs() < 0.1 && self.prev_roll_command.abs() > 0.1 { self.hold_bank_angle = atti.roll; } self.prev_roll_command = input.x; output.y = match () { _ if atti.pitch < self.min_pitch => -f32::max(atti....
random
[ { "content": "pub fn replace(config: &Config) {\n\n unsafe { CONFIG_ITERATION += 1 }\n\n unsafe { CONFIG = Some(config.clone()) }\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 1, "score": 215484.90815095056 }, { "content": "pub fn to_serial_config(config: &SerialConfig) -> Con...
Rust
crates/tanoshi/src-tauri/src/server.rs
fadhlika/tanoshi
66056cb6aa3e185a9fafcbc8fbd76035edda66e8
use tanoshi_vm::prelude::{ExtensionManager, Source}; use tauri::{ plugin::{Plugin, Result as PluginResult}, AppHandle, Runtime, }; use tanoshi::{ application::worker, domain::services::{ chapter::ChapterService, download::DownloadService, history::HistoryService, image::ImageService, library::Library...
use tanoshi_vm::prelude::{ExtensionManager, Source}; use tauri::{ plugin::{Plugin, Result as PluginResult}, AppHandle, Runtime, }; use tanoshi::{ application::worker, domain::services::{ chapter::ChapterService, download::DownloadService, history::HistoryService, image::ImageService, library::Library...
}
l::new(pool.clone()); let chapter_svc = ChapterService::new(chapter_repo.clone(), extension_manager.clone()); let library_repo = LibraryRepositoryImpl::new(pool.clone()); let libary_svc = LibraryService::new(library_repo.clone()); let history_repo = HistoryRepositoryImpl::new(pool.clone()); ...
function_block-function_prefixed
[ { "content": "pub fn decode_jwt(secret: &str, token: &str) -> Result<Claims> {\n\n Ok(jsonwebtoken::decode::<Claims>(\n\n token,\n\n &DecodingKey::from_secret(secret.as_bytes()),\n\n &Validation::default(),\n\n )?\n\n .claims)\n\n}\n\n\n", "file_path": "crates/tanoshi/src/infra...
Rust
src/nn/npz.rs
coreylowman/stag
21c068c2b44b43dbf38ab49887d85e7472f1e5a2
use super::*; use crate::{ numpy::{self, NpyError}, prelude::HasArrayData, }; use std::{ fs::File, io::{BufReader, BufWriter, Read, Seek, Write}, path::Path, }; use zip::{ result::{ZipError, ZipResult}, ZipArchive, ZipWriter, }; pub trait SaveToNpz { ...
use super::*; use crate::{ numpy::{self, NpyError}, prelude::HasArrayData, }; use std::{ fs::File, io::{BufReader, BufWriter, Read, Seek, Write}, path::Path, }; use zip::{ result::{ZipError, ZipResult}, ZipArchive, ZipWriter, }; pub trait SaveToNpz { ...
#[test] fn test_save_tuple() { let model: ( Linear<1, 2>, ReLU, Linear<2, 3>, (Dropout, Linear<1, 2>, Linear<3, 4>), ) = Default::default(); let file = NamedTempFile::new().expect("failed to create tempfile"); model .s...
fn test_save_linear() { let model: Linear<5, 3> = Default::default(); let file = NamedTempFile::new().expect("failed to create tempfile"); model .save(file.path().to_str().unwrap().to_string()) .expect("failed to save model"); let f = File::open(file.path()).expec...
function_block-full_function
[ { "content": "/// Writes the data to a [Write].\n\n///\n\n/// This is implemented for an arbitrarily shaped array.\n\n/// See [WriteNumbers] for how this is done (recursive array traits!).\n\npub fn write<T, W>(w: &mut W, t: &T) -> Result<usize>\n\nwhere\n\n T: NumpyDtype + NumpyShape + WriteNumbers,\n\n ...
Rust
src/ed25519.rs
KandareJ/did-key.rs
6df484cb4f367d986735171e8ade9758fba7ce35
use super::{generate_seed, Ecdsa}; use crate::{ didcore::{DIDCore, Document, VerificationMethod}, x25519::X25519KeyPair, AsymmetricKey, DIDKey, DIDKeyTypeInternal, KeyMaterial, Payload, }; use curve25519_dalek::edwards::CompressedEdwardsY; use ed25519_dalek::*; use std::convert::{TryFrom, TryInto}; pub typ...
use super::{generate_seed, Ecdsa}; use crate::{ didcore::{DIDCore, Document, VerificationMethod}, x25519::X25519KeyPair, AsymmetricKey, DIDKey, DIDKeyTypeInternal, KeyMaterial, Payload, }; use curve25519_dalek::edwards::CompressedEdwardsY; use ed25519_dalek::*; use std::convert::{TryFrom, TryInto}; pub typ...
, _ => unimplemented!("payload type not supported for this key"), } } } #[cfg(test)] pub mod test { use crate::{DIDKey, DIDKeyType, Payload}; use super::*; #[test] fn test_demo() { let secret_key = "6Lx39RyWn3syuozAe2WiPdAYn1ctMx17t8yrBMGFBmZy"; let public_key =...
match self.public_key.verify(payload.as_slice(), &sig) { Ok(_) => Ok(()), _ => Err(String::from("verify failed")), }
if_condition
[ { "content": "fn get_hash(payload: &Vec<u8>) -> [u8; 32] {\n\n let hash = Sha256::digest(&payload);\n\n let mut output = [0u8; 32];\n\n output.copy_from_slice(&hash[..32]);\n\n output\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use super::*;\n\n\n\n //Are these tests sufficient? Or do I nee...
Rust
src/chit/details/mod.rs
Darth-Knoppix/chit
ccdb44da44da72d9e5b5e31c9e3b7df5b8cf1b04
use colored::*; use super::extract; use super::format; use super::sources::crates; use super::sources::get; mod alternatives; pub fn print_details(crate_name: String) { let mut width = format::get_width(); println!( "{} {}...", "Searching for".magenta(), &crate_name.bright_blue() ...
use colored::*; use super::extract; use super::format; use super::sources::crates; use super::sources::get; mod alternatives; pub fn print_details(crate_name: String) { let mut width = format::get_width(); println!( "{} {}...", "Searching for".magenta(), &crate_name.bright_blue() ...
); } None => println!("Failed to get crate owner details"), } println!("{}", format::end_bar(width)); }
} if !found_alternative { format::print( "Alternatives: None listed - Know one? Make a PR!".to_string(), ); } } Err(err) =...
random
[ { "content": "fn describe_versions(width: usize, fields: extract::package::Crate) -> Vec<String> {\n\n let mut lines = Vec::new();\n\n\n\n lines.push(format!(\"{}\", format::title_bar(width, &fields.name)));\n\n lines.push(format!(\"{}\", \"Versions:\".bright_blue()));\n\n\n\n for version in fields....
Rust
store/tests/sumtree.rs
bradneuman/grin
866ec977da0b5fa21ed9afdb08c9354c4abeae1e
extern crate env_logger; extern crate grin_core as core; extern crate grin_store as store; extern crate time; use std::fs; use core::ser::*; use core::core::pmmr::{Backend, HashSum, Summable, PMMR}; use core::core::hash::Hashed; #[test] fn sumtree_append() { let (data_dir, elems) = setup("append"); let mut backe...
extern crate env_logger; extern crate grin_core as core; extern crate grin_store as store; extern crate time; use std::fs; use core::ser::*; use core::core::pmmr::{Backend, HashSum, Summable, PMMR}; use core::core::hash::Hashed; #[test] fn sumtree_append() { let (data_dir, elems) = setup("append"); let mut backe...
}
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> { try!(writer.write_u32(self.0[0])); try!(writer.write_u32(self.0[1])); try!(writer.write_u32(self.0[2])); writer.write_u32(self.0[3]) }
function_block-full_function
[ { "content": "/// Gets the postorder traversal index of all peaks in a MMR given the last\n\n/// node's position. Starts with the top peak, which is always on the left\n\n/// side of the range, and navigates toward lower siblings toward the right\n\n/// of the range.\n\npub fn peaks(num: u64) -> Vec<u64> {\n\n\...
Rust
crates/penrose_proc/src/stub.rs
kN1e1ght/penrose
5efd2bcfa3831d02b87056583e66eac8bb92cb9d
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{ fold::Fold, parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, token::Comma, Attribute, Block, Error, Expr, ExprMethodCall, FnArg, Ident, ItemTrait, Lit, Meta, MetaNameValue, ReturnType, Token, Tr...
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{ fold::Fold, parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, token::Comma, Attribute, Block, Error, Expr, ExprMethodCall, FnArg, Ident, ItemTrait, Lit, Meta, MetaNameValue, ReturnType, Token, Tr...
fn parse_args_meta(meta: Vec<Meta>) -> Result<(String, bool, bool), TokenStream> { if meta.len() <= 2 { let mut prefix = DEFAULT_PREFIX.to_string(); let mut test_only = false; let mut doc_hidden = false; for m in meta.iter() { if let Meta::NameValue(ref nv) = m { ...
e) -> Result<ValidArg, TokenStream> { if nv.path.is_ident("prefix") { if let Lit::Str(ref s) = nv.lit { return Ok(ValidArg::Prefix(s.value())); } } if nv.path.is_ident("test_only") { if let Lit::Str(ref s) = nv.lit { let s = s.value(); match s.as_...
function_block-function_prefixed
[]
Rust
actix-framed/src/route.rs
NickKolpinskiy/actix-web
b9e268e95fb433aa69f3ac08cbbebd820afe0e05
use std::fmt; use std::future::Future; use std::marker::PhantomData; use std::task::{Context, Poll}; use actix_codec::{AsyncRead, AsyncWrite}; use actix_http::{http::Method, Error}; use actix_service::{Service, ServiceFactory}; use futures_util::future::{ok, FutureExt, LocalBoxFuture, Ready}; use log::error; use crat...
use std::fmt; use std::future::Future; use std::marker::PhantomData; use std::task::{Context, Poll}; use actix_codec::{AsyncRead, AsyncWrite}; use actix_http::{http::Method, Error}; use actix_service::{Service, ServiceFactory}; use futures_util::future::{ok, FutureExt, LocalBoxFuture, Ready}; use log::error; use crat...
} pub struct FramedRouteService<Io, S, F, R, E> { handler: F, methods: Vec<Method>, _t: PhantomData<(Io, S, R, E)>, } impl<Io, S, F, R, E> Service for FramedRouteService<Io, S, F, R, E> where Io: AsyncRead + AsyncWrite + 'static, F: FnMut(FramedRequest<Io, S>) -> R + Clone, R: Future<Output =...
fn new_service(&self, _: ()) -> Self::Future { ok(FramedRouteService { handler: self.handler.clone(), methods: self.methods.clone(), _t: PhantomData, }) }
function_block-full_function
[ { "content": "/// Async handler converter factory\n\npub trait Factory<T, R, O>: Clone + 'static\n\nwhere\n\n R: Future<Output = O>,\n\n O: Responder,\n\n{\n\n fn call(&self, param: T) -> R;\n\n}\n\n\n\nimpl<F, R, O> Factory<(), R, O> for F\n\nwhere\n\n F: Fn() -> R + Clone + 'static,\n\n R: Futu...
Rust
src/auto/ge.rs
Xelrees/breadx
71eff13c878dd62d9650655a30683a03005966fe
#![allow(warnings)] use super::prelude::*; #[derive(Clone, Debug, Default)] pub struct QueryVersionRequest { pub req_type: u8, pub length: u16, pub client_major_version: Card16, pub client_minor_version: Card16, } impl QueryVersionRequest {} impl AsByteSequence for QueryVersionRequest { #[inline...
#![allow(warnings)] use super::prelude::*; #[derive(Clone, Debug, Default)] pub struct QueryVersionRequest { pub req_type: u8, pub length: u16, pub client_major_version: Card16, pub client_minor_version: Card16, } impl QueryVersionRequest {} impl AsByteSequence for QueryVersionRequest { #[inline...
#[inline] fn size(&self) -> usize { self.reply_type.size() + 1 + self.sequence.size() + self.length.size() + self.major_version.size() + self.minor_version.size() + 20 } }
index..])?; index += sz; index += 20; Some(( QueryVersionReply { reply_type: reply_type, sequence: sequence, length: length, major_version: major_version, minor_version: minor_version, }, ...
function_block-function_prefixed
[ { "content": "#[inline]\n\nfn put_bits(source: &[u8], mut dstoffset: usize, mut numbits: usize, dest: &mut [u8]) {\n\n let mut src_index = 0;\n\n let mut dst_index = dstoffset >> 3;\n\n\n\n dstoffset &= 7;\n\n let hibits = 8 - dstoffset;\n\n let mut chlo = dest[dst_index] & LOMASK[dstoffset];\n\n...
Rust
graph/src/node/render/group/simple.rs
Moxinilian/rendy
c521b6d97d8154042bcc2215c7d7906cc70d7282
use { super::{RenderGroup, RenderGroupDesc}, crate::{ command::{QueueId, RenderPassEncoder}, factory::Factory, graph::GraphContext, node::{ render::PrepareResult, BufferAccess, DescBuilder, ImageAccess, NodeBuffer, NodeImage, }, resource::{DescriptorSe...
use { super::{RenderGroup, RenderGroupDesc}, crate::{ command::{QueueId, RenderPassEncoder}, factory::Factory, graph::GraphContext, node::{ render::PrepareResult, BufferAccess, DescBuilder, ImageAccess, NodeBuffer, NodeImage, }, resource::{DescriptorSe...
fn depth_stencil(&self) -> Option<gfx_hal::pso::DepthStencilDesc> { Some(gfx_hal::pso::DepthStencilDesc { depth: gfx_hal::pso::DepthTest::On { fun: gfx_hal::pso::Comparison::Less, write: true, }, depth_bounds: false, sten...
fn colors(&self) -> Vec<gfx_hal::pso::ColorBlendDesc> { vec![gfx_hal::pso::ColorBlendDesc( gfx_hal::pso::ColorMask::ALL, gfx_hal::pso::BlendState::ALPHA, )] }
function_block-full_function
[ { "content": "/// Dynamic node builder that emits `DynNode`.\n\npub trait NodeBuilder<B: Backend, T: ?Sized>: std::fmt::Debug {\n\n /// Pick family for this node to be executed onto.\n\n fn family(&self, factory: &mut Factory<B>, families: &[Family<B>]) -> Option<FamilyId>;\n\n\n\n /// Get buffer acces...
Rust
src/modules/gcloud.rs
ocdy1001/starship
77bd80839ef6ac94cbf8e95095c566afd4f9b499
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::path::PathBuf; use std::str::FromStr; use super::{Context, Module, RootModuleConfig}; use crate::configs::gcloud::GcloudConfig; use crate::formatter::StringFormatter; type Account = String; type Project = ...
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::path::PathBuf; use std::str::FromStr; use super::{Context, Module, RootModuleConfig}; use crate::configs::gcloud::GcloudConfig; use crate::formatter::StringFormatter; type Account = String; type Project = ...
let reader = BufReader::new(file); let lines = reader.lines().filter_map(Result::ok); let account_line = lines .skip_while(|line| line != "[core]") .skip(1) .take_while(|line| !line.starts_with('[')) .find(|line| line.starts_with("account"))?; let account = account_line.s...
cloud_account_from_config(current_config: &PathBuf) -> Option<Account> { let file = File::open(&current_config).ok()?;
function_block-random_span
[]
Rust
crates/core/tedge/src/cli/connect/c8y_direct_connection.rs
PradeepKiruvale/localworkflow
b5f3c97c835cb36ae87f14b8697bedcca5d22619
use super::{BridgeConfig, ConnectError}; use rumqttc::{ self, certs, pkcs8_private_keys, rsa_private_keys, Client, Event, Incoming, MqttOptions, Outgoing, Packet, QoS, Transport, }; use rustls_0_19::ClientConfig; use std::fs; use std::io::{Error, ErrorKind}; use std::{fs::File, io::BufReader}; use tedge_conf...
use super::{BridgeConfig, ConnectError}; use rumqttc::{ self, certs, pkcs8_private_keys, rsa_private_keys, Client, Event, Incoming, MqttOptions, Outgoing, Packet, QoS, Transport, }; use rustls_0_19::ClientConfig; use std::fs; use std::io::{Error, ErrorKind}; use std::{fs::File, io::BufReader}; use tedge_conf...
fn read_pvt_key( user_manager: UserManager, key_file: tedge_config::FilePath, ) -> Result<rustls_0_19::PrivateKey, ConnectError> { let _user_guard = user_manager.become_user(tedge_users::BROKER_USER)?; parse_pkcs8_key(key_file.clone()).or_else(|_| parse_rsa_key(key_file)) } fn parse_pkcs8_key( ...
t_store: &mut rustls_0_19::RootCertStore, cert_dir: FilePath, ) -> Result<(), ConnectError> { for file_entry in fs::read_dir(cert_dir)? { let file = file_entry?; let f = File::open(file.path())?; let mut rd = BufReader::new(f); let _ = root_store.add_pem_file(&mut rd).map(|_| ())...
function_block-function_prefixed
[ { "content": "fn build_upload_certificate_url(host: &str, tenant_id: &str) -> Result<Url, CertError> {\n\n let url_str = format!(\n\n \"https://{}/tenant/tenants/{}/trusted-certificates\",\n\n host, tenant_id\n\n );\n\n\n\n Ok(Url::parse(&url_str)?)\n\n}\n\n\n", "file_path": "crates/c...
Rust
src/media/rtp/rtp_transceiver.rs
Flakebi/webrtc
90e6cb4713327a95e4011ea3bf67ac0317df9ff8
#[cfg(test)] mod rtp_transceiver_test; use crate::api::media_engine::MediaEngine; use crate::error::Error; use crate::media::rtp::rtp_codec::*; use crate::media::rtp::rtp_receiver::{RTCRtpReceiver, RTPReceiverInternal}; use crate::media::rtp::rtp_sender::RTCRtpSender; use crate::media::rtp::rtp_transceiver_direction::...
#[cfg(test)] mod rtp_transceiver_test; use crate::api::media_engine::MediaEngine; use crate::error::Error; use crate::media::rtp::rtp_codec::*; use crate::media::rtp::rtp_receiver::{RTCRtpReceiver, RTPReceiverInternal}; use crate::media::rtp::rtp_sender::RTCRtpSender; use crate::media::rtp::rtp_transceiver_direction::...
pub async fn mid(&self) -> String { let mid = self.mid.lock().await; mid.clone() } pub fn kind(&self) -> RTPCodecType { self.kind } pub fn direction(&self) -> RTCRtpTransceiverDirection { self.direction.load(Ordering::SeqCst).into() } pub(c...
pub(crate) async fn set_mid(&self, mid: String) -> Result<()> { let mut m = self.mid.lock().await; if !m.is_empty() { return Err(Error::ErrRTPTransceiverCannotChangeMid.into()); } *m = mid; Ok(()) }
function_block-full_function
[ { "content": "/// match_all always returns true\n\npub fn match_all(_b: &[u8]) -> bool {\n\n true\n\n}\n\n\n", "file_path": "src/util/mux/mux_func.rs", "rank": 0, "score": 200638.7918848638 }, { "content": "/// MatchFuncs as described in RFC7983\n\n/// https://tools.ietf.org/html/rfc7983\...
Rust
atari2600/src/address_space.rs
bl-nero/atari-emulator
ac581216800aac1ae9acc0ebcae8b8d2640e08ca
use std::fmt; use ya6502::memory::dump_zero_page; use ya6502::memory::Read; use ya6502::memory::Write; use ya6502::memory::{Memory, ReadError, ReadResult, WriteError, WriteResult}; #[derive(Debug)] pub struct AddressSpace<T: Memory, RA: Memory, RI: Memory, RO: Read> { pub tia: T, pub ram: RA, pub riot: RI,...
use std::fmt; use ya6502::memory::dump_zero_page; use ya6502::memory::Read; use ya6502::memory::Write; use ya6502::memory::{Memory, ReadError, ReadResult, WriteError, WriteResult}; #[derive(Debug)] pub struct AddressSpace<T: Memory, RA: Memory, RI: Memory, RO: Read> { pub tia: T, pub ram: RA, pub riot: RI,...
address_space.write(0, 8)?; address_space.write(0x7F, 5)?; address_space.write(0x80, 81)?; address_space.write(0xFF, 45)?; address_space.write(0x280, 67)?; address_space.write(0x29F, 68)?; address_space.rom.bytes[0xF000] = 15; address_spa...
let mut address_space = AddressSpace { tia: Ram::new(16), ram: Ram::new(16), riot: Ram::new(16), rom: Ram::new(16), };
assignment_statement
[ { "content": "fn canonical_write_address(address: u16) -> u16 {\n\n if address & 0b0001_0100 == 0b0001_0100 {\n\n address & 0b0001_0111\n\n } else if address & 0b0001_0100 == 0b0000_0100 {\n\n address & 0b0000_0101\n\n } else {\n\n address & 0b0011\n\n }\n\n}\n\n\n\nmod register...
Rust
execution-engine/wasm-prep/src/lib.rs
clvasile-test/CasperLabs
023b96662a7c2d3bf521d9f11f52959bee5cf7b9
extern crate parity_wasm; extern crate pwasm_utils; extern crate vm; use parity_wasm::elements::{self, deserialize_buffer, Error as ParityWasmError, Module}; use pwasm_utils::{externalize_mem, inject_gas_counter, rules}; use std::error::Error; use std::iter::Iterator; use vm::wasm_costs::WasmCosts; const ALLOWED_IMPO...
extern crate parity_wasm; extern crate pwasm_utils; extern crate vm; use parity_wasm::elements::{self, deserialize_buffer, Error as ParityWasmError, Module}; use pwasm_utils::{externalize_mem, inject_gas_counter, rules}; use std::error::Error; use std::iter::Iterator; use vm::wasm_costs::WasmCosts; const ALLOWED_IMPO...
() { elements::External::Function(_) => { if !ALLOWED_IMPORTS.contains(&entry.field()) { invalid_imports_error::<bool, String>(format!( "'{}' is not supported by the runtime", entry.field() ...
erError)?; Ok(module) } } fn gas_rules(wasm_costs: &WasmCosts) -> rules::Set { rules::Set::new(wasm_costs.regular, { let mut vals = ::std::collections::BTreeMap::new(); vals.insert( rules::InstructionType::Load, rules::Metering::Fixed(wasm_costs.mem as u32), ...
random
[ { "content": "// I don't know why I need a special version of to_ptr for\n\n// &str, but the compiler complains if I try to use the polymorphic\n\n// version with T = str.\n\npub fn str_ref_to_ptr(t: &str) -> (*const u8, usize, Vec<u8>) {\n\n let bytes = t.to_bytes();\n\n let ptr = bytes.as_ptr();\n\n ...
Rust
crates/sui-core/src/authority/authority_notifier.rs
bmwill/sui
a0f57697ad546bf97b30cffffef132028783b88f
use super::*; use std::{ collections::BTreeSet, sync::atomic::{AtomicBool, AtomicU64}, }; use sui_types::batch::TxSequenceNumber; use tokio::sync::Notify; use typed_store::traits::Map; use parking_lot::Mutex; pub struct TransactionNotifier { state: Arc<AuthorityStore>, low_watermark: AtomicU64, ...
use super::*; use std::{ collections::BTreeSet, sync::atomic::{AtomicBool, AtomicU64}, }; use sui_types::batch::TxSequenceNumber; use tokio::sync::Notify; use typed_store::traits::Map; use parking_lot::Mutex; pub struct TransactionNotifier { state: Arc<AuthorityStore>, low_watermark: AtomicU64, ...
igest::random()); } let x = iter.next().await; assert!(matches!(x, Some((4, _)))); assert!(timeout(Duration::from_millis(10), iter.next()) .await .is_err()); let t5 = notifier.ticket().expect("ok"); let t6 = notifier.ticket().expect("o...
} transaction_notifier.notify.notified().await; } }, ))) } pub fn close(&self) { self.is_closed .store(true, std::sync::atomic::Ordering::SeqCst); self.notify.notify_one(); } } struct IterU...
random
[ { "content": "/// Subtract the gas balance of \\p gas_object by \\p amount.\n\n/// This function should never fail, since we checked that the budget is always\n\n/// less than balance, and the amount is capped at the budget.\n\npub fn deduct_gas(gas_object: &mut Object, deduct_amount: u64, rebate_amount: u64) {...
Rust
src/docker.rs
intel/dimgen
911a8917c24a31d14b5a89d560992719f8aff985
use std::env; use std::string::FromUtf8Error; use log::info; use crate::utils::{execute_command, trim}; pub struct Image { pub name: String, pub hash: String, } pub struct Container { pub id: String, pub img: Image, } pub struct Os { pub name: String, pub version: String, } pub fn is_dock...
use std::env; use std::string::FromUtf8Error; use log::info; use crate::utils::{execute_command, trim}; pub struct Image { pub name: String, pub hash: String, } pub struct Container { pub id: String, pub img: Image, } pub struct Os { pub name: String, pub version: String, } pub fn is_dock...
String::from_utf8(result).unwrap()[..11].to_string() } pub fn fetch_image(img_name: &str) { let command = format!("docker inspect {}", img_name); let exists = execute_command(&command); if exists.len() == 3 { println!("image doesn't exists, attempting to pull t...
if result.is_empty() { println!("image :: {} cannot be pulled, exiting..", self.name); std::process::exit(1); }
if_condition
[ { "content": "///trim end of line and whitespace from end of string\n\npub fn trim(string: &mut String) {\n\n while string.ends_with('\\n') || string.ends_with('\\r') {\n\n string.pop();\n\n }\n\n while string.starts_with('\"') || string.ends_with('\"') {\n\n string.pop();\n\n stri...
Rust
src/main.rs
Momingcoder/spelling_corrector
e30233540d4554b6ea99f7401b0b8ba5b5206a64
extern crate regex; extern crate hashbrown; use hashbrown::HashMap; use regex::Regex; use std::fs::File; use std::io::Read; use std::error; use std::time::Instant; const ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz"; #[derive(Debug)] struct Dictionary { counter: HashMap<String, u32>, } impl...
extern crate regex; extern crate hashbrown; use hashbrown::HashMap; use regex::Regex; use std::fs::File; use std::io::Read; use std::error; use std::time::Instant; const ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz"; #[derive(Debug)] struct Dictionary { counter: HashMap<String, u32>, } impl...
.filter(|(_, right)| right.len() > 0) .map(move |(left, right)| [left, &ALPHABET[i..i+1], &right[1..]].concat()) ); let splits_clone = splits.clone(); let inserts = (0..26).flat_map(move |i| splits_clone.clone() .map(move |(left, right)| [left, &ALPHABET[i..i+...
cands } } } } } fn edit_once(word: &str) -> Vec<String> { let splits = (0..=word.len()) .map(|i| (&word[..i], &word[i..])); let deletes = splits.clone() .filter(|(_, right)| right.len() > 0) .map(|(left, right)| [l...
random
[ { "content": "var ALPHABET = []byte(\"abcdefghijklmnopqrstuvwxyz\")\n", "file_path": "spelling.go", "rank": 3, "score": 35258.76886742352 }, { "content": "func edit(word string) []string {\n\n\tvar words []string\n\n\tvar buf bytes.Buffer\n\n\tvar splits []Pair\n\n\n\n\tfor i := 0; i <= len(...
Rust
src/gpio/gpio_func16_out_sel_cfg.rs
ducktec/esp32c3
64b9547e200a3ee7e6587d81178be8732e99bee9
#[doc = "Reader of register GPIO_FUNC16_OUT_SEL_CFG"] pub type R = crate::R<u32, super::GPIO_FUNC16_OUT_SEL_CFG>; #[doc = "Writer for register GPIO_FUNC16_OUT_SEL_CFG"] pub type W = crate::W<u32, super::GPIO_FUNC16_OUT_SEL_CFG>; #[doc = "Register GPIO_FUNC16_OUT_SEL_CFG `reset()`'s with value 0"] impl crate::ResetValue...
#[doc = "Reader of register GPIO_FUNC16_OUT_SEL_CFG"] pub type R = crate::R<u32, super::GPIO_FUNC16_OUT_SEL_CFG>; #[doc = "Writer for register GPIO_FUNC16_OUT_SEL_CFG"] pub type W = crate::W<u32, super::GPIO_FUNC16_OUT_SEL_CFG>; #[doc = "Register GPIO_FUNC16_OUT_SEL_CFG `reset()`'s with value 0"] impl crate::ResetValue...
rites raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } impl R { #[doc = "Bit 10"] #[inline(always)] pub fn gpio_func16_oen_inv_sel(&self) -> GPIO_FUNC16_OEN_INV_S...
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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `GPIO_FUNC16_OEN_SEL`"] pub type GPIO_FUNC16_OE...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/futurecore.rs
Lompik/wezterm
a833cf29b4c1f9c9ffa42c3d83c37ce9386c0fc7
use failure::Error; use futures::executor::{self, Notify, Spawn}; use futures::future::{ExecuteError, Executor}; use futures::{Async, Future}; use std::cell::{Cell, RefCell}; use std::sync::mpsc; use std::sync::{Arc, Mutex}; pub trait CoreSender: Send { fn send(&self, idx: usize) -> Result<(), Error>; } pub tra...
use failure::Error; use futures::executor::{self, Notify, Spawn}; use futures::future::{ExecuteError, Executor}; use futures::{Async, Future}; use std::cell::{Cell, RefCell}; use std::sync::mpsc; use std::sync::{Arc, Mutex}; pub trait CoreSender: Send { fn send(&self, idx: usize) -> Result<(), Error>; } pub tra...
elf, future: F) -> Result<(), ExecuteError<F>> { self.spawn(future); Ok(()) } } struct Notifier { tx: Mutex<Box<CoreSender>>, } impl Notify for Notifier { fn notify(&self, id: usize) { self.tx.lock().unwrap().send(id).ok(); } }
(&mut Slot::RunningFuture(_)) => panic!("vacant points to running future"), None => { assert_eq!(idx, tasks.len()); tasks.push(Slot::Vacant { next_vacant: 0 }); self.next_vacant.set(idx + 1); } } tasks[idx] = Slot::RunningFuture(Som...
random
[ { "content": "/// Construct a new instance of Terminal.\n\n/// The terminal will have a renderer that is influenced by the configuration\n\n/// in the provided `Capabilities` instance.\n\n/// The terminal will explicitly open `/dev/tty` on Unix systems and\n\n/// `CONIN$` and `CONOUT$` on Windows systems, so th...
Rust
src/font/mod.rs
ony/wezterm
a26a94b5bb0f8f872f9a2ee7a7c1b414cd2bbda4
use failure::{bail, format_err, Error}; use log::{debug, error}; use serde_derive::*; mod ftfont; mod hbwrap; use self::hbwrap as harfbuzz; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; pub mod system; pub use self::system::*; pub mod ftwrap; #[cfg(all(unix, any(feature...
use failure::{bail, format_err, Error}; use log::{debug, error}; use serde_derive::*; mod ftfont; mod hbwrap; use self::hbwrap as harfbuzz; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; pub mod system; pub use self::system::*; pub mod ftwrap; #[cfg(all(unix, any(feature...
} #[allow(dead_code)] pub fn shape_with_harfbuzz( font: &mut dyn NamedFont, font_idx: system::FallbackIdx, s: &str, ) -> Result<Vec<GlyphInfo>, Error> { let features = vec![ harfbuzz::feature_from_string("kern")?, harfbuzz::feature_from_string("liga")?, ...
lf, attrs: &CellAttributes) -> &TextStyle { macro_rules! attr_match { ($ident:ident, $rule:expr) => { if let Some($ident) = $rule.$ident { if $ident != attrs.$ident() { continue; ...
function_block-function_prefixed
[ { "content": "pub fn language_from_string(s: &str) -> Result<hb_language_t, Error> {\n\n unsafe {\n\n let lang = hb_language_from_string(s.as_ptr() as *const i8, s.len() as i32);\n\n ensure!(!lang.is_null(), \"failed to convert {} to language\");\n\n Ok(lang)\n\n }\n\n}\n\n\n", "f...
Rust
coppe-wm/src/wm/mod.rs
Anfid/waswm
d683e3861450c8ca9c93ceeb618e7acc57e813f0
use log::*; use std::{collections::HashSet, sync::mpsc}; use x11rb::connection::Connection; use x11rb::errors::{ReplyError, ReplyOrIdError}; use x11rb::protocol::xproto::*; use x11rb::x11_utils::X11Error; mod handler; use crate::events::WmEvent; use crate::x11::X11Info; pub struct WindowManager { x11: X11Info, ...
use log::*; use std::{collections::HashSet, sync::mpsc}; use x11rb::connection::Connection; use x11rb::errors::{ReplyError, ReplyOrIdError}; use x11rb::protocol::xproto::*; use x11rb::x11_utils::X11Error; mod handler; use crate::events::WmEvent; use crate::x11::X11Info; pub struct WindowManager { x11: X11Info, ...
} Ok(()) } pub fn manage_window( &self, win: Window, geom: &GetGeometryReply, ) -> Result<(), ReplyOrIdError> { info!("Managing window {:?}", win); let aux = ConfigureWindowAux::default() .x(i32::from(geom.x)) .y(i32::from(g...
if let (Ok(attr), Ok(geom)) = (attr.reply(), geom.reply()) { if !attr.override_redirect && attr.map_state != MapState::UNMAPPED { self.manage_window(win, &geom)?; } }
if_condition
[ { "content": "pub fn resize(id: WindowId, width: u16, height: u16) {\n\n ffi::window_resize(id, width, height)\n\n}\n\n\n", "file_path": "libcoppe/rust/coppe-core/src/window.rs", "rank": 0, "score": 139043.61553003316 }, { "content": "pub fn window_resize(id: WindowId, width: u16, height:...
Rust
2021/day-20/src/main.rs
dstoza/advent-2017
22de531632c1633814ed1d2b9827590af989fb6e
#![feature(test)] extern crate test; use std::{ collections::VecDeque, fs::File, io::{BufRead, BufReader}, mem::swap, }; fn parse_input<I: Iterator<Item = String>>(mut lines: I) -> ([u8; 512], VecDeque<VecDeque<u8>>) { let algorithm: [u8; 512] = lines.next().unwrap().as_bytes().try_into().unwrap()...
#![feature(test)] extern crate test; use std::{ collections::VecDeque, fs::File, io::{BufRead, BufReader}, mem::swap, }; fn parse_input<I: Iterator<Item = String>>(mut lines: I) -> ([u8; 512], VecDeque<VecDeque<u8>>) { let algorithm: [u8; 512] = lines.next().unwrap().as_bytes().try_into().unwrap()...
; let start = if previous_flattened.is_some() { 6 } else { 0 }; let flattened = OFFSETS[start..].iter().fold( accumulator, |accumulator, (offset_x, offset_y)| { let x = (x as isize + offset_x) as usize; ...
if let Some(previous) = previous_flattened { previous & 0x3F } else { 0 }
if_condition
[ { "content": "fn flash_cell(lines: &mut [Vec<u8>], row: usize, column: usize) {\n\n if lines[row][column] != 10 {\n\n return;\n\n }\n\n\n\n for (row_delta, column_delta) in [\n\n (-1, -1),\n\n (-1, 0),\n\n (-1, 1),\n\n (0, -1),\n\n (0, 1),\n\n (1, -1),\n...
Rust
fuzzcheck/src/mutators/integer_within_range.rs
loiclec/fuzzcheck-rs
7a807586babdb2cf3d7553c5f6d7d2c69dd6683a
use crate::mutators::integer::{ binary_search_arbitrary_u16, binary_search_arbitrary_u32, binary_search_arbitrary_u64, binary_search_arbitrary_u8, }; use crate::Mutator; use std::ops::Bound; use std::ops::RangeBounds; const INITIAL_MUTATION_STEP: u64 = 0; macro_rules! impl_int_mutator_constrained { ($name:ide...
use crate::mutators::integer::{ binary_search_arbitrary_u16, binary_search_arbitrary_u32, binary_search_arbitrary_u64, binary_search_arbitrary_u8, }; use crate::Mutator; use std::ops::Bound; use std::ops::RangeBounds; const INITIAL_MUTATION_STEP: u64 = 0; macro_rules! impl_int_mutator_constrained { ($name:ide...
e = (); type MutationStep = u64; type ArbitraryStep = u64; type UnmutateToken = $name; #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { 0 } #[no_coverage] fn validate_value(&self, ...
}; let end = match range.end_bound() { Bound::Included(b) => *b, Bound::Excluded(b) => { assert_ne!(*b, <$name>::MIN); *b - 1 } Bound::Unbounded => <$name>::MAX, ...
random
[ { "content": "#[no_coverage]\n\npub fn grammar_based_string_mutator(grammar: Rc<Grammar>) -> impl Mutator<String> {\n\n let grammar_cloned = grammar.clone();\n\n let parse = move |string: &String| parse_from_grammar(string, grammar_cloned.clone());\n\n IncrementalMapMutator::<AST, String, ASTMutator, A...
Rust
src/types/message_forward_origin.rs
vhaoran/rust-tdlib
08504eb5c53e699518e9b161f7fc3de70ca38429
use crate::errors::*; use crate::types::*; use uuid::Uuid; use std::fmt::Debug; pub trait TDMessageForwardOrigin: Debug + RObject {} #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "@type")] pub enum MessageForwardOrigin { #[doc(hidden)] _Default, #[serde(rename( serialize = "m...
use crate::errors::*; use crate::types::*; use uuid::Uuid; use std::fmt::Debug; pub trait TDMessageForwardOrigin: Debug + RObject {} #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "@type")] pub enum MessageForwardOrigin { #[doc(hidden)] _Default, #[serde(rename( serialize = "m...
: MessageForwardOriginChat, } impl RTDMessageForwardOriginChatBuilder { pub fn build(&self) -> MessageForwardOriginChat { self.inner.clone() } pub fn sender_chat_id(&mut self, sender_chat_id: i64) -> &mut Self { self.inner.sender_chat_id = sender_chat_id; self } pub fn aut...
} pub fn author_signature(&self) -> &String { &self.author_signature } } #[doc(hidden)] pub struct RTDMessageForwardOriginChatBuilder { inner
random
[ { "content": "pub trait RFunction: Debug + RObject + Serialize {\n\n fn to_json(&self) -> RTDResult<String> {\n\n Ok(serde_json::to_string(self)?)\n\n }\n\n}\n\n\n\nimpl<'a, RObj: RObject> RObject for &'a RObj {\n\n fn extra(&self) -> Option<&str> {\n\n (*self).extra()\n\n }\n\n fn ...
Rust
tezos/interop/src/ffi.rs
drlef/tezedge
fa65f5ec128ea0e575f8cbd81e143f1e346f0731
use std::convert::TryFrom; use std::sync::Once; use crypto::hash::{ContextHash, ProtocolHash}; use ocaml_interop::{ocaml_frame, to_ocaml, OCaml, OCamlRuntime, ToOCaml}; use tezos_api::ffi::*; use tezos_api::ocaml_conv::FfiPath; use crate::runtime; type TzResult<T> = Result<T, TezosErrorTrace>; mod tezos_ffi { ...
use std::convert::TryFrom; use std::sync::Once; use crypto::hash::{ContextHash, ProtocolHash}; use ocaml_interop::{ocaml_frame, to_ocaml, OCaml, OCamlRuntime, ToOCaml}; use tezos_api::ffi::*; use tezos_api::ocaml_conv::FfiPath; use crate::runtime; type TzResult<T> = Result<T, TezosErrorTrace>; mod tezos_ffi { ...
orageInitError::InitializeError { message: p.to_string(), }) }) } pub fn genesis_result_data( context_hash: RustBytes, chain_id: RustBytes, protocol_hash: RustBytes, genesis_max_operations_ttl: u16, ) -> Result<CommitGenesisResult, GetDataError> { runtime::execute(move |rt: ...
rt, (commit_genesis, enable_testchain, readonly), configuration ); let patch_context_tuple = to_ocaml!( rt, patch_context.map(|pc| (pc.key, pc.json)), patch_c...
random
[ { "content": "/// Gets data for genesis\n\npub fn genesis_result_data(\n\n context_hash: &ContextHash,\n\n chain_id: &ChainId,\n\n protocol_hash: &ProtocolHash,\n\n genesis_max_operations_ttl: u16,\n\n) -> Result<CommitGenesisResult, GetDataError> {\n\n ffi::genesis_result_data(\n\n contex...
Rust
components/win-users/src/sid.rs
tyler-ball/habitat
f94970d1af39736f1e030509e878918d9214fd66
#![allow(non_snake_case)] use std::{io, mem, ptr::{copy, null_mut}}; use widestring::WideCString; use winapi::{shared::{minwindef::{BOOL, BYTE, DWORD, FALSE, ...
#![allow(non_snake_case)] use std::{io, mem, ptr::{copy, null_mut}}; use widestring::WideCString; use winapi::{shared::{minwindef::{BOOL, BYTE, DWORD, FALSE, ...
&mut pacl, &mut dacl_exist))?; let mut size_info = ACL_SIZE_INFORMATION { aceCount: 0, aclBytesInUse: mem::size_of::<ACL>() as DWOR...
LPCWSTR, MAXDWORD, PACL, PHANDLE, PSECURITY_DESCRIPTOR, PSECURITY_INFORMATION, PSID, TOKEN_READ}}}; #[repr(C)] struct ACL_SI...
random
[ { "content": "fn stdio_piped_handle(stdio_id: DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {\n\n let ours_readable = stdio_id != STD_INPUT_HANDLE;\n\n let pipes = anon_pipe(ours_readable)?;\n\n *pipe = Some(pipes.ours);\n\n cvt(unsafe {\n\n handleapi::SetHandleInformation(pipes.t...
Rust
src/bin/constraint_demo.rs
passcod/armstrong
612e96df6186c105165042ae0dda1b8c8e2e843d
#![forbid(unsafe_code)] #![deny(clippy::pedantic)] use armstrong::proto::{self, *}; use armstrong::system::*; fn main() { armstrong::init(); let sys = System::new(); println!("IPs: {:?}", sys.belonging_ips().unwrap()); println!("Hostname: {:?}", sys.hostname()); println!("GPU detection enabled: {...
#![forbid(unsafe_code)] #![deny(clippy::pedantic)] use armstrong::proto::{self, *}; use armstrong::system::*; fn main() { armstrong::init(); let sys = System::new(); println!("IPs: {:?}", sys.belonging_ips().unwrap()); println!("Hostname: {:?}", sys.hostname()); println!("GPU detection enabled: {...
n!( "\n{:?}\nPasses: {}", gpucomp1, sys.check_resource(&gpucomp1).unwrap() ); let gpucomp2 = Resource::Gpu(GpuKind::OpenCL); println!( "\n{:?}\nPasses: {}", gpucomp2, sys.check_resource(&gpucomp2).unwrap() ); let ipcon1 = Resource::NetworkBelong(NetR...
function_block-function_prefixed
[ { "content": "pub fn init() {\n\n dotenv::dotenv().unwrap_or_else(|err| log::debug!(\"No .env file loaded: {:?}\", err));\n\n\n\n if std::env::var(\"RUST_LOG\").is_err() {\n\n std::env::set_var(\"RUST_LOG\", \"armstrong=info,ws=info\");\n\n }\n\n\n\n env_logger::init();\n\n}\n", "file_pat...
Rust
miette-derive/src/forward.rs
jntrnr/miette
f5ecdddf15a536fbdd7160a63ff083cc5f74882f
use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ parenthesized, parse::{Parse, ParseStream}, spanned::Spanned, }; pub enum Forward { Unnamed(usize), Named(syn::Ident), } impl Parse for Forward { fn parse(input: ParseStream) -> syn::Result<Self> { let forward =...
use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ parenthesized, parse::{Parse, ParseStream}, spanned::Spanned, }; pub enum Forward { Unnamed(usize), Named(syn::Ident), } impl Parse for Forward { fn parse(input: ParseStream) -> syn::Result<Self> { let forward =...
pub fn catchall_arm(&self) -> TokenStream { match self { Self::Code => quote! {}, _ => quote! { _ => None, }, } } } impl Forward { pub fn for_transparent_field(fields: &syn::Fields) -> syn::Result<Self> { let make_err = || { syn::Er...
e! { fn url<'a>(&'a self) -> std::option::Option<std::boxed::Box<dyn std::fmt::Display + 'a>> }, Self::Severity => quote! { fn severity(&self) -> std::option::Option<miette::Severity> }, Self::Snippets => quote! { fn snippet...
function_block-function_prefixed
[ { "content": "fn get_severity(input: &str, span: Span) -> syn::Result<String> {\n\n match input.to_lowercase().as_ref() {\n\n \"error\" | \"err\" => Ok(\"Error\".into()),\n\n \"warning\" | \"warn\" => Ok(\"Warning\".into()),\n\n \"advice\" | \"adv\" | \"info\" => Ok(\"Advice\".into()),\n...
Rust
macros/src/lib.rs
jeremyandrews/cio
5c98cda6e31219e5063d591062086bbc370adbea
extern crate proc_macro; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use serde::Deserialize; use serde_tokenstream::from_tokenstream; use serde_tokenstream::Error; use syn::{Field, ItemStruct}; #[derive(Deserialize, Debug)] struct Metadata { new_name: String, table: Option<String>, bas...
extern crate proc_macro; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use serde::Deserialize; use serde_tokenstream::from_tokenstream; use serde_tokenstream::Error; use syn::{Field, ItemStruct}; #[derive(Deserialize, Debug)] struct Metadata { new_name: String, table: Option<String>, bas...
#[cfg(test)] mod tests { use super::*; #[test] fn test_db_struct() { let ret = do_db_struct( quote! { new_name = DuplicatedItem, base_id = AIRTABLE_BASE_ID_CUSTOMER_LEADS, table = AIRTABLE_RFD_TABLE, } .into(), ...
fn do_db_struct( attr: TokenStream, item: TokenStream, ) -> Result<TokenStream, Error> { let metadata = from_tokenstream::<Metadata>(&attr).unwrap(); let new_name = format_ident!("{}", metadata.new_name); let old_struct: ItemStruct = syn::parse2(item.clone()).unwrap(); let mut fields: Vec<&Fiel...
function_block-full_function
[ { "content": "/// Generate a random string that we can use as a temporary password for new users\n\n/// when we set up their account.\n\npub fn generate_password() -> String {\n\n thread_rng().sample_iter(&Alphanumeric).take(30).collect()\n\n}\n\n\n\n/// A Google group.\n\n#[derive(Default, Clone, Debug, Ser...
Rust
src/syscon/cpuctrl.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[doc = "Reader of register CPUCTRL"] pub type R = crate::R<u32, super::CPUCTRL>; #[doc = "Writer for register CPUCTRL"] pub type W = crate::W<u32, super::CPUCTRL>; #[doc = "Register CPUCTRL `reset()`'s with value 0x2c"] impl crate::ResetValue for super::CPUCTRL { type Type = u32; #[inline(always)] fn reset...
#[doc = "Reader of register CPUCTRL"] pub type R = crate::R<u32, super::CPUCTRL>; #[doc = "Writer for register CPUCTRL"] pub type W = crate::W<u32, super::CPUCTRL>; #[doc = "Register CPUCTRL `reset()`'s with value 0x2c"] impl crate::ResetValue for super::CPUCTRL { type Type = u32; #[inline(always)] fn reset...
#[doc = "Checks if the value of the field is `RELEASED`"] #[inline(always)] pub fn is_released(&self) -> bool { *self == CPU1RSTEN_A::RELEASED } #[doc = "Checks if the value of the field is `ASSERTED`"] #[inline(always)] pub fn is_asserted(&self) -> bool { *self == CPU1RSTEN...
pub fn variant(&self) -> CPU1RSTEN_A { match self.bits { false => CPU1RSTEN_A::RELEASED, true => CPU1RSTEN_A::ASSERTED, } }
function_block-full_function
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
src/cache/registry_sources.rs
Toughee/cargo-cache
5115b63769dcdb8a42009f8572c6843cce6f5e9c
use std::fs; use std::path::PathBuf; use crate::cache::caches::{get_cache_name, RegistrySubCache, RegistrySuperCache}; use rayon::prelude::*; use walkdir::WalkDir; #[derive(Debug, Clone)] pub(crate) struct RegistrySourceCache { name: String, path: PathBuf, size: Option<u64>, nu...
use std::fs; use std::path::PathBuf; use crate::cache::caches::{get_cache_name, RegistrySubCache, RegistrySuperCache}; use rayon::prelude::*; use walkdir::WalkDir; #[derive(Debug, Clone)] pub(crate) struct RegistrySourceCache { name: String, path: PathBuf, size: Option<u64>, nu...
} fn number_of_subcaches(&mut self) -> usize { self.caches.len() } fn total_number_of_files(&mut self) -> usize { if let Some(number) = self.total_number_of_files { number } else { let total = self .caches .iter_mut(...
if let Some(size) = self.total_size { size } else { let total_size = self.caches.iter_mut().map(|cache| cache.total_size()).sum(); self.total_size = Some(total_size); total_size }
if_condition
[ { "content": "#[inline]\n\nfn name_from_path(path: &Path) -> String {\n\n // path: .../xz2-0.1.4.crate\n\n let last_item = path.file_name().unwrap().to_str().unwrap().to_string();\n\n // last_item: xz2-0.1.4.crate\n\n let mut v = last_item.split('-').collect::<Vec<_>>();\n\n let _ = v.pop(); // ...
Rust
src/ui.rs
PapugaPower/bevyjam
c484cfecfbfcbf3261d4e3e4dd464d756c24fd47
use bevy::{prelude::*, reflect::TypeUuid}; use bevy_asset_loader::AssetCollection; use bevy_kira_audio::*; use bevy_ninepatch::*; use crate::{AppState, FuckStages}; mod ninepatches; pub mod gameover; pub mod mainmenu; pub mod hud; pub struct UiSetupPlugin; impl Plugin for UiSetupPlugin { fn build(&self, app: &...
use bevy::{prelude::*, reflect::TypeUuid}; use bevy_asset_loader::AssetCollection; use bevy_kira_audio::*; use bevy_ninepatch::*; use crate::{AppState, FuckStages}; mod ninepatches; pub mod gameover; pub mod mainmenu; pub mod hud; pub struct UiSetupPlugin; impl Plugin for UiSetupPlugin { fn build(&self, app: &...
cked } fn button_interact_visual( mut cmd: Commands, uicfg: Option<Res<UiAssets>>, mut query: Query< (Entity, &Interaction, &mut NinePatchData<ContentId>), (/*Changed<Interaction>, */With<GameBtn>), >, ) { if let Some(uicfg) = uicfg { for (e, interaction, mut npdata) in...
r_mut() { match interaction { Interaction::Clicked => { clicked = Some(val.clone()); } _ => (), } } cli
function_block-random_span
[ { "content": "/// impl this Trait for a marker type to enable using it with the editor\n\npub trait Blueprint: Component + Reflect + Default + Clone {\n\n /// Text for the spawn button in the editor ui\n\n const EDITOR_ID: &'static str;\n\n /// Z coordinate to spawn at\n\n const DEFAULT_Z: f32;\n\n\...
Rust
src/traffic_stats/datapass_webstats.rs
jobusam/rust-forensics
ad0d1b88cc25cfb2766cadeb5913df514c4c3aae
use chrono::{Datelike, Utc}; use select::document::Document; use select::predicate::Name; pub fn check_data_limit() { match get_datapass_de_website() { Ok(content) => { extract_data_from_html(content); } Err(e) => println!("Can't access content from datapass.de : {}", e), } ...
use chrono::{Datelike, Utc}; use select::document::Document; use select::predicate::Name; pub fn check_data_limit() { match get_datapass_de_website() { Ok(content) => { extract_data_from_html(content); } Err(e) => println!("Can't access content from datapass.de : {}", e), } ...
fn extract_data_from_html(content: String) { extract_amount(content.clone()); extract_duration(content.clone()); extract_last_update(content.clone()); } fn extract_last_update(content: String) { Document::from(content.as_str()) .find(Name("section")) .filter(|n| n.attr(...
let body: String = ureq::get("https://datapass.de/home?continue=true") .call()? .into_string()?; Ok(body) }
function_block-function_prefix_line
[]
Rust
src/solicit/frame/goaway.rs
weiznich/rust-http2
cd081bbbf30ac1dbadc7628a69e4a149907b9e4c
use std::io; use bytes::Bytes; use error::ErrorCode; use solicit::StreamId; use solicit::frame::{Frame, FrameIR, FrameBuilder, FrameHeader, RawFrame, parse_stream_id}; use solicit::frame::flags::*; pub const GOAWAY_MIN_FRAME_LEN: u32 = 8; pub const GOAWAY_FRAME_TYPE: u8 = 0x7; #[derive(Clone, Debug, PartialEq)] ...
use std::io; use bytes::Bytes; use error::ErrorCode; use solicit::StreamId; use solicit::frame::{Frame, FrameIR, FrameBuilder, FrameHeader, RawFrame, parse_stream_id}; use solicit::frame::flags::*; pub const GOAWAY_MIN_FRAME_LEN: u32 = 8; pub const GOAWAY_FRAME_TYPE: u8 = 0x7; #[derive(Clone, Debug, PartialEq)] ...
rt_eq!(expected, raw); } }
colError); assert_eq!(frame.last_stream_id(), 0); assert_eq!(frame.debug_data(), &Bytes::from(&[1, 2, 3, 4][..])); } #[test] fn test_parse_ignores_reserved_bit() { let raw = raw_frame_from_parts(FrameHeader::new(8, 0x7, 0, 0), vec![0x80, 0, 0, 0, 0, 0, 0, 1]); let frame = Go...
random
[ { "content": "#[inline]\n\nfn parse_stream_id(buf: &[u8]) -> u32 {\n\n let unpacked = unpack_octets_4!(buf, 0, u32);\n\n // Now clear the most significant bit, as that is reserved and MUST be ignored when received.\n\n unpacked & !0x80000000\n\n}\n\n\n\npub const FRAME_HEADER_LEN: usize = 9;\n\n\n\npub...
Rust
src/fse/block.rs
shampoofactory/lzfse_rust
ee42497ec3ce76ee639c47eb2d823df4f6f01808
use crate::base::MagicBytes; use crate::decode::Take; use crate::kit::PackBits; use crate::ops::{Len, ReadData, WriteData}; use crate::types::ShortBuffer; use super::constants::*; use super::error_kind::FseErrorKind; pub fn n_raw_bytes_limit(n_literals: u32, n_lmds: u32) -> u32 { assert!(n_literals <= LITERALS_PE...
use crate::base::MagicBytes; use crate::decode::Take; use crate::kit::PackBits; use crate::ops::{Len, ReadData, WriteData}; use crate::types::ShortBuffer; use super::constants::*; use super::error_kind::FseErrorKind; pub fn n_raw_bytes_limit(n_literals: u32, n_lmds: u32) -> u32 { assert!(n_literals <= LITERALS_PE...
Ok(()) } } impl Default for FseBlock { fn default() -> Self { Self { literal: LiteralParam::default(), lmd: LmdParam::default(), n_raw_bytes: 0 } } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct LmdParam { num: u32, n_payload_bytes: u32, bits: u32, state: [u16;...
if self.n_raw_bytes > n_raw_bytes_limit(self.literal.num, self.lmd.num) { return Err(FseErrorKind::BadRawByteCount.into()); }
if_condition
[ { "content": "pub fn encode(src: &[u8], dst: &mut [u8]) -> usize {\n\n unsafe {\n\n lzfse_encode_buffer(\n\n dst.as_mut_ptr() as *mut _,\n\n dst.len() as size_t,\n\n src.as_ptr() as *const _,\n\n src.len() as size_t,\n\n ptr::null_mut::<c_void>(),...
Rust
ethcontract-generate/src/generate/methods.rs
nlordell/ethcontract
dcbfbe594f65eb2cc9e22a5468b7212ad1aa2a39
use crate::generate::{types, Context}; use crate::util; use anyhow::{anyhow, Context as _, Result}; use ethcontract_common::abi::{Function, Param, StateMutability}; use ethcontract_common::abiext::FunctionExt; use ethcontract_common::hash::H32; use inflector::Inflector; use proc_macro2::{Literal, TokenStream}; use quot...
use crate::generate::{types, Context}; use crate::util; use anyhow::{anyhow, Context as _, Result}; use ethcontract_common::abi::{Function, Param, StateMutability}; use ethcontract_common::abiext::FunctionExt; use ethcontract_common::hash::H32; use inflector::Inflector; use proc_macro2::{Literal, TokenStream}; use quot...
} fn expand_selector(selector: H32) -> TokenStream { let bytes = selector.iter().copied().map(Literal::u8_unsuffixed); quote! { [#( #bytes ),*] } } fn expand_fallback(cx: &Context) -> TokenStream { if cx.contract.abi.fallback || cx.contract.abi.receive { quote! { impl Contract { ...
match outputs.len() { 0 => Ok(quote! { () }), 1 => types::expand(&outputs[0].kind), _ => { let types = outputs .iter() .map(|param| types::expand(&param.kind)) .collect::<Result<Vec<_>>>()?; Ok(quote! { (#( #types ),*) }) ...
if_condition
[ { "content": "fn expand_contract(cx: &Context) -> Result<TokenStream> {\n\n let runtime_crate = &cx.runtime_crate;\n\n let vis = &cx.visibility;\n\n let contract_mod = &cx.contract_mod;\n\n let contract_name = &cx.contract_name;\n\n\n\n let common = common::expand(cx);\n\n let deployment = dep...
Rust
src/core/render_target.rs
timmyL17/three-d
12caa6e4a7c347be43d00df03f054a307af5d052
mod screen; #[doc(inline)] pub use screen::*; mod render_target2d; #[doc(inline)] pub use render_target2d::*; mod render_target2d_array; #[doc(inline)] pub use render_target2d_array::*; mod render_target_cube_map; #[doc(inline)] pub use render_target_cube_map::*; use crate::context::consts; use crate::core::*; #...
mod screen; #[doc(inline)] pub use screen::*; mod render_target2d; #[doc(inline)] pub use render_target2d::*; mod render_target2d_array; #[doc(inline)] pub use render_target2d_array::*; mod render_target_cube_map; #[doc(inline)] pub use render_target_cube_map::*; use crate::context::consts; use crate::core::*; #...
uniform sampler2DArray colorMap; uniform int colorLayer; in vec2 uv; layout (location = 0) out vec4 color; void main() { color = texture(colorMap, vec3(uv, colorLayer)); }" } else { " uniform sampler2...
function_block-function_prefix_line
[ { "content": "fn bind_at(context: &Context, id: &crate::context::Texture, target: u32, location: u32) {\n\n context.active_texture(consts::TEXTURE0 + location);\n\n context.bind_texture(target, id);\n\n}\n\n\n", "file_path": "src/core/texture.rs", "rank": 0, "score": 271806.247568739 }, { ...
Rust
src/main.rs
zacksleo/polyv-ppt-downloader
23848a4e45a8d24b39dbcc3ac4507ae7f8455add
use printpdf::image::GenericImageView; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::error; use std::fs::File; use std::io::copy; use std::io::prelude::*; use std::path::Path; use printpdf::*; use std::io::BufWriter; type Result<T> = std::result::Result<T, Box<dyn error::Error>>; use clap::{AppSett...
use printpdf::image::GenericImageView; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::error; use std::fs::File; use std::io::copy; use std::io::prelude::*; use std::path::Path; use printpdf::*; use std::io::BufWriter; type Result<T> = std::result::Result<T, Box<dyn error::Error>>; use clap::{AppSett...
#[tokio::main] async fn main() -> Result<()> { let opts: Opts = Opts::parse(); let contents = read_to_string(&opts.json)?; let response: Response = serde_json::from_str(&contents)?; for image in &response.convert_file_json.images { println!("下载文件:{}", image); download(image.as_str()).a...
age, layer) = if index > 0 { doc.add_page(Mm(width), Mm(height), "Page 2, Layer 1") } else { (page, layer) }; let mut image_file = File::open(&Path::new(&image)).unwrap(); let image = Image::try_from(image::jpeg::JpegDecoder::new(&mut image_file).unwra...
function_block-function_prefixed
[ { "content": "# polyv-ppt-downloader\n\ndownload ppt from polyv live\n\n\n\n\n\n## Get Started\n\n\n\n```bash\n\ncargo run -- -j /path/to/file.json\n\n```\n", "file_path": "README.md", "rank": 8, "score": 7906.249741688207 } ]
Rust
contracts/lido_terra_hub/src/convert.rs
lidofinance/lido-terra-contracts
3a3b8cbf21c286c8f8b00a2eef92e23a4dfa169b
use crate::contract::{query_total_bluna_issued, query_total_stluna_issued, slashing}; use crate::math::decimal_division; use crate::state::{CONFIG, CURRENT_BATCH, PARAMETERS, STATE}; use cosmwasm_std::{ attr, to_binary, CosmosMsg, DepsMut, Env, Response, StdError, StdResult, Uint128, WasmMsg, }; use cw20::Cw20Exe...
use crate::contract::{query_total_bluna_issued, query_total_stluna_issued, slashing}; use crate::math::decimal_division; use crate::state::{CONFIG, CURRENT_BATCH, PARAMETERS, STATE}; use cosmwasm_std::{ attr, to_binary, CosmosMsg, DepsMut, Env, Response, StdError, StdResult, Uint128, WasmMsg, }; use cw20::Cw20Exe...
fn burn_message(contract: String, amount: Uint128) -> StdResult<CosmosMsg> { let burn_msg = Cw20ExecuteMsg::Burn { amount }; Ok(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: contract, msg: to_binary(&burn_msg)?, funds: vec![], })) }
w20ExecuteMsg::Mint { recipient, amount }; Ok(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: contract, msg: to_binary(&mint_msg)?, funds: vec![], })) }
function_block-function_prefixed
[ { "content": "/// Check whether slashing has happened\n\n/// This is used for checking slashing while bonding or unbonding\n\npub fn slashing(deps: &mut DepsMut, env: Env) -> StdResult<State> {\n\n let state = query_actual_state(deps.as_ref(), env)?;\n\n\n\n STATE.save(deps.storage, &state)?;\n\n\n\n O...
Rust
src/api/role_assignments/store_role_assignment.rs
SierraSoftworks/randy-rs
35ed234a14b0f015b9d86a2133a06cf8c9dfd645
use actix_web::{put, web}; use tracing::instrument; use super::{AuthToken, APIError}; use crate::{models::*, telemetry::TraceMessageExt}; use super::CollectionUserFilter; #[instrument(err, skip(state, token), fields(otel.kind = "internal"))] #[put("/api/v3/collection/{collection}/user/{user}")] async fn store_role_ass...
use actix_web::{put, web}; use tracing::instrument; use super::{AuthToken, APIError}; use crate::{models::*, telemetry::TraceMessageExt}; use super::CollectionUserFilter; #[instrument(err, skip(state, token), fields(otel.kind = "internal"))] #[put("/api/v3/collection/{collection}/user/{user}")] async fn store_role_ass...
StoreCollection { collection_id: 1, principal_id: 0, name: "Test Collection".into() }, StoreRoleAssignment { collection_id: 1, principal_id: 0, role: Role::Owner, } ]); ...
name: "Test Collection".into() }, StoreRoleAssignment { collection_id: 1, principal_id: 0, role: Role::Owner, } ]); let content: RoleAssignmentV3 = test_request!(PUT "/api/v3/collection/0000000000000000000000000...
random
[ { "content": "pub fn auth_token() -> String {\n\n let mut localized_name = LocalizedClaim::new();\n\n localized_name.insert(None, EndUserName::new(\"Testy McTesterson\".to_string()));\n\n\n\n let token = AuthIdToken::new(\n\n AuthIdTokenClaims::new(\n\n IssuerUrl::new(\"https://auth.e...
Rust
src/graphics/camera.rs
MoleTrooper/starframe
41156dc5b6a380757734422bd066d37330eff7a9
use crate::{ input::{DragState, InputCache}, math::{self as m, uv}, }; pub trait Camera { fn view_matrix(&self, viewport_size: (u32, u32)) -> uv::DMat3; fn point_screen_to_world(&self, viewport_size: (u32, u32), point: m::Vec2) -> m::Vec2; } pub enum ScalingStrategy { ConstantS...
use crate::{ input::{DragState, InputCache}, math::{self as m, uv}, }; pub trait Camera { fn view_matrix(&self, viewport_size: (u32, u32)) -> uv::DMat3; fn point_screen_to_world(&self, viewport_size: (u32, u32), point: m::Vec2) -> m::Vec2; } pub enum ScalingStrategy { ConstantS...
} impl Camera for MouseDragCamera { fn view_matrix(&self, viewport_size: (u32, u32)) -> uv::DMat3 { let vp_scaling = uv::DMat3::from_nonuniform_scale_homogeneous( self.scaling_strategy.scaling(viewport_size), ); let my_transform_inv = self.pose.inversed().into_homogeneous_matri...
let cursor_pos = input_cache.cursor_position().get(); let offset = m::Vec2::new( (cursor_pos.x - start.x) as f64, -(cursor_pos.y - start.y) as f64, ); self.pose = pose_at_start; self.pose .append_...
function_block-function_prefix_line
[ { "content": "/// Check whether or not a point intersects with a collider.\n\npub fn point_collider_bool(point: m::Vec2, pose: &m::Pose, coll: &Collider) -> bool {\n\n let p_wrt_c = pose.inversed() * point;\n\n match coll.shape {\n\n ColliderShape::Circle { r } => p_wrt_c.mag_sq() < r * r,\n\n ...
Rust
bench/src/utils.rs
dnlmlr/wry
f07ae144197933c28f8302105b313c2a2afc62af
use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::{ collections::HashMap, fs, io::{BufRead, BufReader}, path::PathBuf, process::{Command, Output, Stdio}, u64, }; #[derive(Default, Clone, Serialize, Deserialize, Debug)] pub struct BenchResult { pub created_at: Stri...
use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::{ collections::HashMap, fs, io::{BufRead, BufReader}, path::PathBuf, process::{Command, Output, Stdio}, u64, }; #[derive(Default, Clone, Serialize, Deserialize, Debug)] pub struct BenchResult { pub created_at: Stri...
#[allow(dead_code)] pub fn read_json(filename: &str) -> Result<Value> { let f = fs::File::open(filename)?; Ok(serde_json::from_reader(f)?) } #[allow(dead_code)] pub fn write_json(filename: &str, value: &Value) -> Result<()> { let f = fs::File::create(filename)?; serde_json::to_writer(f, value)?; Ok(()) }
pub fn run(cmd: &[&str]) { let mut process_builder = Command::new(cmd[0]); process_builder.args(&cmd[1..]).stdin(Stdio::piped()); let mut prog = process_builder.spawn().expect("failed to spawn script"); let status = prog.wait().expect("failed to wait on child"); if !status.success() { panic!("Unexpected e...
function_block-full_function
[ { "content": "fn rlib_size(target_dir: &std::path::Path, prefix: &str) -> u64 {\n\n let mut size = 0;\n\n let mut seen = std::collections::HashSet::new();\n\n println!(\"{:?}\", target_dir);\n\n\n\n for entry in std::fs::read_dir(target_dir.join(\"deps\")).unwrap() {\n\n let entry = entry.unwrap();\n\n ...
Rust
yeditor/src/graphql/api/api_pads.rs
xuwaters/editor.sh
9bf4b6b06d091c6c3363cf2c91dc9e88692e3c91
use crate::{app, db, graphql::ctx::GraphContext}; use chrono::{DateTime, NaiveDateTime, Utc}; use juniper::{FieldError, FieldResult}; pub struct PadsQueryRoot; graphql_object!(PadsQueryRoot: GraphContext |&self| { field all(&executor, req: ApiReqPadsQueryAll) -> FieldResult<ApiRespPadsQueryAll> { query_al...
use crate::{app, db, graphql::ctx::GraphContext}; use chrono::{DateTime, NaiveDateTime, Utc}; use juniper::{FieldError, FieldResult}; pub struct PadsQueryRoot; graphql_object!(PadsQueryRoot: GraphContext |&self| { field all(&executor, req: ApiReqPadsQueryAll) -> FieldResult<ApiRespPadsQueryAll> { query_al...
ue!({"pad": "query_pads_count_failure"}), ) })?; let config: &app::config::Config = app::config(); let pad_limit = config.room.max_pads_per_user as i32; debug!( "pad count = {}, pad limit = {}, user_id = {}", curr_pads_count, pad_limit, user_id ); if pad_limit > 0 && (c...
map(|s| s.user_id).unwrap_or(0); let dao: &db::ApiDao = &ctx.dao; debug!("create_pad user_id = {}, req = {:?}", user_id, req); let curr_pads_count = dao.pads.query_pad_count(user_id).map_err(|e| { debug!("query pad count err = {:?}", e); FieldError::new( "query pads count failu...
function_block-random_span
[ { "content": "fn mutation_user_logout(executor: &juniper::Executor<GraphContext>) -> FieldResult<i32> {\n\n let ctx = executor.context();\n\n info!(\"user_logout req = {:?}, session = {:?}\", \"\", ctx.session);\n\n\n\n match &ctx.session {\n\n Some(ref sess) => {\n\n let dao: &db::Ap...
Rust
src/operator/mod.rs
friktor/eval
40e2475f234b0999cc334425c362d0dc69406678
use std::str::FromStr; use serde_json::Value; use to_value; use error::Error; use node::Node; #[derive(Debug, Clone, PartialEq)] pub enum Operator { Add(u8), Mul(u8), Sub(u8), Div(u8), Rem(u8), Not(u8), Eq(u8), Ne(u8), Gt(u8), Lt(u8), Ge(u8), Le(u8), And(u8), Or...
use std::str::FromStr; use serde_json::Value; use to_value; use error::Error; use node::Node; #[derive(Debug, Clone, PartialEq)] pub enum Operator { Add(u8), Mul(u8), Sub(u8), Div(u8), Rem(u8), Not(u8), Eq(u8), Ne(u8), Gt(u8), Lt(u8), Ge(u8), Le(u8), And(u8), Or...
Operator::LeftSquareBracket(_) => true, _ => false, } } pub fn is_dot(&self) -> bool { match *self { Operator::Dot(_) => true, _ => false, } } pub fn is_value_or_ident(&self) -> bool { match *self { Operator::Value(_)...
> u8 { match *self { Operator::Add(priority) | Operator::Sub(priority) | Operator::Div(priority) | Operator::Mul(priority) | Operator::Eq(priority) | Operator::Ne(priority) | Operator::Gt(priority) | Operator::Lt(pri...
random
[ { "content": "fn is_range(ident: &str) -> bool {\n\n ident.contains(\"..\")\n\n}\n\n\n", "file_path": "src/tree/mod.rs", "rank": 0, "score": 62677.119117683265 }, { "content": "/// Convert variable to `serde_json::Value`\n\npub fn to_value<S: Serialize>(v: S) -> Value {\n\n json_to_val...
Rust
kernel-hal/src/common/context.rs
OSLab-zCore/zCore
4fa3f4cd9f91e98c289d81c1308e290383e60e4f
use crate::{MMUFlags, VirtAddr}; use core::fmt; use trapframe::UserContext as UserContextInner; pub use trapframe::GeneralRegs; cfg_if! { if #[cfg(feature = "libos")] { pub use trapframe::syscall_fn_entry as syscall_entry; } else { pub use dummpy_syscall_entry as syscall_entry; pub f...
use crate::{MMUFlags, VirtAddr}; use core::fmt; use trapframe::UserContext as UserContextInner; pub use trapframe::GeneralRegs; cfg_if! { if #[cfg(feature = "libos")] { pub use trapframe::syscall_fn_entry as syscall_entry; } else { pub use dummpy_syscall_entry as syscall_entry; pub f...
ructionMisaligned) | Trap::Exception(Exception::StoreMisaligned) => Self::UnalignedAccess, Trap::Exception(Exception::LoadPageFault) => Self::PageFault(stval, MMUFlags::READ), Trap::Exception(Exception::StorePageFault) => Self::PageFault(stval, MMUFlags::WRITE), Trap::Exc...
SoftwareBreakpoint, HardwareBreakpoint, UnalignedAccess, GernelFault(usize), } #[cfg(not(feature = "libos"))] pub const TIMER_INTERRUPT_VEC: usize = crate::timer_interrupt_vector(); impl TrapReason { #[cfg(target_arch = "x86_64")] pub fn from(trap_num: usize, error_code: usize) -> Self {...
random
[ { "content": "#[doc(cfg(any(feature = \"libos\", not(feature = \"smp\"))))]\n\npub fn init() {\n\n drivers::init_early();\n\n boot::primary_init();\n\n}\n", "file_path": "kernel-hal/src/libos/mod.rs", "rank": 0, "score": 209168.84914191265 }, { "content": "pub fn init() {\n\n let na...
Rust
linfa-svm/src/permutable_kernel.rs
fgadaleta/linfa
1b8a19e3cebe7002a57a2e233feb463bf38ade35
use crate::Float; use linfa_kernel::Kernel as LinfaKernel; use ndarray::{Array1, OwnedRepr}; pub type Kernel<'a, A> = LinfaKernel<'a, A, OwnedRepr<A>>; pub trait Permutable<'a, A: Float> { fn swap_indices(&mut self, i: usize, j: usize); fn distances(&self, idx: usize, length: usize) -> Vec<A>; fn self_dis...
use crate::Float; use linfa_kernel::Kernel as LinfaKernel; use ndarray::{Array1, OwnedRepr}; pub type Kernel<'a, A> = LinfaKernel<'a, A, OwnedRepr<A>>; pub trait Permutable<'a, A: Float> { fn swap_indices(&mut self, i: usize, j: usize); fn distances(&self, idx: usize, length: usize) -> Vec<A>; fn self_dis...
fn inner(&self) -> &'a Kernel<'a, A> { self.kernel } fn self_distance(&self, idx: usize) -> A { let idx = self.kernel_indices[idx]; self.kernel_diag[idx] } } pub struct PermutableKernelRegression<'a, A: Float> { kernel: &'a Kernel<'a, A>, kernel_diag: Array...
fn distances(&self, idx: usize, length: usize) -> Vec<A> { let idx = self.kernel_indices[idx]; let kernel = self.kernel.column(idx); (0..length) .map(|j| kernel[self.kernel_indices[j]]) .collect() }
function_block-function_prefixed
[ { "content": "/// A Float trait that captures the requirements we need for the various\n\n/// places we use floats. These are basically imposed by NdArray and Argmin.\n\npub trait Float:\n\n ArgminFloat\n\n + NdFloat\n\n + Lapack\n\n + Default\n\n + Clone\n\n + FromPrimitive\n\n + ArgminMul...
Rust
source/state_machines_macros/src/check_birds_eye.rs
BLepers/verus
8f0491dedbf6e28aeab436d6a5dc5e5d5beaf1db
use crate::ast::{LetKind, SpecialOp, Transition, TransitionKind, TransitionStmt}; use syn::parse::Error; pub fn check_birds_eye(trans: &Transition, concurrent: bool, errors: &mut Vec<Error>) { check_birds_eye_rec( &trans.body, trans.kind == TransitionKind::Init, concurrent, false, ...
use crate::ast::{LetKind, SpecialOp, Transition, TransitionKind, TransitionStmt}; use syn::parse::Error; pub fn check_birds_eye(trans: &Transition, concurrent: bool, errors: &mut Vec<Error>) { check_birds_eye_rec( &trans.body, trans.kind == TransitionKind::Init, concurrent, false, ...
=> true, SpecialOp::HaveSome(_) => true, SpecialOp::AddKV(_, _) => false, SpecialOp::RemoveKV(_, _) => true, SpecialOp::HaveKV(_, _) => true, SpecialOp::DepositSome(_) => true, SpecialOp::WithdrawSome(_) => false, SpecialOp::GuardSome(_) => false, Speci...
h op { SpecialOp::AddElement(_) => false, SpecialOp::RemoveElement(_) => true, SpecialOp::HaveElement(_) => true, SpecialOp::AddSome(_) => false, SpecialOp::RemoveSome(_)
function_block-random_span
[ { "content": "pub fn has_any_assert(ts: &TransitionStmt) -> bool {\n\n match ts {\n\n TransitionStmt::Block(_span, v) => {\n\n for t in v.iter() {\n\n if has_any_assert(t) {\n\n return true;\n\n }\n\n }\n\n false\n\n ...
Rust
userland/init_thread/src/vfs/dcache.rs
vincenthouyi/LakeOS
6ede872598f525e1dda7c770b5b0f7bd798e64dd
use alloc::boxed::Box; use alloc::sync::Arc; use alloc::vec::Vec; use core::slice; use async_trait::async_trait; use hashbrown::{HashMap, HashSet}; use spin::Mutex; use naive::ep_server::EP_SERVER; use naive::lmp::LmpListener; use naive::objects::{CapSlot, EpRef}; use naive::path::{Path, PathBuf}; use naive::rpc::{se...
use alloc::boxed::Box; use alloc::sync::Arc; use alloc::vec::Vec; use core::slice; use async_trait::async_trait; use hashbrown::{HashMap, HashSet}; use spin::Mutex; use naive::ep_server::EP_SERVER; use naive::lmp::LmpListener; use naive::objects::{CapSlot, EpRef}; use naive::path::{Path, PathBuf}; use naive::rpc::{se...
hBuf>, ()> { self.inode.as_ref().ok_or(())?.read_dir() } pub fn cached_entries(&self) -> Vec<PathBuf> { self.children.keys().cloned().collect() } } struct DentryNode { dentry: DirEntry, } #[async_trait] impl rpc::RpcRequestHandlers for DentryNode { async fn handle_read_dir( ...
pub fn open(&self) -> Result<Option<EpRef>, ()> { let mut inner = self.0.lock(); if let Some(ep) = &inner.cached_ep { return Ok(Some(ep.clone())); } let ep = inner.open()?; if let Some(ep) = ep { inner.cached_ep = Some(ep.clone()); return Ok...
random
[ { "content": "pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {\n\n let path = path.as_ref();\n\n if path.is_relative() {\n\n let mut path_buf = current_dir()?;\n\n path_buf.push(path);\n\n Ok(path_buf)\n\n } else {\n\n Ok(path.to_path_buf())\n\n }\n\n}\n"...
Rust
crypto-ws-client/tests/okx.rs
crypto-crawler/crypto-crawler-rs
e13e5493b530a7211479987c8b9209157ebdbaa2
use crypto_ws_client::{OkxWSClient, WSClient}; #[macro_use] mod utils; #[tokio::test(flavor = "multi_thread")] async fn okex_index() { gen_test_code!( OkxWSClient, subscribe, &vec![("index-tickers".to_string(), "BTC-USDT".to_string())] ); } #[cfg(test)] mod okx_spot { use crypto_w...
use crypto_ws_client::{OkxWSClient, WSClient}; #[macro_use] mod utils; #[tokio::test(flavor = "multi_thread")] async fn okex_index() { gen_test_code!( OkxWSClient, subscribe, &vec![("index-tickers".to_string(), "BTC-USDT".to_string())] ); } #[cfg(test)] mod okx_spot { use crypto_w...
} #[cfg(test)] mod okx_swap { use crypto_ws_client::{OkxWSClient, WSClient}; #[tokio::test(flavor = "multi_thread")] async fn subscribe() { gen_test_code!( OkxWSClient, subscribe, &vec![("trades".to_string(), "BTC-USDT-SWAP".to_string())] ); } ...
async fn subscribe_candlestick() { gen_test_subscribe_candlestick!(OkxWSClient, &vec![("BTC-USDT-220624".to_string(), 60)]); gen_test_subscribe_candlestick!( OkxWSClient, &vec![("BTC-USDT-220624".to_string(), 604800)] ); }
function_block-full_function
[ { "content": "fn fetch_symbols(kind: &str) -> Result<Vec<String>> {\n\n let all_markets = fetch_raw_markets(kind)?;\n\n let all_symbols: Vec<String> = all_markets.into_iter().map(|x| x.instrument_name).collect();\n\n Ok(all_symbols)\n\n}\n\n\n\npub(super) fn fetch_inverse_future_symbols() -> Result<Vec...
Rust
src/utils/hexdump.rs
Robo210/evtx
7ea6bcd59a4d6d0894a3a7a8d4d2f4d60f8299df
#![allow(dead_code)] use crate::evtx_parser::ReadSeek; use std::cmp; use std::error::Error; use std::fmt::Write; use std::io::SeekFrom; pub fn dump_stream<T: ReadSeek>(cursor: &mut T, lookbehind: i32) -> Result<String, Box<dyn Error>> { let mut s = String::new(); cursor.seek(SeekFrom::Current(lookbehind.into...
#![allow(dead_code)] use crate::evtx_parser::ReadSeek; use std::cmp; use std::error::Error; use std::fmt::Write; use std::io::SeekFrom; pub fn dump_stream<T: ReadSeek>(cursor: &mut T, lookbehind: i32) -> Result<String, Box<dyn Error>> { let mut s = String::new(); cursor.seek(SeekFrom::Current(lookbehind.into...
rom_be(u16::from(line[bytes * b]) << 8) } else { u16::from_be((u16::from(line[bytes * b]) << 8) + u16::from(line[bytes * b + 1])) } } }; match display { 'b' => write!(s, " {:03o}", word)?, 'c' => { if...
function_block-function_prefixed
[ { "content": "pub fn read_processing_instruction_data(cursor: &mut Cursor<&[u8]>) -> Result<String> {\n\n trace!(\n\n \"Offset `0x{:08x}` - ProcessingInstructionTarget\",\n\n cursor.position(),\n\n );\n\n\n\n let data =\n\n try_read!(cursor, len_prefixed_utf_16_str, \"pi_data\")?.u...
Rust
src/sd/sdmmc_cmd.rs
phil-opp/stm32f7-discovery-rewrite
93175983ed22531531138ca0cf9a12324ed9a757
use super::error::*; use stm32f7::stm32f7x6::SDMMC1; pub fn idle(sdmmc: &mut SDMMC1, timeout: u32) -> Result<(), Error> { send_cmd(sdmmc, 0, 0x00, true, false, 0x00); let timeout = ::system_clock::ms() as u32 + timeout; while (::system_clock::ms() as u32) < timeout && sdmmc.sta.read().cmdsent().bit_is_cle...
use super::error::*; use stm32f7::stm32f7x6::SDMMC1; pub fn idle(sdmmc: &mut SDMMC1, timeout: u32) -> Result<(), Error> { send_cmd(sdmmc, 0, 0x00, true, false, 0x00); let timeout = ::system_clock::ms() as u32 + timeout; while (::system_clock::ms() as u32) < timeout && sdmmc.sta.read().cmdsent().bit_is_cle...
pub fn clear_all_static_status_flags(sdmmc: &mut SDMMC1) { sdmmc.icr.modify(|_, w| { w.ccrcfailc().set_bit(); w.dcrcfailc().set_bit(); w.ctimeoutc().set_bit(); w.dtimeoutc().set_bit(); w.txunderrc().set_bit(); w.rxoverrc().set_bit(); w.cmdrendc().set_bit(); ...
fn wait_resp_crc(sdmmc: &mut SDMMC1, timeout: u32) -> Result<(), Error> { wait_resp(sdmmc, timeout)?; if sdmmc.sta.read().ccrcfail().bit_is_set() { sdmmc.icr.modify(|_, w| w.ccrcfailc().set_bit()); return Err(Error::SdmmcError { t: SdmmcErrorType::CmdCrcFailed, }); } ...
function_block-full_function
[ { "content": "fn power_on(sdmmc: &mut SDMMC1) -> Result<CardType, Error> {\n\n // power up the card\n\n sdmmc.clkcr.modify(|_, w| w.clken().clear_bit());\n\n sdmmc.power.modify(|_, w| unsafe { w.pwrctrl().bits(0x03) });\n\n sdmmc.clkcr.modify(|_, w| w.clken().set_bit());\n\n\n\n let mut card_type...
Rust
src/main.rs
alyti/uwuify-mdbook-preprocessor
00f6e838aa4e75386c203c2262315a961471ac60
use crate::uwuify_lib::UwUifier; use clap::{App, Arg, ArgMatches, SubCommand}; use mdbook::book::Book; use mdbook::errors::Error; use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext}; use std::io; use std::process; const NAME: &str = "uwuify"; pub fn make_app() -> App<'static, 'static> { A...
use crate::uwuify_lib::UwUifier; use clap::{App, Arg, ArgMatches, SubCommand}; use mdbook::book::Book; use mdbook::errors::Error; use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext}; use std::io; use std::process; const NAME: &str = "uwuify"; pub fn make_app() -> App<'static, 'static> { A...
sult<String, Error> { let mut buf = String::with_capacity(chapter.content.len()); let events = Parser::new(&chapter.content).map(|e| -> Event { match e { Event::Text(s) => { let b = s.as_bytes(); let mut temp1 = vec![0u8; uwuifier::roun...
cessor") .about("A mdbook preprocessor which uwuifies your books uwu") .subcommand( SubCommand::with_name("supports") .arg(Arg::with_name("renderer").required(true)) .about("Check whether a renderer is supported by this preprocessor"), ) } fn main() {...
random
[ { "content": "# uwuify-mdbook-preprocessor\n\nuwuify preprocessor for mdbook\n", "file_path": "README.md", "rank": 4, "score": 22947.38893680876 }, { "content": "# Unofficial Bevy Cheat Book\n\n\n\nConcise practical reference to the [Bevy game engine](https://github.com/bevyengine/bevy).\n\n...
Rust
src/widgets/mod.rs
manderio/eww
35c88633faf497a935dd4805ff422020247c2b10
use crate::{ config::{element::WidgetDefinition, window_definition::WindowName}, eww_state::*, value::AttrName, }; use anyhow::*; use gtk::prelude::*; use itertools::Itertools; use std::collections::HashMap; use std::process::Command; use widget_definitions::*; pub mod widget_definitions; pub mod widget_n...
use crate::{ config::{element::WidgetDefinition, window_definition::WindowName}, eww_state::*, value::AttrName, }; use anyhow::*; use gtk::prelude::*; use itertools::Itertools; use std::collections::HashMap; use std::process::Command; use widget_definitions::*; pub mod widget_definitions; pub mod widget_n...
struct BuilderArgs<'a, 'b, 'c, 'd, 'e> { eww_state: &'a mut EwwState, widget: &'b widget_node::Generic, unhandled_attrs: Vec<&'c AttrName>, window_name: &'d WindowName, widget_definitions: &'e HashMap<String, WidgetDefinition>, } fn build_builtin_gtk_widget( eww_state: &mut EwwState, wind...
ion::from_millis(200)) { Ok(None) => { log::error!("WARNING: command {} timed out", &cmd); let _ = child.kill(); let _ = child.wait(); } Err(err) => log::error!("Failed to execute command {}: {}"...
function_block-function_prefixed
[ { "content": "/// Run a command and get the output\n\nfn run_command(cmd: &str) -> Result<PrimVal> {\n\n log::debug!(\"Running command: {}\", cmd);\n\n let output = String::from_utf8(Command::new(\"/bin/sh\").arg(\"-c\").arg(cmd).output()?.stdout)?;\n\n let output = output.trim_matches('\\n');\n\n O...
Rust
crates/flowistry/src/infoflow/dependencies.rs
willcrichton/rust-slicer
2f70b97f9ec9a9bc5e2e5b74a25873a22963e913
use log::{debug, trace}; use rustc_middle::mir::*; use rustc_mir_dataflow::ResultsVisitor; use rustc_span::Span; use super::{ analysis::{FlowAnalysis, FlowDomain}, FlowResults, }; use crate::{ block_timer, indexed::{ impls::{LocationSet, PlaceIndex, PlaceSet}, IndexedDomain, }, mir::utils::PlaceExt...
use log::{debug, trace}; use rustc_middle::mir::*; use rustc_mir_dataflow::ResultsVisitor; use rustc_span::Span; use super::{ analysis::{FlowAnalysis, FlowDomain}, FlowResults, }; use crate::{ block_timer, indexed::{ impls::{LocationSet, PlaceIndex, PlaceSet}, IndexedDomain, }, mir::utils::PlaceExt...
pub fn compute_dependency_spans( results: &FlowResults<'_, 'tcx>, targets: Vec<(Place<'tcx>, Location)>, direction: Direction, spanner: &HirSpanner, ) -> Vec<Vec<Span>> { let tcx = results.analysis.tcx; let body = results.analysis.body; let source_map = tcx.sess.source_map(); let deps = compute_depen...
n)| { let state = results.state_at(*location); let mut locations = new_location_set(); for target in targets.indices() { if let Some(dep_locations) = state.row_set(target) { locations.union(&dep_locations); } } locations }; expanded_targets.iter().map(ge...
function_block-function_prefixed
[ { "content": "pub fn iterate_to_fixpoint<'tcx, A: Analysis<'tcx>>(\n\n _tcx: TyCtxt<'tcx>,\n\n body: &Body<'tcx>,\n\n location_domain: Rc<LocationDomain>,\n\n analysis: A,\n\n) -> AnalysisResults<'tcx, A> {\n\n let bottom_value = analysis.bottom_value(body);\n\n\n\n let num_locs = location_domain.num_real...
Rust
calyx/src/pass_manager.rs
ohxh/calyx
78492e894e56e7e8e050ff7665527237410bad8b
use crate::{ errors::{CalyxResult, Error}, ir, ir::traversal, }; use std::collections::{HashMap, HashSet}; pub type PassClosure = Box<dyn Fn(&mut ir::Context) -> CalyxResult<()>>; #[derive(Default)] pub struct PassManager { passes: HashMap<String, PassClosure>, aliases: HashMap<String...
use crate::{ errors::{CalyxResult, Error}, ir, ir::traversal, }; use std::collections::{HashMap, HashSet}; pub type PassClosure = Box<dyn Fn(&mut ir::Context) -> CalyxResult<()>>; #[derive(Default)] pub struct PassManager { passes: HashMap<String, PassClosure>, aliases: HashMap<String...
pub fn add_alias( &mut self, name: String, passes: Vec<String>, ) -> CalyxResult<()> { if self.aliases.contains_key(&name) { return Err(Error::Misc(format!( "Alias with name '{}' already registered.", name ...
if self.passes.contains_key(&name) { return Err(Error::Misc(format!( "Pass with name '{}' is already registered.", name ))); } let pass_closure: PassClosure = Box::new(|ir| { Pass::do_pass_default(ir)?; Ok(()) }); ...
function_block-function_prefix_line
[ { "content": "/// Generate a string given the name of the component and the port.\n\nfn format_port_name(comp: &ir::Id, port: &ir::Id) -> ir::Id {\n\n format!(\"{}_{}\", comp.id, port.id).into()\n\n}\n\n\n\nimpl Visitor for Externalize {\n\n fn start(\n\n &mut self,\n\n comp: &mut ir::Compon...
Rust
forester-crate/src/split.rs
mbillingr/forests
d94bed9d84476fc0024d8c969c719b193ace0fe3
use std::f64; use rand::{thread_rng, Rng}; use criterion::SplitCriterion; use data::{SampleDescription, TrainingData}; use split_between::SplitBetween; #[derive(Debug)] pub struct Split<Theta, Threshold> { pub theta: Theta, pub threshold: Threshold, } pub trait SplitFinder { fn find_split<Sample,...
use std::f64; use rand::{thread_rng, Rng}; use criterion::SplitCriterion; use data::{SampleDescription, TrainingData}; use split_between::SplitBetween; #[derive(Debug)] pub struct Split<Theta, Threshold> { pub theta: Theta, pub threshold: Threshold, } pub trait SplitFinder { fn find_split<Sample,...
assert!(split.threshold <= 4.0); } }
:new(&[0.0, 43.0, 6.0], 11.0), Sample::new(&[0.0, 43.0, 7.0], 12.0), Sample::new(&[0.0, 42.0, 8.0], 11.0), Sample::new(&[0.0, 42.0, 9.0], 12.0), ]; let spl = BestSplitRandomFeature::new(3); let split = spl.find_split(data).unwrap(); assert_eq!(split.th...
function_block-random_span
[ { "content": "/// Data set that can be used for training decision trees\n\npub trait TrainingData<Sample>: DataSet<Sample>\n\n where Sample: SampleDescription\n\n{\n\n type Criterion: SplitCriterion<Sample::Target>;\n\n\n\n /// Return number of samples in the data set\n\n fn n_samples(&self) -> usiz...
Rust
src/utils/utils.rs
genomehubs/goat-cli
b971e2c9de59869218c6869e832523bf8a6c3128
use std::{ fs::File, io::{BufRead, BufReader}, path::Path, }; use anyhow::{bail, Context, Result}; pub fn lines_from_file(filename: impl AsRef<Path>) -> Result<Vec<String>> { let file = File::open(&filename) .with_context(|| format!("Could not open {:?}", filename.as_ref().as_os_str()))?; ...
use std::{ fs::File, io::{BufRead, BufReader}, path::Path, }; use anyhow::{bail, Context, Result}; pub fn lines_from_file(filename: impl AsRef<Path>) -> Result<Vec<String>> { let file = File::open(&filename) .with_context(|| format!("Could not open {:?}", filename.as_ref().as_os_str()))?; ...
fn levenshtein_distance(a: &str, b: &str) -> usize { let mut result = 0; /* Shortcut optimizations / degenerate cases. */ if a == b { return result; } let length_a = a.chars().count(); let length_b = b.chars().count(); if length_a == 0 { return length_b; } if le...
edit_distance, word.to_owned()) }) .collect(); possible_matches.sort(); if let Some((_, first)) = possible_matches.into_iter().next() { Some(first) } else { None } }
function_block-function_prefix_line
[ { "content": "/// Format an expression put into the `-e` flag on the CLI.\n\npub fn format_expression(exp: &str) -> Result<String> {\n\n let mut new_exp = CLIexpression::new(exp);\n\n let parsed_string = new_exp.parse()?;\n\n Ok(parsed_string)\n\n}\n\n\n\n/// Boolean struct containing all of the CLI fl...
Rust
src/protocol/connection/pending.rs
iostat/rtsp-rs
26586cfde2644d83a9cb7304390905902273cdd7
use bytes::BytesMut; use futures::sync::mpsc::UnboundedSender; use futures::sync::oneshot::{self, Canceled}; use futures::{Async, Future, Poll}; use std::time::{Duration, Instant}; use tokio_timer::Delay; use crate::header::types::CSeq; use crate::protocol::connection::{OperationError, RequestTimeoutType}; use crate::...
use bytes::BytesMut; use futures::sync::mpsc::UnboundedSender; use futures::sync::oneshot::{self, Canceled}; use futures::{Async, Future, Poll}; use std::time::{Duration, Instant}; use tokio_timer::Delay; use crate::header::types::CSeq; use crate::protocol::connection::{OperationError, RequestTimeoutType}; use crate::...
.map(|duration| Delay::new(Instant::now() + duration)); } PendingRequestResponse::None => return Err(OperationError::RequestCancelled), PendingRequestResponse::Response(response) => return Ok(Async::Ready(response)), } } Ok(Async::NotReady)...
) -> Poll<Response<BytesMut>, OperationError> { if let Async::Ready(response) = self .rx_response .poll() .expect("`SendRequest.rx_response` should not error") { match response { PendingRequestResponse::Continue(rx_response) => { ...
function_block-random_span
[ { "content": "/// A helper function used to determine whether a given byte slice is a valid token. Tokens as used\n\n/// in [[RFC7826](https://tools.ietf.org/html/rfc782)] are encoded using ASCII-US with a limited\n\n/// subset allowed for use.\n\npub fn is_token(token: &[u8]) -> bool {\n\n if token.is_empty...
Rust
src/util/mod.rs
daviddrysdale/coset
4ed3e03b8f1c94c5f5a3f5b26359d54517235b21
use crate::{ cbor::value::{Integer, Value}, CoseError, Result, }; use alloc::{boxed::Box, vec::Vec}; #[cfg(test)] mod tests; pub(crate) fn cbor_type_error<T>(value: &Value, want: &'static str) -> Result<T> { let got = match value { Value::Integer(_) => "int", Value::Bytes(_) => "bstr", ...
use crate::{ cbor::value::{Integer, Value}, CoseError, Result, }; use alloc::{boxed::Box, vec::Vec}; #[cfg(test)] mod tests; pub(crate) fn cbor_type_error<T>(value: &Value, want: &'static str) -> Result<T> { let got = match value { Value::Integer(_) => "int", Value::Bytes(_) => "bstr", ...
macro_rules! builder { ( $otype: ty ) => { pub fn new() -> Self { Self(<$otype>::default()) } pub fn build(self) -> $otype { self.0 } }; } macro_rules! builder_set { ( $name:ident: $ftype:ty ) => { #[must_use] ...
pub fn expect_err<T: core::fmt::Debug, E: core::fmt::Debug>(result: Result<T, E>, err_msg: &str) { use alloc::format; assert!( result.is_err(), "expected error containing '{}', got success {:?}", err_msg, result ); let err = result.err(); assert!( format!("{:?...
function_block-full_function
[ { "content": "/// Extension trait that adds tagged serialization/deserialization methods.\n\npub trait TaggedCborSerializable: AsCborValue {\n\n /// The associated tag value.\n\n const TAG: u64;\n\n\n\n /// Create an object instance from serialized CBOR data in a slice, expecting an initial\n\n /// ...
Rust
src/bin/cli.rs
austinsheep/rs-orbit-db-http-client
d78c24a35f273a660388e2c3bc6d1b9ce0cfe946
use orbit_db_http_client::{Client, DatabaseType, Query}; use structopt::StructOpt; #[derive(StructOpt)] #[structopt(name = "OrbitDB HTTP Client", version = "0.1", author = "Austin Baugh")] struct CmdLine { #[structopt(short, long)] server_url: url::Url, #[structopt(subcommand)] cmd: Command,...
use orbit_db_http_client::{Client, DatabaseType, Query}; use structopt::StructOpt; #[derive(StructOpt)] #[structopt(name = "OrbitDB HTTP Client", version = "0.1", author = "Austin Baugh")] struct CmdLine { #[structopt(short, long)] server_url: url::Url, #[structopt(subcommand)] cmd: Command,...
= client.get_db_index(&dbname).await?; dbg!(index); } Command::GetIdentity => { let identity = client.get_identity().await?; dbg!(identity); } Command::CreateDb { dbname, dbtype } => { let value = client.create_db(&dbname, dbtype, None, fa...
ult<(), surf::Exception> { let args = CmdLine::from_args(); let client = Client::new(args.server_url.clone()); match args.cmd { Command::GetDbs => { let dbs = client.get_dbs().await?; dbg!(dbs); } Command::GetDb { dbname } => { ...
function_block-random_span
[ { "content": "fn client() -> Result<Client, url::ParseError> {\n\n Ok(Client::new(url::Url::parse(\"https://localhost:3000\")?))\n\n}\n\n\n\n/// Tests `client.get_dbs()`\n\n#[async_attributes::test]\n\nasync fn get_dbs() -> Result<(), Exception> {\n\n let client = client()?;\n\n\n\n client.get_dbs().aw...
Rust
benches/mono-raster.rs
rmanoka/geo-crossings
b1bfa2ab10735ed23ac6c4213662fc1d109cb066
#[path = "utils/random.rs"] mod random; use random::Samples; #[path = "utils/rasterize.rs"] mod rasterize; use rasterize::{our_area, our_rasterize, geo_intersects, geo_rasterize}; use std::f64::consts::PI; use criterion::{measurement::Measurement, *}; use geo::{ prelude::{Area, ConvexHull}, rotate::RotatePoi...
#[path = "utils/random.rs"] mod random; use random::Samples; #[path = "utils/rasterize.rs"] mod rasterize; use rasterize::{our_area, our_rasterize, geo_intersects, geo_rasterize}; use std::f64::consts::PI; use criterion::{measurement::Measurement, *}; use geo::{ prelude::{Area, ConvexHull}, rotate::RotatePoi...
fn run_circular<T: Measurement>(c: &mut Criterion<T>) { const SAMPLE_SIZE: usize = 16; const NUM_SLICES: usize = 1024; let mut group = c.benchmark_group("Circular polygon rasterize"); group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)); (3..12).for_each(|scale| ...
y, _)| { geo_rasterize(poly, NUM_SLICES, NUM_SLICES); }, BatchSize::SmallInput, ); }); group.bench_with_input(BenchmarkId::new("montone_rasterize", steps), &(), |b, _| { b.iter_batched( polys.sampler(), ...
function_block-function_prefixed
[ { "content": "pub fn steppy_polygon<R: Rng>(mut rng: R, steps: usize) -> Polygon<f64> {\n\n let mut ring = Vec::with_capacity(2 * steps);\n\n\n\n let ystep = 1.0;\n\n let nudge_std = ystep / 1000.0;\n\n let mut y = 0.0;\n\n let normal = Normal::new(0.0, nudge_std * nudge_std).unwrap();\n\n let...