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/kernel/graphics/gop/writer.rs
xiuxiu62/vonnegut
473666f0f25ee5e71dd790d2af786d51e0201682
use super::{ buffer::{Buffer, Color, ColorCode}, Direction, Position, }; use alloc::{ fmt::{self, Write}, string::{String, ToString}, vec::Vec, }; use bootloader::boot_info::{FrameBuffer, Optional}; use font8x8::UnicodeFonts; use spin::Mutex; static TEXT_WRITER: Mutex<Option<TextWriter>> = Mutex::n...
use super::{ buffer::{Buffer, Color, ColorCode}, Direction, Position, }; use alloc::{ fmt::{self, Write}, string::{String, ToString}, vec::Vec, }; use bootloader::boot_info::{FrameBuffer, Optional}; use font8x8::UnicodeFonts; use spin::Mutex; static TEXT_WRITER: Mutex<Option<TextWriter>> = Mutex::n...
fn decrement_y(&mut self) { match self.position { Position { x: _, y: 0 } => (), Position { x: _, y } => self.position = Position::new(self.dimensions.x, y - 1), } } } impl Write for TextWriter<'_> { fn write_str(&mut self, s: &str) -> fmt::Result { self.wr...
fn increment_y(&mut self) { match self.position { Position { x: _, y } if y == self.dimensions.y => self.shift(), Position { x: _, y } => self.position = Position::new(0, y + 1), } }
function_block-full_function
[ { "content": "fn kernel_init(boot_info: &'static mut BootInfo) -> Result<(), String> {\n\n serial_println!(\"test\");\n\n lib_sorrow::gdt::init();\n\n lib_sorrow::interrupts::idt_init();\n\n lib_sorrow::interrupts::pics_init();\n\n // lib_sorrow::interrupts::enable();\n\n\n\n // Initialize pag...
Rust
src/day19/mod.rs
sheredom/AOC2020
324fc01d428a297f4a7273b058dbc3af69bad07b
use itertools::Itertools; fn matches<'a>(rules: &[Rule], input: &'a str, next: usize) -> Vec<&'a str> { let lambda = |vec: &Vec<usize>| -> Vec<&str> { let mut work = Vec::new(); work.push(input); for next in vec { let mut next_work = Vec::new(); for input in work {...
use itertools::Itertools; fn matches<'a>(rules: &[Rule], input: &'a str, next: usize) -> Vec<&'a str> { let lambda = |vec: &Vec<usize>| -> Vec<&str> { let mut work = Vec::new(); work.push(input); for next in vec { let mut next_work = Vec::new(); for input in work {...
p()) .collect(); rules[id] = Rule::Next(next); } } let inputs: Vec<_> = string .lines() .skip_while(|line| !line.is_empty()) .skip(1) .collect(); day19_part01(&rules, &inputs); day19_part02(rules, &inputs); }
function_block-function_prefixed
[ { "content": "fn count_total_bags(id: usize, vec: &[Vec<(usize, usize)>]) -> usize {\n\n vec[id].iter().fold(1, |acc, sub_id| {\n\n acc + sub_id.0 * count_total_bags(sub_id.1, &vec)\n\n })\n\n}\n\n\n", "file_path": "src/day07/mod.rs", "rank": 3, "score": 213383.08027052184 }, { ...
Rust
inve-block/cipher/aes/src/ni/aes128.rs
invarianee/inve-crypt
a36c6befe0899a5e0ec6f77bad6447f0fbe1974e
use super::{arch::*, utils::*}; use crate::{Block, Block8}; use cipher::inout::InOut; use core::mem; pub(super) type RoundKeys = [__m128i; 11]; #[inline] #[target_feature(enable = "aes")] pub(super) unsafe fn encrypt1(keys: &RoundKeys, block: InOut<'_, '_, Block>) { let (in_ptr, out_ptr) = block.into_raw(); l...
use super::{arch::*, utils::*}; use crate::{Block, Block8}; use cipher::inout::InOut; use core::mem; pub(super) type RoundKeys = [__m128i; 11]; #[inline] #[target_feature(enable = "aes")] pub(super) unsafe fn encrypt1(keys: &RoundKeys, block: InOut<'_, '_, Block>) { let (in_ptr, out_ptr) = block.into_raw(); l...
#[inline] #[target_feature(enable = "aes")] pub(super) unsafe fn inv_expanded_keys(keys: &RoundKeys) -> RoundKeys { [ keys[0], _mm_aesimc_si128(keys[1]), _mm_aesimc_si128(keys[2]), _mm_aesimc_si128(keys[3]), _mm_aesimc_si128(keys[4]), _mm_aesimc_si128(keys[5]), ...
expand_round!(keys, 2, 0x02); expand_round!(keys, 3, 0x04); expand_round!(keys, 4, 0x08); expand_round!(keys, 5, 0x10); expand_round!(keys, 6, 0x20); expand_round!(keys, 7, 0x40); expand_round!(keys, 8, 0x80); expand_round!(keys, 9, 0x1B); expand_round!(keys, 10, 0x36); keys }
function_block-function_prefix_line
[ { "content": "pub fn cipher_round_par(blocks: &mut Block8, round_keys: &Block8) {\n\n if_intrinsics_available! {\n\n intrinsics::cipher_round_par(blocks, round_keys)\n\n }\n\n\n\n soft::cipher_round_par(blocks, round_keys);\n\n}\n\n\n", "file_path": "inve-block/cipher/aes/src/hazmat.rs", ...
Rust
src/array.rs
alisomay/libpd-rs
d3853ca464017109d528f15287c179baff6ec7a6
use crate::{ error::{ArrayError, SizeError}, C_STRING_FAILURE, }; use std::ffi::CString; pub fn array_size<T: AsRef<str>>(name: T) -> Result<i32, SizeError> { unsafe { let name = CString::new(name.as_ref()).expect(C_STRING_FAILURE); let result = libpd_sys::libpd_arraysize(name.as_...
use crate::{ error::{ArrayError, SizeError}, C_STRING_FAILURE, }; use std::ffi::CString; pub fn array_size<T: AsRef<str>>(name: T) -> Result<i32, SizeError> { unsafe { let name = CString::new(name.as_ref()).expect(C_STRING_FAILURE); let result = libpd_sys::libpd_arraysize(name.as_...
match libpd_sys::libpd_read_array_double( destination.as_mut_ptr(), name.as_ptr(), source_read_offset, source_read_amount, ) { 0 => Ok(()), _ => Err(ArrayError::FailedToFindArray), } } } pub fn write_double_array_to<T...
if source_read_offset + source_read_amount > array_size(source_name.as_ref()).map_err(|_| ArrayError::FailedToFindArray)? as i32 || source_read_amount < 0 { return Err(ArrayError::OutOfBounds); }
if_condition
[ { "content": "/// Start composition of a new list or typed message of up to max **element** length\n\n///\n\n/// Messages can be of a smaller length as max length is only an upper bound.\n\n/// No cleanup is required for unfinished messages.\n\n/// Returns error if the length is too large.\n\n///\n\n/// # Examp...
Rust
src/infer.rs
raviqqe/subtyped-hm-type-inference
5537748704b5b516f8960faa18639d6b31c2800d
use crate::ast::*; use crate::types::{Type, TypeScheme}; use std::collections::{HashMap, HashSet}; #[derive(Debug)] pub struct InferenceError; pub fn infer_type_scheme(expression: &Expression) -> Result<TypeScheme, InferenceError> { let (_, type_) = infer(&Default::default(), expression)?; Ok(TypeScheme(type...
use crate::ast::*; use crate::types::{Type, TypeScheme}; use std::collections::{HashMap, HashSet}; #[derive(Debug)] pub struct InferenceError; pub fn infer_type_scheme(expression: &Expression) -> Result<TypeScheme, InferenceError> { let (_, type_) = infer(&Default::default(), expression)?; Ok(TypeScheme(type...
Err(InferenceError), }) } fn calculate_free_variables_in_environment( environment: &HashMap<String, TypeScheme>, ) -> HashSet<usize> { let mut variables = HashSet::new(); for type_scheme in environment.values() { variables.extend(type_scheme.free_variables()); } variables }
let function_type = Type::Function(argument_type.into(), result_type.into()).substitute(&substitutions); (substitutions, function_type) } Expression::Let(variable, bound_expression, expression) => { let mut environment = environment.clone(); ...
random
[ { "content": "pub fn let_(\n\n variable: impl Into<String>,\n\n bound_expression: impl Into<Arc<Expression>>,\n\n expression: impl Into<Arc<Expression>>,\n\n) -> Expression {\n\n Expression::Let(variable.into(), bound_expression.into(), expression.into())\n\n}\n\n\n", "file_path": "src/ast.rs", ...
Rust
qiniu-rust/src/storage/uploader/upload_manager.rs
qbox/rust-sdk
5c83599de99e79884b8f08c530e10137216ac253
use super::{ super::{ bucket::Bucket, region::Region, uploader::{UploadPolicy, UploadToken, UploadTokenParseError}, }, BatchUploader, BucketUploaderBuilder, FileUploaderBuilder, }; use crate::{config::Config, credential::Credential, utils::ron::Ron}; use assert_impl::assert_impl; u...
use super::{ super::{ bucket::Bucket, region::Region, uploader::{UploadPolicy, UploadToken, UploadTokenParseError}, }, BatchUploader, BucketUploaderBuilder, FileUploaderBuilder, }; use crate::{config::Config, credential::Credential, utils::ron::Ron}; use assert_impl::assert_impl; u...
pub fn batch_for_upload_policy<'u>( &self, upload_policy: UploadPolicy<'u>, credential: Cow<'u, Credential>, ) -> CreateUploaderResult<BatchUploader> { self.batch_for_upload_token(UploadToken::new(upload_policy, credential)) } pub(crate) fn config(&self) -> &Confi...
if let Some(bucket_name) = policy.bucket() { Ok(BatchUploader::new( &self.for_bucket_name(bucket_name.to_owned(), access_key).build(), upload_token.to_string(), )) } else { Err(CreateUploaderError::BucketIsMissingInUploadToken) } }
function_block-function_prefix_line
[ { "content": " # 查询七牛服务器,根据存储空间名称获取区域列表\n\n #\n\n # @param [String] access_key 七牛 Access Key\n\n # @param [String] bucket_name 存储空间名称\n\n # @param [Config] config 客户端配置\n\n # @return [Array<Region>] 区域列表,区域列表中第一个区域是当前存储空间所在区域,之后的区域则是备用区域\n\n # @raise [ArgumentError] config 参数错...
Rust
bpf-memprof-common/src/client.rs
mambisi/tezedge-debugger
4c98bae5ccd02587d35cbacb2396a60107de93d2
use std::{ io::{self, Write}, fmt, os::unix::net::UnixStream, path::Path, }; use passfd::FdPassingExt; use ebpf_user::RingBufferRegistry; use serde::{Serialize, ser, Deserialize, de}; use super::{event::{Pod, Hex32, Hex64, CommonHeader}, STACK_MAX_DEPTH}; use super::event::{ KFree, KMAlloc, KMAllo...
use std::{ io::{self, Write}, fmt, os::unix::net::UnixStream, path::Path, }; use passfd::FdPassingExt; use ebpf_user::RingBufferRegistry; use serde::{Serialize, ser, Deserialize, de}; use super::{event::{Pod, Hex32, Hex64, CommonHeader}, STACK_MAX_DEPTH}; use super::event::{ KFree, KMAlloc, KMAllo...
k_or(0)?), PageAlloc::SIZE) }, x if Some(x) == PageFree::DISCRIMINANT => { (EventKind::PageFree(PageFree::from_slice(slice).ok_or(0)?), PageFree::SIZE) }, x if Some(x) == PageFreeBatched::DISCRIMINANT => { (EventKind::PageFreeBatched(PageFr...
} } impl<'de> Deserialize<'de> for Hex32 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { use self::de::Error; let s = String::deserialize(deserializer)?; u32::from_str_radix(&s, 16) .map_err(|e| Error::custom(...
random
[ { "content": "#[inline(always)]\n\npub fn dyn_sized<K>(id: EventId, tag: DataTag, data: &[u8], rb: &mut RingBuffer)\n\nwhere\n\n K: Bit,\n\n{\n\n // data len 124 happens often, let's have special case 148 = 124 + sizeof DataDescriptor\n\n let length_to_send = data.len() + mem::size_of::<DataDescriptor>...
Rust
src/witness_rep/quick_simulation.rs
kianfay/TSG-event-system
68dde517474652c51abe5abfa7a6b8ae4107e084
use crate::witness_rep::{ iota_did::create_and_upload_did::{create_n_dids, Key, RunMode}, implementation::{generate_contract, generate_sigs}, implementation::{ interaction::{LazyMethod}, quick_interaction::quick_interaction, user_and_organization::{ UserIdentity, Organiza...
use crate::witness_rep::{ iota_did::create_and_upload_did::{create_n_dids, Key, RunMode}, implementation::{generate_contract, generate_sigs}, implementation::{ interaction::{LazyMethod}, quick_interaction::quick_interaction, user_and_organization::{ UserIdentity, Organiza...
s.push(id); let part_entry = format!("{}: {}\n", part_did_pk, sc.reliability[i]); output.push_str(&part_entry); } let file_name = format!("{}/start_reliability.txt", &folder_name); fs::write(file_name, output).expect("Unable to write file"); if print { println!("Gene...
: Identity<Author<Client>, IdInfo> = Identity{ channel_client: on, id_info: IdInfo { seed: None, did_key: sec, reliability: None, org_cert: generate_sigs::generate_org_cert(pubkey, &repeat_kp, DEFAULT_DURATION)? }, ...
function_block-random_span
[ { "content": "/// BEWARE, this function assumes that an organization uses its own OrgCert\n\npub fn get_index_org_with_pubkey(organizations: &Vec<OrganizationIdentity>, pk: &str) -> usize {\n\n let orgs: Vec<usize> = organizations\n\n .iter()\n\n .enumerate()\n\n .filter(|(_,o)| o.identi...
Rust
src/model_checking/dfa.rs
tmrob2/motap2
9520206d4366417e8e12189cc9681539bc7c744f
use itertools::Itertools; use std::collections::{HashSet}; use super::mdp2; use mdp2::*; #[derive(Debug, Clone)] pub struct DFATransitions<'a> { pub q: u32, pub w: Vec<&'a HashSet<&'a str>>, pub q_prime: u32 } #[derive(Debug)] pub struct DFA<'a> { pub states: Vec<u32>, pub initial: u32, pub d...
use itertools::Itertools; use std::collections::{HashSet}; use super::mdp2; use mdp2::*; #[derive(Debug, Clone)] pub struct DFATransitions<'a> { pub q: u32, pub w: Vec<&'a HashSet<&'a str>>, pub q_prime: u32 } #[derive(Debug)] pub struct DFA<'a> { pub states: Vec<u32>, pub initial: u32, pub d...
#[allow(dead_code)] pub fn reachable_from_initial<'a>(initial: &'a DFAModelCheckingPair, states: &'a [DFAModelCheckingPair], transitions: &'a [DFAProductTransition]) -> Vec<bool> { let mut stack: Vec<&'a DFAModelCheckingPair> = Vec::new(); let mut visited: Vec<bool> = vec![false; states.len()]; stack.push...
pub fn create_reachable_states_with_labels<'a, 'b>(init_state: DFAModelCheckingPair, states: &'b [DFAModelCheckingPair], reachable_state_truth: &'b [bool], dfa: &'a DFA, hini: &'a HashSet<&'a str>, hcom: &'a HashSet<&'a str>, hsuc: &'a HashSet<&'a str>...
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\nfn valid_transition(h: &&HashSet<&str>, mdp_sprime: u32, states: &[LocalProdState],\n\n cross_prod_dfa_trans: &[CrossProdTransition], trans_ix: &[usize], task: i32) -> Vec<(i32, u32,usize)> {\n\n let mut qprime_v: HashSet<(i32, u32, usize)> = HashSet::n...
Rust
src/elems_executable.rs
ryuichiueda/bash_r
b4737681eae147e8a78120d78c4a31ba79b571fa
use nix::unistd::{execvpe, fork, ForkResult, Pid}; use nix::sys::wait::*; use std::ffi::CString; use std::process::exit; use std::env; use crate::{ShellCore,Feeder,CommandPart}; use crate::utils::blue_string; use crate::elems_in_command::{Arg, Substitution}; pub trait Executable { fn eval(&self, _conf: &mut Sh...
use nix::unistd::{execvpe, fork, ForkResult, Pid}; use nix::sys::wait::*; use std::ffi::CString; use std::process::exit; use std::env; use crate::{ShellCore,Feeder,CommandPart}; use crate::utils::blue_string; use crate::elems_in_command::{Arg, Substitution}; pub trait Executable { fn eval(&self, _conf: &mut Sh...
; } }
match waitpid(child, None) .expect("Faild to wait child process.") { WaitStatus::Exited(pid, status) => { if status != 0 { println!("Pid: {:?}, Exit with {:?}", pid, status); }; } WaitStatus::Signaled(pid, signal, _) => ...
if_condition
[ { "content": "pub fn end_of_command(text: &mut Feeder) -> Option<Eoc> {\n\n if text.len() == 0 {\n\n return None;\n\n };\n\n\n\n let pos = scanner_end_of_com(text, 0);\n\n if pos == 0 {\n\n return None;\n\n };\n\n\n\n Some(Eoc{text: text.consume(pos), debug: DebugInfo::init(&text...
Rust
leetcode/src/d12/_1298_maximum_candies_you_can_get_from_boxes.rs
RobWalt/rustgym
b4dc47cb36d59c157095563857b0ac5ca62c68b3
struct Solution; use std::collections::HashSet; use std::collections::VecDeque; impl Solution { fn max_candies( mut status: Vec<i32>, candies: Vec<i32>, keys: Vec<Vec<i32>>, contained_boxes: Vec<Vec<i32>>, initial_boxes: Vec<i32>, ) -> i32 { let mut opened_boxes...
struct Solution; use std::collections::HashSet; use std::collections::VecDeque; impl Solution { fn max_candies( mut status: Vec<i32>, candies: Vec<i32>, keys: Vec<Vec<i32>>, contained_boxes: Vec<Vec<i32>>, initial_boxes: Vec<i32>, ) -> i32 { let mut opened_boxes...
Solution::max_candies(status, candies, keys, contained_boxes, initial_boxes), res ); let status = vec![1, 0, 0, 0, 0, 0]; let candies = vec![1, 1, 1, 1, 1, 1]; let keys = vec_vec_i32![[1, 2, 3, 4, 5], [], [], [], [], []]; let contained_boxes = vec_vec_i32![[1, 2, 3, 4, 5], [], [], [], [], []...
function_block-function_prefix_line
[]
Rust
src/model/deep_links.rs
kilati/stremio-core-web
0fce2aab23316707b2ba89b7d6459fdc5ac0195c
use flate2::write::ZlibEncoder; use flate2::Compression; use itertools::Itertools; use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC}; use serde::Serialize; use std::borrow::Borrow; use std::io; use std::io::Write; use stremio_core::models::installed_addons_with_filters::InstalledAddonsRequest; use...
use flate2::write::ZlibEncoder; use flate2::Compression; use itertools::Itertools; use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC}; use serde::Serialize; use std::borrow::Borrow; use std::io; use std::io::Write; use stremio_core::models::installed_addons_with_filters::InstalledAddonsRequest; use...
} impl From<(&Stream, &ResourceRequest, &ResourceRequest)> for StreamDeepLinks { fn from( (stream, stream_request, meta_request): (&Stream, &ResourceRequest, &ResourceRequest), ) -> Self { StreamDeepLinks { player: format!( "#/player/{}/{}/{}/{}/{}/{}", ...
fn from(stream: &Stream) -> Self { StreamDeepLinks { player: format!( "#/player/{}", utf8_percent_encode( &base64::encode(gz_encode(serde_json::to_string(stream).unwrap()).unwrap()), URI_COMPONENT_ENCODE_SET ), ...
function_block-full_function
[]
Rust
src/main.rs
eggerk/audio_tools
60f23583c2156c954a78678bbdd9854076713c11
use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use failure::{bail, format_err, Error}; use log::info; use simplelog::*; mod interface; mod notification; mod volume; mod volume_control; use crate::interface::Interface; fn get_data_file_path() -> Result<PathBuf,...
use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use failure::{bail, format_err, Error}; use log::info; use simplelog::*; mod interface; mod notification; mod volume; mod volume_control; use crate::interface::Interface; fn get_data_file_path() -> Result<PathBuf,...
_all(format!("{};{}", volume_id, sink_id).as_bytes())?; Ok(()) } #[derive(PartialEq)] enum CommandType { NextInput, VolumeLower, VolumeRaise, VolumeToggleMute, VolumeNotification, } fn parse_args() -> Result<CommandType, Error> { let args: Vec<String> = env::args().collect(); if args....
match get_data_file_path() { Err(_) => { println!("Unknown path to load from!"); return Ok((None, None)); } Ok(p) => p, }; let mut s = String::new(); match File::open(&path) { Err(_) => println!("Could not open file at {:?}!", path), Ok(mut fi...
random
[ { "content": "fn get_current_audio_outputs() -> Result<Vec<Interface>, Error> {\n\n let sinks_list = process::Command::new(\"pacmd\")\n\n .args(&[\"list-sinks\"])\n\n .output()?;\n\n let sinks_output = str::from_utf8(&sinks_list.stdout)?;\n\n\n\n let mut all_interfaces = Vec::new();\n\n ...
Rust
src/raft/bootstrap.rs
oleggator/tarantool-module
d23045cc4dd741341b8d8c883751a09905a20aaa
use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, HashSet, VecDeque}; use std::net::SocketAddr; use crate::error::Error; use super::rpc; pub struct BoostrapController { state: Cell<BootstrapState>, local_id: u64, peers: RefCell<BTreeMap<u64, Vec<SocketAddr>>>, responded_ids: RefCell<Ha...
use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, HashSet, VecDeque}; use std::net::SocketAddr; use crate::error::Error; use super::rpc; pub struct BoostrapController { state: Cell<BootstrapState>, local_id: u64, peers: RefCell<BTreeMap<u64, Vec<SocketAddr>>>, responded_ids: RefCell<Ha...
#[inline] fn broadcast(&self, addrs: impl Iterator<Item = Vec<SocketAddr>>) { for peer_addrs in addrs { self.send_request(peer_addrs.clone()); } } #[inline] fn send_request(&self, to: Vec<SocketAddr>) { let nodes = self .peers .borrow() ...
if !responded_ids.contains(&req.from_id) { let new_nodes = self.merge_nodes_list(&req.nodes); let new_nodes = new_nodes.iter().map(|(_, addrs)| addrs.clone()); self.broadcast(new_nodes); responded_ids.insert(req.from_id); } }
function_block-function_prefix_line
[ { "content": "pub fn encode_ping(stream: &mut impl Write, sync: u64) -> Result<(), Error> {\n\n encode_header(stream, sync, IProtoType::Ping)?;\n\n rmp::encode::write_map_len(stream, 0)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/net_box/protocol.rs", "rank": 0, "score": 250597.86438483972 ...
Rust
kayak_core/src/context_ref.rs
TheRawMeatball/kayak_ui
137c421a3dcc9223676b52ecf283c0d49d4822ba
use std::path::PathBuf; use crate::{Binding, Changeable, Index, KayakContext, WidgetTree}; pub struct KayakContextRef<'a> { pub(crate) context: &'a mut KayakContext, current_id: Option<Index>, tree: Option<WidgetTree>, } impl<'a> KayakContextRef<'a> { pub fn new(context: &'a mut KayakContext, current...
use std::path::PathBuf; use crate::{Binding, Changeable, Index, KayakContext, WidgetTree}; pub struct KayakContextRef<'a> { pub(crate) context: &'a mut KayakContext, current_id: Option<Index>, tree: Option<WidgetTree>, } impl<'a> KayakContextRef<'a> { pub fn new(context: &'a mut KayakContext, current...
pub fn create_state<T: resources::Resource + Clone + PartialEq>( &mut self, initial_state: T, ) -> Option<crate::Binding<T>> { self.context .create_state(self.current_id.unwrap_or_default(), initial_state) } ...
pub fn create_consumer<T: resources::Resource + Clone + PartialEq>( &mut self, ) -> Option<Binding<T>> { self.context .create_consumer(self.current_id.unwrap_or_default()) }
function_block-function_prefix_line
[ { "content": "///\n\n/// Trait implemented by something that is bound to a value\n\n///\n\n// Seperate Trait to allow Bound to be made into an object for BindRef\n\npub trait WithBound<Value>: Changeable + Send + Sync {\n\n ///\n\n /// Mutate instead of replacing value stored in this binding, return true\...
Rust
src/lib.rs
TimLucca/game-of-life
6f354e12968b702d19d0e930c8ceb8932c99c492
mod utils; extern crate js_sys; extern crate fixedbitset; extern crate web_sys; use wasm_bindgen::prelude::*; use fixedbitset::FixedBitSet; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] extern { fn alert(s: &str); } #[wasm_bindge...
mod utils; extern crate js_sys; extern crate fixedbitset; extern crate web_sys; use wasm_bindgen::prelude::*; use fixedbitset::FixedBitSet; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] extern { fn alert(s: &str); } #[wasm_bindge...
} let neighbor_row = (row + delta_row) % self.height; let neighbor_col = (column + delta_col) % self.width; let index = self.get_index(neighbor_row, neighbor_col); count += self.cells[index] as u8; } } count ...
elf.width - 1, 0, 1].iter().cloned() { if delta_row == 0 && delta_col == 0 { continue;
random
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
conjure-runtime/src/client.rs
palantir/conjure-rust-runtime
2a37ba33b0b504d4dc779dc66b8bfffe6a8a0026
use crate::raw::{BuildRawClient, DefaultRawClient, RawBody, Service}; use crate::service::gzip::{DecodedBody, GzipLayer}; use crate::service::http_error::HttpErrorLayer; use crate::service::map_error::MapErrorLayer; use crate::service::metrics::MetricsLayer; use crate::service::node::{NodeMetricsLayer, NodeSelectorLa...
use crate::raw::{BuildRawClient, DefaultRawClient, RawBody, Service}; use crate::service::gzip::{DecodedBody, GzipLayer}; use crate::service::http_error::HttpErrorLayer; use crate::service::map_error::MapErrorLayer; use crate::service::metrics::MetricsLayer; use crate::service::node::{NodeMetricsLayer, NodeSelectorLa...
} #[async_trait] impl<T, B> AsyncClient for Client<T> where T: Service<http::Request<RawBody>, Response = http::Response<B>> + 'static + Sync + Send, T::Error: Into<Box<dyn error::Error + Sync + Send>>, T::Future: Send, B: http_body::Body<Data = Bytes> + 'static + Send, B::Error: Into<Box<dyn erro...
pub(crate) fn new( state: Arc<ArcSwap<ClientState<T>>>, subscription: Option<Subscription<ServiceConfig, Error>>, ) -> Client<T> { Client { state, subscription: subscription.map(Arc::new), } }
function_block-full_function
[ { "content": "struct State<T> {\n\n current_pin: AtomicUsize,\n\n nodes: T,\n\n}\n\n\n\n/// A node selector layer which pins to a host until a request either fails with a 5xx error or IO error, after which\n\n/// it rotates to the next.\n\npub struct PinUntilErrorNodeSelectorLayer<T> {\n\n state: Arc<S...
Rust
src/discovery.rs
BastianZim/cargo-bundle-licenses
8cbe06eea0dddf400f0fc239af1cf95db0f489b2
use std::{collections::HashMap, fs, path::PathBuf}; use cargo_metadata::Package; use regex::Regex; use slug::slugify; use thiserror::Error; use crate::license::License; const HIGH_CONFIDENCE_LIMIT: f32 = 0.10; const LOW_CONFIDENCE_LIMIT: f32 = 0.15; #[derive(Debug, Error)] pub enum DiscoveryError { #[error(tran...
use std::{collections::HashMap, fs, path::PathBuf}; use cargo_metadata::Package; use regex::Regex; use slug::slugify; use thiserror::Error; use crate::license::License; const HIGH_CONFIDENCE_LIMIT: f32 = 0.10; const LOW_CONFIDENCE_LIMIT: f32 = 0.15; #[derive(Debug, Error)] pub enum DiscoveryError { #[error(tran...
fn check_against_template(text: &str, license: &License) -> Confidence { let text_freq = calculate_frequency(text); let template_freq = if let License::Multiple(ref licenses) = *license { let mut template_freq = HashMap::new(); for license in licenses { if let Some(template) = lic...
2>) -> u32 { let mut errors = 0; for (word, &count) in template_freq { let text_count = text_freq.remove(word).unwrap_or(0); let diff = ((text_count as i32) - (count as i32)).abs() as u32; errors += diff; } for (_, count) in text_freq { errors += count; } error...
function_block-function_prefixed
[ { "content": "/// Choose the highest confidence license of all possible licenses.\n\nfn choose(texts: Vec<LicenseText>) -> (BestChoice, Confidence) {\n\n // Partition licnese texts by confidense\n\n let (mut confident, texts): (Vec<LicenseText>, Vec<LicenseText>) = texts\n\n .into_iter()\n\n ...
Rust
tools/mkinitrd/src/main.rs
neri/uefi-pg
7ce0848a3cf98bc5650c93c3aff70de63d8d8e84
use byteorder::*; use std::{ cell::UnsafeCell, env, fs::{read_dir, File}, io::Read, io::Write, path::Path, process, }; fn usage() -> ! { let mut args = env::args_os(); let arg = args.next().unwrap(); let path = Path::new(&arg); let lpc = path.file_name().unwrap(); epri...
use byteorder::*; use std::{ cell::UnsafeCell, env, fs::{read_dir, File}, io::Read, io::Write, path::Path, process, }; fn usage() -> ! { let mut args = env::args_os(); let arg = args.next().unwrap(); let path = Path::new(&arg); let lpc = path.file_name().unwrap(); epri...
} #[derive(Debug)] pub enum VirtualDiskError { OutOfBounds, IoError, }
pub fn flush(self, os: &mut dyn Write) -> Result<(), VirtualDiskError> { let blob = unsafe { &*self.vec.get() }; let mut dir = Vec::with_capacity(self.dir.len()); for dir_ent in &self.dir { dir.extend_from_slice(dir_ent.as_bytes()); } const HEADER_SIZE: usize = 16; ...
function_block-full_function
[ { "content": "#[inline]\n\n#[must_use]\n\npub fn os_open(name: &str, options: usize) -> isize {\n\n unsafe { syscall!(Open, name.as_ptr(), name.len(), options) as isize }\n\n}\n\n\n", "file_path": "lib/megstd/src/sys/wasm/syscall.rs", "rank": 0, "score": 435741.6378745078 }, { "content": ...
Rust
src/interpreter/errors.rs
psFried/pgen
008a4c680cd3651da5442780076523df1e8df86e
use crate::IString; use failure::Error; use crate::AnyFunction; use crate::FunctionPrototype; use itertools::Itertools; use std::fmt::{self, Display}; use std::sync::Arc; use crate::interpreter::ast::{GenType, Span}; use crate::interpreter::Source; #[derive(Debug, Clone, PartialEq)] pub struct SourceRef { pub sour...
use crate::IString; use failure::Error; use crate::AnyFunction; use crate::FunctionPrototype; use itertools::Itertools; use std::fmt::{self, Display}; use std::sync::Arc; use crate::interpreter::ast::{GenType, Span}; use crate::interpreter::Source; #[derive(Debug, Clone, PartialEq)] pub struct SourceRef { pub sour...
} #[test] fn parse_err_is_displayed_correctly() { let source = r##" foo bar baz "##; let location_offset = 17; assert_eq!("r", &source[location_offset..(location_offset + 1)]); { let subject = SourceErrRegion {source, location_offset}; let rendered = format!("{}", su...
err_location; for character in source[err_location..].chars() { if character == '\n' || character == '\r' { break; } line_end += character.len_utf8(); } let rendered = &source[line_start..line_end]; let offset_location = err_location -...
function_block-function_prefixed
[ { "content": "fn filter_matching_arguments<'a, I: Iterator<Item = &'a FunctionPrototype>>(name: IString, arguments: &[AnyFunction], iter: I, caller_source_ref: &SourceRef) -> Result<&'a FunctionPrototype, CompileError> {\n\n let mut first_from_same_module: Option<&'a FunctionPrototype> = None;\n\n let mut...
Rust
src/main.rs
cwaldren/muncher
8d41276563b3ec91fc1d9b3e6a85cbb39f4b9441
extern crate chrono; extern crate clap; extern crate humantime; use chrono::format::ParseError; use clap::App; use std::cmp::Ordering; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let default_duration = chrono::Duration::seconds(10); let usage = format!( ...
extern crate chrono; extern crate clap; extern crate humantime; use chrono::format::ParseError; use clap::App; use std::cmp::Ordering; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let default_duration = chrono::Duration::seconds(10); let usage = format!( ...
tats: &HashMap<i64, u64>) { let max = stats.keys().max().unwrap(); let line = "-".repeat(*max as usize + 1); println!("{}", line); } fn render_row(row: u64, stats: &HashMap<i64, u64>, height: u64) { let icon = "|"; let max = stats.keys().max().unwrap(); let line: String = (0..=*max) .m...
default"); println!("Hint: you may use values like '10s' or '3h'"); None } } } fn app_run(interval: chrono::Duration, path: &str) -> std::io::Result<()> { let input = File::open(path)?; let buffered = BufReader::new(input); let mut buckets: HashMap<i64, u64> = HashMap::...
random
[]
Rust
cargo/vendor/backtrace-0.3.4/src/symbolize/gimli.rs
mfarrugi/cargo-raze-example-stdx
e4283e299d298cea9a534d0623cb4f3b54ef36f5
use addr2line; use findshlibs::{self, Segment, SharedLibrary}; use std::cell::RefCell; use std::env; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use std::u32; use SymbolName; const MAPPINGS_CACHE_SIZE: usize = 4; thread_local! { static MAPPINGS_CACH...
use addr2line; use findshlibs::{self, Segment, SharedLibrary}; use std::cell::RefCell; use std::env; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use std::u32; use SymbolName; const MAPPINGS_CACHE_SIZE: usize = 4; thread_local! { static MAPPINGS_CACH...
pub fn name(&self) -> Option<SymbolName> { self.name.as_ref().map(|s| SymbolName::new(s.as_bytes())) } pub fn addr(&self) -> Option<*mut c_void> { Some(self.addr as *mut c_void) } pub fn filename(&self) -> Option<&Path> { Some(self.file.as_ref()) } pub fn lineno(...
fn new(addr: usize, file: PathBuf, line: Option<u64>, name: Option<String>) -> Symbol { Symbol { addr, file, line, name, } }
function_block-full_function
[ { "content": "fn main() {\n\n env_logger::init().unwrap();\n\n\n\n info!(\"All is well.\"); \n\n}\n", "file_path": "example/example.rs", "rank": 0, "score": 15112.634085037585 }, { "content": "fn main() {\n\n use std::io::Read;\n\n\n\n let mut resp = reqwest::get(\"https://www.ru...
Rust
liblumen_codegen/src/llvm.rs
xtian/lumen
20a3095697ce05c860f825ae573fa4e70e740026
#![allow(dead_code)] mod enums; mod memory_buffer; mod target; use std::ffi::CString; use std::sync::{Once, ONCE_INIT}; use llvm_sys::core::*; use llvm_sys::prelude::*; use llvm_sys::target::*; use llvm_sys::*; use codemap_diagnostic::{ColorConfig, Diagnostic, Emitter, Level}; use super::CodeGenError; pub use sel...
#![allow(dead_code)] mod enums; mod memory_buffer; mod target; use std::ffi::CString; use std::sync::{Once, ONCE_INIT}; use llvm_sys::core::*; use llvm_sys::prelude::*; use llvm_sys::target::*; use llvm_sys::*; use codemap_diagnostic::{ColorConfig, Diagnostic, Emitter, Level}; use super::CodeGenError; pub use sel...
(&self, id: &str) -> Block { Block::new(unsafe { LLVMAppendBasicBlock(self.fun, c_str!(id)) }) } pub fn num_blocks(&self) -> u32 { let n = unsafe { LLVMCountBasicBlocks(self.fun) }; n as u32 } pub fn entry_block(&self) -> Block { Block::new(unsafe { LLVMGetEntryBasicBlo...
level(severity: LLVMDiagnosticSeverity) -> Level { match severity { LLVMDiagnosticSeverity::LLVMDSError => Level::Error, LLVMDiagnosticSeverity::LLVMDSWarning => Level::Warning, LLVMDiagnosticSeverity::LLVMDSRemark => Level::Help, LLVMDiagnosticSeverity::LLVMDSNote => Level::Note, ...
random
[ { "content": "pub fn initialize() {\n\n llvm::initialize();\n\n}\n\n\n", "file_path": "lumen/src/compiler/codegen/mod.rs", "rank": 1, "score": 322369.2255717075 }, { "content": "pub fn set_code(code: Code) {\n\n *RW_LOCK_CODE.write() = code;\n\n}\n\n\n", "file_path": "lumen_runtime...
Rust
src/syntax/surf/parse.rs
ice1000/voile-rs
71def16def25b12eb58296c7b1632c9a02f6a6a5
use pest_derive::Parser; use voile_util::level::Level; use voile_util::loc::{Ident, Loc}; use voile_util::pest_util::{end_of_rule, strict_parse}; use voile_util::tags::{Plicit, VarRec}; use voile_util::vec1::Vec1; use crate::syntax::surf::LabExpr; use super::ast::Param; use super::{Decl, DeclKind, Expr}; #[derive(P...
use pest_derive::Parser; use voile_util::level::Level; use voile_util::loc::{Ident, Loc}; use voile_util::pest_util::{end_of_rule, strict_parse}; use voile_util::tags::{Plicit, VarRec}; use voile_util::vec1::Vec1; use crate::syntax::surf::LabExpr; use super::ast::Param; use super::{Decl, DeclKind, Expr}; #[derive(P...
ody, rest) } fn lambda(rules: Tok) -> Expr { let loc = Loc::from(rules.as_span()); let (params, ret) = lambda_internal(rules); let ret = ret.unwrap(); Expr::lam(loc, params, ret) } fn type_keyword(rules: Tok) -> Expr { let loc = Loc::from(rules.as_span()); let mut inner: Tik = rules.into_inner...
r { let (params, ret) = sig_expr_internal(rules); let ret = ret.unwrap(); if params.is_empty() { ret } else { Expr::sig(params, ret) } } fn case_expr(rules: Tok) -> Expr { let mut inner: Tik = rules.into_inner(); let label = next_ident(&mut inner); let binding = next_ide...
random
[ { "content": "#[inline]\n\npub fn end_of_rule<Rule: RuleType>(inner: &mut Pairs<Rule>) {\n\n debug_assert_eq!(inner.next(), None);\n\n}\n\n\n\nimpl<'a> From<Span<'a>> for Loc {\n\n fn from(span: Span) -> Self {\n\n Loc {\n\n line: span.start_pos().line_col().0,\n\n start: span...
Rust
orchestrator/gorc/src/config.rs
CeruleanAtMonaco/gravity-bridge
6c4fce8dd1655ed7b3431476b587657cc0f48cd3
use aws_sdk_secretsmanager::client::Client; use cosmos_gravity::crypto::DEFAULT_HD_PATH; use serde::{Deserialize, Serialize}; use signatory::FsKeyStore; use std::io; use std::net::SocketAddr; use std::path::Path; #[derive(Clone, Debug, Deserialize, Serialize)] pub enum Keystore { File(String), Aws, } impl Def...
use aws_sdk_secretsmanager::client::Client; use cosmos_gravity::crypto::DEFAULT_HD_PATH; use serde::{Deserialize, Serialize}; use signatory::FsKeyStore; use std::io; use std::net::SocketAddr; use std::path::Path; #[derive(Clone, Debug, Deserialize, Serialize)] pub enum Keystore { File(String), Aws, } impl Def...
} else { Err(e) } } impl Keystore { pub fn load(&self, name: &signatory::KeyName) -> signatory::Result<pkcs8::PrivateKeyDocument> { match self { Keystore::File(path) => { let keystore = Path::new(path); let keystore = FsKeyStore::create_or_o...
Ok(signatory::KeyInfo { name: signatory::KeyName::new(name).map_err(|_| e)?, algorithm: None, encrypted: false, })
call_expression
[ { "content": "pub fn get_chain_id() -> String {\n\n \"gravity-test\".to_string()\n\n}\n\n\n", "file_path": "orchestrator/test_runner/src/main.rs", "rank": 0, "score": 214987.59554924347 }, { "content": "pub fn get_test_token_name() -> String {\n\n \"footoken\".to_string()\n\n}\n\n\n", ...
Rust
src/lib.rs
filalex77/moe
88a8c1edbd697ddebc436bd74e07422ea1723c7a
#[deny(missing_docs)] extern crate base64; extern crate reqwest; extern crate serde; extern crate snafu; use serde::Serialize; use snafu::{ResultExt, Snafu}; pub mod types; pub use types::Doc; use types::{Me, SearchRequest, SearchResponse}; pub struct Client { pub base_uri: String, pub token: Opt...
#[deny(missing_docs)] extern crate base64; extern crate reqwest; extern crate serde; extern crate snafu; use serde::Serialize; use snafu::{ResultExt, Snafu}; pub mod types; pub use types::Doc; use types::{Me, SearchRequest, SearchResponse}; pub struct Client { pub base_uri: String, pub token: Opt...
: reqwest::Error }, JsonFailed { source: reqwest::Error }, ResponseEmpty { source: reqwest::Error }, ImageEmpty, InvalidToken, ImageTooLarge, RateLimit { message: String }, InternalServerError, } pub type Result<T, E = Error> = std::result::Result<T, E>;
Result<Me> { self.request(reqwest::Method::GET, "me", "")? .json() .context(JsonFailed) } fn request<T>(&self, method: reqwest::Method, path: &str, body: &T) -> Result<reqwest::Response> where T: Serialize + ?Sized, { let url = format!("{}/{}", self.base_...
random
[ { "content": "type MalID = u32;\n\n\n\n/// The body of a search request.\n\n#[derive(Serialize)]\n\npub struct SearchRequest {\n\n /// The Base64-encoded image.\n\n pub image: String,\n\n /// An optional AniList ID to filter on.\n\n pub filter: Option<AnilistID>,\n\n}\n\n\n\nimpl SearchRequest {\n\n...
Rust
src/lib.rs
samcrow/rust-x-plane-plugin
780dc752de22c40694565f46769190a4a59328fa
pub struct PluginInfo<'a, 'b, 'c> { pub name: &'a str, pub signature: &'b str, pub description: &'c str, } pub trait Plugin : Sized { fn start() -> Option<Self>; fn enable(&mut self); fn disable(&mut self); fn info<'a, 'b, 'c>(&self) -> PluginInfo<...
pub struct PluginInfo<'a, 'b, 'c> { pub name: &'a str, pub signature: &'b str, pub description: &'c str, } pub trait Plugin : Sized { fn start() -> Option<Self>; fn enable(&mut self); fn disable(&mut self); fn info<'a, 'b, 'c>(&self) -> PluginInfo<...
let plugin_option = PluginType::start(); match plugin_option { Some(plugin) => { PLUGIN = Box::into_raw(Box::new(plugin)); let info = (*PLUGIN).info(); match ffi::CString::new(info.name).ok()...
a, 'b, 'c>; fn stop(&mut self); } #[macro_export] macro_rules! xplane_plugin { ($plugin_type: ty) => ( extern crate libc; use std::ptr; use std::ffi; type PluginType = $plugin_type; type PluginPtr = *mut PluginType; static mut PLUGIN: PluginPtr = 0...
random
[ { "content": "\n\n# X-Plane plugin macro for Rust\n\n\n\n## Purpose\n\n\n\nThis library provides a macro for easy creation of plugins for X-Plane.\n\n\n\nWith this library and the [xplm](https://crates.io/crates/xplm)\n\ncrate, X-Plane plugins can be easily developed in Rust.\n\n\n\n## Use\n\n\n\nTo import the ...
Rust
src/lib/core/src/net/work/worker.rs
workanator/wrustlr
0e38becaae2bd2af6059616ebe2b13bf50933ef1
use std::io::Write; use std::sync::Arc; use std::sync::atomic::Ordering; use std::thread; use wrust_async::crossbeam::sync::chase_lev::Steal; use wrust_io::mio::{TryRead, TryWrite, EventSet}; use wrust_types::{Result, Error}; use wrust_types::net::Protocol; use wrust_types::net::connection::State; use wrust_module::s...
use std::io::Write; use std::sync::Arc; use std::sync::atomic::Ordering; use std::thread; use wrust_async::crossbeam::sync::chase_lev::Steal; use wrust_io::mio::{TryRead, TryWrite, EventSet}; use wrust_types::{Result, Error}; use wrust_types::net::Protocol; use wrust_types::net::connection::State; use wrust_module::s...
fn try_write_buf(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> { client.then_on_socket(|sock| -> Result<Option<usize>> { match sock { &mut Protocol::Tcp(ref mut stream) => match stream.try_write(buf) { Ok(count) => Ok(count), Err(msg) => Error::new("Cannot write to client socke...
fn try_read_buf(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> { client.then_on_socket(|sock| -> Result<Option<usize>> { match sock { &mut Protocol::Tcp(ref mut stream) => match stream.try_read_buf(buf) { Ok(count) => Ok(count), Err(msg) => Error::new("Cannot read from client socke...
function_block-full_function
[]
Rust
crates/wasm-encoder/src/component/instances.rs
cfallin/wasm-tools
fcb052fd9a05686d54ff085942edbf6a2735e406
use crate::{encode_section, ComponentExport, ComponentSection, ComponentSectionId, Encode}; #[derive(Debug, Clone)] pub enum ModuleArg { Instance(u32), } impl Encode for ModuleArg { fn encode(&self, sink: &mut Vec<u8>) { match self { Self::Instance(index) => { sink.pus...
use crate::{encode_section, ComponentExport, ComponentSection, ComponentSectionId, Encode}; #[derive(Debug, Clone)] pub enum ModuleArg { Instance(u32), } impl Encode for ModuleArg { fn encode(&self, sink: &mut Vec<u8>) { match self { Self::Instance(index) => { sink.pus...
sink.push(kind); index.encode(sink); } } #[derive(Clone, Debug, Default)] pub struct InstanceSection { bytes: Vec<u8>, num_added: u32, } impl InstanceSection { pub fn new() -> Self { Self::default() } pub fn len(&self) -> u32 { self.num_added } ...
let (kind, index) = match self { Self::Module(index) => (0x00, *index), Self::Component(index) => (0x01, *index), Self::Instance(index) => (0x02, *index), Self::Function(index) => (0x03, *index), Self::Value(index) => (0x04, *index), Self::Type(ind...
assignment_statement
[ { "content": "fn encode_section(sink: &mut Vec<u8>, id: impl Into<u8>, count: u32, bytes: &[u8]) {\n\n sink.push(id.into());\n\n (encoding_size(count) + bytes.len()).encode(sink);\n\n count.encode(sink);\n\n sink.extend(bytes);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #...
Rust
src/schema/virtual_machines/resources/compute/mod.rs
rafawo/hcsrs
c8d70a431eed24ccc53b4119975cc11fc8972d6a
use crate::schema::utils::is_default; use serde::{Deserialize, Serialize}; #[cfg(feature = "19h1")] impl std::default::Default for MemoryBackingPageSize { fn default() -> Self { MemoryBackingPageSize::Small } } #[cfg(feature = "19h1")] #[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] pub e...
use crate::schema::utils::is_default; use serde::{Deserialize, Serialize}; #[cfg(feature = "19h1")] impl std::default::Default for MemoryBackingPageSize { fn default() -> Self { MemoryBackingPageSize::Small } } #[cfg(feature = "19h1")] #[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] pub e...
le_perfmon_pmu: bool, #[cfg(feature = "19h1")] #[serde( default, rename = "EnablePerfmonPebs", skip_serializing_if = "is_default" )] pub enable_perfmon_pebs: bool, #[cfg(feature = "19h1")] #[serde( default, rename = "EnablePerfmonLbr", skip_seria...
lt")] pub enable_cold_hint: bool, #[cfg(feature = "19h1")] #[serde( default, rename = "EnableColdDiscardHint", skip_serializing_if = "is_default" )] pub enable_cold_discard_hint: bool, #[serde( default, rename = "EnableDeferredCommit", ...
random
[ { "content": "pub fn is_default<T>(obj: &T) -> bool\n\nwhere\n\n T: std::default::Default + std::cmp::PartialEq,\n\n{\n\n *obj == T::default()\n\n}\n\n\n", "file_path": "src/schema/utils/mod.rs", "rank": 0, "score": 177541.1192185915 }, { "content": "/// Reads guest primary memory (RAM...
Rust
src/state/hierarchy.rs
adamnemecek/tuix
e79db9f4b38bce17c51d01f6112130bca1d0e181
use crate::entity::Entity; #[derive(Clone)] pub struct Hierarchy { pub entities: Vec<Entity>, pub parent: Vec<Option<Entity>>, pub first_child: Vec<Option<Entity>>, pub next_sibling: Vec<Option<Entity>>, pub prev_sibling: Vec<Option<Entity>>, } impl Hierarchy { pub fn new() -> Hierarchy { ...
use crate::entity::Entity; #[derive(Clone)] pub struct Hierarchy { pub entities: Vec<Entity>, pub parent: Vec<Option<Entity>>, pub first_child: Vec<Option<Entity>>, pub next_sibling: Vec<Option<Entity>>, pub prev_sibling: Vec<Option<Entity>>, } impl Hierarchy { pub fn new() -> Hierarchy { ...
} self.current_node = None; } } return r; } } pub struct ParentIterator<'a> { hierarchy: &'a Hierarchy, current: Option<Entity>, } impl<'a> Iterator for ParentIterator<'a> { type Item = Entity; fn next(&mut self) -> Option<Entity> { ...
if let Some(sibling) = self.hierarchy.next_sibling[temp.unwrap().index()] { self.current_node = Some(sibling); return r; } else { temp = self.hierarchy.parent[temp.unwrap().index()]; }
if_condition
[ { "content": "pub fn apply_styles(state: &mut State, hierarchy: &Hierarchy) {\n\n\n\n // Loop through all entities\n\n for entity in hierarchy.into_iter() {\n\n\n\n if entity == Entity::new(0, 0) {\n\n continue;\n\n }\n\n\n\n // Possible point to ad Cascading\n\n\n\n ...
Rust
src/hikapi/event_type.rs
CornerBit/HikSink
07f5e5757ce58d2484c6657020772a4d874a38e7
use std::{fmt, str::FromStr}; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Hash, Clone)] pub struct EventIdentifier { pub channel: Option<String>, pub event_type: EventType, } impl EventIdentifier { pub fn new(channel: Option<String>, event_type: EventType) ...
use std::{fmt, str::FromStr}; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Hash, Clone)] pub struct EventIdentifier { pub channel: Option<String>, pub event_type: EventType, } impl EventIdentifier { pub fn new(channel: Option<String>, event_type: EventType) ...
tType::BadVideo => "BadVideo".to_string(), EventType::StorageDetection => "StorageDetection".to_string(), EventType::RecordingFailure => "RecordingFailure".to_string(), EventType::DiskFull => "DiskFull".to_string(), EventType::DiskError => "DiskError".to_string(), ...
ntType::DiskError, "nicbroken" => EventType::NicBroken, "ipconflict" => EventType::IpConflict, "illaccess" => EventType::IllegalAccess, _ => { if s.chars().all(|c| c.is_ascii_alphanumeric()) { EventType::Unknown(s.to_st...
random
[ { "content": "pub fn load_config(data: impl figment::Provider) -> Result<Config, String> {\n\n let mut cfg: Config = Figment::new()\n\n .merge(figment::providers::Env::prefixed(\"HIKSINK_\"))\n\n .merge(data)\n\n .extract()\n\n .map_err(|e| e.to_string())?;\n\n\n\n // Generate ...
Rust
src/skylink.rs
SkynetLabs/skynet-substrate
ad7304e13e96f02643dce0f3f1b64c378ad023e5
use crate::crypto::hash_all; use crate::encoding::{ decode_hex_to_bytes, decode_skylink_base64, encode_prefixed_bytes, encode_skylink_base64, }; use crate::util::{str_to_bytes, trim_prefix, URI_SKYNET_PREFIX}; use bytes::{BufMut, BytesMut}; use sp_std::vec::Vec; pub const BASE64_ENCODED_SKYLINK_SIZE: usize = 46; ...
use crate::crypto::hash_all; use crate::encoding::{ decode_hex_to_bytes, decode_skylink_base64, encode_prefixed_bytes, encode_skylink_base64, }; use crate::util::{str_to_bytes, trim_prefix, URI_SKYNET_PREFIX}; use bytes::{BufMut, BytesMut}; use sp_std::vec::Vec; pub const BASE64_ENCODED_SKYLINK_SIZE: usize = 46; ...
#[test] fn should_create_v2_skylinks_correctly() { const PUBLIC_KEY: &str = "a1790331b8b41a94644d01a7b482564e7049047812364bcabc32d399ad23f7e2"; const DATA_KEY: &str = "d321b3c31337047493c9b5a99675e9bdaea44218a31aad2fd7738209e7a5aca1"; const EXPECTED_SKYLINK: &str = "AQB7zHVDtD...
fn should_return_correct_specifier() { const SPECIFIER: &str = "testing"; const EXPECTED: &[u8] = &[116, 101, 115, 116, 105, 110, 103, 0, 0, 0, 0, 0, 0, 0, 0, 0]; assert_eq!(new_specifier(SPECIFIER), EXPECTED); }
function_block-full_function
[ { "content": "/// Decodes the encoded base64 skylink to raw bytes.\n\npub fn decode_skylink_base64(skylink: &str) -> Vec<u8> {\n\n let skylink_bytes = str_to_bytes(skylink);\n\n let mut buf = Vec::new();\n\n // Make sure we'll have a slice big enough.\n\n buf.resize(RAW_SKYLINK_SIZE, 0);\n\n\n\n ...
Rust
src/main.rs
jac3km4/try-redscript
ee10e50beebe6f958dd7ec6ddbee82a6d79eeb60
use std::cell::RefCell; use std::path::PathBuf; use std::rc::Rc; use redscript::ast::Span; use redscript_compiler::error::Error; use redscript_compiler::source_map::Files; use redscript_compiler::unit::CompilationUnit; use redscript_vm::{args, native, VM}; use wasm_bindgen::prelude::*; use yew::html::Scope; use yew::p...
use std::cell::RefCell; use std::path::PathBuf; use std::rc::Rc; use redscript::ast::Span; use redscript_compiler::error::Error; use redscript_compiler::source_map::Files; use redscript_compiler::unit::CompilationUnit; use redscript_vm::{args, native, VM}; use wasm_bindgen::prelude::*; use yew::html::Scope; use yew::p...
fn rendered(&mut self, _ctx: &Context<Self>, first_render: bool) { if first_render { let editor = edit("editor"); editor.set_theme("ace/theme/tomorrow_night"); editor.get_session().set_mode("ace/mode/swift"); self.editor = Some(editor); } } } #[...
e> <code> { if self.output.is_empty() { "No output" } else { &self.output } } </code> </pre> </div> </div> </div> </div> } }
function_block-function_prefixed
[ { "content": "# Try REDscript\n\nSource code of https://try-redscript.surge.sh.\n\n\n\nThis website bundles the redscript [compiler](https://github.com/jac3km4/redscript) and [virtual machine](https://github.com/jac3km4/redscript-vm) in a WebAssembly module which makes it possible to run snippets of code direct...
Rust
rust/tools/authorization-logic/src/souffle/souffle_emitter.rs
somerongit/raksha
83ee5253f1e278d33620fd171bd2eef15b8e4b62
/* * Copyright 2021 The Raksha Authors * * 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 agr...
/* * Copyright 2021 The Raksha Authors * * 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 agr...
AstPredicate { name: p.name.clone(), args: (0..p.args.len()) .map(|i| String::from("x") + &i.to_string()) .collect(), } } fn emit_pred(&mut self, p: &AstPredicate) -> String { let decl = SouffleEmitter::pred_to_declaration(p); ...
ND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::{ast::*, souffle::datalog_ir::*}; use std::collections::HashSet; pub struct SouffleEmitter { decls: HashSet<AstPredicate>, } impl SouffleEmitter { ...
random
[ { "content": "namespace raksha::utils {\n\n\n\n// See overloaded_test.cc for an example usage. \n\ntemplate<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };\n\n\n\n// Allows using in-place lambas for the different types of a variant when\n\n// visiting a std::variant type. This won't be ne...
Rust
radish/src/compiler/scope.rs
accusatorySteve/radish-lang
3b2d087c44c52c7df154386cc5341fe4c8ee7e1f
use crate::common::span::Span; use crate::compiler::ast::{FunctionDecl, ClassDecl}; use std::{collections::HashMap, fmt}; #[derive(Debug, PartialEq, Copy, Clone, Eq, Hash)] pub enum SymbolKind { Var, Fun { arg_count: usize }, Class, Con, } #[derive(Debug, PartialEq, Clone)] pub struct Symbol(pub Symbo...
use crate::common::span::Span; use crate::compiler::ast::{FunctionDecl, ClassDecl}; use std::{collections::HashMap, fmt}; #[derive(Debug, PartialEq, Copy, Clone, Eq, Hash)] pub enum SymbolKind { Var, Fun { arg_count: usize }, Class, Con, } #[derive(Debug, PartialEq, Clone)] pub struct Symbol(pub Symbo...
pub fn extend(&mut self, other: ScopeMap) { self.locals.extend(other.locals); self.non_locals.extend(other.non_locals); } pub fn add_local(&mut self, key: &str, value: Symbol) -> Option<Symbol> { self.locals.insert(key.to_string(), value) } pub fn add_non_local(&mut self,...
pub fn with_depth(depth: usize) -> Self { ScopeMap { locals: HashMap::new(), non_locals: HashMap::new(), depth, } }
function_block-full_function
[ { "content": "fn walk_class_decl(visitor: &mut Visitor, class: &mut ClassDecl) -> VisitorResult {\n\n Ok(())\n\n}\n\n\n", "file_path": "radish/src/compiler/visitor.rs", "rank": 0, "score": 165827.64352403118 }, { "content": "pub fn resolve_symbols(ast: &mut AST) -> Result<(), SyntaxError>...
Rust
waros/botengine/src/runtime.rs
georobGWJ/rust_flavoured_wasm
3f5982ca1fd5a63dab7a48edc047ff34fa63172e
use crate::game::{ readlock, scanner::ScannerSystem, writelock }; use crate::{ Error, Kind }; use nalgebra::Point2; use std::sync::Arc; use wasmi::{ Error as InterpreterError, Externals, FuncInstance, FuncRef, ModuleImportResolver, RuntimeArgs, RuntimeValue, Signature, Trap, ValueType, }; pub struct RuntimeM...
use crate::game::{ readlock, scanner::ScannerSystem, writelock }; use crate::{ Error, Kind }; use nalgebra::Point2; use std::sync::Arc; use wasmi::{ Error as InterpreterError, Externals, FuncInstance, FuncRef, ModuleImportResolver, RuntimeArgs, RuntimeValue, Signature, Trap, ValueType, }; pub struct RuntimeM...
fn sqrt(&mut self, number: i32) -> WasmRuntimeResult { let val = (number as f32).sqrt(); Ok(Some(RuntimeValue::from(val as i32))) } fn sin(&mut self, degree: i32) -> WasmRuntimeResult { Ok(Some(RuntimeValue::from(ScannerSystem::to_user_heading( (degree as f32)...
and::Rng; let mut rng = rand::thread_rng(); let n: i32 = rng.gen_range(0, limit); Ok(Some(RuntimeValue::from(n))) }
function_block-function_prefixed
[]
Rust
src/type_checker.rs
markhakansson/simple-rustc
50c59d620f646c678c8600e67f9e65ee165abd08
use crate::ast::*; use crate::context::*; use crate::parser::*; pub type TypeRes<T> = Result<T, TypeErr>; #[derive(Debug, Clone, PartialEq, Eq)] pub struct TypeErr(pub String); fn tc_expr( expr: Expr, fn_list: &mut Functions, fn_context: &mut ContextStack<Type>, ) -> TypeRes<Type> { match expr.clone(...
use crate::ast::*; use crate::context::*; use crate::parser::*; pub type TypeRes<T> = Result<T, TypeErr>; #[derive(Debug, Clone, PartialEq, Eq)] pub struct TypeErr(pub String); fn tc_expr
t)?; if var_type == val_type { match op { Op::RelOp(_) => return Ok(Type::Bool), _ => (), }; Ok(var_type) } else { Err(TypeErr(format!( "when changing the variable to ´{} {} {}´ -> expected type {{{}}}, found type {{{}}}", String::...
( expr: Expr, fn_list: &mut Functions, fn_context: &mut ContextStack<Type>, ) -> TypeRes<Type> { match expr.clone() { Expr::Num(_) => Ok(Type::Int32), Expr::Bool(_) => Ok(Type::Bool), Expr::Var(s) => fn_context.get_last_context()?.get_val(&s), Expr::BinOp(l, op, r) => tc_...
random
[ { "content": "pub fn eval_fn_call(\n\n fn_call: FunctionCall,\n\n fn_tree: &mut Functions,\n\n fn_context: &mut FnContext,\n\n) -> EvalRes<Value> {\n\n println!(\"{:#?}\", fn_context);\n\n // Get the argument values.\n\n let mut arg_values: Vec<Value> = Vec::new();\n\n for arg in fn_call.ar...
Rust
src/cli/doc_remove.rs
steveyen/couchbase-shell
694ac73c9970f622e99854a438a2a5d0c1688797
use crate::state::State; use couchbase::RemoveOptions; use crate::cli::util::{collection_from_args, run_interruptable}; use async_trait::async_trait; use futures::stream::StreamExt; use futures::FutureExt; use nu_cli::{CommandArgs, OutputStream}; use nu_errors::ShellError; use nu_protocol::{MaybeOwned, Signature, Sy...
use crate::state::State; use couchbase::RemoveOptions; use crate::cli::util::{collection_from_args, run_interruptable}; use async_trait::async_trait; use futures::stream::StreamExt; use futures::FutureExt; use nu_cli::{CommandArgs, OutputStream}; use nu_errors::ShellError; use nu_protocol::{MaybeOwned, Signature, Sy...
fn usage(&self) -> &str { "Removes a document through the data service" } async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { run_get(self.state.clone(), args).await } } async fn run_get(state: Arc<State>, args: CommandArgs) -> Result<OutputStream, ShellError...
fn signature(&self) -> Signature { Signature::build("doc remove") .optional("id", SyntaxShape::String, "the document id") .named( "id-column", SyntaxShape::String, "the name of the id column if used with an input stream", No...
function_block-full_function
[ { "content": "pub fn in_directory(str: impl AsRef<Path>) -> String {\n\n let path = str.as_ref();\n\n let path = if path.is_relative() {\n\n root().join(path)\n\n } else {\n\n path.to_path_buf()\n\n };\n\n\n\n path.display().to_string()\n\n}\n", "file_path": "tests/common/fs.rs"...
Rust
src/usbctrl_regs/usb_muxing.rs
Szpadel/rp2040-pac
4006f1937b8f57c4b4d6543bfd7aa7158a640fb0
#[doc = "Reader of register USB_MUXING"] pub type R = crate::R<u32, super::USB_MUXING>; #[doc = "Writer for register USB_MUXING"] pub type W = crate::W<u32, super::USB_MUXING>; #[doc = "Register USB_MUXING `reset()`'s with value 0"] impl crate::ResetValue for super::USB_MUXING { type Type = u32; #[inline(always...
#[doc = "Reader of register USB_MUXING"] pub type R = crate::R<u32, super::USB_MUXING>; #[doc = "Writer for register USB_MUXING"] pub type W = crate::W<u32, super::USB_MUXING>; #[doc = "Register USB_MUXING `reset()`'s with value 0"] impl crate::ResetValue for super::USB_MUXING { type Type = u32; #[inline(always...
) != 0) } #[doc = "Bit 1"] #[inline(always)] pub fn to_extphy(&self) -> TO_EXTPHY_R { TO_EXTPHY_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0"] #[inline(always)] pub fn to_phy(&self) -> TO_PHY_R { TO_PHY_R::new((self.bits & 0x01) != 0) } } impl W { #[doc...
self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
tests/test.rs
cypherlink/rckad
2c0de40ceb947d6242114104f27faad14fc0a83c
#[cfg(test)] mod tests { use rckad::KadTree; #[test] fn it_works() { let mut kad = KadTree::new(0, "0"); kad.add(2, "b"); kad.add(3, "c"); kad.add(4, "e"); assert_eq!(Some((&2, &"b", true)), kad.search(&2)); assert_eq!(true, kad.contains(&2)); asser...
#[cfg(test)] mod tests { use rckad::KadTree; #[test] fn it_works() { let mut kad = KadTree::new(0, "0"); kad.add(2, "b"); kad.add(3, "c"); kad.add(4, "e"); assert_eq!(Some((&2, &"b", true)), kad.search(&2)); assert_eq!(true, kad.contains(&2)); asser...
lake3::hash(&postcard::to_allocvec(&15).unwrap()) ); println!( "16 {:?}", blake3::hash(&postcard::to_allocvec(&16).unwrap()) ); println!( "17 {:?}", blake3::hash(&postcard::to_allocvec(&17).unwrap()) ); println!( ...
_allocvec(&4).unwrap())); println!("5 {:?}", blake3::hash(&postcard::to_allocvec(&5).unwrap())); println!("6 {:?}", blake3::hash(&postcard::to_allocvec(&6).unwrap())); println!("7 {:?}", blake3::hash(&postcard::to_allocvec(&7).unwrap())); println!("8 {:?}", blake3::hash(&postcard::to_all...
function_block-random_span
[ { "content": "//! # rckad\n\n//! Efficient and flexible S/Kademlia implementation.\n\n//!\n\n//! ```\n\n//! use rckad::KadTree;\n\n//!\n\n//! fn main() {\n\n//! let mut kad = KadTree::new(0, \"0\");\n\n//! kad.add(2, \"b\");\n\n//! kad.add(3, \"c\");\n\n//! kad.add(4, \"e\");\n\n//!\n\n//! a...
Rust
src/file.rs
avbhandaru/csvql
4c5d726f802537e53d4dcae03d0333af433f5112
use crate::table; use crate::types; use io::BufRead; use regex; use std::io::Write; use std::{fs, io, path}; #[derive(Debug)] pub struct Error { pub path: path::PathBuf, pub message: String, } impl Error { fn new(path: String, message: String) -> Self { Self { path: path::Path::new(path.as_str()).to_...
use crate::table; use crate::types; use io::BufRead; use regex; use std::io::Write; use std::{fs, io, path}; #[derive(Debug)] pub struct Error { pub path: path::PathBuf, pub message: String, } impl Error { fn new(path: String, message: String) -> Self { Self { path: path::Path::new(path.as_str()).to_...
pub fn export_json(path: &path::Path, table: &table::Table) -> Result<(), Error> { todo!(); Ok(()) } fn read_first_line(path: &path::Path) -> Result<String, Error> { match fs::File::open(path) { Ok(file) => { let mut buffer = String::new(); io::BufReader::new(file) .read_line(&mut...
e)| format!("{}({})", &col_name, &col_type.to_uppercase())) .collect::<Vec<String>>() .join(","); let rows = table .rows .clone() .into_iter() .map(|row| row.join(",")) .collect::<Vec<String>>() .join("\n"); write_file(path, format!("{}\n{}\n", header, rows)) }
function_block-function_prefixed
[ { "content": "fn copy_into_query(table_path: &str, name: &str, header: &table::Header) -> String {\n\n let header = header\n\n .into_iter()\n\n .map(|(col_name, _)| col_name.as_str())\n\n .collect::<Vec<_>>()\n\n .join(\",\");\n\n let query = format!(\n\n \"COPY {} ({}) FROM '{}' DELIMITER ',' ...
Rust
src/feed.rs
DarremMolko/rssfilter
72bda21d656fa79411b9128ec3636ba9f13d41f4
use failure::Fail; use reqwest::{header, Client}; use rss::Channel; use std::convert::TryFrom; use std::error::Error; use std::io::Read; #[derive(Fail, Debug)] #[fail(display = "Error loading feed: {}.", _0)] struct FeedError(String); #[derive(Serialize, Clone)] pub struct FeedItem { pub title: String, pub da...
use failure::Fail; use reqwest::{header, Client}; use rss::Channel; use std::convert::TryFrom; use std::error::Error; use std::io::Read; #[derive(Fail, Debug)] #[fail(display = "Error loading feed: {}.", _0)] struct FeedError(String); #[derive(Serialize, Clone)] pub struct FeedItem { pub title: String, pub da...
} pub enum Feed { RSS(Box<rss::Channel>), Atom(Box<atom_syndication::Feed>), } impl Feed { pub fn from_url(url: &str) -> Result<Feed, Box<dyn Error>> { let client = Client::new(); let mut content = Vec::new(); client .get(url) .header(header::USER_AGENT, "...
let date = rss_item.pub_date().unwrap_or_default().to_string(); let dc_contributors: Vec<String> = match rss_item.dublin_core_ext() { Some(dublin_core_ext) => dublin_core_ext.contributors().iter().cloned().collect(), _ => vec![], }; let dc_creators: Vec<String> = match ...
function_block-function_prefix_line
[]
Rust
src/project.rs
naftulikay/nfty
899adae247aff6c35870b293948808541ee2c444
pub mod parse; pub mod templates; mod hooks; #[cfg(test)] mod test; use dirs::home_dir; use lazy_static::lazy_static; use regex::Regex; use std::fmt; use std::io; use std::path::PathBuf; use git2::build::RepoBuilder; use git2::Cred; use git2::FetchOptions; use git2::Progress; use git2::RemoteCallbacks; use git2:...
pub mod parse; pub mod templates; mod hooks; #[cfg(test)] mod test; use dirs::home_dir; use lazy_static::lazy_static; use regex::Regex; use std::fmt; use std::io; use std::path::PathBuf; use git2::build::RepoBuilder; use git2::Cred; use git2::FetchOptions; use git2::Progress; use git2::RemoteCallbacks; use git2:...
, }) } else { Err(io::Error::new(io::ErrorKind::InvalidData, ERR_PROJECT_NAME)) } } pub fn protocol(&self) -> &Protocol { &self.protocol } pub fn host(&self) -> &str { &self.host } pub fn user(&self) -> &str { ...
Some( captures .name("user") .map_or(DEFAULT_USER, |m| m.as_str()) .to_string(), )
call_expression
[ { "content": "/// Clean and reformat project name.\n\n///\n\n/// Converts periods to dashes and strips prefixes of either `ansible-role-` or `docker-`.\n\nfn tmux_session_name(repo_name: &str) -> String {\n\n match repo_name.to_string().replace(\".\", \"-\") {\n\n ref s if s.starts_with(\"ansible-role...
Rust
src/lib.rs
dtolnay/rustflags
8ae73eed07c266a355b2d57ce8e8187b8d8c1126
#![doc(html_root_url = "https://docs.rs/rustflags/0.1.0")] #![allow( clippy::cast_lossless, clippy::derive_partial_eq_without_eq, clippy::doc_markdown, clippy::items_after_statements, clippy::must_use_candidate, clippy::too_many_lines, clippy::type_complexity, clippy::unnecessary_wraps...
#![doc(html_root_url = "https://docs.rs/rustflags/0.1.0")] #![allow( clippy::cast_lossless, clippy::derive_partial_eq_without_eq, clippy::doc_markdown, clippy::items_after_statements, clippy::must_use_candidate, clippy::too_many_lines, clippy::type_complexity, clippy::unnecessary_wraps...
CrateType::Staticlib => "staticlib", CrateType::ProcMacro => "proc-macro", }) } } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum Emit { Asm, LlvmBc, LlvmIr, Obj, Metadata, Link, DepInfo, M...
Z(String), ErrorFormat(ErrorFormat), Json(String), Color(Color), RemapPathPrefix { from: PathBuf, to: PathBuf }, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum LibraryKind { Dependenc...
random
[ { "content": "#[track_caller]\n\nfn test(encoded: &str, expected: &[Flag]) {\n\n let mut iterator = RustFlags {\n\n encoded: encoded.to_owned(),\n\n pos: 0,\n\n repeat: None,\n\n short: false,\n\n };\n\n\n\n let mut flags = Vec::new();\n\n for expected in expected {\n\n ...
Rust
src/frontend/js.rs
bbmsoft/frost
c86c19e62dab336719aa8d77c385e985da7eb740
use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "/js/location.js")] extern "C" { #[wasm_bindgen(catch)] fn is_geolocation_supported_js() -> Result<bool, JsValue>; #[wasm_bindgen(catch)] fn get_location_js( on_success: &Closure<dyn Fn(f32, f32)>, on_error: &Closure<dyn Fn(u16, Stri...
use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "/js/location.js")] extern "C" { #[wasm_bindgen(catch)] fn is_geolocation_supported_js() -> Result<bool, JsValue>; #[wasm_bindgen(catch)] fn get_location_js( on_success: &Closure<dyn Fn(f32, f32)>, on_error: &Closure<dyn Fn(u16, Stri...
) -> bool { unsafe { are_notifications_supported_js().unwrap_or(false) } } #[allow(unused_unsafe)] pub fn request_notification_permission(on_result: &Closure<dyn Fn(JsValue)>) { unsafe { if let Err(e) = request_notification_permission_js(on_result) { error!("Error getting location: {:?}", e...
, e); } } } #[allow(unused_unsafe)] pub fn is_geolocation_supported() -> bool { unsafe { is_geolocation_supported_js().unwrap_or(false) } } #[allow(unused_unsafe)] pub fn are_notifications_supported(
random
[ { "content": "#[wasm_bindgen(start)]\n\npub fn main_js() -> Result<(), JsValue> {\n\n #[cfg(debug_assertions)]\n\n console_error_panic_hook::set_once();\n\n wasm_logger::init(wasm_logger::Config::default());\n\n\n\n info!(\"WASM successfully loaded!\");\n\n\n\n let geolocation_supported = js::is_...
Rust
pac/atsame54p/src/sercom0/i2cs/ctrlb.rs
theatrus/atsamd
8c4035668064609ff1561e32e17e92165cb70187
#[doc = "Reader of register CTRLB"] pub type R = crate::R<u32, super::CTRLB>; #[doc = "Writer for register CTRLB"] pub type W = crate::W<u32, super::CTRLB>; #[doc = "Register CTRLB `reset()`'s with value 0"] impl crate::ResetValue for super::CTRLB { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
#[doc = "Reader of register CTRLB"] pub type R = crate::R<u32, super::CTRLB>; #[doc = "Writer for register CTRLB"] pub type W = crate::W<u32, super::CTRLB>; #[doc = "Register CTRLB `reset()`'s with value 0"] impl crate::ResetValue for super::CTRLB { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
ACT_R::new(((self.bits >> 18) & 0x01) != 0) } } impl W { #[doc = "Bit 8 - Smart Mode Enable"] #[inline(always)] pub fn smen(&mut self) -> SMEN_W { SMEN_W { w: self } } #[doc = "Bit 9 - PMBus Group Command"] #[inline(always)] pub fn gcmd(&mut self) -> GCMD_W { GCMD_W { w: ...
)] pub fn cmd(&self) -> CMD_R { CMD_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bit 18 - Acknowledge Action"] #[inline(always)] pub fn ackact(&self) -> ACKACT_R { ACK
random
[]
Rust
src/parser.rs
delosrogers/spyder
9acd4d368ef7147767f1466298f7f36a07bbad56
use crate::types::{Instruction, Instruction::*}; use nom::{ branch::alt, bytes::complete::tag, character::complete::{alphanumeric1, digit1, line_ending, not_line_ending}, combinator::opt, error::{context, VerboseError}, multi::many1, sequence::{separated_pair, tuple}, IResult, }; #[de...
use crate::types::{Instruction, Instruction::*}; use nom::{ branch::alt, bytes::complete::tag, character::complete::{alphanumeric1, digit1, line_ending, not_line_ending}, combinator::opt, error::{context, VerboseError}, multi::many1, sequence::{separated_pair, tuple}, IResult, }; #[de...
fn call(input: &str) -> Res<&str, Statement> { context("call", separated_pair(tag("call"), tag(" "), alphanumeric1))(input) .map(|(next_input, res)| (next_input, Statement::Call(res.1))) } fn push(input: &str) -> Res<&str, Statement> { context("push", separated_pair(tag("push"), tag(" "), number))(in...
next_input, match res.0 { "goto" => Statement::Goto(res.1), "gotoEqual" => Statement::GotoEqual(res.1), _ => panic!("goto parser tried to parse non goto or gotoifequal"), }, ) }) }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_calling() {\n\n let path = PathBuf::from(\"tests/test_data/call-test.spd\");\n\n let calculated = spyder::run_file(&path, false);\n\n assert!(calculated.is_ok());\n\n assert_eq!(calculated.expect(\"error\"), 50)\n\n}\n\n\n", "file_path": "tests/code_exec.rs", ...
Rust
tests/expectations/tests/disable-nested-struct-naming.rs
rust-lang-nursery/rust-bindgen
5a01c551993e56d20240ef64d0ec78cd4195855d
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct foo { pub b1: bar1, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct bar1 { pub x1: ::std::os::raw::c_int, pub b2: bar1__bindgen_ty...
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct foo { pub b1: bar1, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct bar1 { pub x1: ::std::os::raw::c_int, pub b2: bar1__bindgen_ty...
#[test] fn bindgen_test_layout_bar1__bindgen_ty_1__bindgen_ty_1() { assert_eq!( ::std::mem::size_of::<bar1__bindgen_ty_1__bindgen_ty_1>(), 8usize, concat!("Size of: ", stringify!(bar1__bindgen_ty_1__bindgen_ty_1)) ); assert_eq!( ::std::mem::align_of::<bar1__bindgen_ty_1__bin...
q!( ::std::mem::size_of::<bar4>(), 4usize, concat!("Size of: ", stringify!(bar4)) ); assert_eq!( ::std::mem::align_of::<bar4>(), 4usize, concat!("Alignment of ", stringify!(bar4)) ); assert_eq!( unsafe { let uninit = ::std::mem::MaybeUn...
function_block-function_prefixed
[ { "content": "struct Foo {\n\n T t;\n\n U u;\n\n};\n\n\n\nstatic Foo<bool> bar;\n", "file_path": "tests/headers/default-template-parameter.hpp", "rank": 0, "score": 261765.62776933349 }, { "content": "struct Foo {};\n\ntemplate<typename T>\n\nFoo<T> foo{};\n\n\n\n// Struct inside funct...
Rust
makepad/hub/src/hubui.rs
difference-engine/makepad.github.io
3b4c0ba22cb02ba87d067c0f73b013c66e8bd6bd
use std::sync::{mpsc, Arc, Mutex}; use crate::hubmsg::*; use crate::hubrouter::*; use crate::hubclient::*; pub struct HubUI { pub hub_log:HubLog, pub thread: Option<std::thread::JoinHandle<()>>, pub route_send: HubRouteSend, pub htc_msgs_arc: Arc<Mutex<Vec<FromHubMsg>>>, } impl HubUI { pub fn...
use std::sync::{mpsc, Arc, Mutex}; use crate::hubmsg::*; use crate::hubrouter::*; use crate::hubclient::*; pub struct HubUI { pub hub_log:HubLog, pub thread: Option<std::thread::JoinHandle<()>>, pub route_send: HubRouteSend, pub htc_msgs_arc: Arc<Mutex<Vec<FromHubMsg>>>, } impl HubUI { pub fn...
}
let mut msgs = Vec::new(); std::mem::swap(&mut msgs, &mut htc_msgs); return Some(msgs); } None }
function_block-function_prefix_line
[ { "content": "#[allow(non_upper_case_globals, unused_assignments)]\n\npub fn digest_cycle(a:&mut Digest) {\n\n for i in 0..24 {\n\n let mut array = [0u64; 5];\n\n \n\n // Theta\n\n unroll5!(x, {\n\n unroll5!(y, {\n\n array[x] ^= a.buf[5 * y + x];\n\n ...
Rust
src/vm.rs
kiedtl/zf
d590b630990d2e9ef6422c946f183914490c908b
use std::collections::HashMap; pub const DEFAULT_STACK: &'static str = "_"; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum GuardItem { Any, Number, Str, Quote, Table, Stack, Unchecked, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Guard { pub before: Vec<GuardItem>, pub after: Vec<Guar...
use std::collections::HashMap; pub const DEFAULT_STACK: &'static str = "_"; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum GuardItem { Any, Number, Str, Quote, Table, Stack, Unchecked, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Guard { pub before: Vec<GuardItem>, pub after: Vec<Guar...
} impl std::hash::Hash for Value { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { match self { Value::Number(i) => i.to_bits().hash(state), Value::String(s) => s.hash(state), Value::SymbRef(s) => s.hash(state), Value::Table(t) => for (k, v) in t { ...
l { if !r.contains_key(k) || &r[k] != v { return false; } } for (k, v) in r { if !l.contains_key(k) || &r[k] != v { return false; } } true }, (Guard(l), Guard(r)) => l == r, _ => ...
function_block-function_prefixed
[ { "content": "pub fn bNOT(env: &mut VM) -> Result<bool, String> {\n\n let a = pop_as!(env, Number) as usize;\n\n env.push(Value::Number((!a) as f64));\n\n Ok(false)\n\n}\n\n\n", "file_path": "src/stdlib.rs", "rank": 0, "score": 174579.70254867733 }, { "content": "pub fn bOR(env: &mu...
Rust
server/prisma-rs/migration-engine/connectors/migration-connector/src/steps.rs
otrebu/prisma
298be5c919119847bb8d102d6b16672edd06b2c5
use datamodel::*; use nullable::Nullable; #[derive(Debug, Deserialize, Serialize, PartialEq, Clone)] #[serde(tag = "stepType")] pub enum MigrationStep { CreateModel(CreateModel), UpdateModel(UpdateModel), DeleteModel(DeleteModel), CreateField(CreateField), DeleteField(DeleteField), UpdateField(...
use datamodel::*; use nullable::Nullable; #[derive(Debug, Deserialize, Serialize, PartialEq, Clone)] #[serde(tag = "stepType")] pub enum MigrationStep { CreateModel(CreateModel), UpdateModel(UpdateModel), DeleteModel(DeleteModel), CreateField(CreateField), DeleteField(DeleteField), UpdateField(...
} #[derive(Debug, Deserialize, Serialize, PartialEq, Clone)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct DeleteField { pub model: String, pub name: String, } #[derive(Debug, Deserialize, Serialize, PartialEq, Clone)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Cr...
e() || self.db_name.is_some() || self.is_created_at.is_some() || self.is_updated_at.is_some() || self.id.is_some() || self.default.is_some() || self.scalar_list.is_some() }
function_block-function_prefixed
[ { "content": "/// Loads and builds the internal data model from the data model JSON.\n\npub fn load(db_name: String) -> PrismaResult<InternalDataModelRef> {\n\n let data_model_json = load_string()?;\n\n Ok(serde_json::from_str::<InternalDataModelTemplate>(&data_model_json)?.build(db_name))\n\n}\n\n\n", ...
Rust
plugin/oov/mecab_oov/src/lib.rs
denjiry/sudachi.rs
ab22cba0f0fe02dcdf67cca578e3f720ca33e537
use serde::Deserialize; use serde_json::Value; use std::collections::HashMap; use std::fs; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use sudachi::config::Config; use sudachi::declare_oov_provider_plugin; use sudachi::dic::category_type::CategoryType; use sudachi::dic::character_category::Error as Char...
use serde::Deserialize; use serde_json::Value; use std::collections::HashMap; use std::fs; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use sudachi::config::Config; use sudachi::declare_oov_provider_plugin; use sudachi::dic::category_type::CategoryType; use sudachi::dic::character_category::Error as Char...
fn provide_oov( &self, input_text: &Utf8InputText, offset: usize, has_other_words: bool, ) -> SudachiResult<Vec<Node>> { let mut nodes = vec![]; let byte_len = input_text.get_char_category_continuous_length(offset); if byte_len == 0 { return ...
let categories = MeCabOovPlugin::read_character_property(reader)?; let unk_def_path = config.complete_path( settings .unkDef .unwrap_or_else(|| PathBuf::from(DEFAULT_UNK_DEF_FILE)), ); let reader = BufReader::new(fs::File::open(&unk_def_path)?); ...
function_block-function_prefix_line
[ { "content": "fn build_node_oov(start: usize, end: usize, cost: i32, surface: &str, length: u16) -> Node {\n\n let mut node_ai = Node::new_oov(\n\n 8,\n\n 8,\n\n 6000,\n\n WordInfo {\n\n surface: surface.to_string(),\n\n head_word_length: length,\n\n ...
Rust
bee-message/src/message.rs
grtlr/bee
cf1c35fdf61e6ac1b2e19dd891a59c6aef223d7b
use crate::{ parent::Parents, payload::{OptionalPayload, Payload}, Error, MessageId, }; use bee_pow::providers::{miner::Miner, NonceProvider, NonceProviderBuilder}; use crypto::hashes::{blake2b::Blake2b256, Digest}; use packable::{ error::{UnpackError, UnpackErrorExt}, packer::Packer, unpack...
use crate::{ parent::Parents, payload::{OptionalPayload, Payload}, Error, MessageId, }; use bee_pow::providers::{miner::Miner, NonceProvider, NonceProviderBuilder}; use crypto::hashes::{blake2b::Blake2b256, Digest}; use packable::{ error::{UnpackError, UnpackErrorExt}, packer::Packer, unpack...
; } let nonce = u64::unpack::<_, VERIFY>(unpacker).infallible()?; let message = Self { network_id, parents, payload, nonce, }; let message_len = message.packed_len(); if VERIFY && message_len > Message::LENGTH_M...
Err(UnpackError::Packable(Error::InvalidPayloadKind( Into::<Option<Payload>>::into(payload).unwrap().kind(), )))
call_expression
[ { "content": "fn verify_payload<const VERIFY: bool>(payload: &OptionalPayload) -> Result<(), Error> {\n\n match &payload.0 {\n\n Some(Payload::TaggedData(_)) | None => Ok(()),\n\n Some(payload) => Err(Error::InvalidPayloadKind(payload.kind())),\n\n }\n\n}\n", "file_path": "bee-message/sr...
Rust
wasm/src/style.rs
keiya01/og_image_writer
0542616db2cd9c9135ece82ec0a7683051e69ef4
use og_image_writer::style::{ AlignItems, BorderRadius, FlexDirection, JustifyContent, KernSetting, Margin, Position, Rgba, Style, TextAlign, TextOverflow, WhiteSpace, WindowStyle, WordBreak, }; use std::marker::Copy; use wasm_bindgen::prelude::*; #[wasm_bindgen(typescript_custom_section)] const TYPESCRIPT_DEF...
use og_image_writer::style::{ AlignItems, BorderRadius, FlexDirection, JustifyContent, KernSetting, Margin, Position, Rgba, Style, TextAlign, TextOverflow, WhiteSpace, WindowStyle, WordBreak, }; use std::marker::Copy; use wasm_bindgen::prelude::*; #[wasm_bindgen(typescript_custom_section)] const TYPESCRIPT_DEF...
Style { WindowStyle { height: style.height, width: style.width, background_color: style .background_color .map(|color| Rgba([color.r, color.g, color.b, color.a])), align_items: style.align_items, justify_content: style.justify_content, flex_dir...
function_block-function_prefixed
[ { "content": "fn border_top_left_radius(buf: &mut ImageBuffer<Rgba<u8>, Vec<u8>>, r: i32) {\n\n while_radius(buf, r - 1, (0, 0), |img, (x0, y0), (x, y), color| {\n\n draw_line_segment_mut(\n\n img,\n\n ((x0 + x) as f32, (y0) as f32),\n\n ((x0) as f32, (y0 + y) as f32),...
Rust
below/below_derive/src/queriable.rs
ahornby/below
7b2ce1e135a2a023ae62af3201092e84f7d0db26
use crate::helper::{get_metadata, occurrence_error, parse_option, to_camelcase}; use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{ parse::{Parse, ParseStream}, spanned::Spanned, DeriveInput, Field, Ident, Token, }; mod kw { use syn::custom_keyword; custom_keyword!(field_id...
use crate::helper::{get_metadata, occurrence_error, parse_option, to_camelcase}; use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{ parse::{Parse, ParseStream}, spanned::Spanned, DeriveInput, Field, Ident, Token, }; mod kw { use syn::custom_keyword; custom_keyword!(field_id...
subquery_kw = Some(kw); let base_type = option_type.as_ref().unwrap_or(&field.ty); subquery = Some(syn::parse_quote! { <#base_type as Queriable>::FieldId }); } FieldMeta::Prefer...
if let Some(fst_kw) = subquery_kw { return Err(occurrence_error(fst_kw, kw, "subquery")); }
if_condition
[ { "content": "pub fn enum_to_string_derive_impl(ast: &DeriveInput) -> syn::Result<TokenStream> {\n\n let enum_name = &ast.ident;\n\n\n\n let variant_to_string_arms = get_variants(ast)?\n\n .iter()\n\n .map(|variant| {\n\n let variant_name = &variant.ident;\n\n let snake...
Rust
nameservice/tests/integration.rs
westaking/cosmwasm-examples
f2f0568ebc90d812bcfaa0ef5eb1da149a951552
use cosmwasm::mock::{mock_env, MockApi, MockStorage}; use cosmwasm::types::{Coin, ContractResult, HumanAddr}; use cosmwasm_vm::testing::{handle, init, mock_instance, query}; use cosmwasm_vm::Instance; use cw_storage::deserialize; use cw_nameservice::coin_helpers::{coin, coin_vec}; use cw_nameservice::msg::{HandleM...
use cosmwasm::mock::{mock_env, MockApi, MockStorage}; use cosmwasm::types::{Coin, ContractResult, HumanAddr}; use cosmwasm_vm::testing::{handle, init, mock_instance, query}; use cosmwasm_vm::Instance; use cw_storage::deserialize; use cw_nameservice::coin_helpers::{coin, coin_vec}; use cw_nameservice::msg::{HandleM...
#[test] fn register_available_name_and_query_works() { let mut deps = mock_instance(WASM); mock_init_no_fees(&mut deps); mock_alice_registers_name(&mut deps, &[]); assert_name_owner(&mut deps, "alice", "alice_key"); } #[test] fn fails_on_register_already_taken_name() { let mut deps = mock_i...
fn register_available_name_and_query_works_with_fees() { let mut deps = mock_instance(WASM); mock_init_with_fees(&mut deps, coin("2", "token"), coin("2", "token")); mock_alice_registers_name(&mut deps, &coin_vec("2", "token")); let params = mock_env(&deps.api, "bob_key", &coin_vec("5", "token"), &...
function_block-full_function
[ { "content": "fn assert_name_owner(deps: &mut Extern<MockStorage, MockApi>, name: &str, owner: &str) {\n\n let res = query(\n\n &deps,\n\n QueryMsg::ResolveRecord {\n\n name: name.to_string(),\n\n },\n\n )\n\n .unwrap();\n\n\n\n let value: ResolveRecordResponse = dese...
Rust
src/inspectors/balancer.rs
mattsse/mev-inspect-rs
30db9cf277ff5fa28da91210902e5aea84163ad5
use crate::{ addresses::BALANCER_PROXY, inspectors::find_matching, traits::Inspector, types::{actions::Trade, Classification, Inspection, Protocol}, DefiProtocol, ProtocolContracts, }; use crate::model::{CallClassification, EventLog, InternalCall}; use crate::types::actions::{SpecificAction, Transf...
use crate::{ addresses::BALANCER_PROXY, inspectors::find_matching, traits::Inspector, types::{actions::Trade, Classification, Inspection, Protocol}, DefiProtocol, ProtocolContracts, }; use crate::model::{CallClassification, EventLog, InternalCall}; use crate::types::actions::{SpecificAction, Transf...
} #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use crate::{ addresses::ADDRESSBOOK, inspectors::ERC20, reducers::{ArbitrageReducer, TradeReducer}, types::Inspection, Inspector, Reducer, TxReducer, }; struct MyInspector { erc20:...
ls.insert(Protocol::Balancer); } continue; }; let t1 = find_matching( actions.iter().enumerate().skip(i + 1), |t| t.as_transfer(), |t| t...
function_block-function_prefixed
[ { "content": "/// _collateral, reserve, user, _purchaseAmount, _receiveAToken\n\ntype LiquidationCall = (Address, Address, Address, U256, bool);\n", "file_path": "src/inspectors/aave.rs", "rank": 1, "score": 241792.0448235676 }, { "content": "// Type aliases for Uniswap's `swap` return types...
Rust
program/src/state.rs
solrazr-app/solr-token-sale
20deb9febba3ec4e4697b2b5ee5f51b23162a8eb
use solana_program::{ program_error::ProgramError, program_pack::{IsInitialized, Pack, Sealed}, pubkey::Pubkey, }; use arrayref::{array_mut_ref, array_ref, array_refs, mut_array_refs}; pub struct TokenSale { pub is_initialized: bool, pub init_pubkey: Pubkey, pub sale_token_account_pubkey: Pubk...
use solana_program::{ program_error::ProgramError, program_pack::{IsInitialized, Pack, Sealed}, pubkey::Pubkey, }; use arrayref::{array_mut_ref, array_ref, array_refs, mut_array_refs}; pub struct TokenSale { pub is_initialized: bool, pub init_pubkey: Pubkey, pub sale_token_account_pubkey: Pubk...
fn pack_into_slice(&self, dst: &mut [u8]) { let dst = array_mut_ref![dst, 0, TokenSale::LEN]; let ( is_initialized_dst, init_pubkey_dst, sale_token_account_pubkey_dst, pool_token_account_pubkey_dst, whitelist_map_pubkey_dst, w...
fn unpack_from_slice(src: &[u8]) -> Result<Self, ProgramError> { let src = array_ref![src, 0, TokenSale::LEN]; let ( is_initialized, init_pubkey, sale_token_account_pubkey, pool_token_account_pubkey, whitelist_map_pubkey, whitelist_...
function_block-full_function
[ { "content": "fn process_instruction(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n instruction_data: &[u8],\n\n) -> ProgramResult {\n\n Processor::process(program_id, accounts, instruction_data)\n\n}\n", "file_path": "program/src/entrypoint.rs", "rank": 0, "score": 45761.05...
Rust
src/transport_feedbacks/rapid_resynchronization_request/rapid_resynchronization_request_test.rs
algesten/rtcp
cbc3efdd8dba612d7ee3ab540d317681db591b27
use super::*; use bytes::Bytes; #[test] fn test_rapid_resynchronization_request_unmarshal() { let tests = vec![ ( "valid", Bytes::from_static(&[ 0x85, 0xcd, 0x0, 0x2, 0x90, 0x2f, 0x9e, 0x2e, 0x90, 0x2f, 0x9e, 0x2e, ]), ...
use super::*; use bytes::Bytes; #[test] fn test_rapid_resynchronization_request_unmarshal() { let tests = vec![ ( "valid", Bytes::from_static(&[ 0x85, 0xcd, 0x0, 0x2, 0x90, 0x2f, 0x9e, 0x2e, 0x90, 0x2f, 0x9e, 0x2e, ]), ...
#[test] fn test_rapid_resynchronization_request_roundtrip() { let tests: Vec<(&str, RapidResynchronizationRequest, Option<Error>)> = vec![( "valid", RapidResynchronizationRequest { sender_ssrc: 0x902f9e2e, media_ssrc: 0x902f9e2e, }, None, )]; for (n...
for (name, mut data, want, want_error) in tests { let got = RapidResynchronizationRequest::unmarshal(&mut data); assert_eq!( got.is_err(), want_error.is_some(), "Unmarshal {} rr: err = {:?}, want {:?}", name, got, want_error ...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_receiver_report_unmarshal() {\n\n let tests = vec![\n\n (\n\n \"valid\",\n\n Bytes::from_static(&[\n\n 0x81u8, 0xc9, 0x0, 0x7, // v=2, p=0, count=1, RR, len=7\n\n 0x90, 0x2f, 0x9e, 0x2e, // ssrc=0x902f9e2e\n\n ...
Rust
ffi/emf-core-base-rs-ffi/src/module/native_module.rs
GabeRealB/emf-rs
24a812c052602aeb7aa8747ab306e4c33a0a72d6
use crate::collections::{ConstSpan, NonNullConst, Result}; use crate::errors::Error; use crate::module::{Interface, InterfaceDescriptor, ModuleHandle, ModuleInfo}; use crate::sys::api::{GetFunctionFn, HasFunctionFn}; use crate::{CBase, TypeWrapper}; use std::ptr::NonNull; #[repr(C)] pub struct NativeModule { _du...
use crate::collections::{ConstSpan, NonNullConst, Result}; use crate::errors::Error; use crate::module::{Interface, InterfaceDescriptor, ModuleHandle, ModuleInfo}; use crate::sys::api::{GetFunctionFn, HasFunctionFn}; use crate::{CBase, TypeWrapper}; use std::ptr::NonNull; #[repr(C)] pub struct NativeModule { _du...
face) } #[inline] unsafe fn get_module_info( &self, module: Option<NonNull<NativeModule>>, ) -> Result<NonNullConst<ModuleInfo>, Error> { (self.get_module_info_fn)(module) } #[inline] unsafe fn get_load_dependencies(&self) -> ConstSpan<InterfaceDescriptor> { ...
endencies( &self, module: Option<NonNull<NativeModule>>, ) -> Result<ConstSpan<InterfaceDescriptor>, Error>; unsafe fn get_exportable_interfaces( &self, module: Option<NonNull<NativeModule>>, ) -> Res...
random
[]
Rust
src/query/on_conflict.rs
SeaQL/Sea-Query
6c9527ae08e32c55490ae510be41f646e030c2a2
use crate::{DynIden, Expr, IntoIden, SimpleExpr, Value}; #[derive(Debug, Clone, Default)] pub struct OnConflict { pub(crate) target: Option<OnConflictTarget>, pub(crate) action: Option<OnConflictAction>, } #[derive(Debug, Clone)] pub enum OnConflictTarget { ConflictColumns(Vec<DynIden>), } #[derive(...
use crate::{DynIden, Expr, IntoIden, SimpleExpr, Value}; #[derive(Debug, Clone, Default)] pub struct OnConflict { pub(crate) target: Option<OnConflictTarget>, pub(crate) action: Option<OnConflictAction>, } #[derive(Debug, Clone)] pub enum OnConflictTarget { ConflictColumns(Vec<DynIden>), } #[derive(...
pub fn update_values<C, I>(&mut self, column_values: I) -> &mut Self where C: IntoIden, I: IntoIterator<Item = (C, Value)>, { self.action = Some(OnConflictAction::UpdateExprs( column_values ...
pub fn update_columns<C, I>(&mut self, columns: I) -> &mut Self where C: IntoIden, I: IntoIterator<Item = C>, { self.action = Some(OnConflictAction::UpdateColumns( columns.into_iter()...
random
[ { "content": "#[allow(clippy::many_single_char_names)]\n\n#[cfg(feature = \"with-json\")]\n\n#[cfg_attr(docsrs, doc(cfg(feature = \"with-json\")))]\n\npub fn sea_value_to_json_value(value: &Value) -> Json {\n\n use crate::{CommonSqlQueryBuilder, QueryBuilder};\n\n\n\n match value {\n\n Value::Bool(...
Rust
src/main.rs
KaiWitt/xpub-balance
2d2d937b2f06ad5d4e774839fe0401958c32167c
mod constants; mod esplora; mod print; mod wallet; use anyhow::{anyhow, Context, Result}; use clap::{App, Arg, ArgMatches}; use indicatif::{ProgressBar, ProgressStyle}; use esplora::*; use print::*; use wallet::*; fn main() -> Result<()> { let matches = App::new("xpub-balance") .version("0.1.0") ...
mod constants; mod esplora; mod print; mod wallet; use anyhow::{anyhow, Context, Result}; use clap::{App, Arg, ArgMatches}; use indicatif::{ProgressBar, ProgressStyle}; use esplora::*; use print::*; use wallet::*; fn main() -> Result<()> { let matches = App::new("xpub-balance") .version("0.1.0") ...
r() -> ProgressBar { let spinner = ProgressBar::new_spinner(); spinner.enable_steady_tick(240); spinner.set_message("Requesting data"); spinner.set_style( ProgressStyle::default_spinner() .tick_strings(&[". ", ".. ", "...", " "]) .template("{elapsed_precise} {msg}{spin...
Arg::with_name("change") .help("Show change instead of receive addresses. Doesn't effect the total balance calculation") .short("c") .long("change") .takes_value(false), ) .arg( Arg::with_name("offline") ...
random
[ { "content": "/// Derives and prints addresses of the desired account with their indexes\n\npub fn print_addresses_offline(wallet: &DerivationWallet, args: &Args) -> Result<()> {\n\n let to_print = if args.is_change {\n\n &wallet.change\n\n } else {\n\n &wallet.receive\n\n };\n\n\n\n f...
Rust
hacl-star-sys/src/imp/hash.rs
huitseeker/rust-hacl-star
af3ab7a5f5164234ef9a4498809ee0031a9c3bd6
/* automatically generated by rust-bindgen */ pub type __uint8_t = crate::libc::c_uchar; pub type __uint32_t = crate::libc::c_uint; pub type __uint64_t = crate::libc::c_ulong; pub type FStar_UInt128_uint128 = [u64; 2]; pub type Spec_Hash_Definitions_hash_alg = u8; extern "C" { pub fn Hacl_Hash_Core_Blake2_update_b...
/* automatically generated by rust-bindgen */ pub type __uint8_t = crate::libc::c_uchar; pub type __uint32_t = crate::libc::c_uint; pub type __uint64_t = crate::libc::c_ulong; pub type FStar_UInt128_uint128 = [u64; 2]; pub type Spec_Hash_Definitions_hash_alg = u8; extern "C" { pub fn Hacl_Hash_Core_Blake2_update_b...
nish_384(s: *mut u64, dst: *mut u8); } extern "C" { pub fn Hacl_Hash_Core_SHA2_finish_512(s: *mut u64, dst: *mut u8); } extern "C" { pub fn Hacl_Hash_Definitions_word_len(a: Spec_Hash_Definitions_hash_alg) -> u32; } extern "C" { pub fn Hacl_Hash_Definitions_block_len(a: Spec_Hash_Definitions_hash_alg) -> u3...
u32, dst: *mut u8); } extern "C" { pub fn Hacl_Hash_SHA2_hash_256(input: *mut u8, input_len: u32, dst: *mut u8); } extern "C" { pub fn Hacl_Hash_SHA2_hash_384(input: *mut u8, input_len: u32, dst: *mut u8); } extern "C" { pub fn Hacl_Hash_SHA2_hash_512(input: *mut u8, input_len: u32, dst: *mut u8); } extern ...
random
[ { "content": "pub fn scalarmult(mypublic: &mut [u8; 32], secret: &[u8; 32], basepoint: &[u8; 32]) {\n\n unsafe {\n\n ffi::curve25519::Hacl_Curve25519_51_scalarmult(\n\n mypublic.as_mut_ptr(),\n\n secret.as_ptr() as _,\n\n basepoint.as_ptr() as _,\n\n );\n\n }...
Rust
pre/src/grid.rs
Stunkymonkey/osm_dijkstra
fa8a81e7789fe117803f8ece9b91e3b03dfa9064
use super::*; fn get_min_max(nodes: &[Node]) -> GridBounds { let lat_min = nodes .par_iter() .map(|node| node.latitude) .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap(); let lat_max = nodes .par_iter() .map(|node| node.latitude) ...
use super::*; fn get_min_max(nodes: &[Node]) -> GridBounds { let lat_min = nodes .par_iter() .map(|node| node.latitude) .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap(); let lat_max = nodes .par_iter() .ma
itude: 12.7, rank: 0, }, &grid_bounds, ); assert_eq!(node_id, 3634); } }
p(|node| node.latitude) .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap(); let lng_min = nodes .par_iter() .map(|node| node.longitude) .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap(); let lng_max = node...
random
[ { "content": "/// get distance on earth surface using haversine formula\n\nfn calc_distance(a: Node, b: Node) -> f32 {\n\n let lat_1 = a.latitude;\n\n let long_1 = a.longitude;\n\n let lat_2 = b.latitude;\n\n let long_2 = b.longitude;\n\n let r: f32 = 6371.0; // constant used for meters\n\n le...
Rust
src/relative_duration.rs
olliemath/chronoutil
593c3df11f2d6ba4c3d018cf50197bd269fb1467
use core::ops::{Add, Div, Mul, Neg, Sub}; use std::time::Duration as StdDuration; use chrono::{Date, DateTime, Duration, NaiveDate, NaiveDateTime, TimeZone}; use super::delta::shift_months; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct RelativeDuration { months: i32, duration: Du...
use core::ops::{Add, Div, Mul, Neg, Sub}; use std::time::Duration as StdDuration; use chrono::{Date, DateTime, Duration, NaiveDate, NaiveDateTime, TimeZone}; use super::delta::shift_months; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct RelativeDuration { months: i32, duration: Du...
} impl Neg for RelativeDuration { type Output = RelativeDuration; #[inline] fn neg(self) -> RelativeDuration { RelativeDuration { months: -self.months, duration: -self.duration, } } } impl Add<RelativeDuration> for RelativeDuration { type Output = Relative...
pub fn with_duration(self, duration: Duration) -> RelativeDuration { RelativeDuration { months: self.months, duration, } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn is_leap_year(year: i32) -> bool {\n\n year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)\n\n}\n\n\n\n// If the day lies within the month, this function has no effect. Otherwise, it shifts\n\n// day backwards to the final day of the month.\n\n// XXX: No attempt is made to ...
Rust
src/lib.rs
lifthrasiir/rust-soundchange
51277622dca97365443a60cadd01a00269e87aed
/*! A tool for implementing sound change algorithms. This is strictly modeled after Mark Rosenfelder's [Sound Change Applier][sca], with a necessary tweak for Rust's macro system. [sca]: http://zompist.com/scahelp.html Typical usage and the comparison with the original SCA rules: ``` #[macro_use] extern crate sound...
/*! A tool for implementing sound change algorithms. This is strictly modeled after Mark Rosenfelder's [Sound Change Applier][sca], with a necessary tweak for Rust's macro system. [sca]: http://zompist.com/scahelp.html Typical usage and the comparison with the original SCA rules: ``` #[macro_use] extern crate sound...
let mut buf = String::new(); let mut unmatched = Some(0); from.search_loop(s, preconds, postconds, |found, ss| { if unmatched.is_some() { let last = unmatched.unwrap(); if !found && last == s.subslice_offset(ss) { unmatched = Some(last + ss.len()); ...
f)) => { for c in s.chars() { buf.push(f.call((c,))); } }, Transform::Str(t) => buf.push_str(t), Transform::StrTo(StrTo(ref f)) => f.call((s, buf)), } }
function_block-function_prefixed
[ { "content": "// if the \"word\" contains a hyphen or space, we should split it.\n\nfn map_words<F>(mut s: &str, mut f: F) -> String where F: FnMut(&str) -> String {\n\n let mut ret = String::new();\n\n loop {\n\n match s.find(&[' ', '-'][..]) {\n\n Some(i) => {\n\n let j ...
Rust
src/lib.rs
pczarn/enum_coder
0ef0ddfab44b7e9d7d4af5bfdca1f9c245c1b3b6
extern crate proc_macro; extern crate syn; extern crate quote; use std::collections::{HashMap, HashSet}; use std::mem; use proc_macro::TokenStream; use quote::quote; use syn::{ ItemEnum, ItemFn, Ident, Result, Meta, Fields, FieldsNamed, Stmt, Member, NestedMeta, Expr, FieldValue, ExprPath, ExprStruct, Pat...
extern crate proc_macro; extern crate syn; extern crate quote; use std::collections::{HashMap, HashSet}; use std::mem; use proc_macro::TokenStream; use quote::quote; use syn::{ ItemEnum, ItemFn, Ident, Result, Meta, Fields, FieldsNamed, Stmt, Member, NestedMeta, Expr, FieldValue, ExprPath, ExprStruct, Pat...
} } } else { match self.definition(path) { Definition::Named(..) | Definition::Unnamed => { Some(Expr::Call(expr_call.clone())) } ...
ne, Some(generate_list)) => { assert!(generate_list.is_empty(), "expected no arguments in an attribute"); ProcessFn::GenerateList(item) } (None, None) => { ProcessFn::NormalFn(item) } } } ...
random
[ { "content": "fn main() {\n\n let insns = make_instructions();\n\n let mut state = Stack { v: vec![] };\n\n for ins in insns {\n\n state.run(ins);\n\n }\n\n assert_eq!(\n\n state.pop(),\n\n \"hello, world!\\\n\n hello, world!\\\n\n hello, world!\\\n\n hel...
Rust
src/parser/ast/fragments.rs
wesleywiser/toml-rust
dbdd6278cf28685cb9b8d36b8f44ef973ddf7950
use tokenizer::TomlFragment; #[derive(PartialEq, Debug)] pub enum AstFragment<'a> { Boolean(bool), Whitespace(&'a str), Array(Vec<AstFragment<'a>>), Comma, Integer(i64, &'a str), } #[derive(PartialEq, Debug)] pub struct ParseResult<'a> { pub number_of_consumed_tokens : usize, pub parse_re...
use tokenizer::TomlFragment; #[derive(PartialEq, Debug)] pub enum AstFragment<'a> { Boolean(bool), Whitespace(&'a str), Array(Vec<AstFragment<'a>>), Comma, Integer(i64, &'a str), } #[derive(PartialEq, Debug)] pub struct ParseResult<'a> { pub number_of_consumed_tokens : usize, pub parse_re...
#[test] fn parse_two_element_array_1() { let input = vec![ TomlFragment::BracketOpen, TomlFragment::Boolean("true"), TomlFragment::Comma, TomlFragment::Boolean("false"), TomlFragment::BracketClose ]; let expected = ...
TomlFragment::Boolean("false"), TomlFragment::BracketClose ]; let expected = Ok( ParseResult { number_of_consumed_tokens: 3, parse_result: vec![AstFragment::Array(vec![AstFragment::Boolean(false)])] }); ...
function_block-function_prefix_line
[ { "content": "pub fn tokenize_bracket_close(s: &str) -> Option<ParseResult> {\n\n tokenize_single_char(']', BracketClose, s)\n\n}\n\n\n", "file_path": "src/tokenizer/tokenizer_array.rs", "rank": 0, "score": 190196.18859339663 }, { "content": "pub fn tokenize_comma(s: &str) -> Option<Parse...
Rust
src/lib/mod.rs
fuyutarow/snippets-make
c124b7b3870ac21881200cd7f7648c65d8b170ad
use serde_derive::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs; use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; #[derive(Debug, Deserialize, Serialize)] struct RawDotSnippet { body: String, } #[derive(Debug, Deserialize, Serialize)] struct RawConfig { lang: String, ...
use serde_derive::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs; use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; #[derive(Debug, Deserialize, Serialize)] struct RawDotSnippet { body: String, } #[derive(Debug, Deserialize, Serialize)] struct RawConfig { lang: String, ...
} impl Config { pub fn from_fpath(fpath: PathBuf) -> Self { let mut f = File::open(fpath).expect("file not found"); let mut contents = String::new(); f.read_to_string(&mut contents) .expect("something went wrong reading the file"); Self::from_toml(&contents) } ...
s .into_iter() .map(|(k, v)| { ( k.clone(), DotSnippet { prefix: k, body: v.body, }, ) }) ...
function_block-function_prefixed
[ { "content": "fn main() {\n\n match Opt::from_args() {\n\n Opt { fpath, to, over } => {\n\n let config = Config::from_fpath(fpath);\n\n\n\n match to.as_str() {\n\n \"vscode\" => {\n\n if let Some(editor) = over {\n\n let re...
Rust
src/monitors/windows.rs
awused/wallpapers
55899e6da2e390bef2fd3d106f6e50236ed57b55
use std::ffi::c_void; use std::{io, ptr}; use widestring::U16CString; use winapi::shared::windef::RECT; use winapi::shared::winerror::E_FAIL; use winapi::shared::wtypesbase::CLSCTX_LOCAL_SERVER; use winapi::um::combaseapi::{CoCreateInstance, CoTaskMemFree, CoUninitialize}; use winapi::um::objbase::CoInitialize; use wi...
use std::ffi::c_void; use std::{io, ptr}; use widestring::U16CString; use winapi::shared::windef::RECT; use winapi::shared::winerror::E_FAIL; use winapi::shared::wtypesbase::CLSCTX_LOCAL_SERVER; use winapi::um::combaseapi::{CoCreateInstance, CoTaskMemFree, CoUninitialize}; use winapi::um::objbase::CoInitialize; use wi...
pub fn list() -> Vec<Monitor> { let monitors: Result<_, io::Error> = (|| unsafe { check(CoInitialize(ptr::null_mut()))?; let mut monitors = Vec::new(); let mut desktop: *mut IDesktopWallpaper = ptr::null_mut(); check(CoCreateInstance( &CLSID_DesktopWallpaper, ...
unsafe fn get_monitor(dtop: &IDesktopWallpaper, n: u32) -> Result<Option<Monitor>, io::Error> { let mut monitor_id: *mut u16 = ptr::null_mut(); check(dtop.GetMonitorDevicePathAt(n, &mut monitor_id))?; assert!(!monitor_id.is_null()); let path = U16CString::from_ptr_str(monitor_id); CoTaskMemFr...
function_block-full_function
[ { "content": "// Canonicalize fails to handle files/directories that do not exist.\n\npub fn normalize_path(path: &Path) -> PathBuf {\n\n let mut components = path.components().peekable();\n\n let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {\n\n components.next();...
Rust
crate/src/camera/arc_ball/data.rs
dakom/awsm-renderer
f7ecfa560b19577b188fc16fcdc33ee54a8204c9
use crate::camera::traits::*; use nalgebra::{self as na, Isometry3, Matrix4, Perspective3, Point3, Unit, UnitQuaternion, Vector2, Vector3}; use std::f64; use crate::constants::DEFAULT_ARCBALL_FAR_PLANE; #[derive(Clone, Debug)] pub struct ArcBall { pub(super) at: Point3<f64>, pub(super) yaw: f64, ...
use crate::camera::traits::*; use nalgebra::{self as na, Isometry3, Matrix4, Perspective3, Point3, Unit, UnitQuaternion, Vector2, Vector3}; use std::f64; use crate::constants::DEFAULT_ARCBALL_FAR_PLANE; #[derive(Clone, Debug)] pub struct ArcBall { pub(super) at: Point3<f64>, pub(super) yaw: f64, ...
res.look_at(eye, at); res } pub fn at(&self) -> Point3<f64> { self.at } pub fn set_at(&mut self, at: Point3<f64>) { self.at = at; self.update_projviews(); } pub fn yaw(&self) -> f64 { self.yaw } pub fn set_yaw(&mu...
let mut res = ArcBall { at: Point3::new(0.0, 0.0, 0.0), yaw: 0.0, pitch: 0.0, dist: 0.0, min_dist: 0.00001, max_dist: std::f64::MAX, yaw_step: 0.005, pitch_step: 0.005, min_pitch: 0.01, max_pitch: std...
assignment_statement
[ { "content": "pub fn create_cameras(world:&World, width: f64, height: f64) -> CameraIds {\n\n let arc_ball_entity = world.run(|mut entities:EntitiesViewMut, mut cameras: ViewMut<ArcBall>| {\n\n let mut camera = ArcBall::new(Point3::new(0.0, 0.0, 1000.0), Point3::new(0.0, 0.0, 0.0));\n\n camera....
Rust
src/bundle/tform/string_indexer.rs
Oswfrans/Geoffrey
f4d1121b8f3ac8f42dbdf1a41481d5f605c16342
use std::any::*; use std::collections::HashMap; use bundle::tform::{self, DefaultNode}; use bundle::ser::*; use bundle::frame; use bundle::dsl; pub const OP: &'static StringIndexerOp = &StringIndexerOp { }; #[derive(Clone)] pub struct StringIndexerModel { labels: Vec<String>, label_to_index: HashMap<String, usiz...
use std::any::*; use std::collections::HashMap; use bundle::tform::{self, DefaultNode}; use bundle::ser::*; use bundle::frame; use bundle::dsl; pub const OP: &'static StringIndexerOp = &StringIndexerOp { }; #[derive(Clone)] pub struct StringIndexerModel { labels: Vec<String>, label_to_index: HashMap<String, usiz...
} impl DefaultNode for StringIndexer { fn name(&self) -> &str { &self.name } fn model(&self) -> &Any { &self.model as &Any } fn create_shape(&self) -> dsl::Shape { dsl::Shape::with_standard_io(String::from(self.input_col.as_ref()), String::from(self.output_col.as_ref())) } } impl Op for StringIndexerOp ...
s| { let mut indices: Vec<i32> = Vec::with_capacity(labels.len()); for label in labels.iter() { match self.model.try_encode(label) { Ok(r) => indices.push(r as i32), Err(err) => return Err(err) } } Ok(indices) }).and_then(|indices| { frame.try_with...
function_block-function_prefixed
[ { "content": "pub fn c_string_to_rust(null_terminated_string: *const c_char) -> String {\n\n unsafe {\n\n let c_str = ffi::CStr::from_ptr(null_terminated_string);\n\n String::from(c_str.to_str().unwrap())\n\n }\n\n}\n", "file_path": "src/c/mod.rs", "rank": 0, "score": 157003.12439823273 },...
Rust
src/lib.rs
alexwennerberg/drive-advanced
8dc5920cebb8b6475f243d3391b0b8f719805a56
pub mod auth; pub mod schema; pub mod db; #[macro_use] extern crate diesel; extern crate dotenv; use diesel::prelude::*; use diesel::{debug_query, insert_into}; use std::env; use schema::{files, user_files, parents, permissions}; use reqwest; use serde::{self, Deserialize, Serialize}; use serde_json::Value; use die...
pub mod auth; pub mod schema; pub mod db; #[macro_use] extern crate diesel; extern crate dotenv; use diesel::prelude::*; use diesel::{debug_query, insert_into}; use std::env; use schema::{files, user_files, parents, permissions}; use reqwest; use serde::{self, Deserialize, Serialize}; use serde_json::Value; use die...
#[derive(Debug, Deserialize)] struct Response { #[serde(rename = "nextPageToken")] next_page_token: Option<String>, files: Vec<File>, } #[derive(Debug, Default, Deserialize, Insertable)] #[table_name = "user_files"] pub struct UserFile { id: String, user_email: Option<String>, #[serde(rename ...
for mut perm in &mut permissions { perm.file_id = file["id"].as_str().unwrap().to_string(); } insert_into(permissions::dsl::permissions) .values(&permissions) .on_conflict_do_nothing() .execute(&conn) ...
function_block-function_prefix_line
[ { "content": "/// Either uses a service account or oauth offline refresh token\n\npub fn get_authentication_token(user: Option<&str>) -> String {\n\n debug!(\"Getting authentication token\");\n\n let scope = env::var(\"DRIVE_SCOPE\").expect(\"DRIVE_SCOPE not set. Should be drive or drive.readonly\");\n\n ...
Rust
src/main.rs
mattburgess/webmencoder
9e7d32b66c5de4422808870d012d94abc2e0636c
use glob::glob; use serde::Deserialize; use std::process::Command; use structopt::StructOpt; #[derive(StructOpt)] #[structopt( name = "webmencoder", about = "ffmpeg wrapper to convert MPEG videos to WebM" )] struct Cli { #[structopt(short, long, parse(from_os_str))] input_dir: std::path::PathBuf, ...
use glob::glob; use serde::Deserialize; use std::process::Command; use structopt::StructOpt; #[derive(StructOpt)] #[structopt( name = "webmencoder", about = "ffmpeg wrapper to convert MPEG videos to WebM" )] struct Cli { #[structopt(short, long, parse(from_os_str))] input_dir: std::path::PathBuf, ...
().map(AsRef::as_ref).collect(); ffmpeg_args.extend_from_slice(&mapping_args); let metadata_args: Vec<&str> = a_metadata.iter().map(AsRef::as_ref).collect(); ffmpeg_args.extend_from_slice(&metadata_args); let qual = &quality.to_string(); ffmpeg_args.extend_from_slice(&[ "-vf", &v...
()].contains(field_order) { v_filters.insert(0, "yadif"); } mappings.push("-map".to_string()); mappings.push(format!("0:v:{}", v_idx)); v_idx += 1; } Stream::Subtitle => {} } } let in_file = inp...
function_block-random_span
[ { "content": "### Audio Encoding\n\n\n\n* Codec: Vorbis - Although the WebM container format supports both Vorbis and Opus codecs, some of my existing devices [don't support Opus natively](https://developer.samsung.com/smarttv/develop/specifications/media-specifications/2018-tv-video-specifications.html), resul...
Rust
lib/src/block/huffman/package_merge.rs
markmmm/ribzip2
940ab75bb083441481f76f9b539eed3e1c333102
use std::collections::HashMap; pub(crate) fn compute_lis(weights: &[usize], limit: usize) -> Vec<usize> { let mut coins = vec![]; for i in 1..=limit { for weight in weights { coins.push(Coin { numismatic_value: *weight, demonination_exponential: i, ...
use std::collections::HashMap; pub(crate) fn compute_lis(weights: &[usize], limit: usize) -> Vec<usize> { let mut coins = vec![]; for i in 1..=limit { for weight in weights { coins.push(Coin { numismatic_value: *weight, demonination_exponential: i, ...
; for set in res { assert!( (set.iter() .map(|y| 2f64.powf(-(y.demonination_exponential as f64))) .sum::<f64>() - 1.0) .abs() < f64::EPSILON ); } } }
package_merge(&[ Coin { numismatic_value: 1, demonination_exponential: 3, }, Coin { numismatic_value: 1, demonination_exponential: 3, }, Coin { numismatic_value: 3, ...
call_expression
[ { "content": "pub fn convert_to_code_pad_to_n_bits(mut input: usize, n: usize) -> Vec<Bit> {\n\n let mut output = Vec::new();\n\n let mut counter = 0;\n\n while input > 0 {\n\n match input & 1 {\n\n 0 => output.push(Bit::Zero),\n\n _ => output.push(Bit::One),\n\n }\n...
Rust
src/protocol/client.rs
norlen/faktory-rust
dec323002e064123233d6015532f2c6c0bc9b378
use super::{ commands::{Ack, Beat, End, Fail, Fetch, Flush, Hello, Info, Push}, connection::Connection, frame::Frame, responses::Hi, Error, Job, PROTOCOL_VERSION, }; use serde::Deserialize; #[derive(Clone, Copy, PartialEq)] pub(crate) enum State { Identified, Quiet...
use super::{ commands::{Ack, Beat, End, Fail, Fetch, Flush, Hello, Info, Push}, connection::Connection, frame::Frame, responses::Hi, Error, Job, PROTOCOL_VERSION, }; use serde::Deserialize; #[derive(Clone, Copy, PartialEq)] pub(crate) enum State { Identified, Quiet...
hi } Frame::Error(e) => return Err(Error::ServerError(e.clone())), _ => return Err(err()), }; let mut hello = Hello::new(); if let Some(info) = info { hello.hostname = Some(info.hostname); hello.worker_id = Some(info.w...
if hi.version != PROTOCOL_VERSION { return Err(Error::UnexpectedProtocol(hi.version, PROTOCOL_VERSION)); }
if_condition
[ { "content": "fn skip(src: &mut Cursor<&[u8]>, n: usize) -> Result<(), Error> {\n\n if src.remaining() < n {\n\n Err(Error::Incomplete)\n\n } else {\n\n src.advance(n);\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/protocol/frame.rs", "rank": 0, "score": 134299.786825...
Rust
src/bot.rs
Chronophylos/dungeon-bot
bd5ea2520918ff6e034613961c7d30491724ced8
use anyhow::{Context, Result}; use log::{debug, error, info, trace}; use pest::{iterators::Pairs, Parser}; use pest_derive::Parser; use std::{collections::HashMap, convert::TryInto}; use twitchchat::{ messages::Commands, messages::Privmsg, runner::NotifyHandle, AsyncRunner, Status, UserConfig, }; const GLOBAL_PREF...
use anyhow::{Context, Result}; use log::{debug, error, info, trace}; use pest::{iterators::Pairs, Parser}; use pest_derive::Parser; use std::{collections::HashMap, convert::TryInto}; use twitchchat::{ messages::Commands, messages::Privmsg, runner::NotifyHandle, AsyncRunner, Status, UserConfig, }; const GLOBAL_PREF...
} Status::Quit | Status::Eof => break, Status::Message(..) => continue, } } debug!("end of main loop"); Ok(()) } fn parse_command<'a>(&self, input: &'a str) -> Option<Message<'a>> { M...
if let Some(msg) = self.parse_command(pm.data()) { if let Some(command) = self.get_command(&msg) { debug!("dispatching to: {}", msg.command.escape_debug()); let args = Args { raw: &pm, ...
if_condition
[]
Rust
src/lib.rs
bekker/hangeul-rs
e750463cec0b7e3801de0976b9a75d70e6633e59
pub mod constants; pub mod errors; pub mod models; use crate::constants::*; use crate::errors::*; use crate::models::*; pub fn is_syllable(code: u32) -> bool { matches!(code, SYLLABLE_START..=SYLLABLE_END) } pub fn is_jaeum(code: u32) -> bool { matches!( code, COMPAT_CHOSEONG_START..=COMPAT_C...
pub mod constants; pub mod errors; pub mod models; use crate::constants::*; use crate::errors::*; use crate::models::*; pub fn is_syllable(code: u32) -> bool { matches!(code, SYLLABLE_START..=SYLLABLE_END) } pub fn is_jaeum(code: u32) -> bool { matches!( code, COMPAT_CHOSEONG_START..=COMPAT_C...
pub use self::get_choseong as get_lead; pub fn get_jungseong(c: &char) -> Result<char> { match Jungseong::from_char(c) { Some(jung) => Ok(jung.to_char()), None => Err(HangeulError::JamoNotFound), } } pub use self::get_jungseong as get_middle; pub fn get_jongseong(c: &char) -> Result<char> {...
pub fn get_choseong(c: &char) -> Result<char> { match Choseong::from_char(c) { Some(cho) => Ok(cho.to_char()), None => Err(HangeulError::JamoNotFound), } }
function_block-full_function
[ { "content": "fn check_roundtrip_char(ch: char) {\n\n let decomposed = decompose_char(&ch).expect(\"decompose_char\");\n\n let composed =\n\n compose_char(&decomposed.0, &decomposed.1, decomposed.2.as_ref()).expect(\"compose_char\");\n\n assert_eq!(ch, composed);\n\n}\n\n\n", "file_path": "t...
Rust
src/proofs/asset.rs
jakecraige/provisions
e8ed303feb167d9d28ab201b0e4df1106e709244
use crate::fields::Field256; use crate::proofs::binary::BinaryProof; use crate::proofs::compute_challenge; use crate::secp256k1::{pedersen_commitment, point_mul, point_mul_add, Point}; use crate::serialization::{Deserialize, Serialize}; use num_bigint::BigUint; #[derive(Debug, PartialEq)] pub struct AssetProof { g...
use crate::fields::Field256; use crate::proofs::binary::BinaryProof; use crate::proofs::compute_challenge; use crate::secp256k1::{pedersen_commitment, point_mul, point_mul_add, Point}; use crate::serialization::{Deserialize, Serialize}; use num_bigint::BigUint; #[derive(Debug, PartialEq)] pub struct AssetProof { g...
#[test] fn asset_proof_serialization() { let g = crate::g(); let h = crate::h(); let x = Field256::from(1); let y = &point_mul(Point::g(), &x); let bal = BigUint::from(123u8); let proof = AssetProof::create(Some(x), y, bal, &g, &h); let proof2 = AssetPr...
k() { let g = crate::g(); let h = crate::h(); let x = Field256::from(1); let y = &point_mul(Point::g(), &x); let bal = BigUint::from(123u8); let commitment = AssetProof::create(None, y, bal, &g, &h); assert!(commitment.verify() "commitment not able to be verifie...
function_block-function_prefixed
[ { "content": "// Create commitment of y = g^x * h^r\n\npub fn pedersen_commitment(g: Point, x: &Field256, h: Point, r: &Field256) -> Point {\n\n let mut gx = point_mul(g, x);\n\n let hr = point_mul(h, r);\n\n\n\n gx.add(&hr);\n\n gx\n\n}\n\n\n", "file_path": "src/secp256k1.rs", "rank": 0, ...
Rust
lib/vrl/tests/src/docs.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::{ collections::{BTreeMap, HashMap}, fs, process::Command, }; use serde::Deserialize; use serde_json::{Map, Value}; use crate::Test; const SKIP_FUNCTION_EXAMPLES: &[&str] = &[ "type_def", "encrypt", "random_bytes", "uuid_v4", "strip_ansi_escape_codes", "get_hostname", ...
use std::{ collections::{BTreeMap, HashMap}, fs, process::Command, }; use serde::Deserialize; use serde_json::{M
h", "export", "-e", "remap"]) .output() .expect("failed to execute process"); if output.stdout.is_empty() { Vec::new() } else { let Reference { examples, functions, expressions, } = serde_json::from_slice(&output.stdout).unwrap(); ...
ap, Value}; use crate::Test; const SKIP_FUNCTION_EXAMPLES: &[&str] = &[ "type_def", "encrypt", "random_bytes", "uuid_v4", "strip_ansi_escape_codes", "get_hostname", "now", "get_env_var", "get_metadata_field", "set_metadata_field", "remove_metadata_field", ]; #[derive(De...
random
[ { "content": "const fs = require('fs');\n", "file_path": "website/scripts/create-config-examples.js", "rank": 0, "score": 114945.39885398648 }, { "content": "type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;\n", "file_path": "lib/k8s-test-framework/src/lib.rs", "ra...
Rust
day_7/src/main.rs
kwaegel/AdventOfCode2015
f1b55484b99daf3c64e0d01a170274de6278b8a5
use std::error::Error; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::Path; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::VecDeque; fn get_input_lines(filename: &str) -> Vec<String> { let path = Path::new(file...
use std::error::Error; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::Path; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::VecDeque; fn get_input_lines(filename: &str) -> Vec<String> { let path = Path::new(file...
fn process_gate_queue<'a>(gates: &'a Vec<String>, wires: &mut HashMap<&'a str, u16>, verbose: bool) { let mut remaining_gates: VecDeque<&str> = gates.into_iter().map(AsRef::as_ref).collect(); while remaining_gates.len() > 0 { let opt_gate = r...
fn process_gate_5<'a>(tokens: &Vec<&'a str>, wires: &mut HashMap<&'a str, u16>, verbose: bool) -> bool { let gate_type = tokens[1]; let wire_in_1 = tokens[0]; let wire_in_2 = tokens[2]; let wire_id_out = tokens[4]; let wire_opt_...
function_block-full_function
[ { "content": "// Returns true on overflow\n\nfn increment_char(letter: &mut char) -> bool {\n\n\tif *letter == 'z' {\n\n\t\t*letter = 'a';\n\n\t\treturn true;\n\n\t} else {\n\n\t\t*letter = char::from_u32(*letter as u32 + 1).unwrap();\n\n\t\tfalse\n\n\t}\n\n}\n\n\n\n// ------------------------------------------...
Rust
crates/components/deskc-04-thir/src/visitor.rs
ryo33/desk-lang-prototype
038c44b326c3f9de7eb5a10f444ae4f179034d47
use crate::TypedHir; pub trait TypedHirVisitor { fn visit(&mut self, hir: &TypedHir) { match &hir.expr { crate::Expr::Literal(literal) => self.visit_literal(literal), crate::Expr::Match { input, cases } => self.visit_match(input, cases), crate::Expr::Let { definition, bo...
use crate::TypedHir; pub trait TypedHirVisitor { fn visit(&mut self, hir: &TypedHir) { match &hir.expr { crate::Expr::Literal(literal) => self.visit_literal(literal), crate::Expr::Match { input, cases } => self.visit_match(input, cases), crate::Expr::Let { definition, bo...
fn visit_link_name(&mut self, _link_name: &mut crate::LinkName) {} fn visit_product(&mut self, exprs: &mut [crate::TypedHir]) { for expr in exprs { self.visit(expr); } } fn visit_function(&mut self, parameters: &mut [crate::Type], body: &mut crate::TypedHir) { for pa...
fn visit_apply( &mut self, function: &mut crate::Type, link_name: &mut crate::LinkName, arguments: &mut [crate::TypedHir], ) { self.visit_type(function); self.visit_link_name(link_name); for argument in arguments { self.visit(argument); } ...
function_block-function_prefix_line
[ { "content": "pub fn simplify_effect_expr(expr: &mut EffectExpr) {\n\n EffectExprSimplifier.visit_effect_expr(expr);\n\n}\n\n\n", "file_path": "crates/systems/deskc-04-typeinfer/src/ty/effect_expr.rs", "rank": 0, "score": 287760.80834808364 }, { "content": "fn divide(thirgen: &TypedHirGen...
Rust
neutron_kernel/src/filesystem/ember.rs
SpectralProject/Neutron
8ef8fe8ce8455a73bac318a0276b7101fd84fe5f
use alloc::{string::String, string::ToString, vec, vec::Vec}; use core::option::*; struct EmberFSHeader { database: Vec<EmberFile>, n_files: u64, last_modified: u64, } struct EmberFile { name: String, tags: Vec<EmberTag>, } impl EmberFile { pub fn new(_name: &str, def_ta...
use alloc::{string::String, string::ToString, vec, vec::Vec}; use core::option::*; struct EmberFSHeader { database: Vec<EmberFile>, n_files: u64, last_modified: u64, } struct EmberFile { name: String, tags: Vec<EmberTag>, } impl EmberFile { pub fn new(_name: &str, def_ta...
fn create_tag() { let secret_tag = EmberTag::new("secrets"); let study_tag = EmberTag::new("study"); assert_eq!(secret_tag.get_name(), "secrets"); assert_eq!(study_tag.get_name(), "study"); let mut _file = EmberFile::new("World History", "study"); let r = _file.add_tag("study"); ...
function_block-full_function
[ { "content": "// open() should copy the entire file to RAM at offset 0 to n_bytes-1\n\n// read() in the userspace should see that the file is in RAM and not request driver access and instead use VFS/memory mapped file\n\n// no exceptions\n\nfn read_from_file(file_path: &str, offset: u64, n_bytes: u64) -> Vec<u8...
Rust
src/sim.rs
yodaldevoid/mkl26
dbf0639e529705a2fe2988e614898071ae0d209c
use bit_field::BitField; use embedded_hal::spi::Mode; use volatile_register::{RO, RW}; use crate::adc::{self, Adc}; use crate::atomic::{BmeAtomic, InterruptAtomic}; use crate::i2c::{self, Divider, Multiplier, I2cMaster}; #[cfg(feature = "i2c-slave")] use crate::i2c::{Address, I2cSlave}; use crate::pit::Pit; use crate:...
use bit_field::BitField; use embedded_hal::spi::Mode; use volatile_register::{RO, RW}; use crate::adc::{self, Adc}; use crate::atomic::{BmeAtomic, InterruptAtomic}; use crate::i2c::{self, Divider, Multiplier, I2cMaster}; #[cfg(feature = "i2c-slave")] use crate::i2c::{Address, I2cSlave}; use crate::pit::Pit; use crate:...
pub fn uart<'a, 'b, R: Into<Option<UartRx<'a>>>, T: Into<Option<UartTx<'b>>>>( &mut self, uart: u8, rx: R, tx: T, clkdiv: u16, ) -> Result<Uart<'a, 'b, u8>, ()> { let mut gate = match uart { 0 => ClockGate::new(4, 10), 1 => ClockGate::new...
rtName::C => ClockGate::new(5, 11), PortName::D => ClockGate::new(5, 12), PortName::E => ClockGate::new(5, 13), }; if gate.is_enabled() { panic!("Cannot create Port instance; it is already in use"); } gate.enable(); unsafe { Port::new(port, gat...
function_block-function_prefixed
[ { "content": "/// clock_freq - Frequency of module clock in Hz. UART0 uses the clock specified by\n\n/// SIM_SOPT2[UART0SRC]. UART1 and UART2 use the bus clock.\n\npub fn calc_clkdiv(baud: u32, clock_freq: u32) -> u16 {\n\n ((((clock_freq / 16) + (baud / 2)) / baud) & 0xFFF) as u16\n\n}\n\n\n\n// TODO: flow ...
Rust
styx.rs/src/intrinsics/prelude.rs
6A/styx-history
c1bff1983e2faf5ce7deadb281ee0a936dafadd1
use prelude::*; use prelude::parse::*; use expr::{BuiltIns, Call, Conditional}; use super::syntax; syntaxty!(using_type of size 0: "Styx.Prelude.Using"); pub fn using<'cx>() -> Syntax<'cx> { syntax! { type using_type() => fn parse(parser, diagnostics) { let span = match parser.curre...
use prelude::*; use prelude::parse::*; use expr::{BuiltIns, Call, Conditional}; use super::syntax; syntaxty!(using_type of size 0: "Styx.Prelude.Using"); pub fn using<'cx>() -> Syntax<'cx> { syntax! { type using_type() => fn parse(parser, diagnostics) { let span = match parser.curre...
} }
arser.current_or_report(diagnostics)? { &Token::Comma(_) | &Token::RParen(_) => break Expr::default(), _ => parser.advance() } } }); match parser.current_or_report(diagno...
random
[ { "content": "/// Imports all core types in the given virtual machine.\n\npub fn import_types(_vm: &mut VirtualMachine) {\n\n}\n\n\n", "file_path": "styx.rs/src/core/syscore.rs", "rank": 2, "score": 175029.15841303227 }, { "content": "/// Imports all core types in the given virtual machine.\...
Rust
src/mir/runner.rs
ubsan/cafe-re
876d45fe111f24afd6028e28f26ea73a9e1f3663
use mir::{self, align, Mir}; const UNINITIALIZED: u8 = 0x42; #[derive(Copy, Clone, Debug)] struct FunctionState<'mir, 'ctx: 'mir> { func: &'mir mir::FunctionValue<'ctx>, func_ty: &'mir mir::FunctionType<'ctx>, return_value: usize, params_start: usize, locals_start: usize, ...
use mir::{self, align, Mir}; const UNINITIALIZED: u8 = 0x42; #[derive(Copy, Clone, Debug)] struct FunctionState<'mir, 'ctx: 'mir> { func: &'mir mir::FunctionValue<'ctx>, func_ty: &'mir mir::FunctionType<'ctx>, return_value: usize, params_start: usize, locals_start: usize, ...
}
Int(mir::IntSize::I32) => { println!("log: {}", Self::get_value::<i32>(thing)); } mir::BuiltinType::Bool => { println!("log: {}", Self::get_value::<bool>(thing)); } mir::BuiltinType::Unit => {...
function_block-function_prefixed
[ { "content": "#[derive(Debug)]\n\nstruct FunctionValue<'ctx> {\n\n // NOTE(ubsan): *this is just for stack locals, not for args*\n\n locals: TypeList<'ctx>,\n\n blks: Vec<BlockData>,\n\n bindings: Vec<Binding<'ctx>>,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct FunctionBuilder<'ctx> {\n\n decl: Fun...
Rust
benches/criterion_tests.rs
makingthematrix/uset
2c30b194a8d8b6bd2cda832b03bd52d82e6b42c3
#[macro_use] extern crate criterion; use criterion::Criterion; fn gen_uset(c: &mut Criterion) { c.bench_function("USet generate map 1000", |b| { b.iter({ || gen_cities_uset(1000, 75) }) }); } fn gen_hashset(c: &mut Criterion) { c.bench_function("HashSet generate map 1000", |b| { b.iter({ ...
#[macro_use] extern crate criterion; use criterion::Criterion; fn gen_uset(c: &mut Criterion) { c.bench_function("USet generate map 1000", |b| { b.iter({ || gen_cities_uset(1000, 75) }) }); } fn gen_hashset(c: &mut Criterion) { c.bench_function("HashSet generate map 1000", |b| { b.iter({ ...
pub fn gen_cities_hashset(size: usize, max_roads_per_distance: usize) -> Vec<usize> { let mut city_vec = Vec::with_capacity(size); let mut r = rand::thread_rng(); let all_cities: HashSet<usize> = (0..size).collect(); let capital = r.gen_range(0, size); city_vec.push((capital, capital)); while...
function_block-full_function
[ { "content": "#[test]\n\nfn foo() {}\n", "file_path": "tests/integration_tests.rs", "rank": 13, "score": 32055.89764303676 }, { "content": " /// ```\n\n /// use self::uset::core::uset::*;\n\n ///\n\n /// let set = USet::from_slice(&[2,3,4]);\n\n /// assert_eq!(set.at_index(0),...
Rust
src/slack.rs
a-dma/yubotp
f7202a4664e6d72aa9ba48ec82d3cdcf755f50de
use serde::de::Error; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum Event { Chal(Challenge), Msg(OuterEvent), } #[derive(Debug, Deserialize)] pub struct Challenge { pub token: String, pub challenge: String, #[serde(rename = "type")] pub e...
use serde::de::Error; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum Event { Chal(Challenge), Msg(OuterEvent), } #[derive(Debug, Deserialize)] pub struct Challenge { pub token: String, pub challenge: String, #[serde(rename = "type")] pub e...
ub event: Message, #[serde(rename = "type")] pub event_type: String, pub authed_users: Vec<String>, pub event_id: String, pub event_time: u64, } impl<'de> serde::Deserialize<'de> for Message { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<...
ve(Debug, Deserialize)] pub struct DeletedMessage { #[serde(rename = "type")] pub event_type: String, pub channel: String, pub hidden: bool, pub deleted_ts: String, pub ts: String, pub thread_ts: Option<String>, pub event_ts: String, pub channel_type: String, pub previous_message...
random
[ { "content": "/// Replaces the special dollar syntax and escapes the message\n\nfn prepare_slack_message(text: &str, otp: &str, user: &str) -> String {\n\n slack::slack_escape_text(&text.replace(\"$o\", otp).replace(\"$O\", &shorten_otp(otp)))\n\n .replace(\"$u\", &format!(\"<@{}>\", user))\n\n}\n\n\n...
Rust
src/lib.rs
cssivision/env-proxy
2178b25e13039c3b360877f84244136b6d892c2e
#[cfg(test)] #[macro_use] extern crate lazy_static; extern crate url; use std::env::var_os; use url::Url; fn is_no_proxy(url: &Url) -> bool { let maybe_no_proxy = var_os("no_proxy") .or_else(|| var_os("NO_PROXY")) .map(|v| v.to_str().unwrap_or("").to_string()); if let Some(no_proxy) = maybe_no_proxy { if n...
#[cfg(test)] #[macro_use] extern crate lazy_static; extern crate url; use std::env::var_os; use url::Url; fn is_no_proxy(url: &Url) -> bool { let maybe_no_proxy = var_os("no_proxy") .or_else(|| var_os("NO_PROXY")) .map(|v| v.to_str().unwrap_or("").to_string()); if let Some(no_proxy) = maybe_no_proxy { if n...
#[test] fn no_proxy_simple_name() { let _l = LOCK.lock(); scrub_env(); set_var("no_proxy", "example.org"); set_var("http_proxy", "http://proxy.example.com:8080"); assert!(for_url("http://example.org").is_none()); } #[test] fn no_proxy_global() { let _l = LOCK.lock(); scrub_env(); set_var("no_pro...
fn scrub_env() { remove_var("http_proxy"); remove_var("https_proxy"); remove_var("HTTPS_PROXY"); remove_var("ftp_proxy"); remove_var("FTP_PROXY"); remove_var("all_proxy"); remove_var("ALL_PROXY"); remove_var("no_proxy"); remove_var("NO_PROXY"); }
function_block-full_function
[ { "content": "# env-variables\n\n\n\n[![Build Status](https://img.shields.io/travis/cssivision/env-variables.svg?style=flat-square)](https://travis-ci.org/cssivision/env-variables)\n\n[![crate](https://img.shields.io/crates/v/env-variables.svg)](https://crates.io/crates/env-variables)\n\n[![License](http://img....
Rust
bati-lib/src/kafka.rs
batigo/bati
9cb23468ee8c4f62930aa2bd1f190eac9b364b19
use crate::{deserialize_service_message, PostmanMsg, ServiceMsg}; use futures::channel::mpsc::{Receiver, Sender}; use futures::{SinkExt, StreamExt}; use log::{debug, error, info, warn}; use ntex::{rt, time}; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer:...
use crate::{deserialize_service_message, PostmanMsg, ServiceMsg}; use futures::channel::mpsc::{Receiver, Sender}; use futures::{SinkExt, StreamExt}; use log::{debug, error, info, warn}; use ntex::{rt, time}; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer:...
} } async fn run_consumer( topic: String, service: String, mut sender: Sender<PostmanMsg>, consumer: LoggingConsumer, ) { warn!("kafka consumer run for: {}", topic); loop { match consumer.recv().await { Ok(msg) => match msg.payload() { Some(bs) => { ...
match recevier.next().await { Some(PostmanMsg::Upper(msg)) => { debug!("recv pilot msg in kafka producer: {}",topic); let rec = FutureRecord::to(&topic) .payload(msg.data.to_bytes()) .key(""); producer ...
if_condition
[ { "content": "pub fn parse() -> Result<Cfg, String> {\n\n let args = Args::parse();\n\n\n\n let s = fs::read_to_string(args.file).unwrap();\n\n let r: Result<Cfg, _> = serde_yaml::from_str(&s);\n\n if r.is_err() {\n\n return Err(r.err().unwrap().to_string());\n\n }\n\n\n\n Ok(r.unwrap()...
Rust
crates/tako/src/server/worker.rs
User3574/hyperqueue
d4dea5a805925cb624eb81da65840d5a8226d4a9
use std::fmt; use crate::common::resources::map::ResourceMap; use crate::common::resources::ResourceRequest; use crate::common::resources::{NumOfCpus, TimeRequest}; use crate::common::Set; use crate::messages::common::WorkerConfiguration; use crate::server::task::Task; use crate::server::taskmap::TaskMap; use crate::s...
use std::fmt; use crate::common::resources::map::ResourceMap; use crate::common::resources::ResourceRequest; use crate::common::resources::{NumOfCpus, TimeRequest}; use crate::common::Set; use crate::messages::common::WorkerConfiguration; use crate::server::task::Task; use crate::server::taskmap::TaskMap; use crate::s...
pub fn set_stopping_flag(&mut self, value: bool) { self.flags.set(WorkerFlags::STOPPING, value); } pub fn is_stopping(&self) -> bool { self.flags.contains(WorkerFlags::STOPPING) } } impl Worker { pub fn new( id: WorkerId, configuration: WorkerConfiguration, ...
n has_time_to_run(&self, time_request: TimeRequest, now: std::time::Instant) -> bool { if let Some(time) = self.termination_time { now + time_request < time } else { true } }
function_block-function_prefixed
[ { "content": "pub fn task_transfer_cost(taskmap: &TaskMap, task: &Task, worker_id: WorkerId) -> u64 {\n\n // TODO: For large number of inputs, only sample inputs\n\n task.inputs\n\n .iter()\n\n .take(512)\n\n .map(|ti| {\n\n let t = taskmap.get_task(ti.task());\n\n ...
Rust
src/db/uniprot/evidence.rs
Alexhuszagh/bdb
ba5af69dfeb2ab183cea1669eabee7fdc0d6e8f1
use std::mem; use std::str as stdstr; use traits::{Deserializable, Serializable, Zero}; use util::{Bytes, ErrorKind, Result}; #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum ProteinEvidence { ProteinLevel = 1, TranscriptLevel = 2, Inferred = 3, ...
use std::mem; use std::str as stdstr; use traits::{Deserializable, Serializable, Zero}; use util::{Bytes, ErrorKind, Result}; #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum ProteinEvidence { ProteinLevel = 1, TranscriptLevel = 2, Inferred = 3, ...
dence at protein level"); let text = ProteinEvidence::TranscriptLevel.verbose(); assert_eq!(text, "Evidence at transcript level"); let text = ProteinEvidence::Inferred.verbose(); assert_eq!(text, "Inferred from homology"); let text = ProteinEvidence:...
rred => Self::INFERRED_LEVEL_XML_VERBOSE, ProteinEvidence::Predicted => Self::PREDICTED_LEVEL_XML_VERBOSE, ProteinEvidence::Unknown => Self::UNKNOWN_LEVEL_XML_VERBOSE, } } #[inline(always)] pub fn xml_verbose(&self) -> &'static str { ...
random
[ { "content": "#[allow(dead_code)]\n\nfn format_int_comma_impl<Int: Comma + Integer>(int: &Int) -> Result<Bytes> {\n\n let bytes = to_bytes(int)?;\n\n let mut dst = Bytes::with_capacity(2 * bytes.len());\n\n add_commas_impl(&bytes, &mut dst)?;\n\n\n\n Ok(dst)\n\n}\n\n\n\n/// Internal method to conver...
Rust
async-semaphore/src/tests.rs
nathdobson/rust-public
cad37803e239e92dfeb2be61716502e521138eec
use futures::executor::{LocalPool, ThreadPool, block_on}; use futures::task::{LocalSpawnExt, SpawnExt}; use std::sync::{Arc, Mutex}; use std::rc::Rc; use std::mem; use std::time::Duration; use async_std::future::timeout; use crate::{Semaphore, SemaphoreGuard}; use rand::{thread_rng, Rng}; #[test] fn test_simple() { ...
use futures::executor::{LocalPool, ThreadPool, block_on}; use futures::task::{LocalSpawnExt, SpawnExt}; use std::sync::{Arc, Mutex}; use std::rc::Rc; use std::mem; use std::time::Duration; use async_std::future::timeout; use crate::{Semaphore, SemaphoreGuard}; use rand::{thread_rng, Rng}; #[test] fn test_simple() { ...
dSemaphore { capacity, semaphore: Semaphore::new(capacity), counter: Mutex::new(0), } } async fn acquire(&self, amount: usize) -> SemaphoreGuard<'_> { let guard = self.semaphore.acquire(amount).await; let mut lock = self.counter.lock().unwrap(...
println!("K"); pool.run(); println!("L"); } struct CheckedSemaphore { capacity: usize, semaphore: Semaphore, counter: Mutex<usize>, } impl CheckedSemaphore { fn new(capacity: usize) -> Self { Checke
random
[ { "content": "#[test]\n\nfn test() {\n\n let n = block_on(run_until(async move {\n\n println!(\"S1\");\n\n let handle2 = local_pool::spawn(async move {\n\n println!(\"Enter 1\");\n\n return 2;\n\n });\n\n println!(\"S2\");\n\n let handle3 = local_pool:...
Rust
src/lib.rs
Bubbler-4/TryInBrowser
4342daa290c34b7613ce31764faa73191a0a40ad
#![allow(clippy::wildcard_imports)] pub mod lang; mod runner; mod threading; use data_encoding::BASE64URL_NOPAD as BASE64; use indoc::indoc; use seed::{prelude::*, *}; use std::collections::hash_map::DefaultHasher; use std::hash::Hasher; use threading::prelude::OUT_LIMIT; use web_sys::window; fn init(mut url: Url, o...
#![allow(clippy::wildcard_imports)] pub mod lang; mod runner; mod threading; use data_encoding::BASE64URL_NOPAD as BASE64; use indoc::indoc; use seed::{prelude::*, *}; use std::collections::hash_map::DefaultHasher; use std::hash::Hasher; use threading::prelude::OUT_LIMIT; use web_sys::window; fn init(mut url: Url, o...
fn get_selection() -> Option<String> { let window = window(); let selection = window.and_then(|w| w.get_selection().ok()).flatten(); let s: Option<String> = selection.map(|s| s.to_string().into()); s } fn view(model: &Model) -> Node<Msg> { div![ IF!(cfg!(feature="ui_debug") => div![ ...
fn update_url(url: Url, lang: &str, code: &str, input: &str, args: &str) -> Url { let lang = "@".to_string() + &BASE64.encode(lang.as_bytes()); let code = "@".to_string() + &BASE64.encode(code.as_bytes()); let input = "@".to_string() + &BASE64.encode(input.as_bytes()); let args = "@".to_string() + &BASE...
function_block-full_function
[ { "content": "pub fn run(lang: &str, code: &str, stdin: &str, args: &str) {\n\n reset_result();\n\n let lang = lang.to_string();\n\n let code = code.to_string();\n\n let stdin = stdin.to_string();\n\n let args = args.to_string();\n\n spawn_local(async move {\n\n let mt = get_mt().unwrap...
Rust
src/event_message/key_event_message.rs
WebOfTrust/keriox
02b6dccd5ac26da35bdb6f0a0d1fc87e1c791cb2
use crate::{ error::Error, event::{event_data::EventData, sections::seal::SourceSeal, Event}, prefix::{AttachedSignaturePrefix, IdentifierPrefix, SelfAddressingPrefix}, state::{EventSemantics, IdentifierState}, }; use super::{ dummy_event::{dummy_prefix, DummyEventMessage, DummyInceptionEvent}, ...
use crate::{ error::Error, event::{event_data::EventData, sections::seal::SourceSeal, Event}, prefix::{AttachedSignaturePrefix, IdentifierPrefix, SelfAddressingPrefix}, state::{EventSemantics, IdentifierState}, }; use super::{ dummy_event::{dummy_prefix, DummyEventMessage, DummyInceptionEvent}, ...
, EventData::Dip(_dip) => match &icp_event.event.get_prefix() { IdentifierPrefix::SelfAddressing(sap) => icp_event.check_digest(sap), _ => todo!(), }, _ => Err(Error::SemanticError("Not an ICP or DIP event".into())), } }
match &icp_event.event.get_prefix() { IdentifierPrefix::Basic(bp) => Ok(icp.key_config.public_keys.len() == 1 && bp == icp.key_config.public_keys.first().unwrap()), IdentifierPrefix::SelfAddressing(sap) => { Ok(icp_event.check_digest(sap)? && icp_event.get_digest(...
if_condition
[ { "content": "/// For given sequence of EventTypes check wheather `IdentifierState` is updated correctly\n\n/// by applying `test_update_identifier_state` sequentially.\n\npub fn test_mock_event_sequence(sequence: Vec<EventTypeTag>) -> Result<TestStateData, Error> {\n\n let mut st = get_initial_test_data();\...
Rust
src/main.rs
calmofthestorm/eseb
c7216b1e6e702e07f176c33e92f0d7988a89767d
use std::convert::TryInto; use std::io::{BufRead, Read, Write}; mod keys; use anyhow::{Context, Error, Result}; use clap::App; use keys::{KeyMaterial, SymmetricKey}; use sodiumoxide::crypto::secretstream; include!(concat!(env!("OUT_DIR"), "/generated_stamp.rs")); fn fmain() -> Result<()> { sodiumoxide::init().m...
use std::convert::TryInto; use std::io::{BufRead, Read, Write}; mod keys; use anyhow::{Context, Error, Result}; use clap::App; use keys::{KeyMaterial, SymmetricKey}; use sodiumoxide::crypto::secretstream; include!(concat!(env!("OUT_DIR"), "/generated_stamp.rs")); fn fmain() -> Result<()> { sodiumoxide::init().m...
fn load_key(source: &str) -> Result<SymmetricKey> { source .parse::<SymmetricKey>() .or_else(|_| std::fs::read_to_string(source)?.parse::<SymmetricKey>()) } fn write_record(stdout: &mut std::io::StdoutLock, record: &[u8]) -> anyhow::Result<()> { let len: u32 = record.len() as u32; stdout ...
let mut stream = secretstream::xchacha20poly1305::Stream::init_pull(&header, key.as_ref()) .map_err(|_| Error::msg("init_pull secret stream"))?; read_record(&mut stdin, &mut buf).context("read header from stdin")?; if stream.is_finalized() { return Err(Error::msg("decr...
function_block-function_prefix_line
[ { "content": "fn parse_header<'a>(data: &'a str, header: &str) -> Result<Vec<u8>> {\n\n if data.starts_with(header) {\n\n crc_decode(data, header)\n\n } else {\n\n return Err(Error::msg(format!(\n\n \"key does not start with header {}\",\n\n &header\n\n )));\n\n ...
Rust
src/main.rs
ZReC/rom-breakdown
4f0309c3228b401a62e004bbc075ceb2a9756842
use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::PathBuf; struct Arguments { slf_path: String, out_path: Option<PathBuf>, rom_file: Option<File>, cdl_file: Option<File>, } impl Arguments { pub fn new(slf_path: String) -> Self { Self { slf_pa...
use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::PathBuf; struct Arguments { slf_path: String, out_path: Option<PathBuf>, rom_file: Option<File>, cdl_file: Option<File>, } impl Arguments { pub fn new(slf_path: String) -> Self { Self { slf_pa...
fn print_help(slf_path: String) { println!("Usage:"); println!("\t{} rom_file [cdl_file]\n", slf_path); println!("This program breaks down a ROM file into its parts and stores them in individual files."); println!("Currently supported file format \".nes\""); }
r_count > &0 { "CHR ROM banks count" } else { "CHR RAM only" } ); let flag6 = &header_buffer[6]; let flag7 = &header_buffer[7]; let mapper = ((flag6 & 0xF0) >> 4) | (flag7 & 0xF0); println!( "{}\tMAPPER (See https://wiki.nesdev.org/w/index.php?title=...
function_block-function_prefixed
[ { "content": "# ROM breakdown\n\n\n\n## Usage\n\n\n\n``` sh\n\ngit clone https://github.com/ZReC/rom-breakdown.git\n\ncd rom-breakdown\n\ncargo run path_to_rom_file\n\n```\n\n\n\n---\n\n\n\n## Buy me a Dakimakura \(^o^)/\n\n\n\n<table>\n\n<tr>\n\n<th>Paypal</th>\n\n</tr>\n\n<tr>\n\n<td>\n\n\n\n[Donate~ ^ w ^](h...
Rust
examples/wgpu.rs
revilo196/visgen_graph
d7e5baca39745fb391e74ca45bf07246532a469d
use nannou::prelude::*; use nannou::wgpu::{ CommandEncoderDescriptor, Device, Texture, TextureBuilder, TextureUsage, TextureView, }; struct Model { bind_group: wgpu::BindGroup, render_pipeline: wgpu::RenderPipeline, vertex_buffer: wgpu::Buffer, texture: Texture, } #[repr(C)] #[derive(Clone, Copy...
use nannou::prelude::*; use nannou::wgpu::{ CommandEncoderDescriptor, Device, Texture, TextureBuilder, TextureUsage, TextureView, }; struct Model { bind_group: wgpu::BindGroup, render_pipeline: wgpu::RenderPipeline, vertex_buffer: wgpu::Buffer, texture: Texture, } #[repr(C)] #[derive(Clone, Copy...
fn update(app: &App, model: &mut Model, _update: Update) { let desc = CommandEncoderDescriptor { label: Some("Texture"), }; let mut encoder = app .main_window() .swap_chain_device() .create_command_encoder(&desc); let texture_view = model.texture.view().build(); ...
fn model(app: &App) -> Model { let w_id = app.new_window().size(512, 512).view(view).build().unwrap(); let window = app.window(w_id).unwrap(); let device = window.swap_chain_device(); let format = Frame::TEXTURE_FORMAT; let texture_size = [512, 512]; let vs_mod = wgpu::shader_from_spi...
function_block-full_function
[ { "content": "struct Model {\n\n receiver: osc::Receiver,\n\n tree: TextureTree,\n\n store: ParameterStore,\n\n program: ProgramManager,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 115926.62031538671 }, { "content": "fn model(app: &App) -> Model {\n\n let text...
Rust
src/drivers/abs_normal.rs
Richard-W/advantage
df4ff4828fd7a81c5fc91d81ab6c07bb36b17e65
use super::*; use nalgebra::{Dim, Matrix}; use rayon::prelude::*; #[derive(Debug)] pub struct AbsNormalTape { inner: Box<dyn Tape>, indeps: Vec<usize>, deps: Vec<usize>, n: usize, m: usize, s: usize, } impl AbsNormalTape { pub fn new(inner: Box<dyn Tape>) -> Self { let n =...
use super::*; use nalgebra::{Dim, Matrix}; use rayon::prelude::*; #[derive(Debug)] pub struct AbsNormalTape { inner: Box<dyn Tape>, indeps: Vec<usize>, deps: Vec<usize>, n: usize, m: usize, s: usize, } impl AbsNormalTape { pub fn new(inner: Box<dyn Tape>) -> Self { let n =...
one); std::mem::drop(dep_iter); let mut ops_iter = tape.ops_iter(); assert_eq!(ops_iter.next().unwrap().opcode, OpCode::Sin); assert_eq!(ops_iter.next().unwrap().opcode, OpCode::Abs); assert_eq!(ops_iter.next().unwrap().opcode, OpCode::Cos); assert_eq!(ops_iter.next().un...
a.append(&mut b); a }, ); let mut result = DMatrix::zeros(lhs.nrows(), self.ncols()); for (i, row) in rows.iter() { result.row_mut(*i).copy_from(row); ...
random
[ { "content": "#[allow(clippy::many_single_char_names)]\n\npub fn jacobian_reverse(tape: &dyn Tape) -> DMatrix<f64> {\n\n let n = tape.num_indeps();\n\n let m = tape.num_deps();\n\n\n\n let rows = (0..m)\n\n .collect::<Vec<usize>>()\n\n .par_iter()\n\n .map(|i| {\n\n let ...