lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/elements/component.rs
xarvic/panoramix
db65b4d9cc928baad25aa7bbb9a0a4b7926628ba
use crate::ctx::{CompCtx, ProcessEventCtx, ReconcileCtx}; use crate::element_tree::{Element, VirtualDom}; use crate::elements::ElementBox; use crate::glue::GlobalEventCx; use crate::metadata::{Metadata, NoState}; use derivative::Derivative; use std::fmt::Debug; pub trait Component: Debug + Clone { type Props: Clo...
use crate::ctx::{CompCtx, ProcessEventCtx, ReconcileCtx}; use crate::element_tree::{Element, VirtualDom}; use crate::elements::ElementBox; use crate::glue::GlobalEventCx; use crate::metadata::{Metadata, NoState}; use derivative::Derivative; use std::fmt::Debug; pub trait Component: Debug + Clone { type Props: Clo...
fn process_local_event( &self, children_state: &mut Self::AggregateChildrenState, _widget_seq: &mut Child::TargetWidgetSeq, _cx: &mut GlobalEventCx, ) -> Option<Self::Event> { let event_queue = &mut children_state.0; event_queue.pop() } fn proc...
fn reconcile( &self, prev_value: &Self, widget_seq: &mut Child::TargetWidgetSeq, ctx: &mut ReconcileCtx, ) { self.child.reconcile(&prev_value.child, widget_seq, ctx); }
function_block-full_function
[ { "content": "#[component]\n\nfn NoComponentOutput(ctx: &CompCtx, _props: ()) -> impl Element<Event = NoEvent> {\n\n let md = ctx.use_metadata::<NoEvent, i32>();\n\n let _local_state = ctx.get_local_state(md);\n\n EmptyElement::new()\n\n}\n\n\n", "file_path": "tests/metadata.rs", "rank": 0, ...
Rust
src/bin/s7c53_expandable_messages.rs
dkull/cryptopals
8d6b723b2c7f7905755804631a2bdda4c6b2005e
extern crate cryptopals; use aes::block_cipher_trait::generic_array::GenericArray; use aes::block_cipher_trait::BlockCipher; use aes::Aes128; use cryptopals::bytes_to_hex; use std::collections::{HashMap, HashSet}; use std::convert::TryInto; const BS: usize = 16; const HS: usize = 4; fn md(m: &[u8], h: &[u8; HS]) -> ...
extern crate cryptopals; use aes::block_cipher_trait::generic_array::GenericArray; use aes::block_cipher_trait::BlockCipher; use aes::Aes128; use cryptopals::bytes_to_hex; use std::collections::{HashMap, HashSet}; use std::convert::TryInto; const BS: usize = 16; const HS: usize = 4; fn md(m: &[u8], h: &[u8; HS]) -> ...
let prefix = produce_message(&exp_msg, k, injection_at - 1); println!( "prefix last block: {}", bytes_to_hex(&prefix[prefix.len() - HS..]) ); let final_fake_m = vec![prefix, bridge, m_tail].concat(); let fake_msg_hash = md(&final_fake_m, &zero_block); println!( "fin...
!(L >= k); let mut added_blocks = 0; let mut msg = vec![]; let t = L - k; for i in 0..k { let long_len = expandable_msg[i].1.len() / HS; println!( "k: {} i: {} need: {} added: {} -- new long {}", k, i, L, added_blocks, long_len ); let mask = 0x01 ...
random
[ { "content": "// s2c9\n\npub fn pkcs7_padding(data: &mut Vec<u8>, block_size: usize) {\n\n let missing_bytes = block_size - (data.len() % block_size);\n\n (0..missing_bytes).for_each(|_| data.push(missing_bytes as u8));\n\n}\n", "file_path": "src/block_ciphers.rs", "rank": 0, "score": 150182.5...
Rust
src/command/mod.rs
Shuenhoy/gluon_language-server
d7322580afcd55f1c124178d126aea83704a3bf7
use std::fmt; use crate::completion::{CompletionSymbol, CompletionSymbolContent}; use crate::either; use gluon::{ self, base::{ ast::{Expr, SpannedExpr}, filename_to_module, kind::ArcKind, pos::{BytePos, Spanned}, symbol::Symbol, types::{ArcType, BuiltinType, Ty...
use std::fmt; use crate::completion::{CompletionSymbol, CompletionSymbolContent}; use crate::either; use gluon::{ self, base::{ ast::{Expr, SpannedExpr}, filename_to_module, kind::ArcKind, pos::{BytePos, Spanned}, symbol::Symbol, types::{ArcType, BuiltinType, Ty...
, _ => SymbolKind::Variable, } } async fn retrieve_expr<F, R>( thread: &Thread, text_document_uri: &Url, f: F, ) -> Result<R, ServerError<()>> where F: FnOnce(&Module) -> Result<R, ServerError<()>>, { let filename = strip_file_prefix_with_thread(&thread, &text_document_uri); let mod...
match builtin { BuiltinType::Char | BuiltinType::String => SymbolKind::String, BuiltinType::Byte | BuiltinType::Int | BuiltinType::Float => SymbolKind::Number, BuiltinType::Array => SymbolKind::Array, BuiltinType::Function => SymbolKind::Function, }
if_condition
[ { "content": "pub fn test_url(uri: &str) -> Url {\n\n Url::from_file_path(&env::current_dir().unwrap().join(uri)).unwrap()\n\n}\n\n\n\npub async fn write_message<W, V>(writer: &mut W, value: V) -> io::Result<()>\n\nwhere\n\n W: ?Sized + AsyncWrite + Unpin,\n\n V: Serialize,\n\n{\n\n let mut vec = Ve...
Rust
src/filesystem.rs
minijackson/playfs
df28aae610d67d9eaec78df0e4f096bcb4394944
use fuse_mt::{self, DirectoryEntry, FileAttr, FileType, RequestInfo, ResultEmpty, ResultEntry, ResultOpen, ResultReaddir}; use rusqlite::{types::ToSql, Connection}; use time::Timespec; use libc::{c_int, ENOENT}; use std::ffi::OsString; use std::path::{self, Path}; use std::sync::Mutex; const DEFAU...
use fuse_mt::{self, DirectoryEntry, FileAttr, FileType, RequestInfo, ResultEmpty, ResultEntry, ResultOpen, ResultReaddir}; use rusqlite::{types::ToSql, Connection}; use time::Timespec; use libc::{c_int, ENOENT}; use std::ffi::OsString; use std::path::{self, Path}; use std::sync::Mutex; const DEFAU...
, _ => Err(()), } } impl Filesystem { pub fn new(db: &Path) -> Self { info!("Opening database: {}", db.display()); Filesystem { conn: Mutex::new(Connection::open(db).expect("Could not open database")), } } fn has_thing(&self, request: &'static str, params: ...
Ok(PlayPath::Song { artist: component_to_string(&components[1]), album: component_to_string(&components[2]), song: component_to_string(&components[3]), })
call_expression
[ { "content": "fn main() {\n\n let matches = App::new(\"PlayFS\")\n\n .about(\"A fast Fuse Filesystem for Beets\")\n\n .version(\"0.1\")\n\n .author(\"Rémi NICOLE <minijackson@riseup.net>\")\n\n .arg(Arg::with_name(\"mountpoint\")\n\n .help(\"Where to mount the filesyst...
Rust
src/helpers.rs
nexxeln/license-generator
7fad4a3af9d25f8a51ac752c55672b782ac4b01e
use std::{process::Command, fs, io}; use dialoguer::{console::Style, theme::ColorfulTheme, Input, Select}; use license::LicenseContent; use crate::license; pub fn fill_content(license: &LicenseContent) { let name = get_name(); let year = get_current_year(); let body = license .body .r...
use std::{process::Command, fs, io}; use dialoguer::{console::Style, theme::ColorfulTheme, Input, Select}; use license::LicenseContent; use crate::license; pub fn fill_content(license: &LicenseContent) { let name = get_name(); let year = get_current_year(); let body =
ne() } fn get_git_username() -> Option<String> { let cmd = Command::new("git") .arg("config") .arg("--global") .arg("--get") .arg("user.name") .output() .expect("fail"); let res: Option<String> = match cmd.status.success() { true => Option::from(String::...
license .body .replace("[year]", &year) .replace("[yyyy]", &year) .replace("[fullname]", &name) .replace("[name of copyright owner]", &name) .replace("<year>", &year) .replace("<name of author>", &name); match write_file("LICENSE", &body) { Ok(_)...
random
[ { "content": "fn main() {\n\n // fetch licenses\n\n let licenses = license::Licenses::fetch_licenses();\n\n\n\n // select menu\n\n let license = helpers::select(&licenses.get_license_names());\n\n\n\n // get license content\n\n let license_content = &licenses.get_license_from_name(&license);\...
Rust
relayer/src/supervisor/spawn.rs
interchainio/ibc-rs
194a1714cf9dc807dd7b4e33726319293848dc58
use tracing::{error, info}; use ibc::core::{ ics02_client::client_state::{ClientState, IdentifiedAnyClientState}, ics03_connection::connection::IdentifiedConnectionEnd, ics04_channel::channel::State as ChannelState, ics24_host::identifier::ChainId, }; use crate::{ chain::{counterparty::connection_...
use tracing::{error, info}; use ibc::core::{ ics02_client::client_state::{ClientState, IdentifiedAnyClientState}, ics03_connection::connection::IdentifiedConnectionEnd, ics04_channel::channel::State as ChannelState, ics24_host::identifier::ChainId, }; use crate::{ chain::{counterparty::connection_...
self.workers .spawn(chain, counterparty_chain, &connection_object, self.config) .then(|| { info!( "spawning Connection worker: {}", connection_object.short_name() ); }); ...
let connection_object = Object::Connection(Connection { dst_chain_id: client.client_state.chain_id(), src_chain_id: chain.id(), src_connection_id: connection.connection_id, });
assignment_statement
[]
Rust
src/level.rs
djeedai/libracity
1060f0c0ebefe8b58571f61c56857e348f46e1cb
use bevy::{app::CoreStage, asset::AssetStage, prelude::*}; use crate::{ inventory::{Inventory, Slot}, serialize::{Buildables, Levels}, AppState, Cursor, Grid, RegenerateInventoryUiEvent, ResetPlateEvent, }; #[derive(Debug, Clone, PartialEq, Eq)] pub enum LoadLevel { Next, ByName(String)...
use bevy::{app::CoreStage, asset::AssetStage, prelude::*}; use crate::{ inventory::{Inventory, Slot}, serialize::{Buildables, Levels}, AppState, Cursor, Grid, RegenerateInventoryUiEvent, ResetPlateEvent, }; #[derive(Debug, Clone, PartialEq, Eq)] pub enum LoadLevel { Next, ByName(String)...
} LoadLevel::ByIndex(level_index) => { info!("Load level: #{}", level_index); let level_index = *level_index; if level_index < levels.levels().len() { let level_desc = &levels.levels()[level_index]; ...
if let Some((level_index, level_desc)) = levels .levels() .iter() .enumerate() .find(|(_, l)| l.name == *level_name) { info!("=> Level '{}': #{}", level_name, level_index); (lev...
if_condition
[ { "content": "#[derive(Component)]\n\nstruct InventorySlot {\n\n /// Index of the slot in the [`Inventory`.\n\n index: u32,\n\n /// Number of items in the slot.\n\n count: u32,\n\n /// Entity owning the text with the number of items.\n\n text: Entity,\n\n}\n\n\n\nimpl InventorySlot {\n\n pu...
Rust
rust/src/statistics.rs
MindFlavor/nas_gallery
2b4515099f3f940674798544c3ee7c1dfc2330a2
use crate::file_type::FileType; use crate::options::Options; use prometheus_exporter_base::prelude::*; use rocket::State; use std::collections::HashMap; use std::sync::{Arc, RwLock}; #[inline] pub(crate) fn track_authorized_first_level_folders( options: &State<'_, Options>, statistics: &State<'_, Arc<RwLock<St...
use crate::file_type::FileType; use crate::options::Options; use prometheus_exporter_base::prelude::*; use rocket::State; use std::collections::HashMap; use std::sync::{Arc, RwLock}; #[inline] pub(crate) fn track_authorized_first_level_folders( options: &State<'_, Options>, statistics: &State<'_, Arc<RwLock<St...
self.unathorized_static.iter().for_each(|(key, val)| { pc.render_and_append_instance( &PrometheusInstance::new() .with_label("path", key.as_ref()) .with_value(*val), ); }); s.push_str(&pc.render()); s.push...
let mut pc = PrometheusMetric::build() .with_name("nas_gallery_unauthorized_access_to_static_content") .with_metric_type(MetricType::Counter) .with_help("Unauthorized access to static content") .build();
assignment_statement
[ { "content": "fn generate_thumb_folder_path(options: &Options, size: u64, original_path: &PathBuf) -> PathBuf {\n\n trace!(\"original_path == {:?}\", &original_path);\n\n let path = Path::new(&options.thumb_folder_path).join(format!(\"{}x{}\", size, size));\n\n trace!(\"generate_thumb_folder_path == {:...
Rust
diesel/src/macros/queryable.rs
robertmaloney/diesel
332ba12617ff05e5077fc1879caf83fe2e7fd8ff
#[macro_export] macro_rules! Queryable { (() $($body:tt)*) => { Queryable! { $($body)* } }; ( $(#[$ignore:meta])* $(pub)* struct $($body:tt)* ) => { Queryable! { $($body)* } }; ( ( ...
#[macro_export] macro_rules! Queryable { (() $($body:tt)*) => { Queryable! { $($body)* } }; ( $(#[$ignore:meta])* $(pub)* struct $($body:tt)* ) => { Queryable! { $($body)* } }; ( ( ...
#[test] fn tuple_struct_without_column_name_annotations() { #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct MyStruct(i32, i32); Queryable! { #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct MyStruct(i32, i32); } let conn = connection(); ...
n_name(foo)] i32, #[column_name(bar)] i32); } let conn = connection(); let data = ::select(sql::<(Integer, Integer)>("1, 2")).get_result(&conn); assert_eq!(Ok(MyStruct(1, 2)), data); }
function_block-function_prefixed
[ { "content": "#[doc(hidden)]\n\npub fn setup_database<Conn: Connection>(conn: &Conn) -> QueryResult<usize> {\n\n conn.setup_helper_functions();\n\n create_schema_migrations_table_if_needed(conn)\n\n}\n\n\n", "file_path": "diesel/src/migrations/mod.rs", "rank": 0, "score": 262751.3958453731 }...
Rust
src/options.rs
avar/hyperfine
4b419c6ab48a2018a5418fb4b70e25dcc401eba1
use std::fmt; use std::process::Command; use crate::error::OptionsError; use crate::units::{Second, Unit}; #[cfg(not(windows))] pub const DEFAULT_SHELL: &str = "sh"; #[cfg(windows)] pub const DEFAULT_SHELL: &str = "cmd.exe"; #[derive(Debug)] pub enum Shell { Default(&'static str), Custom(Vec<Strin...
use std::fmt; use std::process::Command; use crate::error::OptionsError; use crate::units::{Second, Unit}; #[cfg(not(windows))] pub const DEFAULT_SHELL: &str = "sh"; #[cfg(windows)] pub const DEFAULT_SHELL: &str = "cmd.exe"; #[derive(Debug)] pub enum Shell { Default(&'static str), Custom(Vec<Strin...
} impl Shell { pub fn parse<'a>(s: &str) -> Result<Self, OptionsError<'a>> { let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?; if v.is_empty() || v[0].is_empty() { return Err(OptionsError::EmptyShell); } Ok(Shell::Custom(v)) } pub fn c...
Shell::Default(cmd) => write!(f, "{}", cmd), Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)), } }
function_block-function_prefixed
[ { "content": "/// Print error message to stderr and terminate\n\npub fn error(message: &str) -> ! {\n\n eprintln!(\"{} {}\", \"Error:\".red(), message);\n\n std::process::exit(1);\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 143262.61697711638 }, { "content": "/// Like ...
Rust
hal/src/common/thumbv7em/qspi.rs
tomoyuki-nakabayashi/atsamd
3cc824a779f3790ec606411b2a338dc884adf70a
use crate::{ gpio::{Floating, Input, Pa10, Pa11, Pa8, Pa9, Pb10, Pb11, PfH, Port}, target_device::qspi::instrframe, target_device::{MCLK, QSPI}, }; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Error { CommandFunctionMismatch, } pub struct Qspi { qspi: QSPI, _sck: Pb10<PfH>, _...
use crate::{ gpio::{Floating, Input, Pa10, Pa11, Pa8, Pa9, Pb10, Pb11, PfH, Port}, target_device::qspi::instrframe, target_device::{MCLK, QSPI}, }; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Error { CommandFunctionMismatch, } pub struct Qspi { qspi: QSPI, _sck: Pb10<PfH>, _...
pub fn set_clk_divider(&mut self, value: u8) { self.qspi .baud .write(|w| unsafe { w.baud().bits(value.saturating_sub(1)) }); } } #[derive(Default, Debug, Copy, Clone)] struct TransferMode { quad_width: bool, data_enable: bool, opcode_enable: bool, ...
pub fn write_memory(&mut self, addr: u32, buf: &[u8]) { self.qspi.instrframe.write(|w| { w.width().quad_output(); w.addrlen()._24bits(); w.tfrtype().writememory(); w.instren().set_bit(); w.dataen().set_bit(); w.addren().set_bit() })...
function_block-full_function
[]
Rust
drivers/src/net/e1000.rs
YdrMaster/zCore
a35032b540120351b802890ec77603dda8f784b4
use alloc::collections::BTreeMap; use alloc::string::String; use alloc::sync::Arc; use alloc::vec::Vec; use smoltcp::iface::*; use smoltcp::phy::{self, DeviceCapabilities}; use smoltcp::time::Instant; use smoltcp::wire::*; use smoltcp::Result; use super::ProviderImpl; use super::PAGE_SIZE; use crate::net::get_socke...
use alloc::collections::BTreeMap; use alloc::string::String; use alloc::sync::Arc; use alloc::vec::Vec; use smoltcp::iface::*; use smoltcp::phy::{self, DeviceCapabilities}; use smoltcp::time::Instant; use smoltcp::wire::*; use smoltcp::Result; use super::ProviderImpl; use super::PAGE_SIZE; use crate::net::get_socke...
poll got err {}", err); } } } } } impl NetScheme for E1000Interface { fn get_mac(&self) -> EthernetAddress { self.iface.lock().ethernet_addr() } fn get_ifname(&self) -> String { self.name.clone() } fn get_ip_address(&self) -> Vec<IpCidr...
tamp) { Ok(p) => { info!("e1000 try_handle_interrupt poll: {:?}", p); } Err(err) => { warn!("
random
[ { "content": "pub trait IrqScheme: Scheme {\n\n /// Is a valid IRQ number.\n\n fn is_valid_irq(&self, irq_num: usize) -> bool;\n\n\n\n /// Disable IRQ.\n\n fn mask(&self, irq_num: usize) -> DeviceResult;\n\n\n\n /// Enable IRQ.\n\n fn unmask(&self, irq_num: usize) -> DeviceResult;\n\n\n\n /...
Rust
palette/src/rgb/channels.rs
alexfertel/palette
6765af7d69124e54b458fbfa10412c443ea32390
use crate::{cast::ComponentOrder, rgb}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Abgr; impl<S, T> ComponentOrder<rgb::Rgba<S, T>, [T; 4]> for Abgr { #[inline] fn pack(color: rgb::Rgba<S, T>) -> [T; 4] { let [red, green, blue, alpha]: [T; 4] = color.into(); [alpha, blue, green,...
use crate::{cast::ComponentOrder, rgb}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Abgr; impl<S, T> ComponentOrder<rgb::Rgba<S, T>, [T; 4]> for Abgr { #[inline] fn pack(color: rgb::Rgba<S, T>) -> [T; 4] { let [red, green, blue, alpha]: [T; 4] = color.into(); [alpha, blue, green,...
#[test] fn bgra() { let a1: Packed<Bgra, u32> = Srgb::new(0.5, 0.0, 0.0).into_format().into(); let a2: Packed<Bgra, u32> = Srgb::new(0.0, 1.0, 0.0).into_format().into(); let a3: Packed<Bgra, u32> = Srgb::new(0.0, 0.0, 0.5).into_format().into(); let x1: u32 = 0x0000_80FF; ...
fn argb() { let a1: Packed<Argb, u32> = Srgb::new(0.5, 0.0, 0.0).into_format().into(); let a2: Packed<Argb, u32> = Srgb::new(0.0, 1.0, 0.0).into_format().into(); let a3: Packed<Argb, u32> = Srgb::new(0.0, 0.0, 0.5).into_format().into(); let x1: u32 = 0xFF80_0000; let x2: u32 = 0x...
function_block-full_function
[ { "content": "#[test]\n\npub fn color_mine_from_rgb() {\n\n data_color_mine::run_from_rgb_tests();\n\n}\n", "file_path": "palette/tests/convert/mod.rs", "rank": 0, "score": 258515.81500016944 }, { "content": "#[test]\n\npub fn color_mine_from_linear_rgb() {\n\n data_color_mine::run_fro...
Rust
src/tests/default_connector_test.rs
aschaeffer/inexor-rgf-plugin-connector
97f904278f847e672869c6941c1dae3438f42081
use crate::behaviour::relation::connector::Connector; use crate::behaviour::relation::connector::CONNECTORS; use crate::model::{PropertyInstanceGetter, PropertyInstanceSetter}; use crate::tests::utils::create_connector; use crate::tests::utils::create_random_entity_instance; use crate::tests::utils::r_string; use serde...
use crate::behaviour::relation::connector::Connector; use crate::behaviour::relation::connector::CONNECTORS; use crate::model::{PropertyInstanceGetter, PropertyInstanceSetter}; use crate::tests::utils::create_connector; use crate::tests::utils::create_random_entity_instance; use crate::tests::utils::r_string; use serde...
#[test] fn default_connector_test() { let outbound_property_name = r_string(); let inbound_property_name = r_string(); let outbound_entity = Arc::new(create_random_entity_instance( outbound_property_name.clone(), )); let inbound_entity = Arc::new(create_random_entity_instance(inbound_prope...
let outbound_property_name = "lhs"; let inbound_property_name = "result"; let full_type_name = Connector::type_name(type_name, outbound_property_name, inbound_property_name); assert_eq!("default_connector--lhs--result", full_type_name); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn propagation_function_test() {\n\n let expected_propagation_functions = vec![\n\n \"debug_connector\",\n\n \"default_connector\",\n\n \"parse_float_connector\",\n\n \"parse_int_connector\",\n\n \"to_string_connector\",\n\n \"trace_connector...
Rust
services/common/src/wrapper/v0/node_traits.rs
tiagolobocastro/Mayastor
c9cf777e7776f529a2433d29b8513d1c601684a6
use super::*; pub struct GrpcContext { pub client: MayaClient, } pub type MayaClient = MayastorClient<Channel>; impl GrpcContext { pub async fn new(endpoint: String) -> Result<GrpcContext, SvcError> { let uri = format!("http://{}", endpoint); let uri = http::uri::Uri::from_str(&uri).unwrap(); ...
use super::*; pub struct GrpcContext { pub client: MayaClient, } pub type MayaClient = MayastorClient<Channel>; impl GrpcContext { pub async fn new(endpoint: String) -> Result<GrpcContext, SvcError> { let uri = format!("http://{}", endpoint); let uri = http::uri::Uri::from_str(&uri).unwrap(); ...
async fn share_nexus( &self, request: &ShareNexus, ) -> Result<String, SvcError> { Err(SvcError::NotImplemented {}) } async fn unshare_nexus( &self, request: &UnshareNexus, ) -> Result<(), SvcError> { Err(SvcError::NotImplemented {}) }...
async fn destroy_nexus( &self, request: &DestroyNexus, ) -> Result<(), SvcError> { Err(SvcError::NotImplemented {}) }
function_block-full_function
[ { "content": "pub fn bdev_get_name(uri: &str) -> Result<String, NexusBdevError> {\n\n Ok(Uri::parse(uri)?.get_name())\n\n}\n\n\n\nimpl std::cmp::PartialEq<url::Url> for &Bdev {\n\n fn eq(&self, uri: &url::Url) -> bool {\n\n match Uri::parse(&uri.to_string()) {\n\n Ok(device) if device.ge...
Rust
tio-rust/tio/src/slip.rs
twinleaf/twinleaf-web-ui
69b57c080c1e72a79c6a9a8a0111c60309e5048b
/* SLIP protocol module Thomas Kornack Twinleaf LLC 2016 NOTE: this implementation was mostly copy/paste from old code. Did run `cargo fmt. */ use anyhow::{anyhow, Result}; use std::convert::TryInto; const SLIP_END: u8 = 0xC0; const SLIP_ESC: u8 = 0xDB; const SLIP_ESC_END: u8 = 0xDC; const SLIP_ESC_ESC: u8 = 0xDD; ...
/* SLIP protocol module Thomas Kornack Twinleaf LLC 2016 NOTE: this implementation was mostly copy/paste from old code. Did run `cargo fmt. */ use anyhow::{anyhow, Result}; use std::convert::TryInto; const SLIP_END: u8 = 0xC0; const SLIP_ESC: u8 = 0xDB; const SLIP_ESC_END: u8 = 0xDC; const SLIP_ESC_ESC: u8 = 0xDD; ...
#[cfg(test)] mod test { use super::*; #[test] fn encode_decode() { let mut msg: Vec<u8> = Vec::with_capacity(256); for i in 0..255 { msg.push(i); } let slip_msg = tio_slip_encode(&msg); let msg2 = tio_slip_decode(&slip_...
slip_msg.push(SLIP_ESC_ESC); } _ => { slip_msg.push(*byte); } } } let tx_crc = crc32fast::hash(msg); for byte in tx_crc.to_le_bytes() { match byte { SLIP_END => { slip_msg.push(SLIP_ESC); slip_msg...
function_block-function_prefix_line
[ { "content": "/// Takes a pointer to some bytes, returns a RawPacket\n\n///\n\n/// Could probably take a pointer to an array of bytes or something like that instead.\n\npub fn raw_packet_from_bytes(bytes: &[u8]) -> Result<JsValue, JsValue> {\n\n match RawPacket::from_bytes(bytes) {\n\n Ok(raw_packet) ...
Rust
rcalc/src/lib.rs
smackem/rust-calc
0a7ccdc5a81fd763ba6fbf807ea9e408f30985e5
extern crate regex; #[macro_use] extern crate lazy_static; extern crate num; #[macro_use] extern crate log; mod lexer; mod parser; mod value; mod interpreter; mod util; use std::collections::HashMap; use std::thread; use std::io::{ BufWriter, Write }; use interpreter::Context; use lexer::Lexer; use ...
extern crate regex; #[macro_use] extern crate lazy_static; extern crate num; #[macro_use] extern crate log; mod lexer; mod parser; mod value; mod interpreter; mod util; use std::collections::HashMap; use std::thread; use std::io::{ BufWriter, Write }; use interpreter::Context; use lexer::Lexer; use ...
pub fn calc_parallel(&mut self, srcs: Vec<String>) -> &RuntimeItem { let mut threads = vec![]; for src in srcs { let context_map = self.get_context(); threads.push(thread::s...
pub fn calc(&mut self, src: &str) -> Result<&RuntimeItem, String> { let input = try!(self.lexer.lex(&src)); info!("Tokens: {:?}", input); let stmt = try!(parser::parse(&input)); info!("Ast: {:?}", stmt); let item = try!(interpreter::interpret(&stmt, &mut *self.ctx)); ...
function_block-full_function
[ { "content": "/// Interprets the given `Stmt`, using the specified `Context` for binding\n\n/// lookup and storage. Returns either the resulting `RuntimeItem` if successful\n\n/// or an error message.\n\npub fn interpret(stmt: &Stmt, ctx: &mut Context) -> Result<RuntimeItem, String> {\n\n let item = match *s...
Rust
ogu-lang/src/backend/modules/symbols/exprs/arithmetics.rs
lnds/Ogu
881ec221d7cc735f43753c8cd91b9b88e093a091
use anyhow::Result; use crate::backend::modules::symbols::exprs::comparable_trait::resolve_comparable; use crate::backend::modules::types::basic_type::{FLOAT_TYPE, INT_TYPE}; use crate::backend::modules::types::trait_type::TRAIT_NUM; use crate::backend::scopes::symbol::Symbol; use crate::backend::scopes::types::Type; ...
use anyhow::Result; use crate::backend::modules::symbols::exprs::comparable_trait::resolve_comparable; use crate::backend::modules::types::basic_type::{FLOAT_TYPE, INT_TYPE}; use crate::backend::modules::types::trait_type::TRAIT_NUM; use crate::backend::scopes::symbol::Symbol; use crate::backend::scopes::types::Type; ...
pub(crate) fn new_mod(l: Box<dyn Symbol>, r: Box<dyn Symbol>) -> Box<dyn Symbol> { Box::new(ArithmeticExpr { op: Op::Mod(l, r), ty: None, }) } pub(crate) fn new_pow(l: Box<dyn Symbol>, r: Box<dyn Symbol>) -> Box<dyn Symbol> { Box::new(ArithmeticExpr { ...
pub(crate) fn new_int_div(l: Box<dyn Symbol>, r: Box<dyn Symbol>) -> Box<dyn Symbol> { Box::new(ArithmeticExpr { op: Op::IntDiv(l, r), ty: None, }) }
function_block-full_function
[ { "content": "type NewFn = fn(Box<dyn Symbol>, Box<dyn Symbol>) -> Box<dyn Symbol>;\n\n\n\nimpl UnaryOpExpr {\n\n pub(crate) fn new_add(expr: Option<Box<dyn Symbol>>) -> Box<dyn Symbol> {\n\n Self::make_lambda(expr, TRAIT_NUM, ArithmeticExpr::new_add)\n\n }\n\n\n\n pub(crate) fn new_mul(expr: Op...
Rust
src/ui/ui_section.rs
raybritton/weather-examiner
3ce2f6209e591bc039dc47081cb03c5e39dba39a
use crate::Error; use std::io::{stdout, stdin, Write}; use crossterm::style::{Print, Color}; use crossterm::{ExecutableCommand, QueueableCommand, cursor}; use crossterm::event::KeyCode; use crossterm::event::Event::Key; use crate::app::WeatherApp; use log::error; use crossterm::cursor::MoveTo; use crossterm::terminal::...
use crate::Error; use std::io::{stdout, stdin, Write}; use crossterm::style::{Print, Color}; use crossterm::{ExecutableCommand, QueueableCommand, cursor}; use crossterm::event::KeyCode; use crossterm::event::Event::Key; use crate::app::WeatherApp; use log::error; use crossterm::cursor::MoveTo; use crossterm::terminal::...
fn wait_for_char(&self, message: &str) -> Result<KeyCode, Error> { consume_all_input()?; stdout() .execute(Print(message))?; crossterm::terminal::enable_raw_mode()?; loop { let result = crossterm::event::read()?; ...
while input.trim().is_empty() { if let Err(err) = stdin().read_line(&mut input) { error!("Can not read input: {}", err); std::process::exit(1); } } stdout() .execute(cursor::Hide)?; return Ok(input.trim().to_owned()); }
function_block-function_prefix_line
[]
Rust
prae/src/core.rs
teenjuna/prae
fdaf48da574c2cac7bdacd8d1af9918837c18a25
use std::hash::Hash; use std::ops::{Deref, Index}; use std::{error, fmt}; pub trait Bound { type Target: fmt::Debug; type Error: fmt::Debug; fn apply(v: &mut Self::Target) -> Result<(), Self::Error>; } pub trait Guard where Self: Sized, { type Bound: Bound; fn ...
use std::hash::Hash; use std::ops::{Deref, Index}; use std::{error, fmt}; pub trait Bound { type Target: fmt::Debug; type Error: fmt::Debug; fn apply(v: &mut Self::Target) -> Result<(), Self::Error>; } pub trait Guard where Self: Sized, { type Bound: Bound; fn ...
} #[cfg(feature = "serde")] impl<B> serde::Serialize for Guarded<B> where B: Bound, B::Target: serde::Serialize, B::Error: std::fmt::Display + std::fmt::Debug, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { B::Target::serialize(...
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Self::new(B::Target::deserialize(deserializer)?) .map_err(|e| serde::de::Error::custom(e.inner)) }
function_block-full_function
[ { "content": "#[test]\n\nfn mutation_error_can_be_transormed_into_inner() {\n\n let _err = || -> Result<(), UsernameError> {\n\n let mut un = Username::new(\"user\").unwrap();\n\n un.try_mutate(|u| *u = \"\".to_owned())\n\n .map_err(|e| e.into_inner())?;\n\n Ok(())\n\n }();...
Rust
src/lib.rs
mthiesen/pcx
cc19d6e6504a4a969b1ec6a04ea5de7e619f62de
extern crate byteorder; #[cfg(test)] extern crate walkdir; #[cfg(test)] extern crate image; use std::io; pub use reader::Reader; pub use writer::{WriterRgb, WriterPaletted}; pub mod low_level; mod reader; mod writer; #[cfg(test)] mod test_samples; fn user_error<T>(error: &str) -> io::Result<T> { Err(io::Erro...
extern crate byteorder; #[cfg(test)] extern crate walkdir; #[cfg(test)] extern crate image; use std::io; pub use reader::Reader; pub use writer::{WriterRgb, WriterPaletted}; pub mod low_level; mod reader; mod writer; #[cfg(test)] mod test_samples; fn user_error<T>(error: &str) -> io::Result<T> { Err(io::Erro...
fn round_trip_paletted(width: u16, height: u16) { let mut pcx = Vec::new(); let palette: Vec<u8> = (0..256 * 3).map(|v| (v % 0xFF) as u8).collect(); { let mut writer = WriterPaletted::new(&mut pcx, (width, height), (300, 300)).unwrap(); let mut p: Vec<u8> = iter::...
w(); let written_rgb: Vec<u8> = (0..(width as usize) * 3).map(|v| (v & 0xFF) as u8).collect(); { let mut writer = WriterRgb::new(&mut pcx, (width, height), (300, 300)).unwrap(); for _ in 0..height { writer.write_row(&written_rgb).unwrap(); } ...
function_block-function_prefixed
[ { "content": "fn lane_proper_length(width: u16, bit_depth: u8) -> u16 {\n\n (((width as u32) * (bit_depth as u32) - 1) / 8 + 1) as u16\n\n}\n\n\n\nimpl Header {\n\n pub fn load<R: io::Read>(stream: &mut R) -> io::Result<Self> {\n\n let magic = stream.read_u8()?;\n\n if magic != MAGIC_BYTE {\...
Rust
usql/src/ast/types/literal.rs
koushiro/usql
ab2ac5e4ccf33223308773afc7e9a6c67944cd88
#[cfg(not(feature = "std"))] use alloc::string::String; use core::fmt; use crate::ast::utils::escape_single_quote_string; #[derive(Clone, Debug, Eq, PartialEq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Literal { Null, Boolean(bool), Numbe...
#[cfg(not(feature = "std"))] use alloc::string::String; use core::fmt; use crate::ast::utils::escape_single_quote_string; #[derive(Clone, Debug, Eq, PartialEq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Literal { Null, Boolean(bool), Numbe...
assert_eq!( Literal::Interval(interval).to_string(), "INTERVAL '1.1' SECOND(2, 2)" ); let interval = Interval { value: "1.1".into(), leading_field: Some(DateTimeField::Second), leading_precision: Some(2), tailing_field: No...
let interval = Interval { value: "1.1".into(), leading_field: Some(DateTimeField::Second), leading_precision: Some(2), tailing_field: None, fractional_seconds_precision: Some(2), };
assignment_statement
[ { "content": "/// The configuration of the parser part of dialect.\n\npub trait DialectParserConf: Clone + Debug {}\n", "file_path": "usql/src/dialect.rs", "rank": 0, "score": 146335.68048831887 }, { "content": "/// The configuration of the lexer part of dialect.\n\npub trait DialectLexerCon...
Rust
src/types.rs
iJohnnyH/mangadex-rust
97b4cf31f0d2bbcb28981d02acd01c59e50a005f
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; #[derive(Serialize, Deserialize, Debug)] pub struct DataObject { pub id: String, pub r#type: String, } #[derive(Serialize, Deserialize, Debug, PartialEq, Default)] #[serde(rename_all = "camelCase")] pub struct Author { ...
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; #[derive(Serialize, Deserialize, Debug)] pub struct DataObject { pub id: String, pub r#type: String, } #[derive(Serialize, Deserialize, Debug, PartialEq, Default)] #[serde(rename_all = "camelCase")] pub struct Author { ...
}
fn from(i: Value) -> Manga { let attr = &i["data"]["attributes"]; let mut alt = Vec::new(); for map in attr["altTitles"].as_array().unwrap().iter() { alt.push(_to_str_map(map.as_object().unwrap())); } let mut tags = Vec::new(); for map in attr["tags"].as_array...
function_block-full_function
[ { "content": "#[test]\n\nfn test_mangas() -> serde_json::Result<()> {\n\n let json_str = r#\"\n\n {\"limit\": 2,\"offset\": 0,\"results\": [{\"data\": {\"attributes\": {\"altTitles\": [{\"en\": \"I am the only the one who levels up\"},{\"en\": \"I level up alone\"},{\"en\": \"Na Honjaman Lebel-eob\"},...
Rust
virtio-devices/src/watchdog.rs
mythi/cloud-hypervisor
592babaadd0a38a20d77193bc302209f497dfa02
use super::Error as DeviceError; use super::{ ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, Queue, VirtioCommon, VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1, }; use crate::seccomp_filters::{get_seccomp_filter, Thread}; use crate::{VirtioInter...
use super::Error as DeviceError; use super::{ ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, Queue, VirtioCommon, VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1, }; use crate::seccomp_filters::{get_seccomp_filter, Thread}; use crate::{VirtioInter...
fn run( &mut self, paused: Arc<AtomicBool>, paused_sync: Arc<Barrier>, ) -> result::Result<(), EpollHelperError> { let mut helper = EpollHelper::new(&self.kill_evt, &self.pause_evt)?; helper.add_event(self.queue_evt.as_raw_fd(), QUEUE_AVAIL_EVENT)?; helper.add_e...
nterrupt_cb .trigger(&VirtioInterruptType::Queue, Some(&self.queues[0])) .map_err(|e| { error!("Failed to signal used queue: {:?}", e); DeviceError::FailedSignalingUsedQueue(e) }) }
function_block-function_prefixed
[ { "content": "fn is_valid_alignment(fd: RawFd, alignment: usize) -> bool {\n\n let layout = Layout::from_size_align(alignment, alignment).unwrap();\n\n let ptr = unsafe { alloc_zeroed(layout) };\n\n\n\n let ret = unsafe {\n\n ::libc::pread(\n\n fd,\n\n ptr as *mut c_void,\n...
Rust
intel8080cpu/src/intel8080cpu.rs
AgustinCB/emulators
7d4602cee4f35bd478843bee23315ba099f56526
use alloc::boxed::Box; use alloc::fmt; use alloc::string::{String, ToString}; use alloc::vec::Vec; use super::cpu::{InputDevice, OutputDevice}; use super::CpuError; use helpers::two_bytes_to_word; pub const ROM_MEMORY_LIMIT: usize = 8192; pub(crate) const MAX_INPUT_OUTPUT_DEVICES: usize = 0x100; pub const HERTZ: i64 =...
use alloc::boxed::Box; use alloc::fmt; use alloc::string::{String, ToString}; use alloc::vec::Vec; use super::cpu::{InputDevice, OutputDevice}; use super::CpuError; use helpers::two_bytes_to_word; pub const ROM_MEMORY_LIMIT: usize = 8192; pub(crate) const MAX_INPUT_OUTPUT_DEVICES: usize = 0x100; pub const HERTZ: i64 =...
pub fn toggle_hard_stop(&mut self) { match self.state { State::HardStop => { self.state = self.prev_state; } _ => { self.prev_state = self.state; self.state = State::HardStop; } } } #[inline] ...
pub fn is_hard_stopped(&self) -> bool { match self.state { State::HardStop => true, _ => false, } }
function_block-full_function
[ { "content": "fn get_instructions_for_cpu(cpu: &str, bytes: [u8; ROM_MEMORY_LIMIT]) -> InstructionsResult {\n\n match cpu {\n\n \"mos6502\" => get_instructions::<Mos6502Instruction>(bytes),\n\n \"intel8080\" => get_instructions::<Intel8080Instruction>(bytes),\n\n \"smoked\" => get_instru...
Rust
src/lib.rs
andrewjensen/blockly-parser-rs
b9ecec23b874dd0bf1956627efbb9b664d9c697e
extern crate sxd_document; use std::collections::HashMap; use sxd_document::{ parser, Package, }; use sxd_document::dom::{ Document, ChildOfRoot, Element, ChildOfElement, }; #[derive(Debug)] pub struct Program { pub groups: Vec<StatementBody> } #[derive(PartialEq, Debug)] pub struct Stat...
extern crate sxd_document; use std::collections::HashMap; use sxd_document::{ parser, Package, }; use sxd_document::dom::{ Document, ChildOfRoot, Element, ChildOfElement, }; #[derive(Debug)] pub struct Program { pub groups: Vec<StatementBody> } #[derive(PartialEq, Debug)] pub struct Stat...
}
field name="TIME">100</field> </block> </next> </block> </next> </block> </statement> </block> </xml> "#...
function_block-function_prefix_line
[ { "content": "# Blockly Parser\n\n\n\nDeserialize XML generated by the [Google Blockly](https://developers.google.com/blockly/) UI into data structures.\n\n\n\n## Example usage:\n\n\n\n```rust\n\nextern crate blockly_parser;\n\n\n\nuse blockly_parser::{\n\n Program,\n\n StatementBody,\n\n Block,\n\n ...
Rust
src/alpha_bleed.rs
Vorlias/tarmac
dd3e436be29ae5161a1a74321d3f352b65858a71
use std::collections::VecDeque; use image::{DynamicImage, GenericImage, GenericImageView, Rgba}; pub(crate) fn alpha_bleed(img: &mut DynamicImage) { let (w, h) = img.dimensions(); let mut can_be_sampled = Mask2::new(w, h); let mut visited = Mask2::new(w, h); ...
use std::collections::VecDeque; use image::{DynamicImage, GenericImage, GenericImageView, Rgba}; pub(crate) fn alpha_bleed(img: &mut DynamicImage) { let (w, h) = img.dimensions(); let mut can_be_sampled = Mask2::new(w, h); let mut visited = Mask2::new(w, h); ...
data: vec![false; (w * h) as usize], } } fn get(&self, x: u32, y: u32) -> bool { let index = x + y * self.size.0; self.data[index as usize] } fn set(&mut self, x: u32, y: u32) { let index = x + y * self.size.0; self.data[index as usize] = true; } }
visited.set(x, y); to_visit.push_back((x, y)); } } } while let Some((x, y)) = to_visit.pop_front() { let mut new_color = (0, 0, 0); let mut contributing = 0; for (x_source, y_source) in...
random
[ { "content": "fn default_max_spritesheet_size() -> (u32, u32) {\n\n (1024, 1024)\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\n#[serde(deny_unknown_fields, rename_all = \"kebab-case\")]\n\npub struct InputConfig {\n\n /// A glob that will match all files that should be consider...
Rust
web_ui/src/pages/preview_2d.rs
jacobh/roller
4640ac9e2feec6aa211ba0b47b77f287a439f67b
use im_rc::HashMap; use itertools::Itertools; use yew::prelude::*; use roller_protocol::fixture::{FixtureId, FixtureParams, FixtureState}; use crate::pure::{Pure, PureComponent}; fn sorted_unique<T>(items: impl Iterator<Item = T>) -> Vec<T> where T: PartialOrd + PartialEq, { items.fold(Vec::with_capacity(8),...
use im_rc::HashMap; use itertools::Itertools; use yew::prelude::*; use roller_protocol::fixture::{FixtureId, FixtureParams, FixtureState}; use crate::pure::{Pure, PureComponent}; fn sorted_unique<T>(items: impl Iterator<Item = T>) -> Vec<T> where T: PartialOrd + PartialEq, { items.fold(Vec::with_capacity(8),...
}) .collect(); for fixture in fixtures.into_iter() { if let Some(location) = fixture.params.location.as_ref() { let row_idx = find_index(&sorted_rows, &location.y).unwrap(); let col_idx = find_index(&sorted_columns, &locati...
.iter() .filter_map(|fixture| fixture.params.location.as_ref()) .map(|location| location.y), ); let sorted_columns: Vec<isize> = sorted_unique( fixtures .iter() .filter_map(|fixture| fixture.params.location.as_ref()) ...
function_block-random_span
[]
Rust
src/interface/cli.rs
TomRegan/roots
7d8ed6675878c6ddcecc18b19cdfca08983b96ef
use { clap::{App, AppSettings, Arg, SubCommand}, database::query::{list_fields, list_titles}, std::path::Path, }; use application::book::Book; use internet::metadata; use crate::application::command::Command; use crate::configuration::Configuration; pub struct Application { cfg: Configuration, } impl...
use { clap::{App, AppSettings, Arg, SubCommand}, database::query::{list_fields, list_titles}, std::path::Path, }; use application::book::Book; use internet::metadata; use crate::application::command::Command; use crate::configuration::Configuration; pub struct Application { cfg: Configuration, } impl...
#[test] fn update_handles_no_database() { let assert = Command::cargo_bin("roots").unwrap().arg("update").assert(); assert .success() .stdout("No titles found, is roots initialised?\n") .code(0); } #[test] fn import_returns_successfully() { ...
atabase() { let assert = Command::cargo_bin("roots").unwrap().arg("list").assert(); assert .success() .stdout("No titles to list, is roots initialised?\n") .code(0); }
function_block-function_prefixed
[ { "content": "fn defaults() -> Config {\n\n let user_config_path = user_config_path();\n\n Config::default()\n\n .set_default(\"debug\", false).unwrap()\n\n .set_default(\"directory\", \"~/Books\".to_string()).unwrap()\n\n .set_default(\"library\", \"library.db\".to_string()).unwrap()...
Rust
crates/lang/codegen/src/generator/trait_def/trait_registry.rs
LedgerProject/ink
7432565b7e91cbe41f47be57ee0a344429724cc8
use super::TraitDefinition; use crate::{ generator::{self,}, traits::GenerateCode, EnforcedErrors, }; use derive_more::From; use proc_macro2::{ Span, TokenStream as TokenStream2, }; use quote::{ format_ident, quote, quote_spanned, }; use syn::{ parse_quote, spanned::Spanned, };...
use super::TraitDefinition; use crate::{ generator::{self,}, traits::GenerateCode, EnforcedErrors, }; use derive_more::From; use proc_macro2::{ Span, TokenStream as TokenStream2, }; use quote::{ format_ident, quote, quote_spanned, }; use syn::{ parse_quote, spanned::Spanned, };...
, message.mutates(), ); let inout_guards = Self::generate_inout_guards_for_message(message); let impl_body = match option_env!("INK_COVERAGE_REPORTING") { Some("true") => { quote! { ...
trs(); let output_ident = generator::output_ident(message.ident()); let output_type = message .output() .cloned() .unwrap_or_else(|| parse_quote! { () }); let mut_token = message.receiver().is_ref_mut().then(|| quote! { mut }); let (input_bindings, inp...
function_block-random_span
[ { "content": "/// Returns the associated output type for an ink! trait message.\n\npub fn output_ident(message_name: &syn::Ident) -> syn::Ident {\n\n format_ident!(\"{}Output\", message_name.to_string().to_camel_case())\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/generator/arg_list.rs", "rank"...
Rust
src/operations/mod.rs
AndreVuillemot160/QuickDash
156c15e369a8e5c594430eb56d70727cb47f6114
/* Copyright [2021] [Cerda] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in wri...
/* Copyright [2021] [Cerda] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://ww
Result::unwrap) { try_contains(&line, &mut hashes)?; } Ok(hashes) } fn try_contains(line: &str, hashes: &mut BTreeMap<String, String>) -> Result<(), Error> { if line.is_empty() { return Err(Error::HashesFileParsingFailure); } static LINE_RGX1: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^([[:xdigit:]-]+)\...
w.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions ...
random
[ { "content": "/// Hash the specified file using the specified hashing algorithm.\n\npub fn hash_file(algo: Algorithm, path: &Path) -> String {\n\n\thash_reader(algo, &mut File::open(path).unwrap())\n\n}\n\n\n", "file_path": "src/hashing/mod.rs", "rank": 1, "score": 18270.098607971686 }, { "c...
Rust
hdf5-sys/src/h5f.rs
p-gerhard/hdf5-rust
27a59c2811b877d4729d50f9ffd5a2f3386f7f9f
use std::mem; pub use self::H5F_close_degree_t::*; pub use self::H5F_libver_t::*; pub use self::H5F_mem_t::*; pub use self::H5F_scope_t::*; #[cfg(not(feature = "1.10.0"))] pub use { H5F_info1_t as H5F_info_t, H5F_info1_t__sohm as H5F_info_t__sohm, H5Fget_info1 as H5Fget_info, }; #[cfg(feature = "1.10.0")] pub use...
use std::mem; pub use self::H5F_close_degree_t::*; pub use self::H5F_libver_t::*; pub use self::H5F_mem_t::*; pub use self::H5F_scope_t::*; #[cfg(not(feature = "1.10.0"))] pub use { H5F_info1_t as H5F_info_t, H5F_info1_t__sohm as H5F_info_t__sohm, H5Fget_info1 as H5Fget_info, }; #[cfg(feature = "1.10.0")] pub use...
unsafe { mem::zeroed() } } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct H5F_info2_t { pub super_: H5F_info2_t__super, pub free: H5F_info2_t__free, pub sohm: H5F_info2_t__sohm, } impl Default for H5F_info2_t { fn default() -> Self { ...
for H5F_close_degree_t { fn default() -> Self { Self::H5F_CLOSE_DEFAULT } } #[cfg_attr(feature = "1.10.0", deprecated(note = "deprecated in HDF5 1.10.0, use H5F_info2_t"))] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct H5F_info1_t { pub super_ext_size: hsize_t, pub sohm: H5F_info1_t__sohm...
random
[ { "content": "/// Convert a `String` or a `&str` into a zero-terminated string (`const char *`).\n\npub fn to_cstring<S: Borrow<str>>(string: S) -> Result<CString> {\n\n let string = string.borrow();\n\n #[allow(clippy::map_err_ignore)]\n\n CString::new(string).map_err(|_| format!(\"null byte in string...
Rust
src/platform_impl/linux/x11/util/hint.rs
mahkoh/winit
62e917bdf928b0a9d45e5ebb7f0aff9b10994a5c
use std::sync::Arc; use super::*; use std::convert::TryInto; use thiserror::Error; use xcb_dl_util::hint::{XcbHints, XcbHintsError, XcbSizeHints, XcbSizeHintsError}; use xcb_dl_util::property::XcbGetPropertyError; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, Add = 1, Tog...
use std::sync::Arc; use super::*; use std::convert::TryInto; use thiserror::Error; use xcb_dl_util::hint::{XcbHints, XcbHintsError, XcbSizeHints, XcbSizeHintsError}; use xcb_dl_util::property::XcbGetPropertyError; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, Add = 1, Tog...
pub fn get_motif_hints(&self, window: ffi::xcb_window_t) -> MotifHints { let motif_hints = self.get_atom("_MOTIF_WM_HINTS"); let mut hints = MotifHints::new(); if let Ok(props) = self.get_property::<u32>(window, motif_hints, motif_hints) { hints.hints.flags = props.get(0).clo...
S, ffi::XCB_ATOM_WM_SIZE_HINTS, PropMode::Replace, normal_hints.as_bytes(), ) }
function_block-function_prefixed
[ { "content": "pub fn has_flag<T>(bitset: T, flag: T) -> bool\n\nwhere\n\n T: Copy + PartialEq + BitAnd<T, Output = T>,\n\n{\n\n bitset & flag == flag\n\n}\n\n\n", "file_path": "src/platform_impl/windows/util.rs", "rank": 0, "score": 377559.9592201411 }, { "content": "pub fn has_flag<T>...
Rust
src/main.rs
uuhan/sonnerie
7ddf1c2c32e50afc6760b60ca0dd382b6c04e887
use sonnerie::formatted; use std::path::Path; use std::fs::File; use sonnerie::*; use std::io::Write; fn main() -> std::io::Result<()> { use clap::{SubCommand,Arg}; let matches = clap::App::new("sonnerie") .version("0.5.8") .author("Charles Samuels <kalle@eventures.vc>") .about("A compressed timeseries d...
use sonnerie::formatted; use std::path::Path; use std::fs::File; use sonnerie::*; use std::io::Write; fn main() -> std::io::Result<()> { use clap::{SubCommand,Arg}; let matches = clap::App::new("sonnerie") .version("0.5.8") .author("Charles Samuels <kalle@eventures.vc>") .about("A compressed timeseries d...
check = matches.is_present("unsafe-nocheck"); let ts_format = matches.value_of("timestamp-format"); add(&dir, format, ts_format, nocheck); } else if let Some(matches) = matches.subcommand_matches("compact") { let gegnum = matches.value_of_os("gegnum"); let ts_format = matches.value_of("timestamp-format").unw...
int timestamps as seconds since the unix epoch (rounded down if necessary)") .conflicts_with("timestamp-format") .conflicts_with("timestamp-nanos") ) .arg(Arg::with_name("before") .long("before") .help("read values before (but not including) this key") .takes_value(true) .c...
random
[ { "content": "#[deprecated]\n\npub fn print_record<W: std::io::Write>(\n\n\trecord: &crate::record::OwnedRecord,\n\n\tout: &mut W,\n\n) -> std::io::Result<()>\n\n{\n\n\tlet fmt = parse_row_format(record.format());\n\n\tlet key = record.key();\n\n\tlet ts = &record.value()[0..8];\n\n\tlet value = &record.value()...
Rust
yewdux/src/dispatch.rs
Quetzal2/yewdux
2329d74ef86a75dc6c0b37bcba147febd4327b14
use std::rc::Rc; use std::{cell::RefCell, future::Future}; use yew::{Callback, Properties}; use crate::{ service::{ServiceBridge, ServiceOutput, ServiceRequest, ServiceResponse}, store::Store, }; type Model<T> = <T as Store>::Model; pub trait Dispatcher { type Store: Store; #[doc(hidden)] fn b...
use std::rc::Rc; use std::{cell::RefCell, future::Future}; use yew::{Callback, Properties}; use crate::{ service::{ServiceBridge, ServiceOutput, ServiceRequest, ServiceResponse}, store::Store, }; type Model<T> = <T as Store>::Model; pub trait Dispatcher { type Store: Store; #[doc(hidden)] fn b...
} impl<STORE: Store, SCOPE: 'static> PartialEq for DispatchProps<STORE, SCOPE> { fn eq(&self, other: &Self) -> bool { self.dispatch == other.dispatch && self .state .borrow() .as_ref() .zip(other.state.borrow().as_ref()) ...
fn clone(&self) -> Self { Self { state: self.state.clone(), dispatch: self.dispatch.clone(), } }
function_block-full_function
[ { "content": "/// This hook allows getting a [`Dispatch`] to the store.\n\n///\n\n/// Do not use the `state` method on the [`Dispatch`]. The dispatch should only be used to create callbacks.\n\n/// The proper way to access the state is via the [`use_store`] hook.\n\n///\n\n/// # Example\n\n/// ```ignore\n\n/// ...
Rust
src/generation/city/landmass_shape.rs
ScottyThePilot/glt-mc-generator
1666b9ca0035030cec34dc8a02b2a249c10870d1
use std::collections::VecDeque; use glam::{DVec2, IVec2, Vec2}; use grid::SparseGrid; use noise::{Fbm, MultiFractal, NoiseFn, Perlin}; use rand::Rng; use crate::utility::{cardinal4, cardinal8}; const MIN_BUILDING_SIZE: u32 = 5; const MAX_BUILDING_SIZE: u32 = 9; const MIN_BUILDING_HEIGHT: u32 = 2; const MAX_BUILDING_...
use std::collections::VecDeque; use glam::{DVec2, IVec2, Vec2}; use grid::SparseGrid; use noise::{Fbm, MultiFractal, NoiseFn, Perlin}; use rand::Rng; use crate::utility::{cardinal4, cardinal8}; const MIN_BUILDING_SIZE: u32 = 5; const MAX_BUILDING_SIZE: u32 = 9; const MIN_BUILDING_HEIGHT: u32 = 2; const MAX_BUILDING_...
fn get_neighbor_count_if_vacant(grid: &SparseGrid<Value>, building: &BuildingShape) -> Option<usize> { let min = building.edge_min - IVec2::ONE; let max = building.edge_max + IVec2::ONE; let mut neighbor_count = 0; for x in min.x..=max.x { let is_edge_x = x == min.x || x == max.x; for...
y..=building.edge_max.y { if let Some(value @ &mut Value::Vacant) = grid.get_mut(IVec2::new(x, y)) { *value = Value::Occupied(i); } else { panic!("`put_building_in_vacancy` requires that all positions be vacant"); }; }; }; }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn cardinal8(center: IVec2) -> impl Iterator<Item = IVec2> {\n\n CARDINAL8.into_iter().map(move |offset| offset + center)\n\n}\n\n\n\n\n\n\n", "file_path": "src/utility.rs", "rank": 5, "score": 181594.5483579758 }, { "content": "fn sample_checkered(size: u32, ...
Rust
services/mgmt/security/src/package_preview_2021_12/models.rs
reidav/azure-sdk-for-rust
3a6695ea0c81f326db78bae0b22a5785fbbd8c75
#![doc = "generated by AutoRust"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[doc = "Describes an Azure resource with location"] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AzureTrackedResourceLocation { #[doc = "Location where ...
#![doc = "generated by AutoRust"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[doc = "Describes an Azure resource with location"] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AzureTrackedResourceLocation { #[doc = "Location where ...
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastModifiedByType { User, Application, ManagedIdentity, Key, } }
rde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[doc = "The identity that last modified the resource."] #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<String>, #[doc = "T...
random
[]
Rust
crates/core/src/utils/string_utils.rs
bartlomieju/dprint
da162e4a63d981d663834019cd61dee863d5540f
pub fn get_line_number_of_pos(text: &str, pos: usize) -> usize { let text_bytes = text.as_bytes(); let mut line_count = 1; for i in 0..pos { if text_bytes.get(i) == Some(&('\n' as u8)) { line_count += 1; } } line_count } pub fn get_column_number_of_pos(text: &str, pos...
pub fn get_line_number_of_pos(text: &str, pos: usize) -> usize { let text_bytes = text.as_bytes(); let mut line_count = 1; for i in 0..pos { if text_bytes.get(i) == Some(&('\n' as u8)) { line_count += 1; } } line_count } pub fn get_column_number_of_pos(text: &str, pos...
); } #[test] fn should_get_range_highlight_on_second_line() { let message = get_range_text_highlight("test\ntest\ntest", (5, 9)); assert_eq!( message, concat!( "test\n", "~~~~" ) ); } #[test] fn should...
text_and_error_range(range: (usize, usize), file_text: &str) -> ((usize, usize), (usize, usize)) { let (start, end) = range; let start_column_number_byte_count = start - get_line_start_byte_pos(file_text, start); let line_end = get_line_end(file_text, end); let text_start = start - std::...
random
[ { "content": "pub fn format_text(text: &str, config: &Configuration) -> Result<String, String> {\n\n let print_items = parse_items(text, config)?;\n\n\n\n Ok(print(print_items, PrintOptions {\n\n indent_width: config.indent_width,\n\n max_width: config.line_width,\n\n use_tabs: config...
Rust
src/app.rs
Netdex/niinii
d2fa91f3c16b1bdc20d7799a79e1d354247cd55e
use std::sync::mpsc; use imgui::*; use crate::{ backend::renderer::Env, gloss::{Gloss, GlossError, Glossator}, translation::{self, Translation}, view::{mixins::help_marker, rikai::RikaiView, settings::SettingsView}, }; const ERROR_MODAL_TITLE: &str = "Error"; #[derive(thiserror::Error, Debug)] enum ...
use std::sync::mpsc; use imgui::*; use crate::{ backend::renderer::Env, gloss::{Gloss, GlossError, Glossator}, translation::{self, Translation}, view::{mixins::help_marker, rikai::RikaiView, settings::SettingsView}, }; const ERROR_MODAL_TITLE: &str = "Error"; #[derive(thiserror::Error, Debug)] enum ...
fn request_translation(&self, text: &str) { let channel_tx = self.channel_tx.clone(); let text = text.to_owned(); let deepl_api_key = self.settings.deepl_api_key.clone(); rayon::spawn(move || { let translation = translation::translate(&deepl_api_key, &text); ...
r) { let channel_tx = self.channel_tx.clone(); let glossator = &self.glossator; let text = text.to_owned(); let variants = if self.settings.more_variants { 5 } else { 1 }; rayon::spawn(enclose! { (glossator) move || { let gloss = glossator.gloss(&text, variants); ...
function_block-function_prefixed
[ { "content": "pub fn translate(deepl_api_key: &str, text: &str) -> Result<Translation, deepl_api::Error> {\n\n let text = filter_text(text);\n\n let deepl = DeepL::new(deepl_api_key.to_string());\n\n let deepl_text = deepl\n\n .translate(\n\n None,\n\n TranslatableTextList ...
Rust
near/oysterpack-smart-near/src/domain/public_key.rs
oysterpack/oysterpack-smart
f2985636d7c035de06e319f7ac8bec92e1293362
use crate::asserts::ERR_INVALID; use crate::Error; use near_sdk::json_types::Base58PublicKey; use near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, serde::{Deserialize, Deserializer, Serialize, Serializer}, }; use std::fmt::{Debug, Formatter}; use std::{ convert::{TryFrom, TryInto}, fmt::{sel...
use crate::asserts::ERR_INVALID; use crate::Error; use near_sdk::json_types::Base58PublicKey; use near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, serde::{Deserialize, Deserializer, Serialize, Serializer}, }; use std::fmt::{Debug, Formatter}; use std::{ convert::{TryFrom, TryInto}, fmt::{sel...
} impl<'de> Deserialize<'de> for PublicKey { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de>, { let key: Base58PublicKey = Deserialize::deserialize(deserializer)?; Ok(key.into()) } } impl TryFrom<&[u8]> for PublicK...
serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { let key = Base58PublicKey::from(*self); Serialize::serialize(&key, serializer) }
function_block-function_prefixed
[]
Rust
src/librustpkg/package_source.rs
thomcc/rust
c6515ee6a7f424679e2b53336974a991dd3b71c8
use target::*; use package_id::PkgId; use core::path::Path; use core::option::*; use core::{os, run, str, vec}; use context::*; use crate::Crate; use messages::*; use path_util::pkgid_src_in_workspace; use util::compile_crate; use version::{ExactRevision, SemanticVersion, NoVersion}; pub struct PkgSrc { root: Pa...
use target::*; use package_id::PkgId; use core::path::Path; use core::option::*; use core::{os, run, str, vec}; use context::*; use crate::Crate; use messages::*; use path_util::pkgid_src_in_workspace; use util::compile_crate; use version::{ExactRevision, SemanticVersion, NoVersion}; pub struct PkgSrc { root: Pa...
&dir, self.libs, cfgs, Lib); debug!("Building mains"); self.build_crates(ctx, &dst_dir, &dir, self.mains, cfgs, Main); debug!("Building tests"); self.build_crates(ctx, &dst_dir, &dir, self.tests, cfgs, Test); debug!("Building benches"); self.build_crates(ctx, &dst_dir, &...
{ return true; } else { for self_id.iter().advance |pth| { if pth.starts_with("rust_") && match p.filestem() { Some(s) => str::eq_slice(s, pth.slice(5, pth.len())), None => false ...
random
[ { "content": "// xfail-test\n\npub fn main() { let early_error: @fn(str) -> ! = {|msg| fail!() }; }\n", "file_path": "src/test/run-pass/issue-1516.rs", "rank": 0, "score": 706562.2886381538 }, { "content": "pub fn main() { let mut v: ~[int] = ~[]; }\n", "file_path": "src/test/run-pass/...
Rust
research/gaia-x/pegasus/pegasus/src/operator/iteration/feedback.rs
bmmcq/GraphScope
a480d941f3a3f1270ddc0570e72059e6a34dab24
use crate::api::Notification; use crate::communication::input::{new_input_session, InputProxy}; use crate::communication::output::{new_output, OutputProxy}; use crate::errors::JobExecError; use crate::graph::Port; use crate::operator::{DefaultNotify, Notifiable, OperatorCore}; use crate::progress::{EndSignal, Weight}; ...
use crate::api::Notification; use crate::communication::input::{new_input_session, InputProxy}; use crate::communication::output::{new_output, OutputProxy}; use crate::errors::JobExecError; use crate::graph::Port; use crate::operator::{DefaultNotify, Notifiable, OperatorCore}; use crate::progress::{EndSignal, Weight}; ...
if let Some(end) = dataset.take_end() { if count == 0 { let sync = end.tag.clone(); debug_worker!("detect if termination on {:?}", sync); let end = EndSignal::new(sync, Weight::all()); o...
if !dataset.is_empty() { count += 1; output.push_batch_mut(dataset)?; }
if_condition
[ { "content": "pub fn new_input_session<D: Data>(input: &Box<dyn InputProxy>) -> InputSession<D> {\n\n RefWrapInput::<D>::downcast(input).new_session()\n\n}\n", "file_path": "interactive_engine/executor/engine/pegasus/pegasus/src/communication/input/mod.rs", "rank": 0, "score": 305640.9122772126 ...
Rust
src/io/tls/rustls_io.rs
fulara/rust-mysql-simple
f985535a15ea689517d03b4b90fda0bee7d99115
#![cfg(feature = "rustls-tls")] use std::{ convert::TryInto, fs::File, io::{self, Read}, sync::Arc, }; use bufstream::BufStream; use rustls::{ client::{ServerCertVerifier, WebPkiVerifier}, Certificate, ClientConfig, OwnedTrustAnchor, RootCertStore, }; use rustls_pemfile::certs; use crate::{ ...
#![cfg(feature = "rustls-tls")] use std::{ convert::TryInto, fs::File, io::{self, Read}, sync::Arc, }; use bufstream::BufStream; use rustls::{ client::{ServerCertVerifier, WebPkiVerifier}, Certificate, ClientConfig, OwnedTrustAnchor, RootCertStore, }; use rustls_pemfile::certs; use crate::{ ...
}
t( end_entity, intermediates, server_name, scts, ocsp_response, now, ) { Ok(assertion) => Ok(assertion), Err(ref e) if e.to_string().contains("CertNotValidForNa...
function_block-function_prefixed
[ { "content": " /// Trait for protocol markers [`crate::Binary`] and [`crate::Text`].\n\n pub trait Protocol: crate::conn::query_result::Protocol {}\n\n impl Protocol for crate::Binary {}\n\n impl Protocol for crate::Text {}\n\n}\n\n\n\n#[doc(inline)]\n\npub use crate::myc::params;\n\n\n\n#[doc(hidde...
Rust
tests/fuzz.rs
johannesvollmer/rust-openexr
404e2a123fb8191e86067c3d56fc045113d02161
use std::panic::{catch_unwind}; use rand::rngs::{StdRng}; use rand::{Rng}; extern crate exr; use exr::prelude::*; use std::path::PathBuf; use std::ffi::OsStr; use std::fs::File; use std::io::{Write, Cursor}; use exr::image::read::read_first_rgba_layer_from_file; use exr::image::pixel_vec::PixelVec; fn exr_files(pat...
use std::panic::{catch_unwind}; use rand::rngs::{StdRng}; use rand::{Rng}; extern crate exr; use exr::prelude::*; use std::path::PathBuf; use std::ffi::OsStr; use std::fs::File; use std::io::{Write, Cursor}; use exr::image::read::read_first_rgba_layer_from_file; use exr::image::pixel_vec::PixelVec; fn exr_files(pat...
tes(); match read_all_data.from_buffered(Cursor::new(file)) { Err(Error::Invalid(error)) => println!("✓ No Panic. [{}]: Invalid: {}.", fuzz_index, error), Err(Error::NotSupported(error)) => println!("- No Panic. [{}]: Unsupported: {}.", fuzz_index, error), ...
pedantic ({}): {:?}", error, file); true } else { println!("✗ Oh no, there is nothing wrong with: {:#?}", file); false } }, _ => unreachable!(), }; } assert!(passed, "A ...
random
[ { "content": "pub fn decompress_bytes(mut remaining: Bytes<'_>, expected_byte_size: usize, pedantic: bool) -> Result<ByteVec> {\n\n let mut decompressed = Vec::with_capacity(expected_byte_size.min(8*2048));\n\n\n\n while !remaining.is_empty() && decompressed.len() != expected_byte_size {\n\n let co...
Rust
src/bin/join.rs
andreaskipf/parquet-sampler
c04e6f07e1872c6c8e1ab85e699206f0e804db6b
use std::collections::HashSet; use std::env; use std::fs::File; use std::path::Path; use parquet::file::reader::{FileReader, SerializedFileReader}; use parquet::schema::types::Type; fn main() { let args: Vec<String> = env::args().collect(); let in_file_name = &args[1]; let in_file_col_name = &args[2]; let ...
use std::collections::HashSet; use std::env; use std::fs::File; use std::path::Path; use parquet::file::reader::{FileReader, SerializedFileReader}; use parquet::schema::types::Type; fn main() { let args: Vec<String> = env::args().collect(); let in_file_name = &args[1]; let in_file_col_name = &args[2]; let ...
let val = row .get_column_iter() .map(|c| c.1.to_string()) .nth(probe_side_col_idx) .unwrap(); if ht.contains(&val) { output_rows.push(row); } curr_row += 1; } println!("finished probing hash table"); println!( "semi-join reduced input by {} rows",...
if curr_row % 1000000 == 0 { println!( "read {}% of input", (curr_row as f64 * 100.0 / num_probe_rows as f64) as usize ); }
if_condition
[ { "content": "pub fn write_output(rows: &Vec<parquet::record::Row>, schema: &Type, file_name: &String) {\n\n // Create output parquet file.\n\n let path = Path::new(&file_name);\n\n let file = File::create(&path).unwrap();\n\n\n\n // Parquet writer requires the schema as a string.\n\n let mut buf = Vec::ne...
Rust
src/day18/mod.rs
hulthe/aoc2002
1bb5fdbd6dcce9670becaf1d6db81c23d21a57d4
#[derive(Clone, Copy, Debug)] pub enum Token { Op(Op), Num(u64), LParen, RParen, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Op { Add, Mul, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum RPN { Op(Op), Num(u64), } pub fn parse<'a>(input: &'a str) -> impl Iterator<Item ...
#[derive(Clone, Copy, Debug)] pub enum Token { Op(Op), Num(u64), LParen, RParen, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Op { Add, Mul, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum RPN { Op(Op), Num(u64), } pub fn parse<'a>(input: &'a str) -> impl Iterator<Item ...
fn evalutate_rpn(ops: &[RPN]) -> u64 { let mut stack = Vec::new(); for &op in ops { match op { RPN::Num(num) => stack.push(num), RPN::Op(op) => { let rhs = stack.pop().expect("invalid op arg count, was 0"); let lhs = stack.pop().expect("invalid ...
k, Some(StackElem::Op(op)) => output.push(RPN::Op(op)), } }, } } while let Some(elem) = stack.pop() { match elem { StackElem::Op(op) => output.push(RPN::Op(op)), StackElem::Stack...
function_block-function_prefixed
[ { "content": "/// Map every (parent, num, child) combination of the input into a closure\n\nfn parse_into<'a, F>(input: &'a str, mut into: F)\n\nwhere\n\n F: FnMut(&'a str, usize, &'a str),\n\n{\n\n for capture in input.lines().flat_map(|line| LINE_RGX.captures(line)) {\n\n let parent = capture.nam...
Rust
exonum/src/runtime/execution_context.rs
mobilipia/milestone-core
53134d0816264f9c60d3b86e28947669c3ccc609
use crate::{ blockchain::Schema as CoreSchema, crypto::{Hash, PublicKey}, helpers::{Height, ValidateInput}, merkledb::{access::Prefixed, BinaryValue, Fork}, runtime::{ ArtifactId, BlockchainData, CallSite, CallType, Caller, CoreError, Dispatcher, DispatcherSchema, ExecutionError, I...
use crate::{ blockchain::Schema as CoreSchema, crypto::{Hash, PublicKey}, helpers::{Height, ValidateInput}, merkledb::{access::Prefixed, BinaryValue, Fork}, runtime::{ ArtifactId, BlockchainData, CallSite, CallType, Caller, CoreError, Dispatcher, DispatcherSchema, ExecutionError, I...
rrectInstanceId)?; if state.status != Some(InstanceStatus::Stopped) { return Err(CoreError::ServiceNotStopped.into()); } let mut spec = state.spec; spec.artifact = artifact; let runtime = self .0 .dispatcher .runtime_by_id(spec.a...
uctor: impl BinaryValue, ) -> Result<(), ExecutionError> { debug_assert!(spec.validate().is_ok(), "{:?}", spec.validate()); let runtime = self .dispatcher .runtime_by_id(spec.artifact.runtime_id) .ok_or(CoreError::IncorrectRuntime)?; let context ...
random
[ { "content": "#[doc(hidden)]\n\npub fn remove_local_migration_result(fork: &Fork, service_name: &str) {\n\n Schema::new(fork)\n\n .local_migration_results()\n\n .remove(service_name);\n\n}\n", "file_path": "exonum/src/runtime/dispatcher/schema.rs", "rank": 0, "score": 440123.2529413...
Rust
weave/tests/forest/product.rs
tclchiam/weave-ce
03c7b01b50111c48f6d1b471a23638825d0dbf0e
use std::fmt::Debug; use weave::Forest; pub fn left_is_empty_right_is_unit<'a, F: Forest<&'a str> + Debug + Eq + Clone>() -> (F, F, F) { let forest1 = F::unit(&["1", "2"]); let forest2 = F::empty(); let expected = F::empty(); (forest1, forest2, expected) } pub fn overlapping_unit_forests<'a, F: For...
use std::fmt::Debug; use weave::Forest; pub fn left_is_empty_right_is_unit<'a, F: Forest<&'a str> + Debug + Eq + Clone>() -> (F, F, F) { let forest1 = F::unit(&["1", "2"]); let forest2 = F::empty(); let expected = F::empty(); (forest1, forest2, expected) } pub fn overlapping_unit_forests<'a, F: For...
let forest2 = F::unique(&["3", "4"]); let expected = F::many(&[ vec!["1", "3"], vec!["1", "4"], vec!["2", "3"], vec!["2", "4"], ]); (forest1, forest2, expected) } pub fn forests_are_disjoint_many<'a, F: Forest<&'a str> + Debug + Eq + Clone>() -> (F, F, F) { let fore...
= F::unit(&["3", "4"]); let expected = F::many(&[ vec!["1", "2", "3", "4"], vec!["5", "6", "3", "4"], ]); (forest1, forest2, expected) } pub fn disjoint_unique_forests<'a, F: Forest<&'a str> + Debug + Eq + Clone>() -> (F, F, F) { let forest1 = F::unique(&["1", "2"]);
random
[ { "content": "pub fn empty_forest<'a, F: Forest<&'a str> + Debug + Eq + Clone>() -> (F, &'a str, F) {\n\n let forest = F::empty();\n\n let element = \"1\";\n\n\n\n let expected = F::empty();\n\n\n\n (forest, element, expected)\n\n}\n\n\n", "file_path": "weave/tests/forest/subset_not.rs", "ra...
Rust
kernel/system/src/ia_32e/cpu/pic.rs
VenmoTools/OperatingSystem
479ce57719c67541ade7d15ed22904d937b80cc4
use super::{Port, UnsafePort}; const EOI: u8 = 0x20; const ICW4: u8 = 0x01; const ICW1: u8 = 0x11; const ICW3_M: u8 = 0x04; const ICW3_S: u8 = 0x02; const MASKED: u8 = 0xff; #[derive(Debug)] struct Pic { offset: u8, command: UnsafePort<u8>, data: UnsafePort<u8>, } impl Pic { fn handle_...
use super::{Port, UnsafePort}; const EOI: u8 = 0x20; const ICW4: u8 = 0x01; const ICW1: u8 = 0x11; const ICW3_M: u8 = 0x04; const ICW3_S: u8 = 0x02; const MASKED: u8
offset: offset_1, command: UnsafePort::new(0x20), data: UnsafePort::new(0x21), }, slave: Pic { offset: offset_2, command: UnsafePort::new(0xA0), data: UnsafePort::new(0xA1), }, } } ...
= 0xff; #[derive(Debug)] struct Pic { offset: u8, command: UnsafePort<u8>, data: UnsafePort<u8>, } impl Pic { fn handle_interrupt(&self, interrupt_id: u8) -> bool { self.offset <= interrupt_id && interrupt_id < self.offset + 8 } unsafe fn end_interrupt(&mut self) {...
random
[ { "content": "pub fn add_scan_code(code: u8) {\n\n let lock = scan_queue_mut();\n\n if let Err(_) = lock.push(code) {\n\n println!(\"scan code queue full dropping keyboard input\")\n\n } else {\n\n SCAN_CODE_WAKER.wake();\n\n }\n\n}\n\n\n\npub struct ScanCodeStream;\n\n\n\nimpl ScanCod...
Rust
src/sfc.rs
sambuc/ironsea_index_sfc_dbc
09cdd3d569848d8281a7de5ec90805a43fb1f7eb
#![allow(clippy::type_repetition_in_bounds)] use std::cmp::PartialEq; use std::fmt::Debug; use std::hash::Hash; use std::iter::FromIterator; use std::ops::Index; pub use ironsea_index::IndexedDestructured; pub use ironsea_index::Record; pub use ironsea_index::RecordFields; use serde::Deserialize; use serde::Seriali...
#![allow(clippy::type_repetition_in_bounds)] use std::cmp::PartialEq; use std::fmt::Debug; use std::hash::Hash; use std::iter::FromIterator; use std::ops::Index; pub use ironsea_index::IndexedDestructured; pub use ironsea_index::Record; pub use ironsea_index::RecordFields; use serde::Deserialize; use serde::Seriali...
fn find_range<'i>(&'i self, start: &K, end: &K) -> Box<dyn Iterator<Item = (K, &F)> + 'i> { match self.limits(start, end) { Ok(limits) => { let iter = (limits.start.idx..limits.end.idx) .filter_map(move |idx| { match self.value(self.i...
e } }, )); } } } } Box::new(Vec::with_capacity(0).into_iter()) }
function_block-function_prefixed
[ { "content": "#[derive(Clone, Debug, Deserialize, Serialize)]\n\nstruct CellDictionary<K, V> {\n\n table: Vec<Cell<V>>,\n\n max_offset: usize,\n\n _marker: marker::PhantomData<K>,\n\n}\n\n\n\nimpl<K, V> CellDictionary<K, V>\n\nwhere\n\n K: Debug + Index<usize, Output = V>,\n\n V: Clone + Debug + ...
Rust
src/world/mod.rs
tgolsson/physics2d-rs
ff7b4cf4f06fa54c43148fbb2e26cdb6342fb50c
mod body; mod collections; pub mod debug; mod transform; pub(crate) use self::body::BodyPair; pub use self::body::{Body, BodyId, Material}; pub(crate) use self::collections::{Bodies, ConstraintsMap}; pub use self::transform::Transform; use crate::{ collision::broad_phase::{BoundsTreeBroadPhase, BroadPhase}, c...
mod body; mod collections; pub mod debug; mod transform; pub(crate) use self::body::BodyPair; pub use self::body::{Body, BodyId, Material}; pub(crate) use self::collections::{Bodies, ConstraintsMap}; pub use self::transform::Transform; use crate::{ collision::broad_phase::{BoundsTreeBroadPhase, BroadPhase}, c...
}
itialize_velocity(&self.bodies, dt); self.contact_constraints .warm_start_velocity(&mut self.bodies, dt); self.joints.initialize_velocity(&self.bodies, dt); self.joints.warm_start_velocity(&mut self.bodies, dt); for _ in 0..self.velocity_iterations { self.joints...
function_block-function_prefixed
[ { "content": "/// Clamps (limits) the value of `x` in the inclusive range from `0.0` to `1.0`.\n\n///\n\n/// If `x < 0.0`, `0.0` is returned. If `x > 1.0`, `1.0` is returned.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # use physics2d::math::clamp01;\n\n///\n\n/// assert_eq!(clamp01(-10.0), 0.0);\n\n/// a...
Rust
c2rust-refactor/src/scripting/ast_visitor.rs
martin-t/c2rust
f565bc63d87f15f79b5b232cb7155eb8ec5bbfe2
use rlua::prelude::{LuaFunction, LuaResult, LuaTable}; macro_rules! call_lua_visitor_method { ($obj: expr , $method: ident ($($params: expr),*)) => { let opt_visit_method: Option<LuaFunction> = $obj.get(stringify!($method))?; if let Some(visit_method) = opt_visit_method { let proceed =...
use rlua::prelude::{LuaFunction, LuaResult, LuaTable}; macro_rules! call_lua_visitor_method { ($obj: expr , $method: ident ($($params: expr),*)) => { let opt_visit_method: Option<LuaFunction> = $obj.get(stringify!($method))?; if let Some(visit_method) = opt_visit_method { let proceed =...
pub fn finish(&self) -> LuaResult<()> { call_lua_visitor_method!(self.visitor,finish()); Ok(()) } }
call_lua_visitor_method!(self.visitor,visit_fn_like(fn_like)); let opt_block = fn_like.get("block")?; if let Some(block) = opt_block { self.visit_block(block)?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "fn build_struct_update(path: Path, fields: Vec<Field>, base: P<Expr>) -> Stmt {\n\n mk().semi_stmt(\n\n mk().assign_expr(\n\n &base,\n\n mk().struct_expr_base(path, fields, Some(&base))))\n\n}\n\n\n\n\n\n/// # `rename_struct` Command\n\n/// \n\n/// Obsolete - use `r...
Rust
examples/d3d12/compute/main.rs
LNSEAB/dxplr
06aa9329e889dbefaeb4e28669a8eb5547c3a1ea
use dxplr::d3d::IBlob; use dxplr::d3d12::{ ICommandAllocator, ICommandQueue, IDebug, IDescriptorHeap, IDevice, IFence, IGraphicsCommandList, IResource, }; use dxplr::{d3d, d3d12, dxgi}; use std::fs::File; use std::io::{BufReader, Read}; fn main() { let _d3d12_debug = { let debug = d3d12::get_debug_...
use dxplr::d3d::IBlob; use dxplr::d3d12::{ ICommandAllocator, ICommandQueue, IDebug, IDescriptorHeap, IDevice, IFence, IGraphicsCommandList, IResource, }; use dxplr::{d3d, d3d12, dxgi}; use std::fs::File; use std::io::{BufReader, Read};
fn main() { let _d3d12_debug = { let debug = d3d12::get_debug_interface::<d3d12::Debug>().unwrap(); debug.enable_debug_layer(); debug }; let device = d3d12::create_device::<d3d12::Device>(None, d3d::FeatureLevel(12, 0)).unwrap(); let cmd_allocator = device .create_command...
function_block-full_function
[]
Rust
src/main.rs
satylogin/rss-update
5df10fa56ba515df06b6b94605f13b53de772415
pub(crate) mod config; pub(crate) mod display; pub(crate) mod feeds; pub(crate) mod readlist; use chrono::{DateTime, NaiveDate, Utc}; use clap::{App, Arg, ArgMatches}; use std::error::Error; use std::fs; use std::path::Path; pub(crate) fn base_dir() -> String { let base_path = Path::new(&dirs::home_dir().unwrap()...
pub(crate) mod config; pub(crate) mod display; pub(crate) mod feeds; pub(crate) mod readlist; use chrono::{DateTime, NaiveDate, Utc}; use clap::{App, Arg, ArgMatches}; use std::error::Error; use std::fs; use std::path::Path; pub(crate) fn base_dir() -> String { let base_path = Path::new(&dirs::home_dir().unwrap()...
async fn main() -> Result<(), Box<dyn Error>> { let args = parse_args(); match args.subcommand() { (UNREAD, Some(_)) => unread(), (ADD, Some(s_args)) => add_feed(s_args), (SETUP, Some(_)) => setup(), (TRACKING, Some(_)) => tracking(), (REMOVE, Some(s_args)) => remove_feed...
function_block-full_function
[ { "content": "fn _mark_read(mut readlist: ReadList, post: &str) -> ReadList {\n\n for to_read in readlist.values_mut() {\n\n *to_read = to_read\n\n .iter()\n\n .filter(|p| **p != post)\n\n .map(std::clone::Clone::clone)\n\n .collect::<Vec<_>>();\n\n }\n\n...
Rust
weechat/src/hooks/modifier.rs
troethe/rust-weechat
8533abf0e000659f567e404d3c8aa0d773eff685
use libc::c_char; use std::{borrow::Cow, ffi::CStr, os::raw::c_void, ptr}; use weechat_sys::{t_gui_buffer, t_weechat_plugin}; use super::Hook; use crate::{buffer::Buffer, LossyCString, Weechat}; #[cfg_attr(feature = "docs", doc(cfg(unsound)))] pub struct ModifierHook { _hook: Hook, _hook_data: Box<ModifierHo...
use libc::c_char; use std::{borrow::Cow, ffi::CStr, os::raw::c_void, ptr}; use weechat_sys::{t_gui_buffer, t_weechat_plugin}; use super::Hook; use crate::{buffer::Buffer, LossyCString, Weechat}; #[cfg_attr(feature = "docs", doc(cfg(unsound)))] pub struct ModifierHook { _hook: Hook, _hook_data: Box<ModifierHo...
}
e { Weechat::weechat() }; let data = Box::new(ModifierHookData { callback: Box::new(callback), weechat_ptr: weechat.ptr, }); let data_ref = Box::leak(data); let hook_modifier = weechat.get().hook_modifier.unwrap(); let modifier_name = LossyCString::new(...
function_block-function_prefixed
[ { "content": "/// Trait for the bar item callback\n\n///\n\n/// A blanket implementation for pure `FnMut` functions exists, if data needs to\n\n/// be passed to the callback implement this over your struct.\n\npub trait BarItemCallback: 'static {\n\n /// The callback that should be called after the bar items...
Rust
src/widget/menu/menu_entry.rs
codec-abc/kas
5193ecd446e2147e7eb60e0081c1f66af049f244
use std::fmt::{self, Debug}; use super::Menu; use kas::class::{CloneText, HasBool, SetAccel}; use kas::draw::TextClass; use kas::event::VirtualKeyCodes; use kas::layout::{RulesSetter, RulesSolver}; use kas::prelude::*; use kas::widget::{AccelLabel, CheckBoxBare}; #[widget(config=noauto)] #[handler(handle=noauto)] #...
use std::fmt::{self, Debug}; use super::Menu; use kas::class::{CloneText, HasBool, SetAccel}; use kas::draw::TextClass; use kas::event::VirtualKeyCodes; use kas::layout::{RulesSetter, RulesSolver}; use kas::prelude::*; use kas::widget::{AccelLabel, CheckBoxBare}; #[widget(config=noauto)] #[handler(handle=noauto)] #...
#[inline] pub fn on_toggle<M, F>(self, f: F) -> MenuToggle<M> where F: Fn(bool) -> M + 'static, { MenuToggle { core: self.core, layout_data: self.layout_data, checkbox: self.checkbox.on_toggle(f), label: self.label, ...
pub fn new<T: Into<AccelString>>(label: T) -> Self { MenuToggle { core: Default::default(), layout_data: Default::default(), checkbox: CheckBoxBare::new(), label: AccelLabel::new(label), } }
function_block-full_function
[ { "content": "struct WidgetHeirarchy<'a>(&'a dyn WidgetConfig, usize);\n\nimpl<'a> fmt::Display for WidgetHeirarchy<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {\n\n write!(\n\n f,\n\n \"\\n{}{}\\t{}\\tpos={:?}\\tsize={:?}\",\n\n \"- \".re...
Rust
src/sc-core/src/services/public_api/mod.rs
vinimin/fluvio
142c050a2f1aaa83aeda19705fedd670fffaf1a1
mod public_server; mod flv; mod kf; mod api { pub use super::flv::api_versions_req::*; pub use super::kf::metadata_req::*; pub use super::flv::create_topics_req::*; pub use super::flv::delete_topics_req::*; pub use super::flv::fetch_topics_req::*; pub use super::flv::...
mod public_server; mod flv; mod kf; mod api { pub use super::flv::api_versions_req::*; pub use super::kf::metadata_req::*; pub use super::flv::create_topics_req::*; pub use super::flv::delete_topics_req::*; pub use super::flv::fetch_topics_req::*; pub use super::flv::...
Ok(()) } pub async fn delete<S>( &self, name: &str, ) -> Result<(),C::MetadataClientError> where S: K8Spec + Serialize + Default + Debug + Clone + DeserializeOwned , <S as K8Spec>::Status: Default + Debug + DeserializeOwned { ...
ersion: S::api_version(), kind: S::kind(), metadata: InputObjectMeta { name, namespace: self.namespace.clone(), ..Default::default() }, spec, ..Default::default() }; ...
random
[ { "content": "// start server\n\npub fn create_public_server(addr: SocketAddr, ctx: DefaultSharedGlobalContext) -> PublicApiServer\n\n{\n\n info!(\"starting SPU: {} at public service at: {}\", ctx.local_spu_id(),addr);\n\n\n\n KfApiServer::new(addr, ctx, PublicService::new())\n\n}\n", "file_path": "sr...
Rust
src/filter.rs
jos61404/ffm
e8afb9025a457013c05d5012069c416492aa4135
use crate::file::{isolation_extension, isolation_name}; use console::style; use indicatif::ProgressBar; use std::convert::TryInto; use std::path::*; #[derive(Debug)] pub struct FilterDataStruct { pub path: PathBuf, pub dir_name: String, pub file_name: String, } pub fn name( pb_filter_name: ProgressBar...
use crate::file::{isolation_extension, isolation_name}; use console::style; use indicatif::ProgressBar; use std::convert::TryInto; use std::path::*; #[derive(Debug)] pub struct FilterDataStruct { pub path: PathBuf, pub dir_name: String, pub file_name: String, } pub fn name( pb_filter_name: ProgressBar...
_message(&format!( "{} 過濾副名 : {}", style("[5/6]").bold().dim(), "完成" )); pb_filter_extension.finish(); return Ok(filter_data); }
er_name.set_message(&format!( "{} 過濾名稱 : {}", style("[4/6]").bold().dim(), "完成" )); pb_filter_name.finish(); return Ok(filter_data); } pub fn extension( pb_filter_extension: ProgressBar, pb_copy_file: &ProgressBar, filter_path: &String, paths: &Vec<PathBuf>, filt...
random
[ { "content": "pub fn add(original_path: &Path, file_path: String, file_name: String) -> std::io::Result<()> {\n\n let mut log_path = String::from(&file_path);\n\n log_path.push_str(\"/log.txt\");\n\n\n\n let mut log_file = fs::OpenOptions::new()\n\n .read(true)\n\n .write(true)\n\n ...
Rust
crates/rune-cli/src/inspect.rs
ferrous-systems/rune
11d752759003ee2707efb904f596cbe8f9ee07a6
use std::{ collections::{BTreeMap, HashMap}, path::PathBuf, }; use anyhow::{Context, Error}; use build_info::BuildInfo; use hotg_rune_syntax::{ hir::{HirId, Rune, SourceKind}, yaml::{Type, Value}, }; use serde::{Serialize, Serializer}; use strum::VariantNames; use wasmparser::{Parser, Payload}; use crat...
use std::{ collections::{BTreeMap, HashMap}, path::PathBuf, }; use anyhow::{Context, Error}; use build_info::BuildInfo; use hotg_rune_syntax::{ hir::{HirId, Rune, SourceKind}, yaml::{Type, Value}, }; use serde::{Serialize, Serializer}; use strum::VariantNames; use wasmparser::{Parser, Payload}; use crat...
} fn resolve_type(rune: &Rune, type_id: HirId) -> Type { let (primitive, dims) = match &rune.types[&type_id] { hotg_rune_syntax::hir::Type::Primitive(p) => (p, vec![1]), hotg_rune_syntax::hir::Type::Buffer { underlying_type, dimensions, } => match &rune.types[underl...
s, outputs, }, ); }, hotg_rune_syntax::hir::Stage::Sink(_) => {}, hotg_rune_syntax::hir::Stage::Model(_) => {}, hotg_rune_syntax::hir::Stage::ProcBlock(_) => {}, } ...
function_block-function_prefixed
[ { "content": "fn generate_graph(w: &mut dyn Write, rune: &Rune) -> Result<(), Error> {\n\n writeln!(w, \"digraph {{\")?;\n\n writeln!(w, \" rankdir=TD;\")?;\n\n writeln!(w, \" node [shape=plaintext];\")?;\n\n\n\n declare_nodes(w, &rune.stages, &rune.names)?;\n\n declare_edges(w, &rune)?;\n\n\n\...
Rust
src/helpers.rs
jmagnuson/uds
e35887f3468d5917c4a36b8a6936732efeb2b9ee
/* See each function for copyright holders */ use std::os::unix::io::{RawFd, AsRawFd, IntoRawFd}; use std::io::{self, ErrorKind}; use std::mem; use libc::{c_int, sockaddr, socklen_t, AF_UNIX}; use libc::{bind, connect, getsockname, getpeername}; use libc::{socket, accept, close, listen, socketpair}; use libc::{ioctl,...
/* See each function for copyright holders */ use std::os::unix::io::{RawFd, AsRawFd, IntoRawFd}; use std::io::{self, ErrorKind}; use std::mem; use libc::{c_int, sockaddr, socklen_t, AF_UNIX}; use libc::{bind, connect, getsockname, getpeername}; use libc::{socket, accept, close, listen, socketpair}; use libc::{ioctl,...
pub fn bind_to(socket: RawFd, addr: &UnixSocketAddr) -> Result<(), io::Error> { unsafe { set_unix_addr(socket, bind, addr) } } pub fn connect_to(socket: RawFd, addr: &UnixSocketAddr) -> Result<(), io::Error> { unsafe { set_unix_addr(socket, connect, addr) } } type GetSide = unsafe extern "C" fn(RawFd, *mu...
let err = io::Error::last_os_error(); if err.kind() != ErrorKind::Interrupted { break Err(err); } } }
function_block-function_prefix_line
[ { "content": "pub fn peer_credentials(_: RawFd) -> Result<ConnCredentials, io::Error> {\n\n Err(io::Error::new(Other, \"not available\"))\n\n}\n\n\n\n\n\n\n\n#[cfg(any(target_os=\"linux\", target_os=\"android\"))]\n\npub type RawReceivedCredentials = libc::ucred;\n\n\n\n\n\n/// Process credentials received t...
Rust
cs39/src/compile.rs
gretchenfrage/CS639S20_Demos
d75a16cf66b6b95eb74fc8f101020672b62e5a90
use crate::navigate::{find_demo, DemoLookup}; use std::{ path::{Path, PathBuf}, ffi::{OsStr, OsString}, fs::{ self, read_to_string, read_dir, create_dir_all, FileType }, env, collections::HashMap, process::{ Command, ExitStatus, } ...
use crate::navigate::{find_demo, DemoLookup}; use std::{ path::{Path, PathBuf}, ffi::{OsStr, OsString}, fs::{ self, read_to_string, read_dir, create_dir_all, FileType }, env, collections::HashMap, process::{ Command, ExitStatus, } ...
edit(&mut code); let temp = repo.as_ref().join("tmp").join(format!("rng-{}", random::<u16>())); println!("[INFO] building code in {:?}", temp); create_dir_all(&temp).unwrap(); for (file, content) in code { let path = temp.join(file); fs::write(path,...
let mut code: HashMap<OsString, String> = cpp_files(&path) .map(|file| ( file.clone(), read_to_string(path.join(file)).unwrap() )) .collect();
assignment_statement
[ { "content": "/// `run` task.\n\npub fn run_demo(lookup: &DemoLookup, major: u32, minor: u32) -> Result<(), ()> {\n\n let Compiled { workdir, binary } = compile(lookup, major, minor)?;\n\n \n\n println!(\"[INFO] running\");\n\n println!();\n\n let status = Command::new(&binary)\n\n .curren...
Rust
src/model/readout/xi.rs
merfishtools/merfishtools
3a9d5e749a9f5d8df7a15936beb8cf34ff135bda
use std::mem; use itertools::Itertools; use ndarray::prelude::*; use bio::stats::{LogProb, Prob}; use crate::io::codebook::Codeword; pub struct Xi { p0: Vec<LogProb>, p1: Vec<LogProb>, } impl Xi { pub fn new(p0: &[Prob], p1: &[Prob]) -> Self { let tolog = |&p| LogP...
use std::mem; use itertools::Itertools; use ndarray::prelude::*; use bio::stats::{LogProb, Prob}; use crate::io::codebook::Codeword; pub struct Xi { p0: Vec<LogProb>, p1: Vec<LogProb>, } impl Xi { pub fn new(p0: &[Prob], p1: &[Prob]) -> Self { let tolog = |&p| LogP...
truth_mismatch); } }
truth - p1 + p1.ln_one_minus_exp(), truth - p0 + p0.ln_one_minus_exp(), ]); assert_relative_eq!(*p[1], *truth_mismatch, epsilon = 0.001); } #[test] fn test_xi_exact_total() { let p0 = LogProb::from(Prob(0.005)); let p1 = LogProb::from(Pr...
random
[ { "content": "pub fn parse_codeword(codeword: &[u8]) -> Codeword {\n\n let mut _codeword = BitVec::with_capacity(codeword.len());\n\n for &b in codeword {\n\n if b == b'1' {\n\n _codeword.push(true);\n\n } else if b == b'0' {\n\n _codeword.push(false)\n\n } else ...
Rust
src/jot.rs
brian-dawn/jot
411acce3d7dd7c72954adf162d59fc3a15fb0184
use anyhow::Result; use chrono::prelude::*; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::path::PathBuf; use colorful::Colorful; use itertools::Itertools; use regex::Regex; use std::collections::HashSet; use crate::config; use crate::constants::*; use crate::utils; use crate::utils::{count...
use anyhow::Result; use chrono::prelude::*; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::path::PathBuf; use colorful::Colorful; use itertools::Itertools; use regex::Regex; use std::collections::HashSet; use crate::config; use crate::constants::*; use crate::utils; use crate::utils::{count...
} pub fn stream_jots(config: config::Config, reversed: bool) -> Result<impl Iterator<Item = Jot>> { assert!(config.journal_path.is_dir()); let mut dirs = std::fs::read_dir(config.journal_path)? .map(|entry| Ok(entry?.path())) .collect::<Result<Vec<_>>>()?; if reversed { dirs.sort...
e))), )) } } _ => Some((id_part, MessageType::Note)), } }
function_block-function_prefixed
[ { "content": "/// Pluralize words e.g. Hour => Hours, etc.\n\npub fn pluralize_time_unit(amount: i64, time_unit: &str) -> String {\n\n if amount == 1 {\n\n return time_unit.to_string();\n\n }\n\n return format!(\"{}s\", time_unit);\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 0, ...
Rust
libs/bart_derive/src/parser.rs
maghoff/stache
9f947b550b48427f3e207491c64cba4457b105ff
use ast::Ast; use std::iter::*; use token::*; #[derive(Debug)] pub enum Error<'a> { Mismatch { expected: &'static str, found: Option<Token<'a>> } } fn section<'a, T>(token_stream: &mut Peekable<T>) -> Result<Ast<'a>, Error<'a>> where T: Iterator<Item=Token<'a>> { let (section_type, name) = match token_str...
use ast::Ast; use std::iter::*; use token::*; #[derive(Debug)] pub enum Error<'a> { Mismatch { expected: &'static str, found: Option<Token<'a>> } } fn section<'a, T>(token_stream: &mut Peekable<T>) -> Result<Ast<'a>, Error<'a>> where T: Iterator<Item=Token<'a>> { let (section_type, name) = match token_str...
#[test] fn simple_scope() { assert_eq!( Ast::Sequence(vec![ Ast::Literal("text a"), Ast::Scope { name: simple_name("x"), nested: Box::new(Ast::Sequence(vec![ Ast::Literal("text b"), ...
fn simple_negative_conditional() { assert_eq!( Ast::Sequence(vec![ Ast::Literal("text a"), Ast::NegativeConditional { name: simple_name("x"), nested: Box::new(Ast::Sequence(vec![ Ast::Literal("text b"), ...
function_block-full_function
[ { "content": "#[cfg(test)]\n\npub fn simple_name(name: &'static str) -> Name<'static> {\n\n Name {\n\n leading_dots: 0,\n\n segments: vec![name],\n\n function_call: false,\n\n }\n\n}\n", "file_path": "libs/bart_derive/src/token.rs", "rank": 0, "score": 232040.98408252635 ...
Rust
cli/tools/vendor/mod.rs
divy-work/deno
5bde4c7ecae35cb29a003504eafa03f1776ee3a0
use std::path::Path; use std::path::PathBuf; use deno_ast::ModuleSpecifier; use deno_core::anyhow::bail; use deno_core::anyhow::Context; use deno_core::error::AnyError; use deno_core::resolve_url_or_path; use deno_runtime::permissions::Permissions; use log::warn; use crate::config_file::FmtOptionsConfig; use crate:...
use std::path::Path; use std::path::PathBuf; use deno_ast::ModuleSpecifier; use deno_core::anyhow::bail; use deno_core::anyhow::Context; use deno_core::error::AnyError; use deno_core::resolve_url_or_path; use deno_runtime::permissions::Permissions; use log::warn; use crate::config_file::FmtOptionsConfig; use crate:...
.unwrap(); assert_eq!( text, r#"{ "tasks": { "task1": "other" }, "importMap": "./vendor/import_map.json" } "# ); } #[test] fn update_config_text_update_prop() { let text = update_config_text( r#"{ "importMap": "./local.json" } "#, "./vendor/import_map.json", ...
update_config_text( r#"{ "tasks": { "task1": "other" } } "#, "./vendor/import_map.json", &Default::default(), )
call_expression
[ { "content": "fn success_text(module_count: &str, dir: &str, has_import_map: bool) -> String {\n\n let mut text = format!(\"Vendored {} into {} directory.\", module_count, dir);\n\n if has_import_map {\n\n text.push_str(&\n\n format!(\n\n concat!(\n\n \"\\n\\nTo use vendored modules, s...
Rust
bn-expression/src/basic.rs
Bindernews/minblur
7915e7d8765eb3785da4fabda38e744702ec5985
use std::collections::HashMap; use std::{cmp::Ordering, fmt}; use nom::InputTake; use crate::{enum_to_from_str, error::EvalError, expression::EvalContext, AValue, ExpressionOp}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub enum BasicOp { Add,...
use std::collections::HashMap; use std::{cmp::Ordering, fmt}; use nom::InputTake; use crate::{enum_to_from_str, error::EvalError, expression::EvalContext, AValue, ExpressionOp}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub enum BasicOp { Add,...
fn precedence(&self) -> usize { match self { Self::Mul | Self::Div | Self::Mod | Self::IDiv => 1, Self::Add | Self::Sub => 2, Self::BAnd | Self::BOr | Self::BXor => 4, Self::LAnd | Self::LOr | Self::LXor => 5, Self::Shl | Self::Shr => 6, ...
Self::BOr => left.apply_int_math(right, "||", |lh, rh| lh | rh), Self::BXor => left.apply_int_math(right, "^^", |lh, rh| lh ^ rh), Self::Not => Ok((!left.is_truthy()).into()), Self::Equal => helper_cmp(left, right, |f| f.is_eq()), Self::NotEqual => helper_cmp(left, right,...
function_block-function_prefix_line
[ { "content": "/// Returns a nom error if the input string isn't empty\n\n///\n\n/// Param `f` should generate an approriate error given the input\n\npub fn assert_input_consumed<'a, F, O>(mut f: F) -> impl FnMut(Span<'a>) -> MyResult<'a, ()>\n\nwhere\n\n F: Parser<Span<'a>, O, ErrType<'a>>,\n\n{\n\n move ...
Rust
examples/stm32l0x2/main.rs
lulf/rust-sx12xx
b055776e945041d91a6b52430c702aaa228031b7
#![cfg_attr(not(test), no_std)] #![no_main] extern crate nb; extern crate panic_rtt_target; use log::LevelFilter; use panic_rtt_target as _; use rtt_logger::RTTLogger; use rtt_target::rtt_init_print; use core::fmt::Write; use lorawan_crypto::LorawanCrypto as Crypto; use lorawan_device::{ radio, Device as Lorawan...
#![cfg_attr(not(test), no_std)] #![no_main] extern crate nb; extern crate panic_rtt_target; use log::LevelFilter; use panic_rtt_target as _; use rtt_logger::RTTLogger; use rtt_target::rtt_init_print; use core::fmt::Write; use lorawan_crypto::LorawanCrypto as Crypto; use lorawan_device::{ radio, Device as Lorawan...
resources.timer_context.lock(|context| { context.enable = false; }); } LorawanResponse::NoJoinAccept => { log::info!("No Join Accept Received"); ctx.spawn .lorawan_event(LorawanEve...
int: exti, button, radio_irq, lorawan: Some(lorawan), timer, } } #[idle(resources = [button], spawn = [send_ping])] fn idle(ctx: idle::Context) -> ! { let mut pressed = true; loop { if ctx.resources.button.is_low()....
random
[ { "content": "pub fn new(\n\n spi_peripheral: pac::SPI1,\n\n rcc: &mut Rcc,\n\n spi_sck: gpiob::PB3<Uninitialized>,\n\n spi_miso: gpioa::PA6<Uninitialized>,\n\n spi_mosi: gpioa::PA7<Uninitialized>,\n\n spi_nss_pin: gpioa::PA15<Uninitialized>,\n\n reset: gpioc::PC0<Uninitialized>,\n\n rx:...
Rust
src/parser.rs
jackmott/evolution
a88c4b2501bf9fb9bdb00eb9bbd2e85720d715d4
use std::sync::mpsc::*; #[derive(Debug, PartialEq)] pub enum Token<'a> { OpenParen(usize), CloseParen(usize), Operation(&'a str, usize), Constant(&'a str, usize), } struct StateFunction(fn(&mut Lexer) -> Option<StateFunction>); pub struct Lexer<'a> { input: &'a str, start: usize, pos: usi...
use std::sync::mpsc::*; #[derive(Debug, PartialEq)] pub enum Token<'a> { OpenParen(usize), CloseParen(usize), Operation(&'a str, usize), Constant(&'a str, usize), } struct StateFunction(fn(&mut Lexer) -> Option<StateFunction>); pub struct Lexer<'a> { input: &'a str, start: usize, pos: usi...
l.emit(Token::OpenParen(l.current_line)); } else if c == ')' { l.emit(Token::CloseParen(l.current_line)); } else if Lexer::is_start_of_number(c) { return Some(StateFunction(Lexer::lex_number)); ...
e)); } else { l.emit(Token::Constant(&l.input[l.start..l.pos], l.current_line)); } return Some(StateFunction(Lexer::determine_token)); } fn determine_token(l: &mut Lexer) -> Option<StateFunction> { loop { match l.next() { Some(c) => { ...
random
[ { "content": "pub fn extract_line_number(token: &Token) -> usize {\n\n match token {\n\n Token::OpenParen(ln) | Token::CloseParen(ln) => *ln,\n\n Token::Constant(_, ln) | Token::Operation(_, ln) => *ln,\n\n }\n\n}\n\n\n", "file_path": "src/pic.rs", "rank": 1, "score": 119992.6993...
Rust
pathfinder/src/diff_solver/post_processing_v5/bt/mod.rs
Simula-UiB/CRHS
8f3dd34c8b99680188d9314c6897e0c790f5358f
pub mod bthandler_trait; use std::collections::BTreeMap; use std::collections::hash_map::DefaultHasher; use std::convert::TryFrom; use std::hash::{Hash, Hasher}; use std::io::{Error, ErrorKind}; pub const PROB_FACTOR: usize = 1000; #[derive(Debug, Clone,)] pub struct BaseTable { table: Vec<Vec<usize>>, prob...
pub mod bthandler_trait; use std::collections::BTreeMap; use std::collections::hash_map::DefaultHasher; use std::convert::TryFrom; use std::hash::{Hash, Hasher}; use std::io::{Error, ErrorKind}; pub const PROB_FACTOR: usize = 1000; #[derive(Debug, Clone,)] pub struct BaseTable { table: Vec<Vec<usize>>, prob...
let mut s = DefaultHasher::new(); self.table.hash(&mut s); s.finish() } fn calculate_k(table: &Vec<Vec<usize>>, probs: &BTreeMap<usize, usize>) -> f64 { let mut counts = BTreeMap::new(); for row in 1..table.len() { for col in 1.. table[0].l...
.expect("Entry not found: Index out of bounds")) .collect() } pub fn nr_of_rows(&self) -> usize { self.table.len() } pub fn nr_of_columns(&self) -> usize { self.table[0].len() } pub fn get_entry(&self, row: u8, column: u8) -> Option<usize> { self.table.ge...
random
[ { "content": "/// bools to less than 8. Takes 'chunk_size' number of bits from 'bits' and turns them into an u8.\n\n /// Returns a vector with the u8's.\n\npub fn bools_to_lt8(bits: &[bool], chunk_size: usize) -> Vec<u8> {\n\n if chunk_size > 8 {\n\n panic!(\"Chunk-sizes above 8 won't fit in an u8!...
Rust
providers/sgx/sgx-app/src/sgx_app.rs
chatchai-hub/tmkms-light
972a739277002704308bfc4e75a0cfa79f62bbb6
pub(crate) mod keypair_seal; mod state; mod cloud; use ed25519_dalek::Keypair; use rand::rngs::OsRng; use sgx_isa::{Report, Targetinfo}; use std::{io, net::TcpStream, thread, time::Duration}; use subtle::ConstantTimeEq; use tendermint_p2p::secret_connection::{self, PublicKey, SecretConnection}; use tmkms_light::{ ...
pub(crate) mod keypair_seal; mod state; mod cloud; use ed25519_dalek::Keypair; use rand::rngs::OsRng; use sgx_isa::{Report, Targetinfo}; use std::{io, net::TcpStream, thread, time::Duration}; use subtle::ConstantTimeEq; use tendermint_p2p::secret_connection::{self, PublicKey, SecretConnection}; use tmkms_light::{ ...
} else { error!("sealing failed"); } } SgxInitRequest::KeyGen { cloud_backup } => { let kp = Keypair::generate(&mut csprng); let cloud_backup_key_data = cloud_backup.and_then(|key| cloud::cloud_backup(&mut csprng, key, &kp)...
match serde_json::to_vec(&response) { Ok(v) => { debug!("writing response"); write_u16_payload(&mut host_response, &v)?; } Err(e) => { error!("keygen error: {}", e); } ...
if_condition
[]
Rust
src/app/components/now_playing/now_playing_model.rs
bertob/spot
ef3309cecf3050ea46a2b714aa36b7ce0e8de549
use gettextrs::gettext; use gio::prelude::*; use gio::SimpleActionGroup; use std::ops::Deref; use std::rc::Rc; use crate::app::components::SimpleHeaderBarModel; use crate::app::components::{labels, PlaylistModel}; use crate::app::models::SongDescription; use crate::app::models::SongListModel; use crate::app::state::Se...
use gettextrs::gettext; use gio::prelude::*; use gio::SimpleActionGroup; use std::ops::Deref; use std::rc::Rc; use crate::app::components::SimpleHeaderBarModel; use crate::app::components::{labels, PlaylistModel}; use crate::app::models::SongDescription; use crate::app::models::SongListModel; use crate::app::state::Se...
fn select_song(&self, id: &str) { let queue = self.queue(); if let Some(song) = queue.songs().get(id) { let song = song.description().clone(); self.dispatcher .dispatch(SelectionAction::Select(vec![song]).into()); } } fn deselect_song(&self,...
menu.append(Some(&*labels::VIEW_ALBUM), Some("song.view_album")); for artist in song.artists.iter() { menu.append( Some(&labels::more_from_label(&artist.name)), Some(&format!("song.view_artist_{}", artist.id)), ); } menu.append(Some(&*labe...
function_block-function_prefix_line
[ { "content": "pub fn n_songs_selected_label(n: usize) -> String {\n\n // this is just to fool xgettext, it doesn't like macros (or rust for that matter) :(\n\n if cfg!(debug_assertions) {\n\n // translators: This shows up when in selection mode. This text should be as short as possible.\n\n ...
Rust
src/interchange/src/json.rs
josharenberg/materialize
afbd0685b98a06ba1603274d4550d0606b955284
use std::collections::HashSet; use repr::adt::numeric::{NUMERIC_AGG_MAX_PRECISION, NUMERIC_DATUM_MAX_PRECISION}; use repr::{ColumnName, ColumnType, ScalarType}; use serde_json::json; fn build_row_schema_field<F: FnMut() -> String>( namer: &mut F, names_seen: &mut HashSet<String>, typ: &ColumnType, ) -> ...
use std::collections::HashSet; use repr::adt::numeric::{NUMERIC_AGG_MAX_PRECISION, NUMERIC_DATUM_MAX_PRECISION}; use repr::{ColumnName, ColumnType, ScalarType}; use serde_json::json; fn build_row_schema_field<F: FnMut() -> String>( namer: &mut F, names_seen: &mut HashSet<String>, typ: &ColumnType, ) -> ...
; json!({ "type": "record", "fields": fields, "name": name }) }
build_row_schema_fields(columns, &mut Default::default(), &mut move || { let ret = format!("com.materialize.sink.record{}", name_idx); name_idx += 1; ret })
call_expression
[ { "content": "pub fn format_string<F>(buf: &mut F, s: &str) -> Nestable\n\nwhere\n\n F: FormatBuffer,\n\n{\n\n buf.write_str(s);\n\n Nestable::MayNeedEscaping\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 1, "score": 458584.64644809946 }, { "content": "pub fn format_u...
Rust
src/lib.rs
alexsnaps/cachers
89853ee9191570f7c15b85ef585a91b6412140dc
#![cfg_attr(feature = "unstable", feature(test))] pub mod asynchronous; mod eviction; mod segment; mod segment2; use std::ops::Fn; use std::sync::{Arc, RwLock}; use crate::segment::Segment; pub struct CacheThrough<K, V> { data: RwLock<Segment<K, V>>, } impl<K, V> CacheThrough<K, V> where K: std::cmp::Eq + st...
#![cfg_attr(feature = "unstable", feature(test))] pub mod asynchronous; mod eviction; mod segment; mod segment2; use std::ops::Fn; use std::sync::{Arc, RwLock}; use crate::segment::Segment; pub struct CacheThrough<K, V> { data: RwLock<Segment<K, V>>, } impl<K, V> CacheThrough<K, V> where K: std::cmp::Eq + st...
pub fn update<F>(&self, key: K, updating_fn: F) -> Option<Arc<V>> where F: Fn(&K, Option<Arc<V>>) -> Option<V>, { self.data.write().unwrap().update(key, updating_fn) } pub fn remove(&self, key: K) { self.data.write().unwrap().update(key, |_, _| None); } #[cfg(...
if let Some(value) = self.data.read().unwrap().get(&key) { return Some(value); } let option = self.data.write(); if option.is_ok() { let mut guard = option.unwrap(); return guard.get_or_populate(key, populating_fn); } None }
function_block-function_prefix_line
[ { "content": "pub trait Evictor<K> {\n\n fn add(&mut self, key: K) -> (usize, Option<K>);\n\n fn touch(&self, index: usize);\n\n}\n\n\n\npub struct ClockEvictor<K> {\n\n capacity: usize,\n\n current_pos: usize,\n\n clock: RwLock<Vec<bool>>,\n\n mapping: HashMap<usize, K>,\n\n}\n\n\n\nimpl<K> ClockEvictor<...
Rust
model/src/gateway/payload/incoming/thread_members_update.rs
vilgotf/twilight
b2cb7a4f80890e328e50cb1696b477c5c10464e5
use crate::{ channel::thread::{ThreadMember, ThreadMemberIntermediary}, id::{ChannelId, GuildId, UserId}, }; use serde::{ de::{value::MapAccessDeserializer, MapAccess, Visitor}, Deserialize, Deserializer, Serialize, }; use std::fmt::{Formatter, Result as FmtResult}; #[derive(Clone, Debug, Eq, Hash, Par...
use crate::{ channel::thread::{ThreadMember, ThreadMemberIntermediary}, id::{ChannelId, GuildId, UserId}, }; use serde::{ de::{value::MapAccessDeserializer, MapAccess, Visitor}, Deserialize, Deserializer, Serialize, }; use std::fmt::{Formatter, Result as FmtResult}; #[derive(Clone, Debug, Eq, Hash, Par...
let activity = Activity { application_id: None, assets: None, buttons: Vec::new(), created_at: Some(1_571_048_061_237), details: None, flags: None, id: Some("aaaaaaaaaaaaaaaa".to_owned()), instance: None, ...
let member = Member { avatar: Some("guild avatar".to_owned()), communication_disabled_until: None, deaf: false, guild_id: GuildId::new(2).expect("non zero"), joined_at, mute: true, nick: Some("twilight".to_owned()), pending:...
assignment_statement
[]
Rust
conmon-rs/server/src/lib.rs
wgahnagl/conmon-rs
a3849a79c82b1992974f25677c9949b56dfbf263
use anyhow::{Context, Result}; use capnp_rpc::{rpc_twoparty_capnp::Side, twoparty, RpcSystem}; use conmon_common::conmon_capnp::conmon; use futures::{AsyncReadExt, FutureExt}; use getset::{Getters, MutGetters}; use log::{debug, info}; use nix::{ libc::_exit, unistd::{fork, ForkResult}, }; use std::{fs::File, io...
use anyhow::{Context, Result}; use capnp_rpc::{rpc_twoparty_capnp::Side, twoparty, RpcSystem}; use conmon_common::conmon_capnp::conmon; use futures::{AsyncReadExt, FutureExt}; use getset::{Getters, MutGetters}; use log::{debug, info}; use nix::{ libc::_exit, unistd::{fork, ForkResult}, }; use std::{fs::File, io...
}
x::new(VatNetwork::new( reader, writer, Side::Server, Default::default(), )); let rpc_system = RpcSystem::new(network, Some(client.clone().client)); task::spawn_local(Box::pin(rpc_system.map(|_| ()))); } }
function_block-function_prefixed
[ { "content": "fn main() -> Result<()> {\n\n Server::new()\n\n .context(\"create server\")?\n\n .start()\n\n .context(\"start server\")\n\n}\n", "file_path": "conmon-rs/server/src/main.rs", "rank": 0, "score": 148350.74080412355 }, { "content": "/// Helper to adjust th...
Rust
core/src/mbc/mbc5.rs
LukasKalbertodt/mahboi
61990b4ccab688a62172ef7836ea15b60f1cc942
use crate::{ log::*, cartridge::{RamSize, RomSize}, primitives::{Byte, Word}, }; use super::Mbc; pub(crate) struct Mbc5 { rom: Box<[Byte]>, ram: Box<[Byte]>, rom_bank: u16, ram_bank: u8, ram_enabled: bool, } impl Mbc5 { pub(crate) fn new(data: &[u8], rom...
use crate::{ log::*, cartridge::{RamSize, RomSize}, primitives::{Byte, Word}, }; use super::Mbc; pub(crate) struct Mbc5 { rom: Box<[Byte]>, ram: Box<[Byte]>, rom_bank: u16, ram_bank: u8, ram_enabled: bool, } impl Mbc5 { pub(crate) fn new(data: &[u8], rom...
fn store_ram_byte(&mut self, addr: Word, byte: Byte) { if !self.ram_enabled { return; } let idx = self.ram_bank as usize * 0x2000 + addr.get() as usize; if idx < self.ram.len() { self.ram[idx] = byte; } else { warn!( ...
n load_ram_byte(&self, addr: Word) -> Byte { if !self.ram_enabled { return Byte::new(0xFF); } self.ram.get(self.ram_bank as usize * 0x2000 + addr.get() as usize) .cloned() .unwrap_or(Byte::new(0xFF)) }
function_block-function_prefixed
[ { "content": "/// Creates a comment string for the given instruction.\n\n///\n\n/// The comment can hold any potentially useful informtion.\n\nfn comment_for(instr: &DecodedInstr, addr: Word) -> String {\n\n fn comment_sep(s: &mut String) {\n\n if !s.is_empty() {\n\n *s += \", \";\n\n ...
Rust
cli/src/main.rs
nical/etagere
1a38a0235070e56a7dd6d21e22cbf7230d26cea8
extern crate etagere; #[macro_use] extern crate serde; use etagere::*; use etagere::euclid::size2; use clap::*; use std::io::prelude::*; use std::fs::{File, OpenOptions}; #[derive(Serialize, Deserialize)] struct Session { atlas: BucketedAtlasAllocator, names: std::collections::HashMap<String, Allocation>, ...
extern crate etagere; #[macro_use] extern crate serde; use etagere::*; use etagere::euclid::size2; use clap::*; use std::io::prelude::*; use std::fs::{File, OpenOptions}; #[derive(Serialize, Deserialize)] struct Session { atlas: BucketedAtlasAllocator, names: std::collections::HashMap<String, Allocation>, ...
, vertical_shelves: args.is_present("VERTICAL_SHELVES"), num_columns: args.value_of("ALIGN_X") .map(|s| s.parse::<i32>().unwrap()) .unwrap_or(default_options.num_columns), }; let session = Session { atlas: BucketedAtlasAllocator::with_options(size2(w, h), &optio...
size2( args.value_of("ALIGN_X") .map(|s| s.parse::<i32>().unwrap()) .unwrap_or(default_options.alignment.width), args.value_of("ALIGN_Y") .map(|s| s.parse::<i32>().unwrap()) .unwrap_or(default_options.alignment.width), )
call_expression
[ { "content": "fn shelf_height(mut size: i32) -> i32 {\n\n let alignment = match size {\n\n 0 ..= 31 => 8,\n\n 32 ..= 127 => 16,\n\n 128 ..= 511 => 32,\n\n _ => 64,\n\n };\n\n\n\n let rem = size % alignment;\n\n if rem > 0 {\n\n size += alignment - rem;\n\n }\n\n...
Rust
cprover_bindings/src/irep/serialize.rs
celinval/kani-dev
677bacdb9ad7ce74dd20bbf6ba3cc6b87a6d7d16
use crate::irep::{Irep, IrepId, Symbol, SymbolTable}; use crate::InternedString; use serde::ser::{SerializeMap, Serializer}; use serde::Serialize; impl Serialize for Irep { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut obj = serializer.ser...
use crate::irep::{Irep, IrepId, Symbol, SymbolTable}; use crate::InternedString; use serde::ser::{SerializeMap, Serializer}; use serde::Serialize; impl Serialize for Irep { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut obj = serializer.ser...
alse, is_thread_local: false, is_lvalue: false, is_file_local: false, is_extern: false, is_volatile: false, is_parameter: false, is_auxiliary: false, is_weak: false, }; sym_table.insert(symbol.clone()); ...
.serialize_entry(k, &v.to_irep(mm))?; } obj.end() } } impl Serialize for InternedString { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.to_string().serialize(serializer) } } struct InternedStringVisitor; impl<'de> serd...
random
[ { "content": "/// Utility functions\n\nfn arguments_irep<'a>(arguments: impl Iterator<Item = &'a Expr>, mm: &MachineModel) -> Irep {\n\n Irep {\n\n id: IrepId::Arguments,\n\n sub: arguments.map(|x| x.to_irep(mm)).collect(),\n\n named_sub: linear_map![],\n\n }\n\n}\n", "file_path":...
Rust
xtask/src/coverage.rs
koutheir/selinux
a23b6acc513cfa4cf20baa6a12aafe00a2e04c7d
use std::ffi::OsStr; use std::fs::File; use std::path::{Path, PathBuf}; use std::{fs, process}; use log::{debug, info}; use crate::errors::{Error, Result}; use crate::utils::*; use crate::{Config, NIGHTLY_TOOLCHAIN}; #[derive(Debug, serde_derive::Deserialize)] struct CargoTestMessageProfile { test: bool, } #[de...
use std::ffi::OsStr; use std::fs::File; use std::path::{Path, PathBuf}; use std::{fs, process}; use log::{debug, info}; use crate::errors::{Error, Result}; use crate::utils::*; use crate::{Config, NIGHTLY_TOOLCHAIN}; #[derive(Debug, serde_derive::Deserialize)] struct CargoTestMessageProfile { test: bool, } #[de...
rustup(config, &args)?; result = find_executable_file(&sys_root, "llvm-profdata"); } let llvm_profdata = result?; let llvm_cov = find_executable_file(&sys_root, "llvm-cov")?; fs::create_dir_all(&config.coverage_dir) .map_err(|r| Error::from_io_path("std::fs::create_dir_all", &...
let args = [ "--quiet", "component", "add", "--toolchain", NIGHTLY_TOOLCHAIN, "llvm-tools-preview", ];
assignment_statement
[ { "content": "fn run_target(config: &Config, target: &str) -> Result<()> {\n\n match target {\n\n \"coverage\" => coverage(config),\n\n\n\n _ => usage(),\n\n }\n\n}\n", "file_path": "xtask/src/main.rs", "rank": 0, "score": 180495.35324010975 }, { "content": "fn cargo_vers...
Rust
client/src/gui/mod.rs
ed-jones/voxel-rs
f3b43867c8b704d84de87611c00bdd246ea301f7
use crate::ui::PrimitiveBuffer; pub mod experiments; pub struct Gui { pub(self) mouse_x: i32, pub(self) mouse_y: i32, pub(self) mouse_down: bool, pub(self) hot_item: u32, pub(self) active_item: u32, pub(self) primitives: PrimitiveBuffer, } impl Gui { pub fn new() -> ...
use crate::ui::PrimitiveBuffer; pub mod experiments; pub struct Gui { pub(self) mouse_x: i32, pub(self) mouse_y: i32, pub(self) mouse_down: bool, pub(self) hot_item: u32, pub(self) active_item: u32, pub(self) primitives: PrimitiveBuffer, } impl Gui { pub fn new() -> ...
pub fn text(&mut self, x: i32, y: i32, h: i32, text: String, color: [f32; 4], z: f32) { self.primitives.draw_text_simple(x, y, h, text, color, z); } } #[must_use] pub struct ButtonBuilder<'a> { gui: &'a mut Gui, id: u32, x: i32, y: i32, w: i32, h: i32, text: Option<(S...
pub fn button(&mut self, id: u32, x: i32, y: i32, w: i32, h: i32) -> ButtonBuilder { ButtonBuilder { gui: self, id: id + 2, x, y, w, h, text: None, } }
function_block-full_function
[ { "content": "fn four_bytes_to_u32(bytes: &[u8], big_endian: bool) -> u32 {\n\n if big_endian {\n\n return ((bytes[0] as u32) << 24)\n\n + ((bytes[1] as u32) << 16)\n\n + ((bytes[2] as u32) << 8)\n\n + (bytes[3] as u32);\n\n } else {\n\n return ((bytes[3] as ...
Rust
jl_compiler/src/cli.rs
vain0x/jacco-lang
f1982710a8b9a6198ebb14692570e83774d3659b
use crate::{ clang::clang_dump, cps::*, front::name_resolution::NameSymbols, logs::{DocLogs, Logs}, parse::{parse_tokens, PTree}, source::{Doc, TRange}, token::tokenize, utils::VecArena, }; use log::error; use std::{ collections::{HashMap, HashSet}, io, mem::take, path::{...
use crate::{ clang::clang_dump, cps::*, front::name_resolution::NameSymbols, logs::{DocLogs, Logs}, parse::{parse_tokens, PTree}, source::{Doc, TRange}, token::tokenize, utils::VecArena, }; use log::error; use std::{ collections::{HashMap, HashSet}, io, mem::take, path::{...
one } } } fn make_path_relative_to_manifest_dir(path: &Path) -> PathBuf { fn segments(path: &Path) -> io::Result<Vec<String>> { Ok(path .canonicalize()? .components() .filter_map(|c| match c { Component::Normal(name) => Some(name.to_string_los...
path.to_string_lossy(), ); } return None; } match project.compile_v2() { Ok(code) => Some(code), Err(errors) => { if errors.is_empty() { unreachable!("エラーがないのにコンパイルエラーが発生しています。"); } for (_, path, range,...
function_block-random_span
[ { "content": "fn logs_into_errors(logs: Logs, tree: &PTree) -> Vec<(TRange, String)> {\n\n logs.finish()\n\n .into_iter()\n\n .map(|item| {\n\n let mut message = item.message().to_string();\n\n let range = match item.loc().inner().and_then(|(_, loc)| loc.range(tree)) {\n\n...
Rust
src/main.rs
shoyo/sudoku
ceda5bb09a9df776b28c4a48e9d9359ce5400776
use std::fmt::{Display, Error, Formatter}; mod boards; const ROWS: usize = 9; const COLS: usize = 9; const CAGE_ROWS: usize = 3; const CAGE_COLS: usize = 3; struct Sudoku { board: Vec<Vec<Option<u8>>>, } impl Sudoku { fn new(initial: Vec<(usize, usize, u8)>) -> Result<Self, String> { ...
use std::fmt::{Display, Error, Formatter}; mod boards; const ROWS: usize = 9; const COLS: usize = 9; const CAGE_ROWS: usize = 3; const CAGE_COLS: usize = 3; struct Sudoku { board: Vec<Vec<Option<u8>>>, } impl Sudoku { fn new(initial: Vec<(usize, usize, u8)>) -> Result<Self, String> { ...
} fn main() { let board = boards::VALID_PUZZLE_1.to_vec(); let mut puzzle = Sudoku::new(board).unwrap(); println!("BEFORE:"); println!("{}", puzzle); match puzzle.solve() { Ok(_) => { println!("AFTER:"); println!("{}", puzzle); } Err(_) =...
fn fmt(&self, _fmt: &mut Formatter<'_>) -> Result<(), Error> { for i in 0..ROWS { for j in 0..COLS { match self.board[i][j] { Some(num) => print!(" {} ", num), None => print!(" - "), } } println!(); ...
function_block-full_function
[]
Rust
native-windows-gui/src/controls/tooltip.rs
cg31/native-windows-gui
19fe8f6fadc3c5cd9365106e78d87e46d9c813dd
use winapi::shared::minwindef::{UINT, LPARAM, WPARAM}; use winapi::um::winnt::WCHAR; use crate::win32::window_helper as wh; use crate::win32::base_helper::{check_hwnd, to_utf16, from_utf16}; use crate::{Icon, NwgError}; use super::{ControlBase, ControlHandle}; use std::{mem, ptr}; const NOT_BOUND: &'static str = "Tool...
use winapi::shared::minwindef::{UINT, LPARAM, WPARAM}; use winapi::um::winnt::WCHAR; use crate::win32::window_helper as wh; use crate::win32::base_helper::{check_hwnd, to_utf16, from_utf16}; use crate::{Icon, NwgError}; use super::{ControlBase, ControlHandle}; use std::{mem, ptr}; const NOT_BOUND: &'static str = "Tool...
} for (handle, text) in self.register { tooltip.register(&handle, text); } for handle in self.register_cb { tooltip.register_callback(&handle); } Ok(()) } }
match (self.ico, self.default_ico) { (Some(ico), None) | (Some(ico), _) => tooltip.set_decoration(title, ico), (None, Some(ico)) => tooltip.set_default_decoration(title, ico), (None, None) => tooltip.set_default_decoration(title, TooltipIcon::None), }
if_condition
[ { "content": "pub fn check_hwnd(handle: &ControlHandle, not_bound: &str, bad_handle: &str) -> HWND {\n\n use winapi::um::winuser::IsWindow;\n\n\n\n if handle.blank() { panic!(\"{}\", not_bound); }\n\n match handle.hwnd() {\n\n Some(hwnd) => match unsafe { IsWindow(hwnd) } {\n\n 0 => {...
Rust
rust/xaynet-analytics/src/data_combination/data_points/was_active_each_past_period.rs
xaynetwork/xaynet
ae6a7b2127599b8ac9cd663a5259d2ff01392fe0
use chrono::{DateTime, Utc}; use std::collections::BTreeMap; use crate::{ data_combination::data_points::data_point::{ CalcWasActiveEachPastPeriod, CalculateDataPoints, DataPointMetadata, }, database::analytics_event::data_model::AnalyticsEvent, }; impl CalcWasActiveEachPastPeriod ...
use chrono::{DateTime, Utc}; use std::collections::BTreeMap; use crate::{ data_combination::data_points::data_point::{ CalcWasActiveEachPastPeriod, CalculateDataPoints, DataPointMetadata, }, database::analytics_event::data_model::AnalyticsEvent, }; impl CalcWasActiveEachPastPeriod ...
ch_past_period = CalcWasActiveEachPastPeriod::new(metadata, Vec::new(), period_thresholds); assert_eq!(was_active_each_past_period.calculate(), vec![0, 0]); } #[test] fn test_calculate_one_event_in_one_period_zero_in_another() { let end_period = DateTime::parse_from_rfc3339("202...
::new(PeriodUnit::Days, 2), end_period); let period_thresholds = vec![ end_period, end_period - Duration::days(1), end_period - Duration::days(2), ]; let was_active_ea
function_block-random_span
[ { "content": "/// Create an [`EventPublisher`]/[`EventSubscriber`] pair with default\n\n/// values similar to those produced in practice when instantiating a\n\n/// new coordinator.\n\npub fn new_event_channels() -> (EventPublisher, EventSubscriber) {\n\n let keys = EncryptKeyPair::generate();\n\n let par...
Rust
client-core/src/service/sync_state_service.rs
Itchibon777/chain
48ddd62c467795757620a5bda011fe0a287b887d
use chain_core::common::H256; use client_common::tendermint::lite; use client_common::{ErrorKind, Result, ResultExt, Storage}; use parity_scale_codec::{Decode, Encode}; use tendermint::validator; const KEYSPACE: &str = "core_wallet_sync"; #[derive(Debug, Encode, Decode)] pub struct SyncState { pub last_block...
use chain_core::common::H256; use client_common::tendermint::lite; use client_common::{ErrorKind, Result, ResultExt, Storage}; use parity_scale_codec::{Decode, Encode}; use tendermint::validator; const KEYSPACE: &str = "core_wallet_sync"; #[derive(Debug, Encode, Decode)] pub struct SyncState { pub last_block...
) } else { Ok(None) } } } #[cfg(test)] mod tests { use parity_scale_codec::{Decode, Encode}; use tendermint::{block::Height, lite}; use super::{lite::TrustedState, SyncState, SyncStateService}; use client_common::storage::MemoryStorage; use test_common::block_genera...
Some(SyncState::decode(&mut bytes.as_slice()).chain( || { ( ErrorKind::DeserializationError, format!( "Unable to deserialize global state for wallet with name {}", name ...
call_expression
[ { "content": "/// Delete wallet state from storage\n\npub fn delete_wallet_state<S: Storage>(storage: &S, name: &str) -> Result<()> {\n\n storage.delete(KEYSPACE, name)?;\n\n Ok(())\n\n}\n\n\n\n/// Wallet state\n\n#[derive(Debug, Encode, Decode)]\n\npub struct WalletState {\n\n /// UTxO\n\n pub unsp...
Rust
src/postgres_driver/utils.rs
phaer/inspektor
2423173199b233ca8c4d7e6ed89bdf8957b7f432
use crate::postgres_driver::errors::DecoderError; use crate::postgres_driver::message::*; use anyhow::*; use byteorder::{ByteOrder, NetworkEndian}; use bytes::{Buf, BufMut, BytesMut}; use std::collections::HashMap; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; pub async fn decode_init_startup_me...
use crate::postgres_driver::errors::DecoderError; use crate::postgres_driver::message::*; use anyhow::*; use byteorder::{ByteOrder, NetworkEndian}; use bytes::{Buf, BufMut, BytesMut}; use std::collections::HashMap; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; pub async fn decode_init_startup_me...
pub fn read_cstr(buf: &mut BytesMut) -> Result<String, Error> { if let Some(pos) = buf.iter().position(|d| *d == 0) { let str = std::str::from_utf8(&buf[..pos]) .map_err(|_| anyhow!("error while reading cstr"))? .to_string(); buf.advance(pos + 1); return Ok(str); ...
pub async fn decode_frame_length<T>(mut conn: T) -> Result<usize, anyhow::Error> where T: AsyncRead + Unpin, { let mut buf = [0; 4]; conn.read_exact(&mut buf).await?; let frame_len = NetworkEndian::read_u32(&buf) as usize; if frame_len < 4 { return Err(anyhow!("invalid frame length"...
function_block-full_function
[ { "content": "pub fn read_config(config_path: &std::path::Path) -> Result<Config, anyhow::Error> {\n\n let config_buf = std::fs::read(config_path)\n\n .map_err(|e| anyhow!(\"error while reading config. err: {:?}\", e))?;\n\n Ok(serde_yaml::from_slice::<Config>(&config_buf[..])?)\n\n}\n\n\n\n#[cfg(t...
Rust
src/chart.rs
longbridgeapp/cli-candlestick-chart
2081638215a330bf1914b008cb94d053a0190390
use colored::Color; use crate::{ chart_data::ChartData, chart_renderer::ChartRenderer, info_bar::InfoBar, volume_pane::VolumePane, y_axis::YAxis, }; use std::cell::RefCell; use std::rc::Rc; #[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize))] pub struct Candle { pub open: f64...
use colored::Color; use crate::{ chart_data::ChartData, chart_renderer::ChartRenderer, info_bar::InfoBar, volume_pane::VolumePane, y_axis::YAxis, }; use std::cell::RefCell; use std::rc::Rc; #[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize))] pub struct Candle { pub open: f64...
self.volume_pane.enabled = enabled; } pub fn set_volume_pane_unicode_fill(&mut self, unicode_fill: char) { self.volume_pane.unicode_fill = unicode_fill; } pub fn set_volume_pane_height(&mut self, height: i64) { self.volume_pane.height = height; } p...
new(candles: &[Candle]) -> Self { Self::new_with_canvas_size(candles, None) } pub fn new_with_canvas_size(candles: &[Candle], canvas_size: Option<(u16, u16)>) -> Self { let renderer = ChartRenderer::new(); let chart_data = match canvas_size { Some(canvas_size) => Rc::new(Ref...
random
[ { "content": "\n\n pub fn new() -> ChartRenderer {\n\n #[cfg(target_os = \"windows\")]\n\n control::set_virtual_terminal(true).unwrap();\n\n\n\n ChartRenderer {\n\n bullish_color: Color::Green,\n\n bearish_color: Color::Red,\n\n }\n\n }\n\n\n\n fn color...
Rust
src/tsort.rs
VladimirMarkelov/todo_lib
6cf36ce3c4ff33266533c25fddae6d4eb10a7e24
use std::cmp::Ordering; use crate::timer; use crate::todo; use crate::todotxt; #[derive(Debug, Clone)] pub struct Conf { pub fields: Option<String>, pub rev: bool, } impl Default for Conf { fn default() -> Conf { Conf { fields: None, rev: fal...
use std::cmp::Ordering; use crate::timer; use crate::todo; use crate::todotxt; #[derive(Debug, Clone)] pub struct Conf { pub fields: Option<String>, pub rev: bool, } impl Default for Conf { fn default() -> Conf { Conf { fields: None, rev: fal...
match *f { "pri" | "priority" => todos[*a].priority.cmp(&todos[*b].priority), "due" => cmp_opt_dates(todos[*a].due_date, todos[*b].due_date), "thr" => cmp_opt_dates(todos[*a].threshold_date, todos[*b].threshold_date), "completed" | "finishe...
ow = a1[idx].to_lowercase(); let s2_low = a2[idx].to_lowercase(); ord = s1_low.cmp(&s2_low); if ord != Ordering::Equal { break; } } if ord == Ordering::Equal { ord = a1.len().cmp(&a2.len()) } ord } pub fn sort(ids: &mut todo::IDVec, todos: &todo::Ta...
random
[ { "content": "fn vec_match(task_list: &[String], filter: &[String]) -> bool {\n\n if filter.is_empty() {\n\n return true;\n\n }\n\n for f in filter.iter() {\n\n if (f == NONE_TITLE && task_list.is_empty()) || (f == ANY_TITLE && !task_list.is_empty()) {\n\n return true;\n\n ...
Rust
src/lib.rs
Flux-Audio/chaos_osc
30fc168cf5738c1cc53a9b63ddc47fc582c4eae7
#[macro_use] extern crate vst; use vst::buffer::AudioBuffer; use vst::plugin::{Category, Info, Plugin, PluginParameters}; use vst::util::AtomicFloat; use std::sync::Arc; mod compute; struct Effect { params: Arc<EffectParameters>, sr: f32, scale: f64, th1: f64, th2: f64, ...
#[macro_use] extern crate vst; use vst::buffer::AudioBuffer; use vst::plugin::{Category, Info, Plugin, PluginParameters}; use vst::util::AtomicFloat; use std::sync::Arc; mod compute; struct Effect { params: Arc<EffectParameters>, sr: f32, scale: f64, th1: f64, th2: f64, ...
fn get_parameter_object(&mut self) -> Arc<dyn PluginParameters> { Arc::clone(&self.params) as Arc<dyn PluginParameters> } } impl PluginParameters for EffectParameters { fn get_parameter(&self, index: i32) -> f32 { match index { 0 => self.len_ratio.g...
2_amt.get() as f64; let o1_f = (self.params.o1_f.get()*8.0 + self.params.o1_fine.get()) as f64; let o2_f = (self.params.o2_f.get()*8.0 + self.params.o2_fine.get()) as f64; let o2_to_o1_mod = self.params.o2_to_o1_mod.get() as f64; let o1_to_o2_mod = self.params.o1_to_o2_mo...
function_block-function_prefixed
[ { "content": "/// this is the simplified version of the double pendulum differential equation\n\n/// system, the old one was broken\n\npub fn step(th1: f64, th2: f64, w1: f64, w2: f64, l1: f64, l2: f64)\n\n -> (f64, f64, f64, f64){\n\n\n\n let c = (th1 - th2).cos();\n\n let s = (th1 - th2).sin(); \...
Rust
drepr/readers/src/iterators/index/unknown_range_iterator.rs
scorpio975/d-repr
1d08024192642233d42d29e1d05f8713ee265bca
use crate::prelude::{Index, RAReader, Value}; use super::IndexIterator; macro_rules! generate_unknown_range_iter { (get_index_type, $mut_kw:ident) => { &'a mut [Index] }; (get_index_type,) => { Vec<Index> }; ($class:ident $(, $mut_kw:ident )?) => { #[derive(Debug)] pub struct $class<'a> { ra_reader: &'a dyn ...
use crate::prelude::{Index, RAReader, Value}; use super::IndexIterator; macro_rules! generate_unknown_range_iter { (get_index_type, $mut_kw:ident) => { &'a mut [Index] }; (get_index_type,) => { Vec<Index> }; ($class:ident $(, $mut_kw:ident )?) => { #[derive(Debug)] pub struct $class<'a> { ra_reader: &'a dyn ...
upperbounds[i] = tree_ptrs[i - 1].len() - neg_upperbounds[i]; } tree_ptrs[i] = tree_ptrs[i - 1].get_child_value(&index[i]); } if last_unknown_dim > 0 { upperbounds[last_unknown_dim] = tree_ptrs[last_unknown_dim - 1].len() - neg_upperbounds[last_unknown_dim]; } }
function_block-function_prefix_line
[ { "content": "pub fn generic_optional_oprop_map(readers: &[Box<dyn RAReader>], writer: &mut dyn StreamClassWriter, oplan: &ObjectProp, oalign: &mut AlignmentFunc, subj_id: &str, subj_val: &Value, subj_idx: &[Index], o_idx: &mut [Index], is_subj_blank: bool, is_new_subj: bool) {\n\n match oalign {\n\n Alignm...
Rust
raster-tools/src/bin/raster-diff/args.rs
AspecScire/rasters.rs
28eb0067dd9ffc4d869d2fcf762c328e081446c2
use clap::*; use raster_tools::{utils::*, *}; use rasters::histogram::Config as HistConfig; use std::path::PathBuf; pub struct Args { pub input_a: PathBuf, pub input_b: PathBuf, pub negate: bool, pub hist: Option<(HistConfig, PathBuf)>, pub polygon: Option<geo::MultiPolygo...
use clap::*; use raster_tools::{utils::*, *}; use rasters::histogram::Config as HistConfig; use std::path::PathBuf; pub struct Args { pub input_a: PathBuf, pub input_b: PathBuf, pub negate: bool, pub hist: Option<(HistConfig, PathBuf)>, pub polygon: Option<geo::MultiPolygo...
p)") .requires_all(&["min", "max", "binning"]), ) .arg( opt!("min") .allow_hyphen_values(true) .requires("hist") .help("Min value to consider"), ) .arg( opt!("max") .allow_hyphen_value...
function_block-function_prefixed
[ { "content": "pub fn edit_dataset(path: &Path) -> Result<Dataset> {\n\n Ok(Dataset::open_ex(&path, Some(1), None, None, None)\n\n .with_context(|| format!(\"editing dataset {}\", path.display()))?)\n\n}\n\n\n\nuse gdal::raster::GdalType;\n", "file_path": "raster-tools/src/utils.rs", "rank": 0,...
Rust
src/diagnose.rs
Icenowy/ciel-rs
6e0f2305f29505d9c735f234b1f450f193fa2ca7
use anyhow::{anyhow, Result}; use console::style; use dbus::blocking::stdintf::org_freedesktop_dbus::Properties; use dbus::blocking::Connection; use fs3::statvfs; use indicatif::HumanBytes; use std::sync::mpsc::channel; use std::{fs::File, io::BufRead, time::Duration}; use std::{ io::{BufReader, Write}, thread,...
use anyhow::{anyhow, Result}; use console::style; use dbus::blocking::stdintf::org_freedesktop_dbus::Properties; use dbus::blocking::Connection; use fs3::statvfs; use indicatif::HumanBytes; use std::sync::mpsc::channel; use std::{fs::File, io::BufRead, time::Duration}; use std::{ io::{BufReader, Write}, thread,...
ing()); } error!("The test file is taking too long to write, suspecting I/O stuck."); Err(anyhow!("Disk I/O is not working correctly")) } fn test_disk_space() -> Result<String> { let stats = statvfs(std::fs::canonicalize(".")?)?; if stats.available_space() < (10 * 1024 * 1024 * 1024) { ...
test_required_binaries() -> Result<String> { for binary in TEST_PROGRAMS { if which(binary).is_err() { return Err(anyhow!("Required program `{}` is not found", binary)); } } Ok("Required binaries are correctly installed".to_string()) } fn test_fs_support() -> Result<String> { ...
random
[ { "content": "/// Setting up cross-namespace bind-mounts for the container using systemd\n\nfn setup_bind_mounts(ns_name: &str, mounts: &[(String, &str)]) -> Result<()> {\n\n let conn = Connection::new_system()?;\n\n let proxy = conn.with_proxy(MACHINE1_DEST, MACHINE1_PATH, Duration::from_secs(10));\n\n ...
Rust
src/day11.rs
Aidiakapi/advent-of-code-2016
f02d8041594ac99a317588ef64866c66141166ef
use crate::prelude::*; trait FacilityBounds = std::array::LengthAtMost32 + Clone + Eq + Ord + std::hash::Hash; fn solve<const N: usize>(input: Vec<Vec<Module>>) -> Result<usize> where [Element; N]: std::array::LengthAtMost32 + Default, [bool; N]: Default, { use std::{collections::VecDeque, rc::Rc}; l...
use crate::prelude::*; trait FacilityBounds = std::array::LengthAtMost32 + Clone + Eq + Ord + std::hash::Hash; fn solve<const N: usize>(input: Vec<Vec<Module>>) -> Result<usize> where [Element; N]: std::array::LengthAtMost32 + Default, [bool; N]: Default, { use std::{collections::VecDeque, rc::Rc}; l...
b, f))) .filter_map(move |(a, b, next_floor)| { let mut new = self.clone(); new.elevator_position = next_floor; #[rustfmt::skip] match a { Moveable::Generator(idx) => new.elements[idx as usize].move_generator(next_floor), ...
if elem.generator() == elevator_position { array.push_unchecked(Moveable::Generator(idx)); } if elem.microchip() == elevator_position { array.push_unchecked(Moveable::Microchip(idx)); } } ...
function_block-random_span
[ { "content": "pub trait Node = Clone + Eq + Hash;\n", "file_path": "src/astar.rs", "rank": 1, "score": 279361.34725252783 }, { "content": "fn is_free_fn(designer_nr: usize) -> impl Fn(&Vec2us) -> bool + Clone + Copy {\n\n move |p| {\n\n (p.x * p.x + 3 * p.x + 2 * p.x * p.y + p.y + ...
Rust
src/statistic/metric/ratio.rs
Uzaaft/barter-rs
08f1ddd9c622d4b7c4cddfc4520242e0c3360c6e
use crate::statistic::summary::pnl::PnLReturnSummary; use serde::{Deserialize, Serialize}; pub trait Ratio { fn init(risk_free_return: f64) -> Self; fn ratio(&self) -> f64; fn trades_per_day(&self) -> f64; fn daily(&self) -> f64 { calculate_daily(self.ratio(), self.trades_per_day()) } f...
use crate::statistic::summary::pnl::PnLReturnSummary; use serde::{Deserialize, Serialize}; pub trait Ratio { fn init(risk_free_return: f64) -> Self; fn ratio(&self) -> f64; fn trades_per_day(&self) -> f64; fn daily(&self) -> f64 { calculate_daily(self.ratio(), self.trades_per_day()) } f...
#[test] fn calmar_ratio_update() { let mut calmar = CalmarRatio::init(0.0); struct TestCase { input_return: PnLReturnSummary, input_max_dd: f64, expected_calmar: f64, } let test_cases = vec![ ...
let test_cases = vec![ TestCase { input_return: sortino_update_input(1, 0.1, 0.0), expected_sortino: 0.0, }, TestCase { input_return: sortino_update_input(2, 0.15, 0.0), expected_sortino...
function_block-function_prefix_line
[]
Rust
bindings/wasm/src/subscriber/subscriberw.rs
Dr-Electron/streams
054bf6d1cd42ba615c43a5ca1e935e942e443f5d
use js_sys::Array; use wasm_bindgen::prelude::*; use crate::{ types::*, user::userw::*, }; use core::cell::RefCell; use iota_streams::{ app::{ futures::executor::block_on, transport::{ tangle::client::Client as ApiClient, TransportOptions, }, }, app_...
use js_sys::Array; use wasm_bindgen::prelude::*; use crate::{ types::*, user::userw::*, }; use core::cell::RefCell; use iota_streams::{ app::{ futures::executor::block_on, transport::{ tangle::client::Client as ApiClient, TransportOptions, }, }, app_...
#[wasm_bindgen(catch)] pub async fn send_signed_packet( self, link: Address, public_payload: Vec<u8>, masked_payload: Vec<u8>, ) -> Result<UserResponse> { self.subscriber .borrow_mut() .send_signed_packet(link.as_inner(), &Bytes(public_payloa...
load: Vec<u8>, masked_payload: Vec<u8>, ) -> Result<UserResponse> { self.subscriber .borrow_mut() .send_tagged_packet(link.as_inner(), &Bytes(public_payload), &Bytes(masked_payload)) .await .map(|(link, seq_link)| UserResponse::new(link.into(), seq_lin...
function_block-function_prefixed
[ { "content": "/// Create a PskId from hex string.\n\npub fn pskid_from_hex_str(hex_str: &str) -> Result<PskId> {\n\n let pskid_bytes =\n\n hex::decode(hex_str).map_err(|e| wrapped_err!(Errors::BadHexFormat(hex_str.into()), WrappedError(e)))?;\n\n try_or!(\n\n PSKID_SIZE == pskid_bytes.len(),...
Rust
src/lib.rs
knoby/printer_operating_box
fe162e9ab06d98999c451feff366f918ad14f623
#![no_std] #![deny(unsafe_code)] #![deny(missing_docs)] #![deny(warnings)] use embedded_hal::digital::v2::{InputPin, OutputPin}; pub struct OpBox<I: InputPin, O: OutputPin> { clk_pin: O, latch_pin: O, output_pin: O, input_pin: I, state_out: [bool; 16], } impl<E, I: InputPin<Error = E>, O: OutputP...
#![no_std] #![deny(unsafe_code)] #![deny(missing_docs)] #![deny(warnings)] use embedded_hal::digital::v2::{InputPin, OutputPin}; pub struct OpBox<I: InputPin, O: OutputPin> { clk_pin: O, latch_pin: O, output_pin: O, input_pin: I, state_out: [bool; 16], } impl<E, I: InputPin<Error = E>, O: OutputP...
pub fn get_s1(&mut self) -> Result<bool, E> { self.set_get_shift_registers().map(|inputs| inputs[0]) } pub fn get_s2(&mut self) -> Result<bool, E> { self.set_get_shift_registers().map(|inputs| inputs[1]) } pub fn get_s3(&mut self) -> Result<bool, E> { self....
e, false], _ => [false; 7], }; self.state_out[8..].clone_from_slice(&display_state); self.set_get_shift_registers().map(|_| ()) }
function_block-function_prefixed
[ { "content": "### Printer Operating Box\n\n\n\nThis operating panel of an old printer consists of 10 LEDs (green and orange) a 7 segment led display and 8 buttions. \n\nThe LEDs and buttons are controlled with 8bit shift registers (74hc595 and 74hc169). The pinout if the following:\n\n\n\n- Clock\n\n- Latch\n\n...
Rust
strict_encoding/derive/src/derive.rs
zkao/rust-lnpbp
5bbbd2291d35408550eae62bcbd235308070cb02
use proc_macro2::TokenStream as TokenStream2; use syn::spanned::Spanned; use syn::{ Data, DataEnum, DataStruct, DeriveInput, Error, Fields, Ident, Index, Result, }; use crate::util::get_encoding_crate; pub(crate) fn encode_inner(input: DeriveInput) -> Result<TokenStream2> { match input.data { Da...
use proc_macro2::TokenStream as TokenStream2; use syn::spanned::Spanned; use syn::{ Data, DataEnum, DataStruct, DeriveInput, Error, Fields, Ident, Index, Result, }; use crate::util::get_encoding_crate; pub(crate) fn encode_inner(input: DeriveInput) -> Result<TokenStream2> { match input.data { Da...
fn encode_inner_enum( input: &DeriveInput, data: &DataEnum, ) -> Result<TokenStream2> { let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let ident_name = &input.ident; let import = get_encoding_crate(input); let mut inner: Vec<TokenStream2> = none!();...
generics #import::StrictDecode for #ident_name #ty_generics #where_clause { #[inline] fn strict_decode<D: ::std::io::Read>(mut d: D) -> Result<Self, #import::Error> { use #import::StrictDecode; Ok(#inner) } } }) }
function_block-function_prefixed
[ { "content": "/// Convenience method for strict encoding of data structures implementing\n\n/// [StrictEncode] into a byte vector.\n\npub fn strict_serialize<T>(data: &T) -> Result<Vec<u8>, Error>\n\nwhere\n\n T: StrictEncode,\n\n{\n\n let mut encoder = io::Cursor::new(vec![]);\n\n data.strict_encode(&...
Rust
rustbasic/src/hello_world/display.rs
rustshby/rustloveu
96af1750a2e7670e605aa2bf69b963fb8e71f97c
use std::fmt; #[allow(dead_code)] struct DisplayPrintable(i32); impl fmt::Display for DisplayPrintable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } #[allow(dead_code)] #[derive(Debug)] struct MinMax(i64, i64);...
use std::fmt; #[allow(dead_code)] struct DisplayPrintable(i32); impl fmt::Display for DisplayPrintable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } #[allow(dead_code)] #[derive(Debug)] struct MinMax(i64, i64);...
ed, self.green, self.blue) ) } } #[allow(dead_code)] pub fn display_show() { let minmax = MinMax(0, 14); println!("Compare structures:"); println!("Display: {}", minmax); println!("Debug: {:?}", minmax); let point = Point2D { x: 3.3, y: 7.2 }; println!("Compare points:"); print...
t fmt::Formatter) -> fmt::Result { write!( f, "RGB ({red}, {green}, {blue}) {rgb}", red = self.red, green = self.green, blue = self.blue, rgb = format!("0x{:02X}{:02X}{:02X}", self.r
function_block-random_span
[]
Rust
src/resolver.rs
htynkn/wkavu
9eae66cd8b2ddcb7f719b03675912856b28740ce
use std::time::Duration; use anyhow::Result; use async_trait::async_trait; use headless_chrome::{Browser, Element}; use log::info; use magnet_url::Magnet; use rbatis::crud::CRUD; use regex::Regex; use scraper::{Html, Selector}; use serde::Deserialize; use serde::Serialize; use thiserror::Error; use crate::global; us...
use std::time::Duration; use anyhow::Result; use async_trait::async_trait; use headless_chrome::{Browser, Element}; use log::info; use magnet_url::Magnet; use rbatis::crud::CRUD; use regex::Regex; use scraper::{Html, Selector}; use serde::Deserialize; use serde::Serialize; use thiserror::Error; use crate::global; us...
#[test] fn test_load() { let _resolver = DefaultResolver::new(); } }
hs = fs::read_dir("./define").unwrap(); for path in paths { let result = std::fs::read_to_string(path.unwrap().path()).unwrap(); let define: ResolverDefine = serde_yaml::from_str(&result).unwrap(); println!("Define:{:?}", define); } }
function_block-function_prefixed
[ { "content": "fn pub_date() -> String {\n\n let time = Utc::now() - Duration::days(1);\n\n time.to_rfc2822()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_zero() {\n\n let page = page(0, 50);\n\n\n\n assert_eq!(page.page_no, 1);\n\n }\n\n\n...
Rust
src/lib.rs
JAD3N/java-props
c9f844ed0b3aa7cd3b0ff14fcb6646e2b568d63b
#[macro_use] extern crate lazy_static; mod parser; mod iterator; mod utils; use iterator::Iterator; use std::io::{self, BufReader, prelude::*}; use std::collections::HashMap; use std::fs::File; use std::char; #[derive(PartialEq, Debug)] pub enum PropertyType { Property, Key, Value, Whitespace, Co...
#[macro_use] extern crate lazy_static; mod parser; mod iterator; mod utils; use iterator::Iterator; use std::io::{self, BufReader, prelude::*}; use std::collections::HashMap; use std::fs::File; use std::char; #[derive(PartialEq, Debug)] pub enum PropertyType { Property, Key, Value, Whitespace, Co...
#[test] fn basic_output_check() { let props_str = String::from("simple\\ key = A fun value!\\nWith multiple lines!"); assert_eq!( Properties::from_str(&props_str).to_string(), props_str, ) } }
fn empty_output_check() { let props_str = String::new(); assert_eq!( Properties::from_str(&props_str).to_string(), props_str, ) }
function_block-function_prefix_line
[ { "content": "pub fn starts_line_break(iter: &mut Iterator) -> bool {\n\n iter.peek().unwrap() == '\\\\' && is_eol(iter.peek_x(1).unwrap())\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 0, "score": 160791.78637780502 }, { "content": "pub fn read_whitespace(iter: &mut Iterator) -> Pro...