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/utils/value.rs
kellda/peripherals
2d7546e7e141a7f9722f961c39c0d2828d87313c
use super::*; pub struct Value<R: RegisterValue> { value: R::Int, _reg: PhantomData<R>, } impl<R: RegisterValue> Value<R> { #[inline] pub fn value(self) -> R::Int { self.value } #[inline] pub unsafe fn from_raw(value: R::Int) -> Value<R> { Val...
use super::*; pub struct Value<R: RegisterValue> { value: R::Int, _reg: PhantomData<R>, } impl<R: RegisterValue> Value<R> { #[inline] pub fn value(self) -> R::Int { self.value
#[inline] fn bitor_assign(&mut self, other: T) { let other = other.into(); self.value = self.value & !other.mask() | other.bits(); } } impl<R: RegisterValue, T: Into<Fields<R>> + MayToggle> BitAnd<T> for Value<R> { type Output = FieldValues<R, T::Toggle>; #[inline] fn bitand(se...
} #[inline] pub unsafe fn from_raw(value: R::Int) -> Value<R> { Value { value, _reg: PhantomData, } } #[inline] pub fn field<T>(self, field: Field<R, T, R::Int>) -> T where R::Int: TryInto<T>, <...
random
[ { "content": "/// A trait for the register associated with a value\n\n///\n\n/// This trait is implemented by the [`register!`] macro for marker types that indicate registers associated to a value.\n\npub trait RegisterValue {\n\n /// The width of this register (`u8`, `u16`, etc.)\n\n type Int: Int;\n\n ...
Rust
src/commandline/generate.rs
Evian-Zhang/Wispha
fc06b3ad5bf0608543abb6270630ac61d5258a8e
use libwispha::core::*; use crate::commandline::CommandlineOption; use serde_json; use structopt::StructOpt; use std::error; use std::fmt; use std::fs; use std::io; use std::env; use std::rc::Rc; use std::cell::RefCell; use std::path::PathBuf; use std::collections::{HashMap, VecDeque}; type Result<T> = std::result::...
use libwispha::core::*; use crate::commandline::CommandlineOption; use serde_json; use structopt::StructOpt; use std::error; use std::fmt; use std::fs; use std::io; use std::env; use std::rc::Rc; use std::cell::RefCell; use std::path::PathBuf; use std::collections::{HashMap, VecDeque}; type Result<T> = std::result::...
path_queue.push_back(child_path); } } Ok(()) } fn generate_direct_node(tree: &Tree, base_node_path: NodePath, dir_path: PathBuf, config: &GenerateConfig) -> Result<(Rc<RefCell<Node>>, Vec<(NodePath, PathBuf)>)> { let na...
t(long, short = "n")] file_name: Option<String>, } struct GenerateConfig { path: PathBuf, file_name: String } impl GenerateConfig { fn from_opt(opt: GenerateOptions) -> Result<Self> { let path = if let Some(path) = opt.path { if path.is_absolute() { path ...
random
[ { "content": "pub fn resolve_handler(link_node: &LinkNode) -> Result<(PathBuf, String), Box<dyn error::Error>> {\n\n let path = if link_node.target.is_absolute() {\n\n link_node.target.clone()\n\n } else {\n\n link_node.node_properties.record_file.parent().unwrap()\n\n .join(...
Rust
day10/src/main.rs
jstuczyn/AdventOfCode2020
589b2fef430bcb2542163f94e9e725e6110daa56
use itertools::Itertools; use std::collections::HashMap; use utils::input_read; fn part1(input: &[usize]) -> usize { let mut adapters = input .iter() .copied() .chain(std::iter::once(0)) .collect_vec(); adapters.sort_unstable(); let mut one_jolt_diffs...
use itertools::Itertools; use std::collections::HashMap; use utils::input_read; fn part1(input: &[usize]) -> usize { let mut adapters = input .iter() .copied() .chain(std::iter::once(0)) .collect_vec(); adapters.sort_unstable(); let mut one_jolt_diffs...
) { let input = vec![16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4]; let expected = 35; assert_eq!(expected, part1(&input)) } #[test] fn part1_sample_input2() { let input = vec![ 28, 33, 18, 42, 31, 14, 46, 20, 48, 47, 24, 23, 49, 45, 19, 38, 39, 11, 1, 32, 25, 35, ...
ith(Vec::new); children.push(*potential_child); } else { continue 'outer; } } } let mut cost_map = HashMap::with_capacity(connection_map.len()); path_cost(0, &connection_map, &mut cost_map) } #[cfg(not(tarpaulin))] fn main()...
random
[ { "content": "fn part1(input: &[usize]) -> usize {\n\n VanEckSequence::new(input.to_vec())\n\n .into_iter()\n\n .nth(2020 - 1) // we subtract one as we count from 0 like a sane person\n\n .unwrap()\n\n}\n\n\n\n// this is not included in coverage for the same reason as the part2 tests\n",...
Rust
srt-protocol/src/protocol/receiver/time.rs
simon-fu/srt-rs
240a6109e2953642e8fe88e16d4a7df503e1be33
use std::time::Instant; use stats::OnlineStats; use crate::{ packet::{TimeSpan, TimeStamp}, protocol::time::TimeBase, }; #[derive(Debug)] pub struct SynchronizedRemoteClock { drift_deviation_tolerance: TimeSpan, time_base: TimeBase, last_monotonic_instant: Option<Instant>, stats: Option<Onlin...
use std::time::Instant; use stats::OnlineStats; use crate::{ packet::{TimeSpan, TimeStamp}, protocol::time::TimeBase, }; #[derive(Debug)] pub struct SynchronizedRemoteClock { drift_deviation_tolerance: TimeSpan, time_base: TimeBase, last_monotonic_instant: Option<Instant>, stats: Option<Onlin...
MAX; let start_ts = TimeStamp::from_micros(100_000_000); let mut clock = SynchronizedRemoteClock::new(start); clock.synchronize(start, start_ts); let mut last_monotonic_instant = clock.monotonic_instant_from(start_ts); for tick_ts in 1..1002 { ...
tart + tick + drift; let now_ts = start_ts + TimeSpan::from_micros(tick_ts); let adjustment = clock.synchronize(now, now_ts); match tick_ts.cmp(&MAX_SAMPLES) { Ordering::Less => prop_assert_eq!(adjustment, None, "the clock should not be adjusted until...
random
[ { "content": "fn complete(mut conn: Conn, start: Instant) -> (Connection, Connection) {\n\n const TIME_LIMIT: Duration = Duration::from_secs(20);\n\n\n\n let mut current_time = start;\n\n\n\n loop {\n\n assert!(current_time - start < TIME_LIMIT);\n\n\n\n let sender_time = loop {\n\n ...
Rust
src/lib.rs
bvssvni/wave_timeline
0968f9174f9f9377d161a682435c37cb440145f0
extern crate graphics; extern crate input; extern crate rect; use graphics::{ Context, Graphics }; use input::{ GenericEvent }; mod drawutils; mod rectangle_box; pub mod timeline_split; pub struct Timeline { pub frames: u32, pub current_frame: u32, pub hover_frame: Option<u32>, pub start_frame: u32, ...
extern crate graphics; extern crate input; extern crate rect; use graphics::{ Context, Graphics }; use input::{ GenericEvent }; mod drawutils; mod rectangle_box; pub mod timeline_split; pub struct Timeline { pub frames: u32, pub current_frame: u32, pub hover_frame: Option<u32>, pub start_frame: u32, ...
pub fn draw_timeline<G: Graphics>(&self, c: &Context, g: &mut G) { use std::cmp::min; let left_to_frame: f64 = self.settings.offset.left; let right_to_frame: f64 = self.settings.offset.right; let top_to_frame: f64 = self.settings.offset.top; let frame_width: f64 = self.set...
offset_x; let end_frame: u32 = computed_settings.end_frame; let (x, y) = (pos[0], pos[1]); let left = self.bounds[0] as f64 + left_to_frame; let right = left + end_frame as f64 * (frame_width + frame_offset_x); let top = self.bounds[1] a...
function_block-function_prefixed
[ { "content": "/// Test drawing for timeline split.\n\nfn test_draw_timeline<G: Graphics>(rect: [u32; 4], c: &Context, g: &mut G) {\n\n let top = 20.0;\n\n let top_factor = 0.3;\n\n if let Some(layout) =\n\n (TimelineSplitInput {\n\n rect: Rect::from_u32(rect),\n\n margin: 4...
Rust
src/bin/server/command.rs
mambisi/escanor
7cb5881b8270da2857198024d22fd19e04e40e98
extern crate regex; use crate::{db, printer}; use crate::error; use crate::error::SyntaxError; use crate::tokenizer; use crate::syntax_analyzer; use crate::unit_conv::Units; use crate::storage; use redis_protocol::types::Frame; use serde_json::Value; use crate::printer::*; pub fn compile_frame(frame: &Frame) -> Re...
extern crate regex; use crate::{db, printer}; use crate::error; use crate::error::SyntaxError; use crate::tokenizer; use crate::syntax_analyzer; use crate::unit_conv::Units; use crate::storage; use redis_protocol::types::Frame; use serde_json::Value; use crate::printer::*; pub fn compile_frame(frame: &Frame) -> Re...
String} -> db::persist); make_command!(TTLCmd{arg_key : String} -> db::ttl); make_command!(ExpireCmd{arg_key: String, arg_value : i64} -> db::expire); make_command!(IncrByCmd{arg_key: String, arg_value : i64} -> db::incr_by); make_command!(ExpireAtCmd{arg_key: String, arg_value : i64} -> db::expire_at); make_command!(K...
and for PingCmd { fn execute(&self, _: Arc<RwLock<Context>>) -> String { printer::print_pong() } } impl Command for AuthCmd { fn execute(&self, context: Arc<RwLock<Context>>) -> String { db::auth(context, self) } } make_command!(AddClusterCmd{arg_addrs : String, arg_node_id: u64} -> sto...
random
[ { "content": "pub fn opt_frame_to_string_panic(f: Option<Frame>, msg: &str) -> String {\n\n f.expect(msg).to_string().expect(msg)\n\n}\n\n\n", "file_path": "redis-protocol/src/utils.rs", "rank": 0, "score": 173336.09526779933 }, { "content": "/// Attempt to encode a frame into `buf`, assumi...
Rust
src/views/overview.rs
maxmindlin/rabbitui
7a779852199728ea6dd81faa0b7dd7f685f0ed9b
use super::{Drawable, StatefulPane}; use crate::{ models::Overview, widgets::{ chart::{ChartData, RChart}, help::Help, }, ManagementClient, }; use std::sync::{mpsc, Arc}; use termion::event::Key; use tui::{ backend::Backend, layout::{Constraint, Direction, Layout, Rect}, st...
use super::{Drawable, StatefulPane}; use crate::{ models::Overview, widgets::{ chart::{ChartData, RChart}, help::Help, }, ManagementClient, }; use std::sync::{mpsc, Arc}; use termion::event::Key; use tui::{ backend::Backend, layout::{Constraint, Direction, Layout, Rect}, st...
fn draw_message_list<B: Backend>(&mut self, f: &mut Frame<B>, area: Rect) { let datasets = [&self.data.ready, &self.data.overall, &self.data.unacked]; let labels = ["Ready", "Total", "Unacked"]; let colors = [Color::Yellow, Color::Cyan, Color::Red]; self.draw_info_list(f, area, lab...
format!("{}{}", val, suffix), Style::default().add_modifier(Modifier::BOLD), ), ]), Spans::from(""), ]) }) .collect(); let list = List::new(items).block(Block:...
function_block-function_prefix_line
[ { "content": "/// The manager gives us a way to structure the relationship\n\n/// between our tabs and panes. Serves as a middleman between\n\n/// app and panes.\n\n///\n\n/// Also provides nicety guarantees. For example, tabs vs panes\n\n/// should always be 1-1 - const generics here enforce that 1-1 size\n\n/...
Rust
rustypwn/src/io/tube.rs
Escapingbug/rustypwn
a2507e4b9f2317299bf0d61d0d44350192612d6d
use super::arg::{Action, Timeout}; use super::buffer::Buffer; use super::error::{Error, ErrorKind}; use rustypwn_derive::action; use std::io; use std::io::{BufRead, Write}; use std::ops::Drop; use std::time::{Duration, SystemTime}; pub trait TubeInternal: Drop { fn mut_buffer(&mut self) -> &mut Buffer; fn...
use super::arg::{Action, Timeout}; use super::buffer::Buffer; use super::error::{Error, ErrorKind}; use rustypwn_derive::action; use std::io; use std::io::{BufRead, Write}; use std::ops::Drop; use std::time::{Duration, SystemTime}; pub trait TubeInternal: Drop { fn mut_buffer(&mut self) -> &mut Buffer; fn...
#[action] fn interactive(&mut self, action: Action) -> Result<(), Error> { let stdin = io::stdin(); print!("$ "); io::stdout().flush().unwrap(); for line in stdin.lock().lines() { let line = line.expect("unable to read line in interactive"); let arg = Ac...
fn recvline(&mut self, action: Action) -> Result<Vec<u8>, Error> { let arg = Action::Recvuntil { timeout: timeout, pattern: "\n".to_string(), }; self.recvuntil(arg) }
function_block-full_function
[ { "content": "#[proc_macro_attribute]\n\npub fn action(\n\n attr: proc_macro::TokenStream,\n\n input: proc_macro::TokenStream,\n\n) -> proc_macro::TokenStream {\n\n let input = parse_macro_input!(input as syn::ItemFn);\n\n let args = parse_macro_input!(attr as CommaSepIdents).idents;\n\n\n\n let ...
Rust
src/configs.rs
whizsid/veye-checker
c9a694a52eba234fa681cdf04cfa19c474103a21
use std::env; use regex::Regex; use std::default::{Default}; use std::io::{Read, Error, ErrorKind}; use std::path::PathBuf; use std::fs::File; use toml; use digest_ext_table::{DigestAlgo, DigestExtTable}; pub static DEFAULT_MAX_SIZE:u64 = 64 * 1024 * 1024; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ...
use std::env; use regex::Regex; use std::default::{Default}; use std::io::{Read, Error, ErrorKind}; use std::path::PathBuf; use std::fs::File; use toml; use digest_ext_table::{DigestAlgo, DigestExtTable}; pub static DEFAULT_MAX_SIZE:u64 = 64 * 1024 * 1024; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ...
} pub fn read_configs(filepath: Option<String>) -> Configs { let conf_filepath = filepath.unwrap_or("veye_checker.toml".to_string()); let conf_file = PathBuf::from(conf_filepath.clone()); let mut confs = Configs::default(); match read_configs_from_toml(&conf_file) { Ok(toml_confs) => to...
fn default() -> Configs { Configs { api: ApiConfigs::default(), csv: CSVConfigs::default(), proxy: ProxyConfigs::default(), digests: DigestExtTable::default(), scan: ScanConfigs::default() } }
function_block-full_function
[ { "content": "pub fn digest_md5(filepath: &Path) -> Result<String, Error> {\n\n let mut f = File::open(filepath).ok().expect(\"Failed to open python package for digest\");\n\n let mut buffer = Vec::new();\n\n\n\n f.read_to_end(&mut buffer).expect(\"Failed to read python package into buffer\");\n\n l...
Rust
core/src/services/metrics/data_collector.rs
jpJuni0r/WebGrid
26e21637ef88e8af9d64c6fce0de55890eaa6dec
use super::structures::{Metric, MetricType, MetricValue}; use crate::libraries::helpers::keys; use crate::libraries::metrics::SESSION_STARTUP_HISTOGRAM_BUCKETS; use redis::{aio::ConnectionLike, AsyncCommands}; static HTTP_METHODS: [&str; 9] = [ "GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "CONNECT", "PATCH",...
use super::structures::{Metric, MetricType, MetricValue}; use crate::libraries::helpers::keys; use crate::libraries::metrics::SESSION_STARTUP_HISTOGRAM_BUCKETS; use redis::{aio::ConnectionLike, AsyncCommands}; static HTTP_METHODS: [&str; 9] = [ "GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "CONNECT", "PATCH",...
for log_level in LOG_LEVELS.iter() { if let Ok(log_codes) = con .hgetall::<_, Vec<(String, f64)>>(keys::metrics::session::log(log_level)) .await { for (log_code, count) in log_codes { metric.values.push( MetricValue::from_value(coun...
ption: "Log codes for sessions".to_string(), metric_type: MetricType::Counter, values: Vec::new(), };
function_block-random_span
[ { "content": "/// Splits the input string into two parts at the first occurence of the separator\n\npub fn split_into_two(input: &str, separator: &'static str) -> Option<(String, String)> {\n\n let parts: Vec<&str> = input.splitn(2, separator).collect();\n\n\n\n if parts.len() != 2 {\n\n return Non...
Rust
src/kmem.rs
tong-os/tongOS
2b7528c138a29869d17e1efd440680c2776724ea
use crate::lock::Mutex; use crate::page; static mut KMEM_ALLOC: usize = 0; static mut KMEM_HEAD: *mut KernelPageDescriptor = core::ptr::null_mut(); static mut KMEM_LOCK: Mutex = Mutex::new(); fn get_kmem_lock() -> &'static mut Mutex { unsafe { &mut KMEM_LOCK } } #[repr(usize)] pub enum KernelPageDescriptorFla...
use crate::lock::Mutex; use crate::page; static mut KMEM_ALLOC: usize = 0; static mut KMEM_HEAD: *mut KernelPageDescriptor = core::ptr::null_mut(); static mut KMEM_LOCK: Mutex = Mutex::new(); fn get_kmem_lock() -> &'static mut Mutex { unsafe { &mut KMEM_LOCK } } #[repr(usize)] pub enum KernelPageDescriptorFla...
} #[global_allocator] static GA: OsGlobalAlloc = OsGlobalAlloc {}; #[alloc_error_handler] pub fn alloc_error(l: Layout) -> ! { panic!( "Allocator failed to allocate {} bytes with {}-byte alignment.", l.size(), l.align() ); }
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { get_kmem_lock().try_lock(); kfree(ptr); get_kmem_lock().unlock(); }
function_block-full_function
[ { "content": "/// Deallocate a page by its pointer\n\npub fn dealloc(ptr: *mut u8) {\n\n get_alloc_lock().spin_lock();\n\n // Make sure we don't try to free a null pointer.\n\n assert!(!ptr.is_null());\n\n unsafe {\n\n let address = HEAP_START + (ptr as usize - PAGE_TABLE_START_ADDRESS) / PAG...
Rust
imxrt1062-pac/imxrt1062-dma0/src/tcd27_biter_elinkyes.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register TCD27_BITER_ELINKYES"] pub type R = crate::R<u16, super::TCD27_BITER_ELINKYES>; #[doc = "Writer for register TCD27_BITER_ELINKYES"] pub type W = crate::W<u16, super::TCD27_BITER_ELINKYES>; #[doc = "Register TCD27_BITER_ELINKYES `reset()`'s with value 0"] impl crate::ResetValue for super::TCD...
#[doc = "Reader of register TCD27_BITER_ELINKYES"] pub type R = crate::R<u16, super::TCD27_BITER_ELINKYES>; #[doc = "Writer for register TCD27_BITER_ELINKYES"] pub type W = crate::W<u16, super::TCD27_BITER_ELINKYES>; #[doc = "Register TCD27_BITER_ELINKYES `reset()`'s with value 0"] impl crate::ResetValue for super::TCD...
#[doc = "Checks if the value of the field is `ELINK_0`"] #[inline(always)] pub fn is_elink_0(&self) -> bool { *self == ELINK_A::ELINK_0 } #[doc = "Checks if the value of the field is `ELINK_1`"] #[inline(always)] pub fn is_elink_1(&self) -> bool { *self == ELINK_A::ELINK_1 ...
A { match self.bits { false => ELINK_A::ELINK_0, true => ELINK_A::ELINK_1, } }
function_block-function_prefixed
[ { "content": "/// Migrate the `lib.rs` of the PAC subscrate, adding\n\n/// our necessary header to the top of the file.\n\nfn write_lib<R: Read>(crate_path: &Path, mut src: R) {\n\n static LIB_PRELUDE: &str = r#\"#![deny(warnings)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(clippy::all)]\n\n#![no_std]\n\...
Rust
src/connectivity/wlan/testing/hw-sim/src/test_utils.rs
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
use { crate::{ wlancfg_helper::{ init_client_controller, start_ap_and_wait_for_confirmation, NetworkConfigBuilder, }, Beacon, EventHandlerBuilder, Sequence, }, fidl::endpoints::create_proxy, fidl_fuchsia_wlan_policy as fidl_policy, fidl_fuchsia_wlan_tap as wlantap, ...
use { crate::{ wlancfg_helper::{ init_client_controller, start_ap_and_wait_for_confirmation, NetworkConfigBuilder, }, Beacon, EventHandlerBuilder, Sequence, }, fidl::endpoints::create_proxy, fidl_fuchsia_wlan_policy as fidl_policy, fidl_fuchsia_wlan_tap as wlantap, ...
pub type ScanResult = (Vec<u8>, [u8; 6], bool, i8); pub async fn scan_for_networks( phy: &Arc<wlantap::WlantapPhyProxy>, beacons: &[ScanTestBeacon], helper: &mut TestHelper, ) -> Vec<ScanResult> { let (client_controller, _update_stream) = init_client_controller().await; let scan_event = phy_...
mpl FnMut(wlantap::WlantapPhyEvent) + 'a { let mut beacon_sequence = Sequence::start(); for beacon in beacons { let mut beacon_to_send = Beacon::send_on_primary_channel(beacon.channel, phy) .bssid(beacon.bssid) .ssid(beacon.ssid.clone()) .protection(beacon.protection...
function_block-function_prefixed
[]
Rust
src/the_way/cli.rs
jonasmalacofilho/the-way
093b1d8f7bacfd93a9d6161011880735fb14c385
use std::path::PathBuf; use structopt::clap::AppSettings; use structopt::clap::Shell; use structopt::StructOpt; use crate::configuration::ConfigCommand; use crate::the_way::filter::Filters; #[derive(Debug, StructOpt)] #[structopt( name = "the-way", rename_all = "kebab-case", global_settings = & [AppSettings::Derive...
use std::path::PathBuf; use structopt::clap::AppSettings; use structopt::clap::Shell; use structopt::StructOpt; use crate::configuration::ConfigCommand; use crate::the_way::filter::Filters; #[derive(Debug, StructOpt)] #[structopt( name = "the-way", rename_all = "kebab-case", global_settings = & [AppSettings::Derive...
index: usize, #[structopt(long, short)] force: bool, }, #[structopt(alias = "copy")] Cp { index: usize, #[structopt(long)] stdout: bool, }, View { index: usize, }, } #[derive(StructOpt, Debug)] pu...
url: Option<String>, }, Export { #[structopt(parse(from_os_str))] file: Option<PathBuf>, #[structopt(flatten)] filters: Filters, }, Clear { #[structopt(long, short)] force: bool, }, Complete { #[structopt(po...
random
[ { "content": "/// List of usize into semicolon-joined byte array\n\npub fn make_indices_string(index_list: &[usize]) -> color_eyre::Result<Vec<u8>> {\n\n Ok(index_list\n\n .iter()\n\n .map(|index| index.to_string())\n\n .collect::<Vec<String>>()\n\n .join(str::from_utf8(&[SEMICOLO...
Rust
src/main.rs
stephenc/zkinit
6565cdb3469b6553fa26f491b9f88abc321cf818
extern crate getopts; extern crate zookeeper; use std::env; use std::fs::File; use std::io::Read; use std::time::Duration; use getopts::Options; use zookeeper::{Acl, CreateMode, WatchedEvent, Watcher, ZkError, ZooKeeper}; fn create_options() -> Options { let mut opts = Options::new(); opts.optflag("h", "he...
extern crate getopts; extern crate zookeeper; use std::env; use std::fs::File; use std::io::Read; use std::time::Duration; use getopts::Options; use zookeeper::{Acl, CreateMode, WatchedEvent, Watcher, ZkError, ZooKeeper}; fn create_options() -> Options { let mut opts = Options::new(); opts.optflag("h", "he...
}, ZkError::NoNode => { eprintln!("Parent node for {} does not exist, consider using --parents command line option", zk_node); std::process::exit(5) } _ => { eprintln!("Could not create node {} :...
if update_if_exists { match zk.set_data(zk_node.as_str(), data, None) { Ok(_) => (), Err(e) => { eprintln!("Could not update {}: {:?}", zk_node, e); std::process::exit(4) ...
if_condition
[]
Rust
rust_dev_preview/dynamodb/src/bin/movies.rs
iconara/aws-doc-sdk-examples
52706b31b4fce8fb89468e56743edf5369e69628
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use std::collections::HashMap; use std::time::Duration; use aws_config::meta::region::RegionProviderChain; use aws_http::retry::AwsErrorRetryPolicy; use aws_sdk_dynamodb::client::fluent_builders::Query...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use std::collections::HashMap; use std::time::Duration; use aws_config::meta::region::RegionProviderChain; use aws_http::retry::AwsErrorRetryPolicy; use aws_sdk_dynamodb::client::fluent_builders::Query...
; println!("Adding items to table."); for value in data { add_item(&client, &table, value).await?; } println!("Making sure table has items."); let films_2222 = movies_in_year(&client, &table.to_string(), 2222) .send() .await .expect("query should succeed"); ...
match serde_json::from_str(include_str!("data.json")).expect("should be valid JSON") { Value::Array(inner) => inner, data => panic!("data must be an array, got: {:?}", data), }
if_condition
[ { "content": " static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();\n", "file_path": "java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/CreateTablesLoadData.java", "rank": 0, "score": 354404.65348112315 }, { "content": "#[derive(Debug, StructOpt)...
Rust
submit/src/update.rs
swilcox3/kafka-cad
3fa3566fd763aad953a90a36401c664bf27e53a8
use super::*; use indexmap::IndexMap; use std::collections::HashSet; fn extract_info(changes: Vec<ChangeMsg>) -> (Vec<RefIdMsg>, IndexMap<String, ChangeMsg>) { let mut ref_ids = Vec::new(); let mut objects = IndexMap::new(); for change in changes { if let Some(change_type) = &change.change_type { ...
use super::*; use indexmap::IndexMap; use std::collections::HashSet; fn extract_info(changes: Vec<ChangeMsg>) -> (Vec<RefIdMsg>, IndexMap<String, ChangeMsg>) { let mut ref_ids = Vec::new(); let mut objects = IndexMap::new(); for change in changes { if let Some(change_type) = &change.change_type { ...
} } } objects.insert(object.id.clone(), change); } change_msg::ChangeType::Delete(msg) => { objects.insert(msg.id.clone(), change); } } } ...
if let Some(owner) = &refer.owner { ref_ids.push(owner.clone()) }
if_condition
[ { "content": "pub fn add(user: &str, obj: ObjectMsg) -> ChangeMsg {\n\n object_state::ChangeMsg {\n\n user: String::from(user),\n\n change_type: Some(object_state::change_msg::ChangeType::Add(obj)),\n\n change_source: Some(object_state::change_msg::ChangeSource::UserAction(\n\n ...
Rust
src/persist.rs
blofroth/corrosive-fog
d5a3f7a30854d63e86ed0719f9af431505c275c7
use dbmodel::*; use std::collections::HashMap; use std::mem; use std::sync::{RwLock}; use diesel::prelude::*; use diesel::pg::PgConnection; use r2d2_diesel::ConnectionManager; use r2d2::Pool; use r2d2; use dotenv::dotenv; use std::env; use diesel; pub type PersistenceError = String; pub trait NoteRepository { fn ...
use dbmodel::*; use std::collections::HashMap; use std::mem; use std::sync::{RwLock}; use diesel::prelude::*; use diesel::pg::PgConnection; use r2d2_diesel::ConnectionManager; use r2d2::Pool; use r2d2; use dotenv::dotenv; use std::env; use diesel; pub type PersistenceError = String; pub trait NoteRepository { fn ...
}
fn upsert_note(&self, username: String, note: Note) -> Result<bool, PersistenceError> { use schema::notes::dsl::*; let connection = &*self.connection_pool.get() .expect("get connection from pool"); diesel::insert(&note).into(notes) .get_result(connection) .ma...
function_block-full_function
[ { "content": "#[get(\"/<username>/notes/<guid>\")]\n\nfn get_user_note(username: String, guid: String, note_repo: State<NoteSyncController>) -> Result<Json<NoteWrapper>, String> {\n\n match note_repo.get_note(username.into(), guid.into()) {\n\n Ok(note) => Ok(Json(NoteWrapper {\n\n note: ve...
Rust
tests/bigint_scalar.rs
gmorenz/num-bigint
666cdc6f2c6a7094042d80214bd6b9cf4c3e27b8
extern crate num_bigint_dig as num_bigint; extern crate num_traits; use num_bigint::BigInt; use num_bigint::Sign::Plus; use num_traits::{Signed, ToPrimitive, Zero}; use std::ops::Neg; mod consts; use consts::*; #[macro_use] mod macros; #[test] fn test_scalar_add() { fn check(x: &BigInt, y: &BigInt, z: &BigInt)...
extern crate num_bigint_dig as num_bigint; extern crate num_traits; use num_bigint::BigInt; use num_bigint::Sign::Plus; use num_traits::{Signed, ToPrimitive, Zero}; use std::ops::Neg; mod consts; use consts::*; #[macro_use] mod macros; #[test] fn test_scalar_add() { fn check(x: &BigInt, y: &BigInt, z: &BigInt)...
fn test_scalar_div_rem() { fn check_sub(a: &BigInt, b: u32, ans_q: &BigInt, ans_r: &BigInt) { let (q, r) = (a / b, a % b); if !r.is_zero() { assert_eq!(r.sign(), a.sign()); } assert!(r.abs() <= From::from(b)); assert!(*a == b * &q + &r); assert!(q == *ans_...
function_block-full_function
[ { "content": "#[test]\n\nfn bigint_zero() {\n\n let tokens = [\n\n Token::Tuple { len: 2 },\n\n Token::I8(0),\n\n Token::Seq { len: Some(0) },\n\n Token::SeqEnd,\n\n Token::TupleEnd,\n\n ];\n\n assert_tokens(&BigInt::zero(), &tokens);\n\n}\n\n\n", "file_path": "te...
Rust
src/configs/mod.rs
MikkelHegn/starship
c4439531d35dfbed008a0dd519aa89bb67dcce24
use crate::config::ModuleConfig; use indexmap::IndexMap; use serde::{self, Serialize}; use starship_module_config_derive::ModuleConfig; pub mod aws; pub mod battery; pub mod character; pub mod cmake; pub mod cmd_duration; pub mod cobol; pub mod conda; pub mod crystal; pub mod custom; pub mod dart; pub mod deno; pub mo...
use crate::config::ModuleConfig; use indexmap::IndexMap; use serde::{self, Serialize}; use starship_module_config_derive::ModuleConfig; pub mod aws; pub mod battery; pub mod character; pub mod cmake; pub mod cmd_duration; pub mod cobol; pub mod conda; pub mod crystal; pub mod custom; pub mod dart; pub mod deno; pub mo...
username: Default::default(), vagrant: Default::default(), vcsh: Default::default(), vlang: Default::default(), zig: Default::default(), custom: Default::default(), } } } #[cfg(test)] mod test { use super::*; use crate::module...
Self { format: "$all".to_string(), right_format: "".to_string(), scan_timeout: 30, command_timeout: 500, add_newline: true, aws: Default::default(), battery: Default::default(), character: Default::default(), ...
function_block-random_span
[ { "content": "pub fn print_configuration(use_default: bool) {\n\n let config = if use_default {\n\n // Get default config\n\n let default_config = crate::configs::FullConfig::default();\n\n // Convert back to Value because toml can't serialize FullConfig directly\n\n toml::value::...
Rust
gdk4/src/event.rs
melix99/gtk4-rs
c382c0536e995584a789a90605a0120ee1aa24eb
use crate::{Event, EventType}; use glib::translate::*; use glib::StaticType; use std::fmt; use std::mem; impl Event { pub fn downcast<T: EventKind>(self) -> Result<T, Event> { unsafe { if T::event_types().contains(&self.event_type()) { Ok(from_glib_full(self.to_glib_full())) ...
use crate::{Event, EventType}; use glib::translate::*; use glib::StaticType; use std::fmt; use std::mem; impl Event { pub fn downcast<T: EventKind>(self) -> Result<T, Event> { unsafe { if T::event_types().contains(&self.event_type()) { Ok(from_glib_full(self.to_glib_full())) ...
} impl fmt::Debug for Event { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Event") .field("event_type", &self.event_type()) .field("history", &self.history()) .field("modifier_state", &self.modifier_state()) .field("pointer_emulated...
e = mem::MaybeUninit::uninit(); let ret = from_glib(ffi::gdk_events_get_distance( self.to_glib_none().0, event.as_ref().to_glib_none().0, distance.as_mut_ptr(), )); if ret { let distance = distance.assume_init(); ...
function_block-function_prefixed
[]
Rust
lib0/src/any.rs
Waidhoferj/y-crdt
a28e23428e7a699183e759769f83c7a264d2874f
use crate::decoding::Read; use crate::encoding::Write; use std::cmp::PartialEq; use std::collections::HashMap; use std::convert::TryInto; #[derive(Debug, Clone, PartialEq)] pub enum Any { Null, Undefined, Bool(bool), Number(f64), BigInt(i64), String(Box<str>), Buffer(Box<[u8]>), Array(B...
use crate::decoding::Read; use crate::encoding::Write; use std::cmp::PartialEq; use std::collections::HashMap; use std::convert::TryInto; #[derive(Debug, Clone, PartialEq)] pub enum Any { Null, Undefined, Bool(bool), Number(f64), BigInt(i64), String(Box<str>), Buffer(Box<[u8]>), Array(B...
} impl<T> Into<Any> for HashMap<String, T> where T: Into<Any>, { fn into(self) -> Any { let mut map = HashMap::with_capacity(self.len()); for (key, value) in self { map.insert(key, value.into()); } Any::Map(Box::new(map)) } } impl TryInto<Any> for u64 { typ...
fn into(self) -> Any { let mut array = Vec::with_capacity(self.len()); for value in self { array.push(value.into()) } Any::Array(array.into_boxed_slice()) }
function_block-full_function
[ { "content": "fn n_concurrent_map_benchmark<F>(c: &mut Criterion, name: &str, f: F)\n\nwhere\n\n F: Fn(&Map, &mut Transaction, usize),\n\n{\n\n let input: Vec<_> = (0..SQRT_N)\n\n .into_iter()\n\n .map(|i| {\n\n let doc = Doc::new();\n\n let mut txn = doc.transact();\n\...
Rust
src/pathmanager/mod.rs
SnakeSolid/rust-pgrestore-web
271ed8be0fac243356f013e50797b1594e0639ff
mod error; pub use self::error::PathManagerError; pub use self::error::PathManagerResult; use std::collections::HashMap; use std::collections::HashSet; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::RwLock; #[derive(Debug, Clone)] pub struct PathManagerRef { inner: Arc<RwLock<Pat...
mod error; pub use self::error::PathManagerError; pub use self::error::PathManagerResult; use std::collections::HashMap; use std::collections::HashSet; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::RwLock; #[derive(Debug, Clone)] pub struct PathManagerRef { inner: Arc<RwLock<Pat...
} #[derive(Debug)] struct PathManager { paths: HashMap<usize, PathBuf>, index: HashMap<String, Vec<usize>>, next_index: usize, } impl PathManager { fn new() -> PathManager { PathManager { paths: HashMap::new(), index: HashMap::new(), next_index: 0, ...
pub fn add_path(&self, path: &Path) -> PathManagerResult<()> { self.with_write(move |pathmanager| { pathmanager.add_path(path); Ok(()) }) }
function_block-full_function
[ { "content": "pub fn handle_request<Req, Res, F>(request: &mut Request, callback: F) -> IronResult<Response>\n\nwhere\n\n Req: DeserializeOwned,\n\n Res: Serialize,\n\n F: FnOnce(Req) -> HandlerResult<Res>,\n\n{\n\n let result = match serde_json::from_reader(request.body.by_ref()) {\n\n Ok(re...
Rust
csml_interpreter/src/parser/step_checksum.rs
suryatmodulus/csml-engine
20a213b9bb0ec52694aa9d4828781306b59f3e11
use crate::data::{ast::*, tokens::*}; use crate::error_format::*; use crate::interpreter::variable_handler::interval::interval_from_expr; use crate::parser::parse_comments::comment; use nom::{ bytes::complete::take_while1, error::ParseError, multi::fold_many0, sequence::preceded, Err, IResult, InputTake, }; f...
use crate::data::{ast::*, tokens::*}; use crate::error_format::*; use crate::interpreter::variable_handler::interval::interval_from_expr; use crate::parser::parse_comments::comment; use nom::{ bytes::complete::take_while1, error::ParseError, multi::fold_many0, sequence::preceded, Err, IResult, InputTake, }; f...
nstructionScope::ImportScope(_) => { let interval = interval_from_expr(block); skip_offsets.push(interval.offset) } InstructionScope::DuplicateInstruction(..) => {} } } offsets.sort_by(|(_, a), (_, b)| a.cmp(b)); skip_offsets.sort_by(|a, b| a.c...
acc.push(item); acc })(s)?; let s: String = vec.into_iter().collect(); Ok((span, s)) } fn get_step_offset( name: &str, offsets: &[(String, usize)], ) -> ((String, usize), Option<(String, usize)>) { let mut step_info = None; let mut index = 0; for (i, (step_name, offset)) in of...
random
[ { "content": "pub fn gen_nom_error<'a, E>(span: Span<'a>, error: &'static str) -> Err<E>\n\nwhere\n\n E: ParseError<Span<'a>>,\n\n{\n\n Err::Error(E::add_context(\n\n span,\n\n error,\n\n E::from_error_kind(span, ErrorKind::Tag),\n\n ))\n\n}\n\n\n", "file_path": "csml_interpret...
Rust
common/datavalues/src/arrays/list/mod.rs
yufan022/datafuse
8bc5b014ff52f920d8dcf5de8c5c098267acf06d
use common_arrow::arrow::array::*; use common_exception::ErrorCode; use common_exception::Result; mod builder; mod iterator; use std::sync::Arc; pub use builder::*; pub use iterator::*; use crate::prelude::*; #[derive(Debug, Clone)] pub struct DFListArray { pub(crate) array: LargeListArray, pub data_type:...
use common_arrow::arrow::array::*; use common_exception::ErrorCode; use common_exception::Result; mod builder; mod iterator; use std::sync::Arc; pub use builder::*; pub use iterator::*; use crate::prelude::*; #[derive(Debug, Clone)] pub struct DFListArray { pub(crate) array: LargeListArray, pub data_type:...
f self.data_type() == array.data_type() { let ca = &*(array_trait as *const dyn SeriesTrait as *const Self); Ok(ca) } else { Err(ErrorCode::IllegalDataType(format!( "cannot unpack array {:?} into matching type {:?}", array, self...
esed.len() { v.push(netesed.try_get(i)?); } Some(v) } }; Ok(DataValue::List(v, self.sub_data_type().clone())) } pub fn len(&self) -> usize { self.array.len() } #[inline] pub fn is_empty(&self) -> bool { ...
random
[ { "content": "// put_uvarint encodes a uint64 into buf and returns the number of bytes written.\n\n// If the buffer is too small, put_uvarint will panic.\n\npub fn put_uvarint(mut buffer: impl AsMut<[u8]>, x: u64) -> usize {\n\n let mut i = 0;\n\n let mut mx = x;\n\n let buf = buffer.as_mut();\n\n w...
Rust
datafusion/src/physical_plan/explain.rs
flock-lab/arrow-datafusion
3c813ed6f9ec9ab0ce142adcdc2d2ac2fceb4c5d
use std::any::Any; use std::sync::Arc; use crate::{ error::{DataFusionError, Result}, logical_plan::StringifiedPlan, physical_plan::{ common::SizedRecordBatchStream, DisplayFormatType, ExecutionPlan, Partitioning, Statistics, }, }; use crate::physical_plan::LambdaExecPlan; use arrow::...
use std::any::Any; use std::sync::Arc; use crate::{ error::{DataFusionError, Result}, logical_plan::StringifiedPlan, physical_plan::{ common::SizedRecordBatchStream, DisplayFormatType, ExecutionPlan, Partitioning, Statistics, }, }; use crate::physical_plan::LambdaExecPlan; use arrow::...
} } } fn statistics(&self) -> Statistics { Statistics::default() } } fn should_show(previous_plan: &StringifiedPlan, this_plan: &StringifiedPlan) -> bool { (previous_plan.plan != this_plan.plan) || this_plan.should_display(false) } #[async_trait] impl LambdaEx...
(&self) -> SchemaRef { self.schema.clone() } fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> { vec![] } fn output_partitioning(&self) -> Partitioning { Partitioning::UnknownPartitioning(1) } fn with_new_children( &self, children: Vec<Arc...
random
[ { "content": "/// Create a column expression\n\npub fn col(name: &str, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {\n\n Ok(Arc::new(Column::new_with_schema(name, schema)?))\n\n}\n", "file_path": "datafusion/src/physical_plan/expressions/column.rs", "rank": 0, "score": 351459.2273560989 }...
Rust
src/io/ipc/read/stream.rs
sd2k/arrow2
6ccb1542467024683b61f7ec4bb0ae67caebfbb2
use std::io::Read; use std::sync::Arc; use arrow_format; use arrow_format::ipc::planus::ReadAsRoot; use crate::array::Array; use crate::chunk::Chunk; use crate::datatypes::Schema; use crate::error::{ArrowError, Result}; use crate::io::ipc::IpcSchema; use super::super::CONTINUATION_MARKER; use super::common::*; use s...
use std::io::Read; use std::sync::Arc; use arrow_format; use arrow_format::ipc::planus::ReadAsRoot; use crate::array::Array; use crate::chunk::Chunk; use crate::datatypes::Schema; use crate::error::{ArrowError, Result}; use crate::io::ipc::IpcSchema; use super::super::CONTINUATION_MARKER; use super::common::*; use s...
?; if batch.is_none() { self.finished = true; } Ok(batch) } } impl<R: Read> Iterator for StreamReader<R> { type Item = Result<StreamState>; fn next(&mut self) -> Option<Self::Item> { self.maybe_next().transpose() } }
read_next( &mut self.reader, &self.metadata, &mut self.dictionaries, &mut self.message_buffer, &mut self.data_buffer, )
call_expression
[ { "content": "/// Reads the schema from `reader`, returning the file's [`Schema`] and [`Compression`].\n\n/// # Error\n\n/// This function errors iff the header is not a valid avro file header.\n\npub fn read_schema<R: Read>(reader: &mut R) -> Result<(Schema, Option<Compression>, [u8; 16])> {\n\n read_metada...
Rust
src/lib.rs
arxanas/cursive-aligned-view
32524749a2c2169e3ad5114ed25d756331d2c34a
use cursive_core::align::{Align, HAlign, VAlign}; use cursive_core::direction::Direction; use cursive_core::event::{AnyCb, Event, EventResult}; use cursive_core::view::{Selector, View, ViewNotFound}; use cursive_core::{Printer, Rect, Vec2}; pub trait Alignable: View + Sized { fn align_top_left(self) -> Alig...
use cursive_core::align::{Align, HAlign, VAlign}; use cursive_core::direction::Direction; use cursive_core::event::{AnyCb, Event, EventResult}; use cursive_core::view::{Selector, View, ViewNotFound}; use cursive_core::{Printer, Rect, Vec2}; pub trait Alignable: View + Sized { fn align_top_left(self) -> Alig...
fn needs_relayout(&self) -> bool { self.needs_relayout || self.view.needs_relayout() } fn required_size(&mut self, constraint: Vec2) -> Vec2 { self.last_size = self.view.required_size(constraint); self.last_size } fn on_event(&mut self, ev: Event) -> EventResult { ...
let x = std::cmp::min(size.x, self.last_size.x); let y = std::cmp::min(size.y, self.last_size.y); self.view.layout(Vec2::new(x, y)); self.needs_relayout = false; }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn align_center() {\n\n let panel = Panel::new(DummyView)\n\n .title(\"Hello, world!\")\n\n .align_center();\n\n assert_eq!(*panel.alignment(), Align::center())\n\n}\n", "file_path": "tests/end2end.rs", "rank": 1, "score": 51516.00375571824 }, { "...
Rust
components/engine_rocks/src/compact.rs
darionyaphet/tikv
007556d3bc0ae058d08caed39e71c4ddd4de4195
use crate::engine::RocksEngine; use crate::util; use engine_traits::{CFNamesExt, CompactExt, Result}; use rocksdb::{CompactOptions, CompactionOptions, DBCompressionType}; use std::cmp; impl CompactExt for RocksEngine { fn auto_compactions_is_disabled(&self) -> Result<bool> { for cf_name in self.cf_names(...
use crate::engine::RocksEngine; use crate::util; use engine_traits::{CFNamesExt, CompactExt, Result}; use rocksdb::{CompactOptions, CompactionOptions, DBCompressionType}; use std::cmp; impl CompactExt for RocksEngine { fn auto_compactions_is_disabled(&self) -> Result<bool> { for cf_name in self.cf_names(...
let level_1 = cf_levels[1].get_files(); assert_eq!(level_1.len(), 1); assert_eq!(level_1[0].get_smallestkey(), &[0]); assert_eq!(level_1[0].get_largestkey(), &[4]); } db.c() .compact_files_in_ra...
estkey() { continue; } if start.is_some() && start.unwrap() > f.get_largestkey() { continue; } input_files.push(f.get_name()); } } if input_files.is_empty() { return Ok(()); ...
random
[ { "content": "pub fn get_cf_handle<'a>(db: &'a DB, cf: &str) -> Result<&'a CFHandle> {\n\n let handle = db\n\n .cf_handle(cf)\n\n .ok_or_else(|| Error::Engine(format!(\"cf {} not found\", cf)))?;\n\n Ok(handle)\n\n}\n\n\n", "file_path": "components/engine_rocks/src/util.rs", "rank": ...
Rust
query/src/servers/http/v1/query/execute_state.rs
willie-lin/databend
52a62a2db71544284449b209e79972a021ff19db
use std::sync::Arc; use common_base::tokio; use common_base::tokio::sync::mpsc; use common_base::tokio::sync::RwLock; use common_base::ProgressValues; use common_base::TrySpawn; use common_datablocks::DataBlock; use common_datavalues::DataSchemaRef; use common_exception::ErrorCode; use common_exception::Result; use ...
use std::sync::Arc; use common_base::tokio; use common_base::tokio::sync::mpsc; use common_base::tokio::sync::RwLock; use common_base::ProgressValues; use common_base::TrySpawn; use common_datablocks::DataBlock; use common_datavalues::DataSchemaRef; use common_exception::ErrorCode; use common_exception::Result; use ...
} } pub struct HttpQueryHandle { pub abort_sender: mpsc::Sender<()>, } impl HttpQueryHandle { pub fn abort(&self) { let sender = self.abort_sender.clone(); tokio::spawn(async move { sender.send(()).await.ok(); }); } } pub(crate) struct ExecuteRunning { se...
match &self.state { Running(r) => Some(r.context.get_progress_value()), Stopped(f) => f.progress.clone(), }
if_condition
[]
Rust
noblit/src/binary.rs
ruuda/noblit
6e7d123f6fce6691a7781527f8626cb75373b065
use std::io; #[inline] pub fn u16_from_le_bytes(buffer: [u8; 2]) -> u16 { 0 | (buffer[1] as u16) << 8 | (buffer[0] as u16) << 0 } #[inline] pub fn u64_from_le_bytes(buffer: [u8; 8]) -> u64 { 0 | (buffer[7] as u64) << 56 | (buffer[6] as u64) << 48 | (buffer[5...
use std::io; #[inline] pub fn u16_from_le_bytes(buffer: [u8; 2]) -> u16 { 0 | (buffer[1] as u16) << 8 | (buffer[0] as u16) << 0 } #[inline] pub fn u64_from_le_bytes(buffer: [u8; 8]) -> u64 { 0 | (buffer[7] as u64) << 56 | (buffer[6] as u64) << 48 | (buffer[5...
#[inline(always)] pub fn slice_8(buffer: &[u8]) -> [u8; 8] { let _ = buffer[7]; [ buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7], ] } pub struct Cursor<'a> { reader: Box<dyn 'a + io:...
pub fn slice_2(buffer: &[u8]) -> [u8; 2] { let _ = buffer[1]; [ buffer[0], buffer[1], ] }
function_block-full_function
[ { "content": "/// Evaluate a closure on byte slices of various lengths, up to 2^16.\n\npub fn for_slices_u16<'a, F>(data: &'a [u8], mut f: F) where F: FnMut(&'a [u8]) -> bool {\n\n let mut left = data;\n\n\n\n while left.len() > 2 {\n\n // Read a 16-bit length prefix.\n\n let len = (left[0] ...
Rust
framework2/leptos_macro/src/rsx.rs
gbj/commonprayer
15197dcb7fc2417b5f5695964eb0afbeb2969f94
use proc_macro2::TokenStream; use quote::{quote, quote_spanned}; use syn::Expr; use syn_rsx::{Node, NodeType}; pub fn node_to_tokens(node: &Node) -> Option<TokenStream> { match node.node_type { NodeType::Element => { let tag = node.name_as_string(); let span = node.name_span().unwra...
use proc_macro2::TokenStream; use quote::{quote, quote_spanned}; use syn::Expr; use syn_rsx::{Node, NodeType}; pub fn node_to_tokens(node: &Node) -> Option<TokenStream> { match node.node_type { NodeType::Element => { let tag = node.name_as_string(); let span = node.name_span().unwra...
let value = attr.value.as_ref(); let span = attr.name_span().unwrap(); value.map(|value| { if attr_name.starts_with("prop:") { quote_spanned! { span => leptos2::property(#real_attr_name, #value) ...
lock => { let value = node.value.as_ref().unwrap(); Some(quote! { #value }) } NodeType::Fragment => { let children = node.children.iter().filter_map(node_to_tokens); Some(quote! { vec![ #(#ch...
random
[ { "content": "pub fn bible_version_select(locale: &str, name: &str, value: Version) -> Node {\n\n view! {\n\n <select name={name}>\n\n {bible_version_select_options(locale, value)}\n\n </select>\n\n }\n\n}\n\n\n", "file_path": "website2/app/src/views/mod.rs", "rank": 0, ...
Rust
examples/chacha20/src/chacha20.rs
tarcieri/hacspec
e6269137e83d86a675459a9140568d7493fc9d43
use hacspec_lib::*; array!(State, 16, U32, type_for_indexes: StateIdx); bytes!(StateBytes, 64); bytes!(IV, 12); bytes!(Key, 32); pub fn state_to_bytes(x: State) -> StateBytes { let mut r = StateBytes::new(); for i in 0..x.len() { let bytes = U32_to_be_bytes(x[i]); r[i * 4] = bytes[3]; ...
use hacspec_lib::*; array!(State, 16, U32, type_for_indexes: StateIdx); bytes!(StateBytes, 64); bytes!(IV, 12); bytes!(Key, 32); pub fn state_to_bytes(x: State) -> StateBytes { let mut r = StateBytes::new(); for i in 0..x.len() { let bytes = U32_to_be_bytes(x[i]); r[i * 4] = bytes[3]; ...
pub fn chacha_block(key: Key, ctr: U32, iv: IV) -> StateBytes { let state = chacha_block_inner(key, ctr, iv); state_to_bytes(state) } pub fn chacha(key: Key, iv: IV, m: &ByteSeq) -> ByteSeq { let mut ctr = U32(1u32); let mut blocks_out = ByteSeq::new(m.len()); for i in 0..m.num_chunks(64) { ...
pub fn chacha_block_inner(key: Key, ctr: U32, iv: IV) -> State { let st = chacha_block_init(key, ctr, iv); let mut state = st; for _i in 0..10 { state = chacha_double_round(state); } for i in 0..16 { state[i] = state[i] + st[i]; } state }
function_block-full_function
[ { "content": "pub fn line(a: u32, b: u32, d: u32, s: u32, m: State) -> State {\n\n let mut state = m;\n\n state[a] = state[a] + state[b];\n\n state[d] = state[d] ^ state[a];\n\n state[d] = state[d] >> s;\n\n let (chunk_size, mut chunk) = state.get_chunk(2usize, 4usize);\n\n if chunk_size < 4us...
Rust
mailmap/src/lib.rs
sobolevn/thanks
3c8459bb55ee05b3663ec96a9627c2937c37bf6c
use std::fmt; use std::pin::Pin; use std::ptr::NonNull; #[cfg(test)] mod test; pub struct Mailmap { buffer: Pin<Box<str>>, entries: Vec<RawMapEntry>, } impl fmt::Debug for Mailmap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut list = f.debug_list(); for entry in &sel...
use std::fmt; use std::pin::Pin; use std::ptr::NonNull; #[cfg(test)] mod test; pub struct Mailmap { buffer: Pin<Box<str>>, entries: Vec<RawMapEntry>, } impl fmt::Debug for Mailmap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut list = f.debug_list(); for entry in &sel...
Some(name); } else { if entry.current_name.is_some() { eprintln!("malformed mailmap on line {}: too many names", idx); } else { entry.current_name = Some(name); } } } else { break; ...
(&mut line) || line.trim().is_empty() { break; } if let Some(email) = read_email(&mut line) { if entry.canonical_email.is_none() { entry.canonical_email = Some(email); } else { if entry.current_email.is_some() { epr...
random
[ { "content": "fn a(name: &str, email: &str) -> Author {\n\n Author {\n\n name: name.into(),\n\n email: email.into(),\n\n }\n\n}\n\n\n", "file_path": "mailmap/src/test.rs", "rank": 0, "score": 213212.7479495813 }, { "content": "fn map(line: &str) -> Mailmap {\n\n Mailma...
Rust
src/math/j1f.rs
MalmarPadecain/libm
b582b946acc8116d73f158e68011bba9cb21484f
/* origin: FreeBSD /usr/src/lib/msun/src/e_j1f.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. busin...
/* origin: FreeBSD /usr/src/lib/msun/src/e_j1f.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. busin...
}
fn test_y1f_2002() { let res = y1f(2.0000002_f32); if cfg!(all(target_arch = "x86", not(target_feature = "sse2"))) && (res == -0.10703231_f32) { return; } assert_eq!(res, -0.10703229_f32); }
function_block-full_function
[ { "content": "fn common(ix: u32, x: f64, y1: bool, sign: bool) -> f64 {\n\n let z: f64;\n\n let mut s: f64;\n\n let c: f64;\n\n let mut ss: f64;\n\n let mut cc: f64;\n\n\n\n /*\n\n * j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x-3pi/4)-q1(x)*sin(x-3pi/4))\n\n * y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(...
Rust
src/blockchain/esplora.rs
davemo88/bdk
77379e926225e82dc41eeba63cb481ae050bc693
use std::collections::{HashMap, HashSet}; use std::fmt; use futures::stream::{self, FuturesOrdered, StreamExt, TryStreamExt}; #[allow(unused_imports)] use log::{debug, error, info, trace}; use serde::Deserialize; use reqwest::{Client, StatusCode}; use bitcoin::consensus::{self, deserialize, serialize}; use bitco...
use std::collections::{HashMap, HashSet}; use std::fmt; use futures::stream::{self, FuturesOrdered, StreamExt, TryStreamExt}; #[allow(unused_imports)] use log::{debug, error, info, trace}; use serde::Deserialize; use reqwest::{Client, StatusCode}; use bitcoin::consensus::{self, deserialize, serialize}; use bitco...
o_hex() } async fn _get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, EsploraError> { let resp = self .client .get(&format!("{}/tx/{}/raw", self.url, txid)) .send() .await?; if let StatusCode::NOT_FOUND = resp.status() { retur...
in::hashes::{sha256, Hash}; use bitcoin::{BlockHash, BlockHeader, Script, Transaction, Txid}; use self::utils::{ElectrumLikeSync, ElsGetHistoryRes}; use super::*; use crate::database::BatchDatabase; use crate::error::Error; use crate::wallet::utils::ChunksIterator; use crate::FeeRate; const DEFAULT_CONCURRENT_REQUEST...
random
[ { "content": "fn main() -> Result<(), bdk::Error> {\n\n let client = Client::new(\"ssl://electrum.blockstream.info:60002\")?;\n\n let wallet = Wallet::new(\n\n \"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/...
Rust
src/day9/challenge_two.rs
Fryuni/advent-of-code-2021
832121aba87516b4c2727eee9869348e1a5a7840
/* * MIT License * * Copyright (c) 2021 Luiz Ferraz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modi...
/* * MIT License * * Copyright (c) 2021 Luiz Ferraz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modi...
fn find_low_points(&self) -> Vec<Coordinate> { self.get_coordinates() .into_iter() .filter(|&point| { self.neighboors_of(point) .into_iter() .all(|neighboor| self.get_value(neighboor) > self.get_value(point)) }) ...
if self.get_value(neighboor) < n { self.increase_counter(neighboor, counter); break; } } } } }
function_block-function_prefix_line
[ { "content": "fn challenge_one(input: &[Vec<u32>]) -> usize {\n\n let max_x = input.len();\n\n let max_y = input[0].len();\n\n\n\n let mut total_sum = 0;\n\n\n\n for (x, y) in get_coordinates(max_x, max_y) {\n\n let mut adjacent = Vec::with_capacity(4);\n\n\n\n if x > 0 {\n\n ...
Rust
src/slog_test.rs
tca-ms/extlog
fbca1521152d5a1b376da948e74d467fc8bf57dd
pub extern crate erased_serde; pub extern crate iobuffer; pub extern crate serde_json; pub extern crate slog_json; pub use super::stats::*; use super::slog; use std::sync::Mutex; use std::io; #[allow(unused_imports)] use std::io::BufRead; pub fn new_test_logger<T: io::Write + Send + 'static>(stream: T) -> slog::L...
pub extern crate erased_serde; pub extern crate iobuffer; pub extern crate serde_json; pub extern crate slo
stat {}", stat.name); let found_stat = found_stat.unwrap(); assert_eq!(found_stat.definition.stype(), stat.stat_type); assert_eq!(found_stat.definition.description(), stat.description); for value in stat.values.iter() { let found_value = found_stat .values ...
g_json; pub use super::stats::*; use super::slog; use std::sync::Mutex; use std::io; #[allow(unused_imports)] use std::io::BufRead; pub fn new_test_logger<T: io::Write + Send + 'static>(stream: T) -> slog::Logger { slog::Logger::root( slog::Fuse::new(Mutex::new(slog_json::Json::default(stream))), ...
random
[ { "content": "/// A trait indicating that this statistic can be used to trigger a statistics change.\n\npub trait StatTrigger {\n\n /// The list of stats that this trigger applies to.\n\n fn stat_list(&self) -> &'static [&'static (StatDefinition + Sync)];\n\n /// The condition that must be satisfied fo...
Rust
common/functions/src/scalars/strings/substring.rs
RainnyNightLover/databend
b3e4c25aea5036b7c16ed8311d1dd426ae166c38
use std::fmt; use common_datavalues2::prelude::*; use common_exception::ErrorCode; use common_exception::Result; use itertools::izip; use crate::scalars::cast_column_field; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::Function2; use crate::scalars::Function2Description; #[derive(Clon...
use std::fmt; use common_datavalues2::prelude::*; use common_exception::ErrorCode; use common_exception::Result; use itertools::izip; use crate::scalars::cast_column_field; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::Function2; use crate::scalars::Function2Description; #[derive(Clon...
Ok(builder.build(input_rows)) } } impl fmt::Display for SubstringFunction { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.display_name) } } #[inline] fn substr_from<'a>(str: &'a [u8], pos: &i64) -> &'a [u8] { substr(str, pos, &(str.len() as u64)) } #[inl...
if columns.len() > 2 { let p2_column = cast_column_field(&columns[2], &UInt64Type::arc())?; let p2_viewer = u64::try_create_viewer(&p2_column)?; let iter = izip!(s_viewer, p_viewer, p2_viewer); for (str, pos, len) in iter { let val = substr_from_for(str,...
if_condition
[ { "content": "pub fn expect_parse_err(sql: &str, expected: String) -> Result<()> {\n\n let result = DfParser::parse_sql(sql);\n\n assert!(result.is_err(), \"'{}' SHOULD BE '{}'\", sql, expected);\n\n assert_eq!(\n\n result.unwrap_err().message(),\n\n expected,\n\n \"'{}' SHOULD BE ...
Rust
src/style/color.rs
legokichi/plotters
be0b18f9bb71cf9ed710f543619e17008f2c2195
use super::palette::Palette; use super::ShapeStyle; use std::marker::PhantomData; pub trait Color { fn rgb(&self) -> (u8, u8, u8); fn alpha(&self) -> f64; fn mix(&self, value: f64) -> RGBAColor { let (r, g, b) = self.rgb(); let a = self.alpha() * value; RGBAColor(r...
use super::palette::Palette; use super::ShapeStyle; use std::marker::PhantomData; pub trait Color { fn rgb(&self) -> (u8, u8, u8); fn alpha(&self) -> f64; fn mix(&self, value: f64) -> RGBAColor { let (r, g, b) = self.rgb(); let a = self.alpha() * value; RGBAColor(r...
:ident, $r:expr, $g:expr, $b:expr, $a: expr, $doc: expr) => { #[doc = $doc] pub struct $name; impl Color for $name { fn rgb(&self) -> (u8,u8,u8) { return ($r, $g, $b); } fn alpha(&self) -> f64 { $a } } } ...
PaletteColor(idx % P::COLORS.len(), PhantomData) } } impl<P: Palette> SimpleColor for PaletteColor<P> { fn rgb(&self) -> (u8, u8, u8) { P::COLORS[self.0] } } pub struct RGBColor(pub u8, pub u8, pub u8); impl SimpleColor for RGBColor { fn rgb(&self) -> (u8, u8, u8) { (self.0, ...
random
[ { "content": "fn make_canvas_color(color: RGBAColor) -> JsValue {\n\n let (r, g, b) = color.rgb();\n\n let a = color.alpha();\n\n format!(\"rgba({},{},{},{})\", r, g, b, a).into()\n\n}\n\n\n\nimpl DrawingBackend for CanvasBackend {\n\n type ErrorType = CanvasError;\n\n\n\n fn get_size(&self) -> (...
Rust
prototype/collection/table/handlers.rs
gitter-badger/tinychain
9ed5ed7f0194032ee0c71e236be4bf2a5ba9e384
use std::iter::FromIterator; use std::ops::Deref; use async_trait::async_trait; use futures::stream::TryStreamExt; use futures::TryFutureExt; use crate::auth::{Scope, SCOPE_READ, SCOPE_WRITE}; use crate::class::{Instance, State, TCType}; use crate::collection::CollectionInstance; use crate::error; use crate::general:...
use std::iter::FromIterator; use std::ops::Deref; use async_trait::async_trait; use futures::stream::TryStreamExt; use futures::TryFutureExt; use crate::auth::{Scope, SCOPE_READ, SCOPE_WRITE}; use crate::class::{Instance, State, TCType}; use crate::collection::CollectionInstance; use crate::error; use crate::general:...
elf.table.key().len() { let bounds = Bounds::from_key(key, self.table.key()); let slice = self.table.clone().slice(bounds)?; let mut stream = slice.stream(txn.id()).await?; let next = stream.try_next().await?; next.map(Value::from_iter) ...
s().into() } fn scope(&self) -> Option<Scope> { Some(SCOPE_WRITE.into()) } async fn handle_post( self: Box<Self>, _request: &Request, txn: &Txn, params: Map<Scalar>, ) -> TCResult<State> { let update = params.try_cast_into(|v| error::bad_request("Inv...
random
[ { "content": "pub fn route<\n\n 'a,\n\n T: NumberInstance + CastFrom<Number> + Add<Output = T> + Mul<Output = T> + Sub<Output = T>,\n\n>(\n\n number: &'a T,\n\n method: MethodType,\n\n path: &[PathSegment],\n\n) -> Option<Box<dyn Handler + 'a>>\n\nwhere\n\n <T as Instance>::Class: Into<TCType>...
Rust
frontend/apps/crates/entry/jig/edit/src/edit/sidebar/actions.rs
LeahWhalen/ji-cloud
adc0712b2a4247a64c863092a967b2dfb1cad3cd
use super::state::*; use dominator::clone; use futures_signals::{ map_ref, signal::{Signal, SignalExt}, }; use shared::{ api::endpoints::{self, ApiEndpoint}, domain::{ jig::{ module::{ModuleCreateRequest, ModuleId, ModuleResponse, ModuleGetQuery}, JigId, JigPlayerSettings...
use super::state::*; use dominator::clone; use futures_signals::{ map_ref, signal::{Signal, SignalExt}, }; use shared::{ api::endpoints::{self, ApiEndpoint}, domain::{ jig::{ module::{ModuleCreateRequest, ModuleId, ModuleResponse, ModuleGetQuery}, JigId, JigPlayerSettings...
}; populate_added_module(Rc::clone(&state), lite_module); }, }; })); }
t { Ok(_) => {}, Err(_) => {}, } })); } pub fn duplicate_module(state: Rc<State>, module_id: &ModuleId) { state.loader.load(clone!(state, module_id => async move { let module = super::module_cloner::clone_module(&state.jig.id, &module_id, &state.jig.id).await.unwrap_ji()...
random
[ { "content": "/// Reads a required env value as a `String`, throwing an error if it is missing.\n\npub fn req_env(key: &str) -> anyhow::Result<String> {\n\n env::var(key).map_err(|_| anyhow::anyhow!(\"Missing required env var `{}`\", key))\n\n}\n\n\n", "file_path": "backend/core/src/env.rs", "rank": ...
Rust
packages/yew-macro/tests/html_macro/component-pass.rs
zstewar1/yew
f5b921984ab8cc9b745cfe5a669a812f6d75e261
#![no_implicit_prelude] #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(no...
#![no_implicit_prelude] #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(no...
} #[derive( ::std::clone::Clone, ::yew::Properties, ::std::default::Default, ::std::cmp::PartialEq, )] pub struct ChildProperties { #[prop_or_default] pub string: ::std::string::String, #[prop_or_default] pub r#fn: ::std::primitive::i32, pub int: ::std::primitive::i32, #[prop_or_default] ...
into(comp)), Self::AltChild(comp) => ::yew::virtual_dom::VNode::VComp(::std::convert::Into::< ::yew::virtual_dom::VComp, >::into(comp)), } }
function_block-function_prefix_line
[ { "content": "/// `0 <= p <= 1`\n\npub fn chance(p: f64) -> bool {\n\n let d = Bernoulli::new(p).unwrap();\n\n rand::thread_rng().sample(d)\n\n}\n\n\n", "file_path": "examples/keyed_list/src/random.rs", "rank": 0, "score": 285602.7680117055 }, { "content": "type ProcessMessage = Rc<dyn...
Rust
src/parsing.rs
chrishulbert/simple-server
84e7fc8ef7c0e4114f74606bbea5537b06ba66ef
use httparse; struct RequestMethodIndices(usize, usize); struct RequestProtocolIndices { path: (usize, usize), } struct HeaderIndices { name: (usize, usize), value: (usize, usize), } pub struct Request { method: RequestMethodIndices, proto: RequestProtocolIndices, headers: Vec<HeaderIndices>...
use httparse; struct RequestMethodIndices(usize, usize); struct RequestProtocolIndices { path: (usize, usize), } struct HeaderIndices { name: (usize, usize), value: (usize, usize), } pub struct Request { method: RequestMethodIndices, proto: RequestProtocolIndices, headers: Vec<HeaderIndices>...
#[cfg(test)] mod parsing_should { use super::*; #[test] fn parse_a_request() { let request = include_bytes!("../tests/big-http-request.txt").to_vec(); let result = try_parse_request(request); assert!(result.is_ok()); match result.unwrap() { ParseResult::Compl...
let request = match request.parse(&*buffer)? { httparse::Status::Partial => None, httparse::Status::Complete(n) => Some((request, n)), }; request .map(|(r, n)| { let proto = RequestProtocolIndices { path: slice_indices(&*buffer, r....
function_block-function_prefixed
[ { "content": "fn build_request(mut req: parsing::Request) -> Result<Request<Vec<u8>>, Error> {\n\n let mut http_req = Request::builder();\n\n\n\n http_req = http_req.method(req.method());\n\n\n\n for header in req.headers() {\n\n http_req = http_req.header(header.name, header.value);\n\n }\n\...
Rust
extension/wallet/src/wallet/make_create_swap_payload.rs
bonomat/droplet
c6d0bad7525f7d61c6d8f029db4f36276f9a98fb
use crate::{ wallet::{current, get_txouts, CreateSwapPayload, SwapUtxo, Wallet}, BTC_ASSET_ID, USDT_ASSET_ID, }; use bdk::bitcoin::Amount; use coin_selection::{self, coin_select}; use elements::{secp256k1_zkp::SECP256K1, AssetId, OutPoint}; use estimate_transaction_size::avg_vbytes; use futures::lock::Mutex; us...
use crate::{ wallet::{current, get_txouts, CreateSwapPayload, SwapUtxo, Wallet}, BTC_ASSET_ID, USDT_ASSET_ID, }; use bdk::bitcoin::Amount; use coin_selection::{self, coin_select}; use elements::{secp256k1_zkp::SECP256K1, AssetId, OutPoint}; use estimate_transaction_size::avg_vbytes; use futures::lock::Mutex; us...
asset: candidate_asset, }) } else { log::debug!( "utxo {} with asset id {} is not the sell asset, ignoring", outpoint, candidate_asset ); None } ...
throw("can get lock"); *guard }; make_create_swap_payload( name, current_wallet, sell_amount, btc_asset_id, btc_asset_id, ) .await } async fn make_create_swap_payload( name: String, current_wallet: &Mutex<Option<Wallet>>, sell_amount: Amount, ...
random
[ { "content": "#[wasm_bindgen(start)]\n\npub fn setup() {\n\n #[cfg(feature = \"console_error_panic_hook\")]\n\n console_error_panic_hook::set_once();\n\n\n\n logger::try_init();\n\n log::info!(\"wallet initialized\");\n\n\n\n let handler = Closure::wrap(\n\n Box::new(handle_storage_update)...
Rust
web-app/src/components/commentary/comment_section.rs
Tiamat-Tech/dit
3da715d5950025d2b5753b59e6cd3ee6e0b4fa0b
use std::collections::HashSet; use std::rc::Rc; use crate::utils::IpfsService; use wasm_bindgen_futures::spawn_local; use yew::prelude::{html, Component, ComponentLink, Html, Properties, ShouldRender}; use yew::services::ConsoleService; use yew::Callback; use linked_data::comments::Comment; use linked_data::feed::C...
use std::collections::HashSet; use std::rc::Rc; use crate::utils::IpfsService; use wasm_bindgen_futures::spawn_local; use yew::prelude::{html, Component, ComponentLink, Html, Properties, ShouldRender}; use yew::services::ConsoleService; use yew::Callback; use linked_data::comments::Comment; use linked_data::feed::C...
}
unwrap_or_else(|x| x); self.comments .insert(index, (cid, Rc::from(name), Rc::from(comment))); #[cfg(debug_assertions)] ConsoleService::info("Content Comments Updated"); true }
function_block-function_prefix_line
[ { "content": "/// Renders a string of Markdown to HTML with the default options (footnotes\n\n/// disabled, tables enabled).\n\npub fn render_markdown(src: &str) -> Html {\n\n let mut elems = vec![];\n\n let mut spine = vec![];\n\n\n\n macro_rules! add_child {\n\n ($child:expr) => {{\n\n ...
Rust
chain/ethereum/src/trigger.rs
mangas/graph-node
a46a8650f38aa209acad92dd6cf896d110581356
use ethabi::LogParam; use graph::blockchain; use graph::blockchain::TriggerData; use graph::prelude::BlockNumber; use graph::prelude::BlockPtr; use graph::prelude::{CheapClone, EthereumCall}; use graph::runtime::asc_new; use graph::runtime::AscHeap; use graph::runtime::AscPtr; use graph::runtime::DeterministicHostError...
use ethabi::LogParam; use graph::blockchain; use graph::blockchain::TriggerData; use graph::prelude::BlockNumber; use graph::prelude::BlockPtr; use graph::prelude::{CheapClone, EthereumCall}; use graph::runtime::asc_new; use graph::runtime::AscHeap; use graph::runtime::AscPtr; use graph::runtime::DeterministicHostError...
}) } } #[derive(Clone, Debug)] pub enum EthereumTrigger { Block(BlockPtr, EthereumBlockTriggerType), Call(Arc<EthereumCall>), Log(Arc<Log>), } impl PartialEq for EthereumTrigger { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Block(a_ptr, a_kind), Se...
transaction, log, params, } => { let ethereum_event_data = EthereumEventData { block: EthereumBlockData::from(block.as_ref()), transaction: EthereumTransactionData::from(transaction.deref()), ...
random
[ { "content": "/// Runs the future on the current thread. Panics if not within a tokio runtime.\n\npub fn block_on<T>(f: impl Future03<Output = T>) -> T {\n\n tokio::runtime::Handle::current().block_on(f)\n\n}\n\n\n", "file_path": "graph/src/task_spawn.rs", "rank": 0, "score": 357012.94408648246 ...
Rust
integration-testing/src/bin/arrow-json-integration-test.rs
PsiACE/arrow2
326fc9d89340ccd22cf0f981a98f56be582d8192
use std::fs::File; use clap::{App, Arg}; use arrow2::io::ipc::read; use arrow2::io::ipc::write::FileWriter; use arrow2::{ error::{ArrowError, Result}, io::json_integration::*, }; use arrow_integration_testing::read_json_file; fn main() -> Result<()> { let matches = App::new("rust arrow-json-integration...
use std::fs::File; use clap::{App, Arg}; use arrow2::io::ipc::read; use arrow2::io::ipc::write::FileWriter; use arrow2::{ error::{ArrowError, Result}, io::json_integration::*, }; use arrow_integration_testing::read_json_file; fn main() -> Result<()> { let matches = App::new("rust arrow-json-integration...
row_file = File::open(arrow_name)?; let metadata = read::read_file_metadata(&mut arrow_file)?; let reader = read::FileReader::new(arrow_file, metadata, None); let arrow_schema = reader.schema().as_ref().to_owned(); if json_file.schema != arrow_schema { return Err(ArrowError::InvalidArgumen...
function_block-function_prefixed
[]
Rust
vrp-core/tests/helpers/models/problem/fleet.rs
PeakBI/ds-reinterpretcat-vrp
62428fdd5438812ddcf37583a14b9a26bdb43225
use crate::models::common::*; use crate::models::problem::*; use hashbrown::{HashMap, HashSet}; use std::sync::Arc; pub const DEFAULT_ACTOR_LOCATION: Location = 0; pub const DEFAULT_ACTOR_TIME_WINDOW: TimeWindow = TimeWindow { start: 0.0, end: 1000.0 }; pub const DEFAULT_VEHICLE_COSTS: Costs = Costs { fixed: 0.0, ...
use crate::models::common::*; use crate::models::problem::*; use hashbrown::{HashMap, HashSet}; use std::sync::Arc; pub const DEFAULT_ACTOR_LOCATION: Location = 0; pub const DEFAULT_ACTOR_TIME_WINDOW: TimeWindow = TimeWindow { start: 0.0, end: 1000.0 }; pub const DEFAULT_VEHICLE_COSTS: Costs = Costs { fixed: 0.0, ...
pub fn get_vehicle_id(vehicle: &Vehicle) -> &String { vehicle.dimens.get_id().unwrap() } pub fn get_test_actor_from_fleet(fleet: &Fleet, vehicle_id: &str) -> Arc<Actor> { fleet.actors.iter().find(|actor| get_vehicle_id(&actor.vehicle) == vehicle_id).unwrap().clone() } pub struct VehicleBuilder { vehicle...
pub fn test_vehicle_with_id(id: &str) -> Vehicle { let mut dimens = Dimensions::new(); dimens.set_id(id); Vehicle { profile: Profile::default(), costs: test_costs(), dimens, details: vec![test_vehicle_detail()] } }
function_block-full_function
[ { "content": "pub fn test_fleet_with_vehicles(vehicles: Vec<Arc<Vehicle>>) -> Fleet {\n\n Fleet::new(vec![Arc::new(test_driver())], vehicles, Box::new(|actors| create_typed_actor_groups(actors)))\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/core.rs", "rank": 1, "score": 368322.875465698...
Rust
integration-tests/tests/secure_client_handle_tests.rs
planet-s/trust-dns
ce6952c9ba5a41fb0b7c5f90cf1870a5e8029e2d
extern crate tokio_core; extern crate trust_dns; extern crate trust_dns_integration; extern crate trust_dns_server; use std::net::*; use std::str::FromStr; use std::sync::Arc; use tokio_core::reactor::Core; use trust_dns::client::{BasicClientHandle, ClientFuture, ClientHandle, MemoizeClientHandle, ...
extern crate tokio_core; extern crate trust_dns; extern crate trust_dns_integration; extern crate trust_dns_server; use std::net::*; use std::str::FromStr; use std::sync::Arc; use tokio_core::reactor::Core; use trust_dns::client::{BasicClientHandle, ClientFuture, ClientHandle, MemoizeClientHandle, ...
s::IN, RecordType::NS)) .expect("query failed"); assert_eq!(response.response_code(), ResponseCode::NoError); assert!(response.answers().is_empty()); } #[test] #[ignore] fn test_dnssec_rollernet_td_udp() { with_udp(dnssec_rollernet_td_test); } #[test] #[ignore] fn test_dnssec_rollernet_td_tcp() {...
e_tcp() { with_tcp(test_secure_query_example); } fn test_secure_query_example<H>(mut client: SecureClientHandle<H>, mut io_loop: Core) where H: ClientHandle + 'static, { let name = Name::from_str("www.example.com").unwrap(); let response = io_loop .run(client.query(name.clone(), DNSClass::IN, R...
random
[ { "content": "#[test]\n\nfn test() {\n\n use std::str::FromStr;\n\n\n\n let rdata = SOA::new(\n\n Name::from_str(\"m.example.com\").unwrap(),\n\n Name::from_str(\"r.example.com\").unwrap(),\n\n 1,\n\n 2,\n\n 3,\n\n 4,\n\n 5,\n\n );\n\n\n\n let mut byt...
Rust
src/aliyun/record.rs
Devifish/aliyun-ddns
571848c3dd1f8afa81d325a09cea083c92eae589
use crate::aliyun::common::{request, CommonResponse, ErrorResponse}; use crate::config::Options; use crate::error::CommonError; use crate::ip::{self, IPOption}; use fehler::{throw, throws}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; use std::net::IpAddr; const RECORD_TYP...
use crate::aliyun::common::{request, CommonResponse, ErrorResponse}; use crate::config::Options; use crate::error::CommonError; use crate::ip::{self, IPOption}; use fehler::{throw, throws}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; use std::net::IpAddr; const RECORD_TYP...
#[throws(CommonError)] pub fn split(opt: &Options) -> HashMap<String, String> { let domains = opt.domains.clone(); let mut records: HashMap<String, String> = HashMap::new(); for domain in domains { let segments: Vec<&str> = domain.split(".").collect(); let l = segments.len(); if l ...
fn get( opt: &Options, record: String, domain: String, ) -> CommonResponse<RecordsResponse, ErrorResponse> { let ak_secret = opt.access_key_secret.clone().ok_or("缺少阿里云AK Secret")?; let ak_id = opt.access_key_id.clone().ok_or("缺少阿里云AK ID")?; let mut req_params = HashMap::new(); req_params.in...
function_block-function_prefix_line
[ { "content": "#[throws(CommonError)]\n\npub fn list(opt: &Options) -> CommonResponse<DomainListResponse, ErrorResponse> {\n\n let ak_secret = opt.access_key_secret.clone().ok_or(\"缺少阿里云AK Secret\")?;\n\n let ak_id = opt.access_key_id.clone().ok_or(\"缺少阿里云AK ID\")?;\n\n\n\n let mut req_params = HashMap:...
Rust
examples/playsine_events.rs
hrydgard/wasapi-rs
db9f48bd8cda92fcacab251159c774fe8aa6c620
use std::f64::consts::PI; use std::rc::Rc; use wasapi::*; #[macro_use] extern crate log; use simplelog::*; struct SineGenerator { time: f64, freq: f64, delta_t: f64, amplitude: f64, } impl SineGenerator { fn new(freq: f64, fs: f64, amplitude: f64) -> Self { SineGenerator { tim...
use std::f64::consts::PI; use std::rc::Rc; use wasapi::*; #[macro_use] extern crate log; use simplelog::*; struct SineGenerator { time: f64, freq: f64, delta_t: f64, amplitude: f64, } impl SineGenerator { fn new(freq: f64, fs: f64, amplitude: f64) -> Self { SineGenerator { tim...
} }
if h_event.wait_for_event(1000).is_err() { error!("error, stopping playback"); audio_client.stop_stream().unwrap(); break; }
if_condition
[ { "content": "// Main loop\n\nfn main() {\n\n let _ = SimpleLogger::init(\n\n LevelFilter::Debug,\n\n ConfigBuilder::new()\n\n .set_time_format_str(\"%H:%M:%S%.3f\")\n\n .build(),\n\n );\n\n\n\n initialize_mta().unwrap();\n\n\n\n let mut gen = SineGenerator::new(1...
Rust
src/lnpd/daemons.rs
crisdut/lnp-node
e81e693d1a92fc5aef10c423648db43e4b755e97
use std::convert::TryFrom; use std::fmt::{self, Debug, Display, Formatter}; use std::net::SocketAddr; use std::os::unix::process::ExitStatusExt; use std::path::{Path, PathBuf}; use std::process::{Child, ExitStatus}; use std::{fs, process, thread}; use amplify::hex::ToHex; use amplify::IoError; use internet2::{LocalN...
use std::convert::TryFrom; use std::fmt::{self, Debug, Display, Formatter}; use std::net::SocketAddr; use std::os::unix::process::ExitStatusExt; use std::path::{Path, PathBuf}; use std::process::{Child, ExitStatus}; use std::{fs, process, thread}; use amplify::hex::ToHex; use amplify::IoError; use internet2::{LocalN...
} #[derive(Clone, Eq, PartialEq, Debug, Display)] pub enum Daemon { #[display("signd")] Signd, #[display("peerd")] Peerd(PeerSocket, PathBuf), #[display("channeld")] Channeld(ActiveChannelId), #[display("routed")] Routed, #[display("watchd")] Watchd, } impl Daemon { pu...
s() { Ok(()) } else { Err(DaemonError::ProcessAborted(name, status)) } }), DaemonHandle::Thread(name, thread) => thread .join() .map_err(|_| DaemonError::ThreadJoin(name.cl...
function_block-function_prefixed
[ { "content": "pub fn run(config: Config) -> Result<(), Error> {\n\n let electrum =\n\n ElectrumClient::new(&config.electrum_url).map_err(|_| Error::ElectrumConnectivity)?;\n\n\n\n let runtime = Runtime { electrum, track_list: empty!() };\n\n\n\n Service::run(config, runtime, false)\n\n}\n\n\n\np...
Rust
src/commands/encode.rs
ddemarco5/anime-machine
a7be254eba411acb3ded5af311edc29f4b534ef7
use crate::commands; use crate::project; use std::process; use std::fs::File; use std::io::{Write}; const AOMENC_BASE_COMMAND: &'static str = "{tools_path}\\aomenc.exe \ -v --ivf --passes=2 \ --pass={pass_num} \ ...
use crate::commands; use crate::project; use std::process; use std::fs::File; use std::io::{Write}; const AOMENC_BASE_COMMAND: &'static str = "{tools_path}\\aomenc.exe \ -v --ivf --passes=2 \ --pass={pass_num} \ ...
-> EncodePass2 { EncodePass2 { chunk: chunk.clone(), cleanup_files: Vec::new(), dirs: project.paths.clone(), } } fn build_batch_file (&mut self) -> String { let args = vec![ ("tools_path", self.dirs.tools.clone()), (...
.replace("{tmp_dir}", &self.dirs.tmp.to_string()); println!("DEBUG BATCH_FILENAME: {}", batch_filename); println!("DEBUG BATCH STRING: {}", batch_command); let mut file = File::create(batch_filename.clone()).expect("Error creating file"); file.write_all(batch_command...
random
[ { "content": "pub fn build_batch_contents(command_template: &str, arguments: Vec<(&str, String)>) -> String {\n\n\n\n let mut filled_command = command_template.clone().to_string();\n\n\n\n for (name, value) in arguments {\n\n // weird, but {{ escapes a curly brace, and we want '{name}' as a result\...
Rust
src/commands/migrate.rs
RamenN00dlez/volt
bd94b03d53c54f718c871966a02684748a837462
/* Copyright 2021 Volt Contributors 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 agre...
/* Copyright 2021 Volt Contributors 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 agre...
}
async fn exec(self, config: VoltConfig) -> Result<()> { ...
function_block-full_function
[ { "content": "#[async_trait]\n\npub trait VoltCommand {\n\n async fn exec(self, config: VoltConfig) -> miette::Result<()>;\n\n}\n\n\n\n/// Volt CLI subcommands\n\n#[derive(Debug, Subcommand)]\n\npub enum VoltSubCmd {\n\n Add(add::Add),\n\n Clone(clone::Clone),\n\n Init(init::Init),\n\n Clean(clea...
Rust
src/testdrive/src/action/avro_ocf.rs
sproutfi/materialize
8bf896c8920f702258b8d1b355d4249aa3ac821c
use std::ffi::OsString; use std::fs::{File, OpenOptions}; use std::io::Write; use std::os::unix::ffi::OsStringExt; use std::path::{self, PathBuf}; use anyhow::{bail, Context}; use async_trait::async_trait; use mz_ore::retry::Retry; use crate::action::{Action, ControlFlow, State, SyncAction}; use crate::format::avr...
use std::ffi::OsString; use std::fs::{File, OpenOptions}; use std::io::Write; use std::os::unix::ffi::OsStringExt; use std::path::{self, PathBuf}; use anyhow::{bail, Context}; use async_trait::async_trait; use mz_ore::retry::Retry; use crate::action::{Action, ControlFlow, State, SyncAction}; use crate::format::avr...
#[async_trait] impl Action for VerifyAction { async fn undo(&self, _state: &mut State) -> Result<(), anyhow::Error> { Ok(()) } async fn redo(&self, state: &mut State) -> Result<ControlFlow, anyhow::Error> { let path = Retry::default() .max_duration(state.default_timeout) ...
let sink = cmd.args.string("sink")?; let expected = cmd.input; cmd.args.done()?; if sink.contains(path::MAIN_SEPARATOR) { bail!("separators in file sink names are forbidden"); } Ok(VerifyAction { sink, expected }) }
function_block-function_prefix_line
[ { "content": "/// Decode a `Value` encoded in Avro format given its `Schema` and anything implementing `io::Read`\n\n/// to read from.\n\n///\n\n/// In case a reader `Schema` is provided, schema resolution will also be performed.\n\n///\n\n/// **NOTE** This function has a quite small niche of usage and does NOT...
Rust
src/lib.rs
indiv0/bevy_webgl2
a53c9ca296a46019d833da9be6f69f099ac63159
mod default_plugins; pub mod renderer; mod webgl2_render_pass; mod webgl2_renderer; mod webgl2_resources; use crate::renderer::WebGL2RenderResourceContext; use bevy::app::prelude::*; use bevy::window::{WindowCreated, Windows}; pub use default_plugins::*; use std::sync::Arc; pub use webgl2_render_pass::*; pub use webgl2...
mod default_plugins; pub mod renderer; mod webgl2_render_pass; mod webgl2_renderer; mod webgl2_resources; use crate::renderer::WebGL2RenderResourceContext; use bevy::app::prelude::*; use bevy::window::{WindowCreated, Windows}; pub use default_plugins::*; use std::sync::Arc; pub use webgl2_render_pass::*; pub use webgl2...
} #[derive(Default)] pub struct State { pub window_created_event_reader: EventReader<WindowCreated>, } pub fn webgl2_handle_window_created_events_system() -> impl FnMut(&mut World, &mut Resources) { let mut window_created_event_reader: EventReader<WindowCreated> = Default::default(); move |_, resources| ...
fn build(&self, app: &mut AppBuilder) { let resources = app.resources_mut(); { let pipelines = resources.get_mut::<Assets<PipelineDescriptor>>().unwrap(); let mut shaders = resources.get_mut::<Assets<Shader>>().unwrap(); let shader_overrides = vec![ (...
function_block-full_function
[ { "content": "pub fn compile_shader(\n\n context: &WebGl2RenderingContext,\n\n shader_type: u32,\n\n source: &str,\n\n) -> Result<GlShader, String> {\n\n let mut bind_groups = GlBindGroups::default();\n\n let bind_group_re =\n\n regex::Regex::new(r\"uniform\\s+(\\w+)\\s*\\{\\s*//\\s*set\\s...
Rust
cranelift-codegen/meta/src/srcgen.rs
jgouly/cranelift-1
470372f0b55cd51199466669cb87d9e038a3f459
#![macro_use] use std::cmp; use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::io::Write; use std::path; use crate::error; static SHIFTWIDTH: usize = 4; macro_rules! fmtln { ($fmt:ident, $fmtstring:expr, $($fmtargs:expr),*) => { $fmt.line(format!($fmtstring, $($fmtargs),*)); }; ...
#![macro_use] use std::cmp; use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::io::Write; use std::path; use crate::error; static SHIFTWIDTH: usize = 4; macro_rules! fmtln { ($fmt:ident, $fmtstring:expr, $($fmtargs:expr),*) => { $fmt.line(format!($fmtstring, $($fmtargs),*)); }; ...
; assert_eq!(fmt.lines, expected_lines); } #[test] fn parse_multiline_works() { let input = "\n hello\n world\n"; let expected = vec!["hello", "world"]; let output = parse_multiline(input); assert_eq!(output, expected); } #[test] fn formatter_basic...
from_raw_string( r#" match x { Green { a, b } => { different body } Orange { a, b } => { some body } _ => { unreachable!() } } "#, )
call_expression
[ { "content": "/// Emit Display and FromStr implementations for enum settings.\n\nfn gen_to_and_from_str(name: &str, values: &[&'static str], fmt: &mut Formatter) {\n\n fmtln!(fmt, \"impl fmt::Display for {} {{\", name);\n\n fmt.indent(|fmt| {\n\n fmtln!(\n\n fmt,\n\n \"fn fmt(...
Rust
src/sources/mod.rs
kaimast/calloop
41c8922dc813d1348b98d19f278ff6e530d3cdd5
use std::cell::RefCell; use std::io; use std::rc::Rc; use std::sync::Arc; use mio::{ event::{Event, Source as MioSource}, Interest, Registry, Token, Waker, }; use crate::list::ErasedList; pub mod channel; pub mod generic; #[cfg(target_os = "linux")] pub mod signals; pub mod timer; pub trait EventSource { ...
use std::cell::RefCell; use std::io; use std::rc::Rc; use std::sync::Arc; use mio::{ event::{Event, Source as MioSource}, Interest, Registry, Token, Waker, }; use crate::list::ErasedList; pub mod channel; pub mod generic; #[cfg(target_os = "linux")] pub mod signals; pub mod timer; pub trait EventSource { ...
nput)) } } pub fn remove(mut self) -> E { if let Some(mio_source) = self.source.as_mio_source() { let _ = self.registry.deregister(mio_source); } let _dispatcher = self.list.borrow_mut().del_source(self.token); self.source } } impl<E: Even...
register(&mut self) -> io::Result<()> { let interest = self.source.interest(); if let Some(mio_source) = self.source.as_mio_source() { self.registry.reregister(mio_source, self.token, interest) } else { Err(io::Error::from(io::ErrorKind::InvalidI
function_block-random_span
[ { "content": "struct Dispatcher<Data, E: MioSource + 'static, F: FnMut(Event<E>, &mut Data)> {\n\n _data: ::std::marker::PhantomData<fn(&mut Data)>,\n\n inner: Rc<RefCell<E>>,\n\n callback: F,\n\n}\n\n\n\nimpl<Data, E: MioSource + 'static, F: FnMut(Event<E>, &mut Data)> EventDispatcher<Data>\n\n for...
Rust
feather/server/src/initial_handler.rs
leElvyn/feather
1e2427b4389fccb61201e10c09cc88545f8108b0
use crate::{connection_worker::Worker, favicon::Favicon}; use anyhow::bail; use base::{ProfileProperty, Text}; use flume::{Receiver, Sender}; use md5::Digest; use num_bigint::BigInt; use once_cell::sync::Lazy; use protocol::{ codec::CryptKey, packets::{ client::{HandshakeState, Ping}, server::...
use crate::{connection_worker::Worker, favicon::Favicon}; use anyhow::bail; use base::{ProfileProperty, Text}; use flume::{Receiver, Sender}; use md5::Digest; use num_bigint::BigInt; use once_cell::sync::Lazy; use protocol::{ codec::CryptKey, packets::{ client::{HandshakeState, Ping}, server::...
const RSA_BITS: usize = 1024; static RSA_KEY: Lazy<RsaPrivateKey> = Lazy::new(|| RsaPrivateKey::new(&mut OsRng, RSA_BITS).expect("failed to create RSA key")); static RSA_KEY_ENCODED: Lazy<Vec<u8>> = Lazy::new(|| { rsa_der::public_key_to_der(&RSA_KEY.n().to_bytes_be(), &RSA_KEY.e().to_bytes_be()) }); async f...
fn offline_mode_uuid(username: &str) -> Uuid { let mut hasher = md5::Md5::default(); hasher.update(format!("OfflinePlayer:{}", username).as_bytes()); let hash = hasher.finalize(); let mut builder = uuid::Builder::from_bytes(hash.try_into().unwrap()); builder .set_variant(uuid::Variant...
function_block-full_function
[ { "content": "/// Compute offline mode UUID\n\n/// https://gist.github.com/games647/2b6a00a8fc21fd3b88375f03c9e2e603\n\npub fn name_to_uuid_offline(username: &str) -> Uuid {\n\n let mut context = md5::Context::new();\n\n context.consume(format!(\"OfflinePlayer:{}\", username).as_bytes());\n\n let compu...
Rust
cli/src/main.rs
absltkaos/indy-sdk
bc14c5b514dc1c76ce62dd7f6bf804120bf69f5e
#![cfg_attr(feature = "fatal_warnings", deny(warnings))] extern crate atty; extern crate ansi_term; extern crate unescape; #[cfg(test)] extern crate lazy_static; extern crate libc; extern crate linefeed; #[macro_use] extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crat...
#![cfg_attr(feature = "fatal_warnings", deny(warnings))] extern crate atty; extern crate ansi_term; extern crate unescape; #[cfg(test)] extern crate lazy_static; extern crate libc; extern crate linefeed; #[macro_use] extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crat...
} fn build_executor() -> CommandExecutor { CommandExecutor::build() .add_command(common::about_command::new()) .add_command(common::exit_command::new()) .add_command(common::prompt_command::new()) .add_command(common::show_command::new()) .add_command(common::load_plugin_co...
ndle(&self, command_executor: &CommandExecutor) -> Result<(), String> { if let Some(ref logger_config) = self.logger_config { utils::logger::IndyCliLogger::init(logger_config)?; println_succ!("Logger has been initialized according to the config file: \"{}\"", logger_config); } ...
function_block-function_prefixed
[ { "content": "pub fn handle_indy_error(err: IndyError, submitter_did: Option<&str>, pool_name: Option<&str>, wallet_name: Option<&str>) {\n\n match err.error_code {\n\n ErrorCode::WalletAlreadyExistsError => println_err!(\"Wallet \\\"{}\\\" already exists\", wallet_name.unwrap_or(\"\")),\n\n Er...
Rust
crate/divvunspell/src/transducer/thfst/index_table.rs
divvun/divvunspell-swift
9231ffb655752c3c3ad646216abd9aff3ec02ef0
use std::ptr; use memmap2::Mmap; use crate::transducer::TransducerError; use crate::types::{SymbolNumber, TransitionTableIndex, Weight}; use crate::vfs::{self, Filesystem}; #[derive(Debug)] pub struct MemmapIndexTable<F> { buf: Mmap, pub(crate) size: u32, _file: std::marker::PhantomData<F>, } const INDE...
use std::ptr; use memmap2::Mmap; use crate::transducer::TransducerError; use crate::types::{SymbolNumber, TransitionTableIndex, Weight}; use crate::vfs::{self, Filesystem}; #[derive(Debug)] pub struct MemmapIndexTable<F> { buf: Mmap, pub(crate) size: u32, _file: std::marker::PhantomData<F>, } const INDE...
} impl<F: vfs::File> IndexTable<F> for FileIndexTable<F> { fn from_path<P, FS>(fs: &FS, path: P) -> Result<Self, TransducerError> where P: AsRef<std::path::Path>, FS: Filesystem<File = F>, { let file = fs.open_file(path).map_err(TransducerError::Io)?...
let mut buf = [0u8; 4]; self.file .read_exact_at(&mut buf, index) .expect("failed to read u32"); u32::from_le_bytes(buf) }
function_block-function_prefix_line
[ { "content": "pub trait IndexTable<F: vfs::File>: Sized {\n\n fn from_path<P, FS>(fs: &FS, path: P) -> Result<Self, TransducerError>\n\n where\n\n P: AsRef<std::path::Path>,\n\n FS: Filesystem<File = F>;\n\n fn input_symbol(&self, i: TransitionTableIndex) -> Option<SymbolNumber>;\n\n f...
Rust
src/world_grid.rs
sarkahn/sark_grids_rs
803ff7c89df3405a0a23be856ad6d3ebaf4a0fde
use itertools::Itertools; use glam::{IVec2, UVec2, Vec2}; use crate::{ point::{GridPoint, Point2d, Size2d}, Pivot, }; #[derive(Default, Debug, Clone)] pub struct WorldGrid { size: UVec2, center_offset: Vec2, pos_offset: Vec2, pivot_offset: Vec2, axis: Vec2, } impl W...
use itertools::Itertools; use glam::{IVec2, UVec2, Vec2}; use crate::{ point::{GridPoint, Point2d, Size2d}, Pivot, }; #[derive(Default, Debug, Clone)] pub struct WorldGrid { size: UVec2, center_offset: Vec2, pos_offset: Vec2, pivot_offset: Vec2, axis: Vec2, } impl W...
#[test] fn center_tile_center_even() { let grid = WorldGrid::new([4, 4], Pivot::Center); assert_eq!([0.5, 0.5], grid.tile_center_from_index2d([0, 0]).to_array()); assert_eq!([1.5, 1.5], grid.tile_center_from_index2d([1, 1]).to_array()); } #[test] fn center_tile_pos_odd() ...
fn center_tile_center_odd() { let grid = WorldGrid::new([3, 3], Pivot::Center); assert_eq!([0.0, 0.0], grid.tile_center_from_index2d([0, 0]).to_array()); assert_eq!( [-1.0, -1.0], grid.tile_center_from_index2d([-1, -1]).to_array() ); }
function_block-full_function
[ { "content": "/// A trait for mixing of the different types representing a 2d size.\n\npub trait Size2d: Clone + Copy {\n\n fn width(&self) -> usize;\n\n fn height(&self) -> usize;\n\n\n\n #[inline]\n\n fn as_uvec2(&self) -> UVec2 {\n\n UVec2::new(self.width() as u32, self.height() as u32)\n\...
Rust
crates/env/src/backend.rs
patractlabs/ink
3688ea2fd7908c2a89df0724802104ef1dcadfd9
use crate::{ call::{ utils::ReturnType, CallParams, CreateParams, }, hash::{ CryptoHash, HashOutput, }, topics::Topics, zk::{ CurvePoint, CurvePointOutput, }, Environment, Result, }; use ink_primitives::Key; pub struct Return...
use crate::{ call::{ utils::ReturnType, CallParams, CreateParams, }, hash::{ CryptoHash, HashOutput, }, topics::Topics, zk::{ CurvePoint, CurvePointOutput, }, Environment, Result, }; use ink_primitives::Key; pub struct Return...
pub(crate) fn into_u32(self) -> u32 { self.value } } pub trait EnvBackend { fn set_contract_storage<V>(&mut self, key: &Key, value: &V) where V: scale::Encode; fn get_contract_storage<R>(&mut self, key: &Key) -> Result<Option<R>> where ...
pub fn set_reverted(mut self, has_reverted: bool) -> Self { match has_reverted { true => self.value |= has_reverted as u32, false => self.value &= !has_reverted as u32, } self }
function_block-full_function
[ { "content": "#[cfg(feature = \"ink-unstable-chain-extensions\")]\n\npub fn call_chain_extension<I, O>(func_id: u32, input: &I) -> Result<O>\n\nwhere\n\n I: scale::Codec + 'static,\n\n O: scale::Codec + 'static,\n\n{\n\n <EnvInstance as OnInstance>::on_instance(|instance| {\n\n EnvBackend::call_...
Rust
tornado/common/src/command/pool.rs
ufoscout/tornado
5c9f711a243ca2c7833fc0dd4085646c3a95defb
use crate::command::{Command, CommandMut}; use async_channel::{bounded, Sender}; use log::*; use std::marker::PhantomData; use tokio::sync::Semaphore; use tornado_executor_common::ExecutorError; use tracing::Span; use tracing_futures::Instrument; pub struct ReplyRequest<I, O> { pub span: Span, pub message: I, ...
use crate::command::{Command, CommandMut}; use async_channel::{bounded, Sender}; use log::*; use std::marker::PhantomData; use tokio::sync::Semaphore; use tornado_executor_common::ExecutorError; use tracing::Span; use tracing_futures::Instrument; pub struct ReplyRequest<I, O> { pub span: Span, pub message: I, ...
}), )); for i in 0..100 { if i % 2 == 0 { let message = format!("hello {}", i); let result = sender.execute(Action::new("", &message).into()).await; match result { Ok(result_message) => assert_eq!(resu...
if action.id.contains("err") { Err(TornadoError::SenderError { message: action.id.to_owned() }) } else { Ok(action.id.to_owned()) }
if_condition
[ { "content": "pub fn action_into_dto(action: Action) -> Result<ActionDto, Error> {\n\n Ok(ActionDto { id: action.id, payload: serde_json::to_value(action.payload)? })\n\n}\n\n\n", "file_path": "tornado/engine_api/src/event/convert.rs", "rank": 0, "score": 303385.15996004926 }, { "content"...
Rust
src/vec3.rs
stanleydesu/cubedesu
89d9f4c70c34e98f0afed5cd4134fa9c74aefee2
use std::{ fmt, ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub}, }; #[derive(Copy, Clone, Debug, PartialEq, Eq)] struct Matrix3([Vec3; 3]); impl Matrix3 { pub fn new(r1: Vec3, r2: Vec3, r3: Vec3) -> Self { Self([r1, r2, r3]) } } impl Mul<Vec3> for Matrix3 { type Output = Vec3; ...
use std::{ fmt, ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub}, }; #[derive(Copy, Clone, Debug, PartialEq, Eq)] struct Matrix3([Vec3; 3]); impl Matrix3 { pub fn new(r1: Vec3, r2: Vec3, r3: Vec3) -> Self { Self([r1, r2, r3]) } } impl Mul<Vec3> for Matrix3 { type Output = Vec3; ...
proptest! { #[test] fn matrix_mult(v1 in gen_vec3(-5, 5), v2 in gen_vec3(-5, 5), v3 in gen_vec3(-5, 5), vec in gen_vec3(-5, 5)) { let product = Matrix3::new(v1, v2, v3) * vec; let expected = Vec3::new(Vec3...
z() { let v = Vec3::new(2, 3, 2); let axis = Axis::Z; assert_eq!(Vec3::rotate_around_axis(v, axis, 1), Vec3::new(3, -2, 2)); assert_eq!(Vec3::rotate_around_axis(v, axis, -3), Vec3::new(3, -2, 2)); assert_eq!(Vec3::rotate_around_axis(v, axis, 2), Vec3::new(-2, -3, 2)); ass...
function_block-function_prefixed
[ { "content": "fn point3_to_vec3(p: Point3) -> Vec3 {\n\n vec3(p.x as f32, p.y as f32, p.z as f32)\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 1, "score": 55481.14750672236 }, { "content": "fn face_to_dimensions(face: Face) -> Vec3 {\n\n match face {\n\n Face::U | Face::D =>...
Rust
example/mini_core_hello_world.rs
mockersf/rustc_codegen_cranelift
356360836e128e1d1eb11caf6ff5186efb211960
#![feature(no_core, lang_items, box_syntax, never_type, linkage, extern_types, thread_local)] #![no_core] #![allow(dead_code, non_camel_case_types)] extern crate mini_core; use mini_core::*; use mini_core::libc::*; unsafe extern "C" fn my_puts(s: *const i8) { puts(s); } macro_rules! assert { ($e:expr) => { ...
#![feature(no_core, lang_items, box_syntax, never_type, linkage, extern_types, thread_local)] #![no_core] #![allow(dead_code, non_camel_case_types)] extern crate mini_core; use mini_core::*; use mini_core::libc::*; unsafe extern "C" fn my_puts(s: *const i8) { puts(s); } macro_rules! assert { ($e:expr) => { ...
} #[cfg(not(jit))] fn test_tls() { unsafe { let mut attr: pthread_attr_t = zeroed(); let mut thread: pthread_t = 0; assert_eq!(TLS, 42); if pthread_attr_init(&mut attr) != 0 { assert!(false); } if pthread_create(&mut thread, &attr, mutate_tls, 0 as *m...
r, _marker: PhantomData, } as Unique<dyn SomeTrait>; struct MyDst<T: ?Sized>(T); intrinsics::size_of_val(&MyDst([0u8; 4]) as &MyDst<[u8]>); struct Foo { x: u8, y: !, } unsafe fn uninitialized<T>() -> T { MaybeUninit { un...
random
[ { "content": "#[start]\n\nfn main(_argc: isize, _argv: *const *const u8) -> isize {\n\n for i in 2..10_000_000 {\n\n black_box((i + 1) % i);\n\n }\n\n\n\n 0\n\n}\n\n\n", "file_path": "example/mod_bench.rs", "rank": 0, "score": 277955.92839869845 }, { "content": "#[start]\n\nf...
Rust
programs/stake_api/src/stake_state.rs
abalaki6/solana
81d43c57a222320a842202f67aaf252d9f103584
use serde_derive::{Deserialize, Serialize}; use solana_sdk::account::KeyedAccount; use solana_sdk::instruction::InstructionError; use solana_sdk::instruction_processor_utils::State; use solana_sdk::pubkey::Pubkey; use solana_vote_api::vote_state::VoteState; #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clon...
use serde_derive::{Deserialize, Serialize}; use solana_sdk::account::KeyedAccount; use solana_sdk::instruction::InstructionError; use solana_sdk::instruction_processor_utils::State; use solana_sdk::pubkey::Pubkey; use solana_vote_api::vote_state::VoteState; #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clon...
fn redeem_vote_credits( &mut self, stake_account: &mut KeyedAccount, vote_account: &mut KeyedAccount, ) -> Result<(), InstructionError> { if let ( StakeState::MiningPool, StakeState::Delegate { voter_id, credits_observed, ...
rn Err(InstructionError::MissingRequiredSignature); } if let StakeState::Delegate { .. } = self.state()? { let vote_state: VoteState = vote_account.state()?; self.set_state(&StakeState::Delegate { voter_id: *vote_account.unsigned_key(), credits_ob...
function_block-function_prefixed
[]
Rust
vendor/im-rc/src/ser.rs
riscv-android-src/toolchain-rustc
bcf972c0208490b0eb3ce3c170c2db486ba945b3
use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::marker::PhantomData; use std::ops::Deref; use crate::hashmap::HashMap; use crate::hashset::HashSet; use crate::ord...
use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::marker::PhantomData; use std::ops::Deref; use crate::hashmap::HashMap; use crate::hashset::HashSet; use crate::ord...
e> Serialize for OrdSet<A> { fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut s = ser.serialize_seq(Some(self.len()))?; for i in self.iter() { s.serialize_element(i.deref())?; } s.end() } } impl<'de, K: Deserial...
re Access: SeqAccess<'de>, { let mut v: Vec<A> = match access.size_hint() { None => Vec::new(), Some(l) => Vec::with_capacity(l), }; while let Some(i) = access.next_element()? { v.push(i) } Ok(From::from(v)) } } struct MapVisit...
random
[]
Rust
compiler/crates/relay-transforms/src/refetchable_fragment/fetchable_query_generator.rs
lpalmes/relay
70bf47751a61ad14798f6dea14fe59e2c8a90aa3
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use super::validation_message::ValidationMessage; use super::{ build_fragment_metadata_as_directive, build_fragment_spread, ...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use super::validation_message::ValidationMessage; use super::{ build_fragment_metadata_as_directive, build_fragment_spread, ...
fn get_fetch_field_id_and_id_arg<'s>( fragment: &FragmentDefinition, schema: &'s SDLSchema, query_type: Type, fetch_field_name: StringKey, ) -> DiagnosticsResult<(FieldID, &'s ArgumentDef)> { let fetch_field_id = schema.named_field(query_type, fetch_field_name); if let Some(fetch_field_id) = f...
y, ) -> DiagnosticsResult<FieldID> { let identifier_field_id = schema.named_field(fragment.type_condition, identifier_field_name); if let Some(identifier_field_id) = identifier_field_id { let identifier_field = schema.field(identifier_field_id); if schema.is_id(identifier_field.type_.inner()) { ...
function_block-function_prefixed
[ { "content": "// A copy of watchman_query_builder::unify_roots, but takes Vec<&PathBuf> as the input\n\nfn unify_roots(mut paths: Vec<&PathBuf>) -> Vec<PathBuf> {\n\n paths.sort();\n\n let mut roots = Vec::new();\n\n for path in paths {\n\n match roots.last() {\n\n Some(prev) if path....
Rust
src/window/mod.rs
ref209/neovide
b0bf7c2e75ededfb580d51f861d1be6aad3ed54f
mod keyboard; mod settings; #[cfg_attr(feature = "sdl2", path = "sdl2/mod.rs")] #[cfg_attr(feature = "winit", path = "winit/mod.rs")] mod window_wrapper; use crate::{ bridge::UiCommand, editor::{DrawCommand, WindowCommand}, renderer::Renderer, INITIAL_DIMENSIONS, }; use crossfire::mpsc::TxUnbounded; u...
mod keyboard; mod settings; #[cfg_attr(feature = "sdl2", path = "sdl2/mod.rs")] #[cfg_attr(feature = "winit", path = "winit/mod.rs")] mod window_wrapper; use crate::{ bridge::UiCommand, editor::{DrawCommand, WindowCommand}, renderer::Renderer, INITIAL_DIMENSIONS, }; use crossfire::mpsc::TxUnbounded; u...
}) .map_err(|msg| msg.to_owned()) }) } pub fn window_geometry_or_default() -> (u64, u64) { window_geometry().unwrap_or(INITIAL_DIMENSIONS) } #[cfg(target_os = "windows")] fn windows_fix_dpi() { println!("dpi fix applied"); use winapi::shared::windef::DPI_AWARENESS_...
if let [width, height] = dimensions[..] { Ok((width, height)) } else { Err(invalid_parse_err.as_str()) }
if_condition
[ { "content": "pub fn build_neovide_command(channel: u64, num_args: u64, command: &str, event: &str) -> String {\n\n let nargs: String = if num_args > 1 {\n\n \"+\".to_string()\n\n } else {\n\n num_args.to_string()\n\n };\n\n if num_args == 0 {\n\n return format!(\n\n ...
Rust
libdeflate-rs/src/decompress_deflate.rs
Guilucand/biloki
7c1d710bd03e797584e7f4db151d7b4c7b4433d7
/* * decompress_template.h * * Copyright 2016 Eric Biggers * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * ...
/* * decompress_template.h * * Copyright 2016 Eric Biggers * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * ...
remove_bits(&mut tmp_data, (entry & HUFFDEC_LENGTH_MASK) as usize); entry >>= HUFFDEC_RESULT_SHIFT; const_assert!( can_ensure(DEFLATE_MAX_EXTRA_LENGTH_BITS + DEFLATE_MAX_OFFSET_CODEWORD_LEN) && can_ensure(DEFLATE_MAX_EXTRA_OFFSET_BITS) ...
if (entry & HUFFDEC_SUBTABLE_POINTER) != 0 { /* Offset subtable required (uncommon case) */ remove_bits(&mut tmp_data, OFFSET_TABLEBITS); entry = d.offset_decode_table[(((entry >> HUFFDEC_RESULT_SHIFT) & 0xFFFF) + bits(&mut tmp_data, (entry & HUFFDEC_...
if_condition
[ { "content": "#[inline(always)]\n\npub fn fill_bits_bytewise<I: DeflateInput, O: DeflateOutput>(data: &mut DecompressTempData<I, O>) {\n\n loop {\n\n if unsafe { likely(data.input_stream.ensure_length(1)) } {\n\n let mut byte = [0];\n\n unsafe {\n\n data.input_stre...
Rust
src/bars/custom.rs
rowan-sl/stati
82024142d368b9439c421a9a893c16dbe2394aa2
use std::time::Instant; mod default { pub const FILLED: &str = "="; pub const EMPTY: &str = "-"; pub const START: &str = "["; pub const END: &str = "]"; pub const UNIT: &str = "its"; } #[derive(Clone, Debug, Hash)] pub struct BarElements { filled: String, empty: String, start: String, ...
use std::time::Instant; mod default { pub const FILLED: &str = "="; pub const EMPTY: &str = "-"; pub const START: &str = "["; pub const END: &str = "]"; pub const UNIT: &str = "its"; } #[derive(Clone, Debug, Hash)] pub struct BarElements { filled: String, empty: String, start: String, ...
must_use] pub fn filled(mut self, v: impl ToString) -> Self { self.elems.filled = v.to_string(); self } #[must_use] pub fn empty(mut self, v: impl ToString) -> Self { self.elems.empty = v.to_string(); self } #[must_use] pub fn start(mut self, v: im...
lements, } impl Builder { #[must_use] pub fn new(name: impl ToString) -> Self { Self { job_name: name.to_string(), hint: 100, elems: BarElements { ..Default::default() }, } } #[must_use] pub fn hint(mut self,...
random
[ { "content": "pub fn term_width() -> Option<u16> {\n\n use terminal_size::{terminal_size, Height, Width};\n\n let size = terminal_size();\n\n if let Some((Width(w), Height(_))) = size {\n\n Some(w)\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "src/utils.rs", "rank": 0, ...
Rust
src/kmer.rs
olgabot/needletail
d9d92bdf3cfffb6cdf4dca7f42a59ea9bf80d26b
use std::borrow::Cow; #[inline] pub fn complement(n: &u8) -> u8 { match *n as char { 'a' => 't' as u8, 'A' => 'T' as u8, 'c' => 'g' as u8, 'C' => 'G' as u8, 'g' => 'c' as u8, 'G' => 'C' as u8, 't' => 'a' as u8, 'T' => 'A' as u8, ...
use std::borrow::Cow; #[inline] pub fn complement(n: &u8) -> u8 { match *n as char { 'a' => 't' as u8, 'A' => 'T' as u8, 'c' => 'g' as u8, 'C' => 'G' as u8, 'g' => 'c' as u8, 'G' => 'C' as u8, 't' => 'a' as u8, 'T' => 'A' as u8, ...
#[test] fn can_minimize() { let minmer = minimizer(&b"ATTTCG"[..], 3); assert_eq!(&minmer[..], b"AAA"); } pub fn is_good_base(chr: u8) -> bool { match chr as char { 'a' | 'c' | 'g' | 't' | 'A' | 'C' | 'G' | 'T' => true, _ => false, } } pub fn has_no_n<'a>(seq: &'a [u8]) -> bool { ...
for (kmer, rc_kmer) in seq.windows(length).zip(reverse_complement.windows(length)) { if kmer < &minmer[..] { minmer = Cow::Borrowed(kmer); } if rc_kmer < &minmer[..] { minmer = Cow::Owned(rc_kmer.to_vec()); } } minmer }
function_block-function_prefix_line
[ { "content": "fn update_position(start_pos: &mut usize, k: u8, buffer: &[u8], initial: bool) -> bool {\n\n // check if we have enough \"physical\" space for one more kmer\n\n if *start_pos + k as usize > buffer.len() {\n\n return false;\n\n }\n\n\n\n let mut kmer_len = (k - 1) as usize;\n\n ...
Rust
sys_util/src/syslog.rs
Xiao-Cong-Cong/crosvm
76148ae9828505f449ee015cfe864620027605e3
use crate::target_os::syslog::PlatformSyslog; use std::env; use std::ffi::{OsStr, OsString}; use std::fmt::{self, Display}; use std::fs::File; use std::io; use std::io::{stderr, Cursor, Write}; use std::os::unix::io::{AsRawFd, RawFd}; use std::path::PathBuf; use std::sync::{MutexGuard, Once}; use sync::Mutex; #[der...
use crate::target_os::syslog::PlatformSyslog; use std::env; use std::ffi::{OsStr, OsString}; use std::fmt::{self, Display}; use std::fs::File; use std::io; use std::io::{stderr, Cursor, Write}; use std::os::unix::io::{AsRawFd, RawFd}; use std::path::PathBuf; use std::sync::{MutexGuard, Once}; use sync::Mutex; #[der...
} } fn get_proc_name() -> Option<String> { env::args_os() .next() .map(PathBuf::from) .and_then(|s| s.file_name().map(OsStr::to_os_string)) .map(OsString::into_string) .and_then(Result::ok) } struct State { stderr: bool, file: Option<File>, proc_name: Optio...
match self { NeverInitialized => write!(f, "initialization was never attempted"), Poisoned => write!(f, "initialization previously failed and cannot be retried"), Socket(e) => write!(f, "failed to create socket: {}", e), Connect(e) => write!(f, "failed to connect socket: ...
if_condition
[ { "content": "/// Loads a kernel from a vmlinux elf image to a slice\n\n///\n\n/// # Arguments\n\n///\n\n/// * `guest_mem` - The guest memory region the kernel is written to.\n\n/// * `kernel_start` - The offset into `guest_mem` at which to load the kernel.\n\n/// * `kernel_image` - Input vmlinux image.\n\npub ...
Rust
sdk/src/cell_collector.rs
LeonLi000/toCKB
fcd07d5454518676d1f396d882ac51865187056f
use crate::indexer::{Cell, IndexerRpcClient, Order, Pagination, ScriptType, SearchKey}; use crate::util::is_mature; use anyhow::Result; use ckb_jsonrpc_types::Uint32; use ckb_types::packed::{self, Script}; use tockb_types::config::UDT_LEN; pub fn get_live_cell_by_typescript( indexer_client: &mut IndexerRpcClient, ...
use crate::indexer::{Cell, IndexerRpcClient, Order, Pagination, ScriptType, SearchKey}; use crate::util::is_mature; use anyhow::Result; use ckb_jsonrpc_types::Uint32; use ckb_types::packed::{self, Script}; use tockb_types::config::UDT_LEN; pub fn get_live_cell_by_typescript( indexer_client: &mut IndexerRpcClient, ...
indexer_client.get_cells(search_key.clone(), Order::Asc, limit, cursor)?; if live_cells.objects.len() == 0 { break; } cursor = Some(live_cells.last_cursor); for (index, cell) in live_cells.objects.into_iter().enumerate() { let (stop, push_info) = terminator(inde...
rminator: F, ) -> Result<Vec<Cell>, String> { let limit = Uint32::from(100u32); let mut infos = Vec::new(); let mut cursor = None; loop { let live_cells: Pagination<Cell> =
random
[ { "content": "pub fn check_capacity(capacity: u64, to_data_len: usize) -> Result<(), String> {\n\n if capacity < MIN_SECP_CELL_CAPACITY {\n\n return Err(format!(\n\n \"Capacity can not less than {} shannons\",\n\n MIN_SECP_CELL_CAPACITY\n\n ));\n\n }\n\n if capacity ...
Rust
styx.rs/src/context.rs
6A/styx-history
c1bff1983e2faf5ce7deadb281ee0a936dafadd1
use diagnostics::{Diagn, Diagnostic}; use emit::Emitter; use procedures::Procs; use symbols::{LookupSym, Symbol}; use typesystem::{Fun, Member, MemberTree, Ty, TyParameters}; use utils::{Generics, InternedString}; use vm::Vm; use std::fmt::{self, Debug, Formatter}; use std::marker::PhantomData; use std::mem::{self, ...
use diagnostics::{Diagn, Diagnostic}; use emit::Emitter; use procedures::Procs; use symbols::{LookupSym, Symbol}; use typesystem::{Fun, Member, MemberTree, Ty, TyParameters}; use utils::{Generics, InternedString}; use vm::Vm; use std::fmt::{self, Debug, Formatter}; use std::marker::PhantomData; use std::mem::{self, ...
} } pub fn get_functions<'a>(&'a self, name: &'a Symbol) -> Vec<&'cx Fun<'cx>> { let name_hash = { let parts = name.parts(); parts[parts.len() - 1] }; match self.members.lookup(name) { Some(node) => node.siblings().filter_map(|n| ...
match self.members.get(name) { Some(member) => member.as_type(), None => match self.parent { Some(parent) => parent.get_type(name), None => None }
function_block-random_span
[ { "content": "fn def_mut_child_fn<'cx>(_self: *mut (), _i: usize) -> Option<*mut Expr<'cx>> { None }\n\n\n\n\n\n// //==========================================================================//\n\n// // EXTENSION //\n\n// //=========================...
Rust
src/app.rs
kivikakk/crates.io
e8cae0e872be4edf02f0876db4e85c082e70ecc9
use std::env; use std::error::Error; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use conduit::{Request, Response}; use conduit_middleware::Middleware; use git2; use oauth2; use r2d2; use curl::easy::Easy; use {db, Config}; #[allow(missing_debug_implementations)] pub struct App { pub diesel_databa...
use std::env; use std::error::Error; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use conduit::{Request, Response}; use conduit_middleware::Middleware; use git2; use oauth2; use r2d2; use curl::easy::Easy; use {db, Config}; #[allow(missing_debug_implementations)] pub struct App { pub diesel_databa...
ore(&self, req: &mut Request) -> Result<(), Box<Error + Send>> { req.mut_extensions().insert(Arc::clone(&self.app)); Ok(()) } fn after( &self, req: &mut Request, res: Result<Response, Box<Error + Send>>, ) -> Result<Response, Box<Error + Send>> { req.mut_exte...
_ => None, }; let db_helper_threads = match (env::var("DB_HELPER_THREADS"), config.env) { (Ok(num), _) => num.parse().expect("couldn't parse DB_HELPER_THREADS"), (_, ::Env::Production) => 3, _ => 1, }; let diesel_db_config = r2d2::Config::bu...
random
[]
Rust
compiler/rustc_codegen_ssa/src/mir/debuginfo.rs
vext01/ykrustc
c6c90278d1cd680bfb2ef37c070e9d7128eab6c9
use crate::traits::*; use rustc_index::vec::IndexVec; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir; use rustc_middle::ty; use rustc_session::config::DebugInfo; use rustc_span::symbol::{kw, Symbol}; use rustc_span::{BytePos, Span}; use rustc_target::abi::{LayoutOf, Size}; use su...
use crate::traits::*; use rustc_index::vec::IndexVec; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir; use rustc_middle::ty; use rustc_session::config::DebugInfo; use rustc_span::symbol::{kw, Symbol}; use rustc_span::{BytePos, Span}; use rustc_target::abi::{LayoutOf, Size}; use su...
} } else { None }; let local_ref = &self.locals[local]; let name = if bx.sess().fewer_names() { None } else { Some(match whole_local_var.or(fallback_var) { Some(var) if var.name != kw::Empty => var.name.to_string(...
Some(PerLocalVarDebugInfo { name, source_info: decl.source_info, dbg_var, projection: ty::List::empty(), })
call_expression
[]
Rust
src/lib/ifaces/mac_vlan.rs
robgc/nispor
32e5d0a2e217322e144fe1ffe916e217133c2b74
use crate::mac::parse_as_mac; use crate::netlink::parse_as_u16; use crate::netlink::parse_as_u32; use crate::Iface; use crate::IfaceType; use crate::NisporError; use netlink_packet_route::rtnl::link::nlas; use netlink_packet_route::rtnl::nlas::NlasIterator; use serde_derive::{Deserialize, Serialize}; use std::collectio...
use crate::mac::parse_as_mac; use crate::netlink::parse_as_u16; use crate::netlink::parse_as_u32; use crate::Iface; use crate::IfaceType; use crate::NisporError; use netlink_packet_route::rtnl::link::nlas; use netlink_packet_route::rtnl::nlas::NlasIterator; use serde_derive::{Deserialize, Serialize}; use std::collectio...
"MAC VLAN IFLA_INFO_DATA NlasIterator failure: {}", e ); } } } Ok(Some(info)) } else { Ok(None) } } fn parse_mac_addr_data(raw: &[u8]) -> Result<Vec<String>, NisporError> { let mut addrs = Vec::new();...
(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] pub struct MacVlanInfo { pub base_iface: String, pub mode: MacVlanMode, pub flags: u16, #[serde(skip_serializing_if = "Option::is_none")] pub allowed_mac_addresses: Option<Vec<String>>, } pub(crate) fn get_mac_vlan_info( data: &nlas::I...
random
[ { "content": "fn parse_brport_designated_port(\n\n data: &[u8],\n\n port_info: &mut BridgePortInfo,\n\n) -> Result<(), NisporError> {\n\n port_info.designated_port = parse_as_u16(data)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/lib/netlink/bridge_port.rs", "rank": 0, "score": 155465.897...
Rust
diesel/src/query_builder/select_statement/boxed.rs
marcelbuesing/diesel
42d5b831ac6b407c74a3659653f5b9d171730851
use std::marker::PhantomData; use backend::Backend; use dsl::AsExprOf; use expression::subselect::ValidSubselect; use expression::*; use insertable::Insertable; use query_builder::distinct_clause::DistinctClause; use query_builder::group_by_clause::GroupByClause; use query_builder::insert_statement::InsertFromSelect; ...
use std::marker::PhantomData; use backend::Backend; use dsl::AsExprOf; use expression::subselect::ValidSubselect; use expression::*; use insertable::Insertable; use query_builder::distinct_clause::DistinctClause; use query_builder::group_by_clause::GroupByClause; use query_builder::insert_statement::InsertFromSelect; ...
} impl<'a, ST, QS, DB, Predicate> FilterDsl<Predicate> for BoxedSelectStatement<'a, ST, QS, DB> where BoxedWhereClause<'a, DB>: WhereAnd<Predicate, Output = BoxedWhereClause<'a, DB>>, Predicate: AppearsOnTable<QS, SqlType = Bool> + NonAggregate, { type Output = Self; fn filter(mut self, predicate: Pr...
Box::new(selection), self.from, self.distinct, self.where_clause, self.order, self.limit, self.offset, self.group_by, ) }
function_block-function_prefix_line
[ { "content": "pub trait SelectClauseQueryFragment<QS, DB: Backend> {\n\n fn walk_ast(&self, source: &QS, pass: AstPass<DB>) -> QueryResult<()>;\n\n}\n\n\n\nimpl<T, QS, DB> SelectClauseQueryFragment<QS, DB> for SelectClause<T>\n\nwhere\n\n DB: Backend,\n\n T: QueryFragment<DB>,\n\n{\n\n fn walk_ast(&...
Rust
src/commands.rs
kavanmevada/cargo-pkg
2517e41edd3f676ed5acfb9c2f2d1ed38cc69ec2
use super::metadata::Metadata; use std::{collections::HashMap, env, ffi::OsStr, path::PathBuf, process::Command}; pub struct Commands<'a> { pub datadir: &'a PathBuf, pub podir: &'a PathBuf, pub metadata: &'a Metadata, pub profile: &'a str, } impl<'a> Commands<'a> { pub fn proce...
use super::metadata::Metadata; use std::{collections::HashMap, env, ffi::OsStr, path::PathBuf, process::Command}; pub struct Commands<'a> { pub datadir: &'a PathBuf, pub podir: &'a PathBuf, pub metadata: &'a Metadata, pub profile: &'a str, } impl<'a> Commands<'a> { pub fn proce...
pub fn install_glib_resources(&self, glibresource: &PathBuf, prefix: &PathBuf) -> Option<()> { let resourcedir = self.datadir.join("resources"); if glibresource.exists() && resourcedir.exists() { let installdir = prefix.join("share").join(&self.metadata.id); std:...
let ndir = prefix.join("share").join(if ttype == "--desktop" { "applications" } else { "appdata" }); let npath = ndir.join(file.file_name()?); std::fs::create_dir_all(&ndir).ok()?; if self.podir.exi...
function_block-function_prefix_line
[ { "content": "struct Builder<'a> {\n\n // Profile can be either \"release\" or \"debug\"\n\n profile: &'a str,\n\n buildflags: &'a [String],\n\n}\n\n\n\nimpl<'a> Builder<'a> {\n\n fn new(buildflags: &'a [String], profile: &'a str) -> Self {\n\n Builder {\n\n buildflags,\n\n ...
Rust
atcoder-problems-backend/atcoder-client/src/atcoder/contest.rs
Balut-moko/AtCoderProblems
fe2824f4e9954b66408ac9c2c677d075bcbb2c03
use anyhow::{anyhow, Result}; use super::AtCoderContest; use chrono::DateTime; use scraper::{Html, Selector}; const PERMANENT_CONTEST_DURATION_SECOND: u64 = 100 * 365 * 24 * 3600; pub(super) fn scrape_normal(html: &str) -> Result<Vec<AtCoderContest>> { Html::parse_document(html) .select(&Selector::parse...
use anyhow::{anyhow, Result}; use super::AtCoderContest; use chrono::DateTime; use scraper::{Html, Selector}; const PERMANENT_CONTEST_DURATION_SECOND: u64 = 100 * 365 * 24 * 3600; pub(super) fn scrape_normal(html: &str) -> Result<Vec<AtCoderContest>> { Html::parse_document(html) .select(&Selector::parse...
#[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::Read; #[test] fn test_scrape_normal() { let mut file = File::open("test_resources/contests_normal").unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let ...
map(|tr| { let selector = Selector::parse("td").unwrap(); let mut tds = tr.select(&selector); let contest = tds.next().ok_or_else(|| anyhow!("Failed to parse html."))?; let contest_title = contest .select(&Selector::parse("a").unwrap()) .n...
function_block-function_prefix_line
[ { "content": "fn create_problem(id: i32) -> ContestProblem {\n\n ContestProblem {\n\n contest_id: format!(\"contest{}\", id),\n\n problem_id: format!(\"problem{}\", id),\n\n }\n\n}\n\n\n\n#[async_std::test]\n\nasync fn test_contest_problem() {\n\n let pool = utils::initialize_and_connect_...
Rust
tests/basic_tests.rs
sjames/cyclonedds-rs
9c7f34badfc9aa800997f94d55f31136e39d4b3e
/* use cyclonedds_rs::{ self, dds_api, dds_topic::DdsTopic, DdsListener, DdsQos, DdsReader, DdsStatus, DdsWriter, Entity, }; use helloworld_data; use std::ffi::{CStr, CString}; use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; /// Simple hello world test. Sending and receiving one message #[test...
/* use cyclonedds_rs::{ self, dds_api, dds_topic::DdsTopic, DdsListener, DdsQos, DdsReader, DdsStatus, DdsWriter, Entity, }; use helloworld_data; use std::ffi::{CStr, CString}; use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; /// Simple hello world test. Sending and receiving one message #[test...
ust\0".as_bytes()) .unwrap() ); tx.send(0).unwrap(); } else { println!("Error reading"); } } */ }) .hook(); if let Ok(mut reader) = DdsReader::create(&part...
{ let msg = msg.as_slice(); println!("Received {} messages", msg.len()); println!("Received message : {}", msg[0].userID); assert_eq!(1, msg[0].userID); assert_eq!( CStr::from_ptr(ms...
random
[ { "content": "pub fn dds_set_status_mask(entity: &DdsEntity, status_mask: DdsStatus) -> Result<(), DDSError> {\n\n unsafe {\n\n let err = cyclonedds_sys::dds_set_status_mask(entity.entity(), status_mask.into());\n\n\n\n if err < 0 {\n\n Err(DDSError::from(err))\n\n } else {\n\...
Rust
query/src/sql/statements/statement_select.rs
willie-lin/databend
52a62a2db71544284449b209e79972a021ff19db
use std::sync::Arc; use common_datablocks::DataBlock; use common_datavalues::DataSchemaRefExt; use common_exception::ErrorCode; use common_exception::Result; use common_planners::expand_aggregate_arg_exprs; use common_planners::find_aggregate_exprs; use common_planners::find_aggregate_exprs_in_expr; use common_plann...
use std::sync::Arc; use common_datablocks::DataBlock; use common_datavalues::DataSchemaRefExt; use common_exception::ErrorCode; use common_exception::Result; use common_planners::expand_aggregate_arg_exprs; use common_planners::find_aggregate_exprs; use common_planners::find_aggregate_exprs_in_expr; use common_plann...
}
th_capacity(exprs.len()); for expr in exprs { new_data_fields.push(expr.to_data_field(schema)?); } Ok(DataBlock::empty_with_schema(DataSchemaRefExt::create( new_data_fields, ))) }
function_block-function_prefixed
[ { "content": "// Rebuilds an `expr` to ColumnExpr when some expressions already processed in upstream\n\n// Skip Sort, Alias because we can go into the inner nest_exprs\n\npub fn rebase_expr_from_input(expr: &Expression, schema: &DataSchemaRef) -> Result<Expression> {\n\n clone_with_replacement(expr, &|nest_...
Rust
src/iter/try_fold.rs
akshay-deepsource/rayon
e035296c50e8758037a8097d2f4cb8ced9131419
use super::plumbing::*; use super::ParallelIterator; use super::Try; use super::private::ControlFlow::{self, Break, Continue}; use std::fmt::{self, Debug}; use std::marker::PhantomData; impl<U, I, ID, F> TryFold<I, U, ID, F> where I: ParallelIterator, F: Fn(U::Output, I::Item) -> U + Sync + Send, ID: Fn(...
use super::plumbing::*; use super::ParallelIterator; use super::Try; use super::private::ControlFlow::{self, Break, Continue}; use std::fmt::{self, Debug}; use std::marker::PhantomData; impl<U, I, ID, F> TryFold<I, U, ID, F> where I: ParallelIterator, F: Fn(U::Output, I::Item) -> U + Sync + Send, ID: Fn(...
fn full(&self) -> bool { self.base.full() } } impl<'r, U, T, C, F> UnindexedConsumer<T> for TryFoldWithConsumer<'r, C, U, F> where C: UnindexedConsumer<U>, F: Fn(U::Output, T) -> U + Sync, U: Try + Send, U::Output: Clone + Send, { fn split_off_left(&self) -> Self { TryFold...
fn into_folder(self) -> Self::Folder { TryFoldFolder { base: self.base.into_folder(), control: Continue(self.item), fold_op: self.fold_op, } }
function_block-full_function
[ { "content": "struct TryReduceConsumer<'r, R, ID> {\n\n identity: &'r ID,\n\n reduce_op: &'r R,\n\n full: &'r AtomicBool,\n\n}\n\n\n\nimpl<'r, R, ID> Copy for TryReduceConsumer<'r, R, ID> {}\n\n\n\nimpl<'r, R, ID> Clone for TryReduceConsumer<'r, R, ID> {\n\n fn clone(&self) -> Self {\n\n *sel...
Rust
src/range_proof/party.rs
gterzian/ristretto-bulletproofs
6d4b132c31c244a2b42304b8db8de8a6730117ad
use curve25519_dalek::ristretto; use curve25519_dalek::ristretto::RistrettoPoint; use curve25519_dalek::scalar::Scalar; use generators::Generators; use rand::Rng; use std::iter; use util; use super::messages::*; pub struct Party {} impl Party { pub fn new( v: u64, v_blinding: Scalar, n:...
use curve25519_dalek::ristretto; use curve25519_dalek::ristretto::RistrettoPoint; use curve25519_dalek::scalar::Scalar; use generators::Generators; use rand::Rng; use std::iter; use util; use super::messages::*; pub struct Party {} impl Party { pub fn new( v: u64, v_blinding: Scalar, n:...
let t_blinding_poly = util::Poly2( self.z * self.z * self.offset_z * self.v_blinding, self.t_1_blinding, self.t_2_blinding, ); let t_x = self.t_poly.eval(pc.x); let t_x_blinding = t_blinding_poly.eval(pc.x); let e_blinding = self.a_blinding ...
if pc.x == Scalar::zero() { return Err("Poly challenge was zero, which would leak secrets, bailing out"); }
if_condition
[ { "content": "/// Raises `x` to the power `n` using binary exponentiation,\n\n/// with (1 to 2)*lg(n) scalar multiplications.\n\n/// TODO: a consttime version of this would be awfully similar to a Montgomery ladder.\n\npub fn scalar_exp_vartime(x: &Scalar, mut n: u64) -> Scalar {\n\n let mut result = Scalar:...
Rust
benches/benchmark.rs
ichi-h/markov_rs
1506fe851d5e12a8364e8e46dc09b604b909a9ff
use markov_rs::MarkovChain; use once_cell::sync::Lazy; use criterion::Criterion; use criterion::{criterion_group, criterion_main}; const LONG_TEXT: Lazy<Vec<&str>> = Lazy::new(|| { const TEXT: &str = include_str!("../assets/long_text.txt"); TEXT.split(" ").collect() }); const MIDDLE_TEXT: Lazy<Vec<&str>> = ...
use markov_rs::MarkovChain; use once_cell::sync::Lazy; use criterion::Criterion; use criterion::{criterion_group, criterion_main}; const LONG_TEXT: Lazy<Vec<&str>> = Lazy::new(|| { const TEXT: &str = include_str!("../assets/long_text.txt"); TEXT.split(" ").collect() }); const MIDDLE_TEXT: Lazy<Vec<&str>> = ...
fn bench_generate_element_using_wam(c: &mut Criterion) { let mut model_1 = MarkovChain::from(&SHORT_TEXT); let mut model_2 = MarkovChain::from(&MIDDLE_TEXT); let mut model_3 = MarkovChain::from(&LONG_TEXT); let mut result = [""; 10]; let mut rng = rand::thread_rng(); c.bench_function("gener...
fn bench_create_cdf_model(c: &mut Criterion) { c.bench_function("create_cdf_model_from_short_text", |b| { b.iter(|| MarkovCSM::from(&SHORT_TEXT)) }); c.bench_function("create_cdf_model_from_middle_text", |b| { b.iter(|| MarkovCSM::from(&MIDDLE_TEXT)) }); c.bench_function("create_cd...
function_block-full_function
[ { "content": "fn main() {\n\n let text = [\n\n \"I\", \"think\", \"that\", \"that\", \"that\", \"that\", \"that\", \"boy\", \"wrote\", \"is\", \"wrong\",\n\n ];\n\n let mut model = MarkovChain::from(&text);\n\n for _ in 0..20 {\n\n print!(\"{} \", model.next());\n\n }\n\n}\n", "...
Rust
src/hubris/session.rs
jroesch/hubris
0333d4d26b7d66924acfe065c94d914e0ba011e4
use super::ast::{Span, SourceMap, ModuleId}; use std::cell::RefCell; use std::collections::{HashSet, HashMap}; use std::env; use std::path::{PathBuf, Path}; use std::process; use std::io; use std::rc::Rc; use std::io::prelude::*; use term::{self, Terminal, color, StdoutTerminal}; pub trait HasSession { #[inline]...
use super::ast::{Span, SourceMap, ModuleId}; use std::cell::RefCell; use std::collections::{HashSet, HashMap}; use std::env; use std::path::{PathBuf, Path}; use std::process; use std::io; use std::rc::Rc; use std::io::prelude::*; use term::{self, Terminal, color, StdoutTerminal}; pub trait HasSession { #[inline]...
pub fn resolve_path(&self, path: &Path) -> PathBuf { self.data.borrow().load_paths[0].join(path) } } impl HasSession for Session { fn session(&self) -> &Session { self } }
filename_str = format!("{}:{}:{}: {}:{} ", source_map.file_name, line_no, col_no, line_no, col_no + (span.hi - span.lo)); try!(write!(terminal, "{}", filename_str)); try!(terminal.fg(color::RED)); try!(write!(terminal, "error: "));...
random
[ { "content": "/// Construct a recursor for `data_type`.\n\npub fn make_recursor(ty_cx: &mut TyCtxt, data_type: &Data) -> Result<(), Error> {\n\n let mut rcx = InductiveCx::new(ty_cx, data_type);\n\n let recursor = try!(rcx.recursor());\n\n\n\n // Add an axiom with the recursor type, and the associated ...
Rust
gremlin-client/src/process/traversal/graph_traversal.rs
yagince/gremlin-rs
e195f678fdf6c135076c8b1f8175de9e1c74da5c
use crate::conversion::FromGValue; use crate::process::traversal::step::by::IntoByStep; use crate::process::traversal::step::dedup::DedupStep; use crate::process::traversal::step::has::IntoHasStep; use crate::process::traversal::step::limit::LimitStep; use crate::process::traversal::step::match_step::IntoMatchStep; use...
use crate::conversion::FromGValue; use crate::process::traversal::step::by::IntoByStep; use crate::process::traversal::step::dedup::DedupStep; use crate::process::traversal::step::has::IntoHasStep; use crate::process::traversal::step::limit::LimitStep; use crate::process::traversal::step::match_step::IntoMatchStep; use...
versal::new(self.terminator, self.builder) } pub fn group_count(mut self) -> GraphTraversal<S, Map, T> where T: Terminator<Map>, { self.builder = self.builder.group_count(None); GraphTraversal::new(self.terminator, self.builder) } pub fn group_count_as<A>(mut self, key:...
pub fn in_v(mut self) -> GraphTraversal<S, Vertex, T> where T: Terminator<Vertex>, { self.builder = self.builder.in_v(); GraphTraversal::new(self.terminator, self.builder) } pub fn label(mut self) -> GraphTraversal<S, String, T> where T: Terminator<String>, { ...
random
[ { "content": "pub fn create_vertex_with_label(graph: &GremlinClient, label: &str, name: &str) -> Vertex {\n\n graph\n\n .execute(\n\n \"g.addV(_label).property('name',name)\",\n\n &[(\"_label\", &label), (\"name\", &name)],\n\n )\n\n .expect(\"it should execute addV...
Rust
arch/src/x86_64/mod.rs
wllenyj/cloud-hypervisor
0374c3dc7116c526aa8a2ad038ab90e9f652e91b
mod gdt; pub mod interrupts; pub mod layout; mod mptable; pub mod regs; use crate::RegionType; use linux_loader::loader::bootparam::{boot_params, setup_header}; use std::mem; use vm_memory::{ Address, ByteValued, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap, GuestUsize, }; const E820_RAM: u32 = 1; const E8...
mod gdt; pub mod interrupts; pub mod layout; mod mptable; pub mod regs; use crate::RegionType; use linux_loader::loader::bootparam::{boot_params, setup_header}; use std::mem; use vm_memory::{ Address, ByteValued, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap, GuestUsize, }; const E820_RAM: u32 = 1; const E8...
#[test] fn test_add_e820_entry() { let e820_table = [(boot_e820_entry { addr: 0x1, size: 4, type_: 1, }); 128]; let expected_params = boot_params { e820_table, e820_entries: 1, ..Default::default() }; ...
let mem_size = 3330 << 20; let arch_mem_regions = arch_memory_regions(mem_size); let ram_regions: Vec<(GuestAddress, usize)> = arch_mem_regions .iter() .filter(|r| r.2 == RegionType::Ram) .map(|r| (r.0, r.1)) .collect(); let gm = GuestMemoryMmap::n...
function_block-function_prefix_line
[ { "content": "/// Stub function that needs to be implemented when aarch64 functionality is added.\n\npub fn arch_memory_regions(size: usize) -> Vec<(GuestAddress, usize, RegionType)> {\n\n vec![(GuestAddress(0), size, RegionType::Ram)]\n\n}\n\n\n", "file_path": "arch/src/aarch64/mod.rs", "rank": 0, ...
Rust
labs/lab6_practice(master)/os/src/memory/mapping/page_table_entry.rs
yunwei37/os-summer-of-code-daily
56dc22b8767691dc900bb5b8ce174a9eacc276f8
use crate::memory::address::*; use bit_field::BitField; use bitflags::*; #[derive(Copy, Clone, Default)] pub struct PageTableEntry(usize); const FLAG_RANGE: core::ops::Range<usize> = 0..8; const PAGE_NUMBER_RANGE: core::ops::Range<usize> = 10..54; impl PageTableEntry { pub fn new(page_number: Option<Phys...
use crate::memory::address::*; use bit_field::BitField; use bitflags::*; #[derive(Copy, Clone, Default)] pub struct PageTableEntry(usize); const FLAG_RANGE: core::ops::Range<usize> = 0..8; const PAGE_NUMBER_RANGE: core::ops::Range<usize> = 10..54; impl PageTableEntry { pub fn new(page_number: Option<Phys...
ntains(Flags::READABLE) || flags.contains(Flags::WRITABLE) || flags.contains(Flags::EXECUTABLE)) } } impl core::fmt::Debug for PageTableEntry { fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { formatter .debug_struct("PageTableEntry") ...
.set_bits(PAGE_NUMBER_RANGE, ppn.into()); } else { self.0 .set_bits(FLAG_RANGE, (self.flags() - Flags::VALID).bits() as usize) .set_bits(PAGE_NUMBER_RANGE, 0); } } pub fn clear(&mut self) { self.0 = 0; } pub fn page_number(&...
random
[ { "content": "#[no_mangle]\n\npub fn handle_interrupt(context: &mut Context, scause: Scause, stval: usize) -> *mut Context {\n\n // 返回的 Context 必须位于放在内核栈顶\n\n match scause.cause() {\n\n // 断点中断(ebreak)\n\n Trap::Exception(Exception::Breakpoint) => breakpoint(context),\n\n // 时钟中断\n\n ...
Rust
front/src/components/sources.rs
sanpii/oxfeed
a8d79bdd115b903bdb05ec475ef4fbc9c1b01108
#[derive(Clone)] pub(crate) enum Message { Add, Cancel, Create(oxfeed_common::source::Entity), Event(crate::event::Event), PageChange(usize), Update(crate::Pager<oxfeed_common::source::Entity>), NeedUpdate, } impl From<crate::event::Api> for Message { fn from(event: crate::event::Api) -...
#[derive(Clone)] pub(crate) enum Message { Add, Cancel, Create(oxfeed_common::source::Entity), Event(crate::event::Event), PageChange(usize), Update(crate::Pager<oxfeed_common::source::Entity>), NeedUpdate, } impl From<crate::event::Api> for Message { fn from(event: crate::event::Api) -...
fn view(&self) -> yew::Html { let add = match &self.scene { Scene::View => yew::html! { <a class=yew::classes!("btn", "btn-primary") title="Add" onclick=self.link.callback(|_| Message::Add) > ...
Add, Self::Message::Update(ref pager) => self.pager = Some(pager.clone()), _ => (), }, Scene::Add => match msg { Self::Message::Cancel => self.scene = Scene::View, Self::Message::Create(ref source) => self.api.sources_create(source)...
function_block-function_prefixed
[ { "content": "#[derive(Clone)]\n\nstruct Link {\n\n count: i64,\n\n icon: &'static str,\n\n label: &'static str,\n\n route: super::app::Route,\n\n}\n\n\n\npub(crate) struct Component {\n\n api: crate::Api<Self>,\n\n current_route: super::app::Route,\n\n event_bus: yew::agent::Dispatcher<cra...
Rust
pallas-miniprotocols/src/txsubmission/mod.rs
txpipe/pallas
25a65529e088ca6f202d66f29aafa71d69fbaf40
use std::fmt::Debug; use itertools::Itertools; use log::debug; use pallas_codec::minicbor::{decode, encode, Decode, Decoder, Encode, Encoder}; use crate::machines::{Agent, MachineError, Transition}; #[derive(Debug, PartialEq, Clone)] pub enum State { Idle, TxIdsNonBlocking, TxIdsBlocking, Txs, Do...
use std::fmt::Debug; use itertools::Itertools; use log::debug; use pallas_codec::minicbor::{decode, encode, Decode, Decoder, Encode, Encoder}; use crate::machines::{Agent, MachineError, Transition}; #[derive(Debug, PartialEq, Clone)] pub enum State { Idle, TxIdsNonBlocking, TxIdsBlocking, Txs, Do...
f !block => { self.on_tx_ids_request(ack as usize, req as usize) } (State::Idle, Message::RequestTxIds(block, _, _)) if block => Ok(Self { state: State::TxIdsBlocking, ..self }), (State::Idle, Message::RequestTxs(ids)) => se...
ebug)] pub struct NaiveProvider { pub state: State, pub fifo_txs: Vec<Tx>, pub requested_ids_count: usize, pub requested_txs: Option<Vec<TxId>>, } impl NaiveProvider { pub fn initial(fifo_txs: Vec<Tx>) -> Self { Self { state: State::Idle, requested_ids_count: 0, ...
random
[ { "content": "fn read_segment(reader: &mut impl Read) -> Result<(u16, u32, Payload), std::io::Error> {\n\n let mut header = [0u8; 8];\n\n\n\n reader.read_exact(&mut header)?;\n\n\n\n if log_enabled!(log::Level::Trace) {\n\n trace!(\"read segment header: {:?}\", hex::encode(&header));\n\n }\n\...
Rust
openmls/src/tree/tests_and_kats/kats/kat_treemath.rs
greydot/openmls
fca1cbd3400d377dae06ef9ceebda5e0392c6c89
#[cfg(test)] use crate::test_utils::*; use crate::tree::{index::*, treemath::*}; use serde::{self, Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TreeMathTestVector { n_leaves: u32, n_nodes: u32, root: Vec<u32>, left: Vec<Option<u32>>, right: Vec<Option<u32>...
#[cfg(test)] use crate::test_utils::*; use crate::tree::{index::*, treemath::*}; use serde::{self, Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TreeMathTestVector { n_leaves: u32, n_nodes: u32, root: Vec<u32>, left: Vec<Option<u32>>, right: Vec<Option<u32>...
)] pub fn run_test_vector(test_vector: TreeMathTestVector) -> Result<(), TmTestVectorError> { let n_leaves = test_vector.n_leaves as usize; let n_nodes = node_width(n_leaves); let leaves = LeafIndex::from(n_leaves); if test_vector.n_nodes != node_width(leaves.as_usize()) as u32 { return Err(TmTe...
!(right(NodeIndex::from(i), leaves))); test_vector .parent .push(convert!(parent(NodeIndex::from(i), leaves))); test_vector .sibling .push(convert!(sibling(NodeIndex::from(i), leaves))); } test_vector } #[test] fn write_test_vectors() { let m...
random
[ { "content": "#[cfg(any(feature = \"test-utils\", test))]\n\npub fn generate_test_vector(n_leaves: u32, ciphersuite: &'static Ciphersuite) -> TreeKemTestVector {\n\n use crate::{extensions::RatchetTreeExtension, test_utils::test_framework::CodecUse};\n\n\n\n // The test really only makes sense with two or...
Rust
src/lib.rs
jashandeep-sohi/cargo-generate
0d8844ef79d369693858a684c4b9d817b37c2615
mod app_config; mod config; mod emoji; mod favorites; mod git; mod ignore_me; mod include_exclude; mod interactive; mod log; mod progressbar; mod project_variables; mod template; mod template_variables; use anyhow::{Context, Result}; use config::{Config, ConfigValues, CONFIG_FILE_NAME}; use console::style; use favor...
mod app_config; mod config; mod emoji; mod favorites; mod git; mod ignore_me; mod include_exclude; mod interactive; mod log; mod progressbar; mod project_variables; mod template; mod template_variables; use anyhow::{Context, Result}; use config::{Config, ConfigValues, CONFIG_FILE_NAME}; use console::style; use favor...
fn create_git(args: Args, name: &ProjectName) -> Result<()> { let force = args.force; let template_values = args .template_values_file .as_ref() .map(|p| Path::new(p)) .map_or(Ok(Default::default()), |path| get_config_file_values(path))?; let remote = args .git ...
pub fn generate(mut args: Args) -> Result<()> { if args.list_favorites { return list_favorites(&args); } resolve_favorite(&mut args)?; let name = match args.name { Some(ref n) => ProjectName::new(n), None if !args.silent => ProjectName::new(interactive::name()?), None =>...
function_block-full_function
[ { "content": "pub fn init(project_dir: &Path, branch: &str) -> Result<Repository> {\n\n Repository::discover(project_dir).or_else(|_| {\n\n let mut opts = RepositoryInitOptions::new();\n\n opts.bare(false);\n\n opts.initial_head(branch);\n\n Repository::init_opts(project_dir, &opt...
Rust
src/lib.rs
JakubOnderka/mrt_parser
30a9ec87c265a1280377a735fa67de637088efb9
use byteorder::{BigEndian, ReadBytesExt}; use ip_network::{IpNetwork, Ipv4Network, Ipv6Network}; use std::io; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; pub mod bgp; pub mod processor; pub trait Message<M> { fn parse<R: ReadBytesExt>(reader: &mut R, header: &MrtHeader) -> io::Result<M>; fn can_parse(typ: Mrt...
use byteorder::{BigEndian, ReadBytesExt}; use ip_network::{IpNetwork, Ipv4Network, Ipv6Network}; use std::io; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; pub mod bgp; pub mod processor; pub trait Message<M> { fn parse<R: ReadBytesExt>(reader: &mut R, header: &MrtHeader) -> io::Result<M>; fn can_parse(typ: Mrt...
let view_number = reader.read_u16::<BigEndian>()?; let sequence_number = reader.read_u16::<BigEndian>()?; let prefix_ip = read_ip_addr(reader, is_ipv6)?; let prefix_length = reader.read_u8()?; let prefix = IpNetwork::new(prefix_ip, prefix_length).unwrap(); let status = ...
let is_ipv6 = match header.typ { MrtType::TableDump(subtype) => match subtype { TableDump::AfiIpv4 => false, TableDump::AfiIpv6 => true, _ => panic!("Only AFI_IPv4 and AFI_IPv6 subtypes are supported"), }, _ => panic!("Only TableDump ty...
assignment_statement
[ { "content": "pub fn get_origin_as_from_afi(afi: &Afi) -> Result<Vec<u32>, Box<dyn Error>> {\n\n let mut output = vec![];\n\n for attribute in afi.get_bgp_attributes()? {\n\n if let Attribute::AsPath(ref as_path) = attribute {\n\n output.append(&mut get_origin_as_from_bgp_attribute_as_pa...
Rust
proxy/src/lib.rs
xiaods/conduit
bc16034fd6d3c88f20a4e7a6dc3f0baa0e3ce06f
#![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))] #![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))] #![deny(warnings)] extern crate abstract_ns; extern crate bytes; extern crate conduit_proxy_controller_grpc; extern crate convert; extern crate domain; extern crate env_logger; #[ma...
#![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))] #![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))] #![deny(warnings)] extern crate abstract_ns; extern crate bytes; extern crate conduit_proxy_controller_grpc; extern crate convert; extern crate domain; extern crate env_logger; #[ma...
; let telemetry = telemetry .make_control(&taps, &executor) .expect("bad news in telemetry town"); let metrics_server = telemetry .serve_metrics(metrics_listener); let client = control_...
serve_control( control_listener, new_service, &executor, )
call_expression
[ { "content": "pub fn init() -> Result<Config, config::Error> {\n\n logging::init();\n\n let config_strings = Env;\n\n Config::try_from(&config_strings)\n\n}\n", "file_path": "proxy/src/app.rs", "rank": 0, "score": 325351.4238073231 }, { "content": "/// Construct the Prometheus metri...
Rust
src/parser/mod.rs
jvcmarcenes/rover
991ac82de002198d1e324bb19e828ea7a3e0ea23
pub mod expression; pub mod statement; use std::{iter::Peekable, vec::IntoIter}; use crate::{lexer::token::{Token, TokenType::{self, *}, Symbol}, utils::{result::{Result, ErrorList, append}, wrap::Wrap}, ast::{Block, module::Module}}; #[derive(Debug, Clone)] pub struct Parser { tokens: Peekable<IntoIter<Token>>, ...
pub mod expression; pub mod statement; use std::{iter::Peekable, vec::IntoIter}; use crate::{lexer::token::{Token, TokenType::{self, *}, Symbol}, utils::{result::{Result, ErrorList, append}, wrap::Wrap}, ast::{Block, module::Module}}; #[derive(Debug, Clone)] pub struct Parser { tokens: Peekable<IntoIter<Token>>, ...
fn expect_any_or_sync(&mut self, expected: &[TokenType]) -> Result<Token> { match self.next() { token if expected.contains(&token.typ) => token.wrap(), token => { self.synchronize(); let expected_str = expected.iter().map(|typ| typ.to_string()).reduce(|a, b| format!("{}, {}", a, b)).expect("Cannot e...
ng()).reduce(|a, b| format!("{}, {}", a, b)).expect("Cannot expect no tokens"); ErrorList::comp(format!("Expected any of ({}), found {}", expected_str, token.typ), token.pos).err() } } }
function_block-function_prefixed
[ { "content": "fn bin_operation_for_token(token: &Token) -> BinaryOperator {\n\n\tmatch token.typ {\n\n\t\tSymbol(Plus) => Add,\n\n\t\tSymbol(Minus) => Sub,\n\n\t\tSymbol(Star) => Mul,\n\n\t\tSymbol(Slash) => Div,\n\n\t\tKeyword(Mod) => Rem,\n\n\t\tSymbol(OpenAng) => Lst,\n\n\t\tSymbol(OpenAngEquals) => Lse,\n\n...
Rust
openrr-plugin/tests/test.rs
mertcookimg/openrr
4bdb49d483383e912b37907c6f651b52f2b7a742
use std::{ sync::Arc, time::{Duration, SystemTime}, }; use arci::{ gamepad::GamepadEvent, BaseVelocity, DummyGamepad, DummyJointTrajectoryClient, DummyLocalization, DummyMoveBase, DummyNavigation, DummySpeaker, DummyTransformResolver, Gamepad, Isometry2, JointTrajectoryClient, Localization, MoveBas...
use std::{ sync::Arc, time::{Duration, SystemTime}, }; use arci::{ gamepad::GamepadEvent, BaseVelocity, DummyGamepad, DummyJointTrajectoryClient, DummyLocalization, DummyMoveBase, DummyNavigation, DummySpeaker, DummyTransformResolver, Gamepad, Isometry2, JointTrajectoryClient, Localization, MoveBas...
( GamepadEvent::AxisChanged(expected_axis, expected_val), GamepadEvent::AxisChanged(actual_axis, actual_val), ) => { assert_eq!(*expected_axis, actual_axis); assert_approx_eq!(*expected_val, actual_val); } (G...
peakerProxy, TransformResolverProxy, }; #[tokio::test] async fn joint_trajectory_client() { let client = Arc::new(DummyJointTrajectoryClient::new(vec![ "a".to_owned(), "b".to_owned(), ])); let proxy = JointTrajectoryClientProxy::new(client.clone()); assert_eq!(proxy.joint_names(), vec!...
random
[ { "content": "fn to_pose_msg(pose: &Isometry2<f64>) -> msg::Pose {\n\n let q = UnitQuaternion::from_axis_angle(&Vector3::z_axis(), pose.rotation.angle());\n\n msg::Pose {\n\n position: msg::Point {\n\n x: pose.translation.x,\n\n y: pose.translation.y,\n\n z: 0.0,\n\...