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
weld/conf/mod.rs
renato2099/weld
cb6303e81920284be98c61b6d512e28ce2837581
use super::WeldConf; use super::error::WeldResult; use optimizer::OPTIMIZATION_PASSES; use optimizer::Pass; use std::path::{Path, PathBuf}; pub const MEMORY_LIMIT_KEY: &'static str = "weld.memory.limit"; pub const THREADS_KEY: &'static str = "weld.threads"; pub const SUPPORT_MULTITHREAD_KEY: &'static str = "weld.co...
use super::WeldConf; use super::error::WeldResult; use optimizer::OPTIMIZATION_PASSES; use optimizer::Pass; use std::path::{Path, PathBuf}; pub const MEMORY_LIMIT_KEY: &'static str = "weld.memory.limit"; pub const THREADS_KEY: &'static str = "weld.threads"; pub const SUPPORT_MULTITHREAD_KEY: &'static str = "weld.co...
} fn parse_passes(s: &str) -> WeldResult<Vec<Pass>> { if s.len() == 0 { return Ok(vec![]); } let mut result = vec![]; for piece in s.split(",") { match OPTIMIZATION_PASSES.get(piece) { Some(pass) => result.push(pass.clone()), None => return compile_err!("Unkno...
match s.parse::<i64>() { Ok(v) if v > 0 => Ok(v), _ => compile_err!("Invalid memory limit: {}", s), }
if_condition
[ { "content": "fn should_be_predicated(e: &mut Expr) -> bool {\n\n e.annotations.predicate()\n\n}\n\n\n", "file_path": "weld/optimizer/transforms/vectorizer.rs", "rank": 1, "score": 248395.0678036603 }, { "content": "/// Predicate an `If` expression by checking for if(cond, merge(b, e), b)...
Rust
opaque-typedef-macros/src/derive/base/base_sized.rs
lo48576/opaque-typedef
f39ee87a4c1f0b0435298028e6fc19612d3cc05c
use proc_macro2::TokenStream; use quote::quote; use crate::input::Input; pub fn gen_base_sized(input: &Input) -> TokenStream { let ty = input.ident(); let (generics_impl, generics_ty, generics_where) = input.generics().split_for_impl(); let ty_inner = input.primary_field().ty(); let ty_error = input...
use proc_macro2::TokenStream; use quote::quote; use crate::input::Input; pub fn gen_base_sized(input: &Input) -> TokenStream { let ty = input.ident(); let (generics_impl, generics_ty, generics_where) = input.generics().split_for_impl(); let ty_inner = input.primary_field().ty(); let ty_error = input...
#[test] fn simple_tuple_explicit_inner() { let input = syn::parse_quote! { #[derive(OpaqueTypedefSized)] pub struct Simple<T>(#[opaque_typedef(inner)] pub T); }; let toks = gen_base_sized(&Input::new(&input).unwrap()); let expected = quote! { ...
fn multi_field_struct() { let input = syn::parse_quote! { #[derive(OpaqueTypedefSized)] pub struct Tagged<T, Tag> { #[opaque_typedef::inner] inner: T, tag: Tag, } }; let toks = g...
function_block-full_function
[ { "content": "/// Generate impl for `OpaqueTypedefUnsized`.\n\npub fn gen_base_unsized(input: &Input) -> TokenStream {\n\n input.ensure_acceptable_unsized_repr_or_panic();\n\n let ty = input.ident();\n\n let (generics_impl, generics_ty, generics_where) = input.generics().split_for_impl();\n\n let ty...
Rust
src/client.rs
orvij/pam
9a17f2d5c3871935eed81f987714097ffef1b67d
use std::env; use crate::{conv, enums::*, functions::*, types::*}; pub struct Client<'a, C: conv::Conversation> { pub close_on_drop: bool, handle: &'a mut PamHandle, conversation: Box<C>, is_authenticated: bool, has_open_session: bool, last_code: PamReturnCode, } impl<'a> Client<'a, con...
use std::env; use crate::{conv, enums::*, functions::*, types::*}; pub struct Client<'a, C: conv::Conversation> { pub close_on_drop: bool, handle: &'a mut PamHandle, conversation: Box<C>, is_authenticated: bool, has_open_session: bool, last_code: PamReturnCode, } impl<'a> Client<'a, con...
pub fn open_session(&mut self) -> PamResult<()> { if !self.is_authenticated { return Err(PamReturnCode::Perm_Denied.into()); } self.last_code = setcred(self.handle, PamFlag::Establish_Cred); if self.last_code != PamReturnCode::Success { ...
sult<()> { self.last_code = authenticate(self.handle, PamFlag::None); if self.last_code != PamReturnCode::Success { return Err(From::from(self.last_code)); } self.is_authenticated = true; self.last_code = acct_mgmt(self.handle, PamFlag::None); i...
function_block-function_prefixed
[]
Rust
rs/tests/src/registry_authentication_test.rs
zhiiker/ic
370af58ea1231cdbb8d2e4f593a089dfd1c803cd
/* tag::catalog[] Title:: A node can authenticate registry queries from the IC Goal:: A node can query the Registry and verify the authenticity of the response, based on the root of trust of the IC. Runbook:: . Deploy the registry canister. . Execute an update() call that adds a key value pair. . Execute query() call...
/* tag::catalog[] Title:: A node can authenticate registry queries from the IC Goal:: A node can query the Registry and verify the authenticity of the response, based on the root of trust of the IC. Runbook:: . Deploy the registry canister. . Execute an update() call that adds a key value pair. . Execute query() call...
pub fn test(handle: IcHandle, ctx: &ic_fondue::pot::Context) { let mut rng = ctx.rng.clone(); let root_subnet_endpoint = get_random_root_node_endpoint(&handle, &mut rng); block_on(root_subnet_endpoint.assert_ready(ctx)); let pk_bytes = handle .ic_prep_working_dir .as_ref() .unwr...
function_block-full_function
[ { "content": "pub fn make_unassigned_nodes_config_record_key() -> String {\n\n UNASSIGNED_NODES_CONFIG_RECORD_KEY.to_string()\n\n}\n\n\n", "file_path": "rs/registry/keys/src/lib.rs", "rank": 0, "score": 461431.4716939748 }, { "content": "pub fn config() -> InternetComputer {\n\n Intern...
Rust
src/decorations.rs
ryanmaclean/bat
beca58ccb3c846ac81da57155df45e518a0f3d9e
use crate::diff::LineChange; use crate::printer::{Colors, InteractivePrinter}; use ansi_term::Style; #[derive(Clone)] pub struct DecorationText { pub width: usize, pub text: String, } pub trait Decoration { fn generate( &self, line_number: usize, continuation: bool, printer...
use crate::diff::LineChange; use crate::printer::{Colors, InteractivePrinter}; use ansi_term::Style; #[derive(Clone)] pub struct DecorationText { pub width: usize, pub text: String, } pub trait Decoration { fn generate( &self, line_number: usize, continuation: bool, printer...
} fn width(&self) -> usize { 4 } } pub struct LineChangesDecoration { cached_none: DecorationText, cached_added: DecorationText, cached_removed_above: DecorationText, cached_removed_below: DecorationText, cached_modified: DecorationText, } impl LineChangesDecoration { #[i...
if continuation { if line_number > self.cached_wrap_invalid_at { let new_width = self.cached_wrap.width + 1; return DecorationText { text: self.color.paint(" ".repeat(new_width)).to_string(), width: new_width, }; ...
if_condition
[ { "content": "pub trait Printer {\n\n fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;\n\n fn print_footer(&mut self, handle: &mut Write) -> Result<()>;\n\n fn print_line(\n\n &mut self,\n\n out_of_range: bool,\n\n handle: &mut Write,\n\n line_n...
Rust
src/bin/convert_from_json.rs
xtuc/binjs-ref
8a3d3206d65e142bcd4d416fb87e751c21c721d4
extern crate binjs; extern crate clap; extern crate env_logger; use binjs::io::{TokenReader, TokenWriter}; use binjs::generic::Node; use std::io::*; use std::thread; use clap::*; struct DummyNode {} impl DummyNode { fn new() -> Self { Self {} } } impl Node for DummyNode { fn name(&self) -> &'...
extern crate binjs; extern crate clap; extern crate env_logger; use binjs::io::{TokenReader, TokenWriter}; use binjs::generic::Node; use std::io::*; use std::thread; use clap::*; struct DummyNode {} impl DummyNode { fn new() -> Self { Self {} } } impl Node for DummyNode { fn name(&self) -> &'...
fn main_aux() { env_logger::init(); let matches = App::new("Converter from BinAST JSON format to other BinAST format") .author("arai <arai@mozilla.com>") .about("Convert a BinAST JSON file to other BinAST format file. To obtain a BinAST JSON file, you may use binjs_encode with command `advanc...
Builder::new() .name("large stack dedicated thread".to_string()) .stack_size(20 * 1024 * 1024) .spawn(|| { main_aux(); }) .expect("Could not launch dedicated thread") .join() .expect("Error in dedicated thread"); }
function_block-function_prefixed
[ { "content": "fn maybe_enter_destructuring_parameter(visitor: &mut AnnotationVisitor, path: &WalkPath) {\n\n if !is_destructuring_parameter(visitor, path) {\n\n return;\n\n }\n\n\n\n visitor\n\n .binding_kind_stack\n\n .push(BindingKind::DestructuringParam { depth: path.len() });\n...
Rust
src/acknowledgement.rs
mathstuf/rust-lapin
f8399ee9b12ef4355f35cd2b26ea440653b49655
use crate::{ publisher_confirm::{Confirmation, PublisherConfirm}, returned_messages::ReturnedMessages, ConfirmationBroadcaster, Error, Promise, Result, }; use parking_lot::Mutex; use std::{ collections::{HashMap, HashSet}, fmt, sync::Arc, }; pub type DeliveryTag = u64; #[derive(Clone)] pub(cra...
use crate::{ publisher_confirm::{Confirmation, PublisherConfirm}, returned_messages::ReturnedMessages, ConfirmationBroadcaster, Error, Promise, Result, }; use parking_lot::Mutex; use std::{ collections::{HashMap, HashSet}, fmt, sync::Arc, }; pub type DeliveryTag = u64; #[derive(Clone)] pub(cra...
}
elf .pending .values() .filter(|(channel, _)| *channel == channel_id) { resolver.swear(Err(error.clone())); } self.pending .retain(|_, (channel, _)| *channel != channel_id); }
function_block-function_prefixed
[ { "content": "pub trait Executor: std::fmt::Debug + Send + Sync {\n\n fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) -> Result<()>;\n\n}\n\n\n\npub(crate) trait ExecutorExt: Executor {\n\n fn spawn_internal(&self, promise: Promise<()>, internal_rpc: InternalRPCHandle) -> Result<()> {\n\n ...
Rust
src/abstract_test_client.rs
akazimierskigl/parsec-client-test
76a43a3b034122dcc2e6066201ba17ecdd32966d
use super::OperationTestClient; use log::error; use parsec_interface::operations::list_opcodes::Operation as ListOpcodes; use parsec_interface::operations::list_providers::{Operation as ListProviders, ProviderInfo}; use parsec_interface::operations::ping::Operation as Ping; use parsec_interface::operations::psa_algor...
use super::OperationTestClient; use log::error; use parsec_interface::operations::list_opcodes::Operation as ListOpcodes; use parsec_interface::operations::list_providers::{Operation as ListProviders, ProviderInfo}; use parsec_interface::operations::ping::Operation as Ping; use parsec_interface::operations::psa_algor...
pub fn generate_rsa_sign_key(&mut self, key_name: String) -> Result<()> { self.generate_key( key_name, KeyAttributes { key_type: KeyType::RsaKeyPair, key_bits: 1024, key_policy: KeyPolicy { key_usage_flag...
pub fn generate_key(&mut self, key_name: String, attributes: KeyAttributes) -> Result<()> { let generate_key = PsaGenerateKey { key_name: key_name.clone(), attributes, }; let _ = self.send_operation(NativeOperation::PsaGenerateKey(generate_key))?; let provider =...
function_block-function_prefix_line
[ { "content": "struct ServiceChecker;\n\n\n\nimpl ServiceChecker {\n\n pub fn run_check(config: &StressTestConfig, recv: Receiver<bool>) {\n\n if config.check_interval.is_none() {\n\n return;\n\n }\n\n\n\n let mut client = TestClient::new();\n\n let key_name = String::fr...
Rust
amethyst_core/src/transform/systems.rs
JayPavlina/amethyst
38509bce20958fd2b229b0ab0cda6c40fdc195e0
use crate::ecs::prelude::{ ComponentEvent, Entities, Join, ReadExpect, ReadStorage, ReaderId, Resources, System, WriteStorage, }; use hibitset::BitSet; use crate::transform::{HierarchyEvent, Parent, ParentHierarchy, Transform}; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; pub struct Tra...
use crate::ecs::prelude::{ ComponentEvent, Entities, Join, ReadExpect, ReadStorage, ReaderId, Resources, System, WriteStorage, }; use hibitset::BitSet; use crate::transform::{HierarchyEvent, Parent, ParentHierarchy, Transform}; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; pub struct Tra...
#[test] #[should_panic] #[cfg(debug_assertions)] fn nan_transform() { let (mut world, mut hs, mut system) = transform_world(); let mut local = Transform::default(); local.set_translation_xyz(0.0 / 0.0, 0.0 / 0.0, 0.0 / 0.0); world.create_entity().with(local.c...
x().clone(); let a2 = local1.matrix(); assert_eq!(a1, a2); a1 }; let global_matrix2 = { let e2_transform = world.read_storage::<Transform>().get(e2).unwrap().clone(); let a1 = e2_transform.global_matrix().clone(); let a2 = togethe...
function_block-function_prefixed
[ { "content": "fn initialise_camera(world: &mut World, parent: Entity) -> Entity {\n\n let (width, height) = {\n\n let dim = world.read_resource::<ScreenDimensions>();\n\n (dim.width(), dim.height())\n\n };\n\n //println!(\"Init camera with dimensions: {}x{}\", width, height);\n\n\n\n l...
Rust
src/structs/types/management_device.rs
mulark/smbios-lib
04918fda6b54763cd6d726e53e60a5f175aa2fcd
use crate::core::{strings::*, UndefinedStruct}; use crate::SMBiosStruct; use serde::{ser::SerializeStruct, Serialize, Serializer}; use std::fmt; use std::ops::Deref; pub struct SMBiosManagementDevice<'a> { parts: &'a UndefinedStruct, } impl<'a> SMBiosStruct<'a> for SMBiosManagementDevice<'a> { const STRUCT_TY...
use crate::core::{strings::*, UndefinedStruct}; use crate::SMBiosStruct; use serde::{ser::SerializeStruct, Serialize, Serializer}; use std::fmt; use std::ops::Deref; pub struct SMBiosManagementDevice<'a> { parts: &'a UndefinedStruct, } impl<'a> SMBiosStruct<'a> for SMBiosManagementDevice<'a> { const STRUCT_TY...
, raw, } } } pub struct ManagementDeviceAddressTypeData { pub raw: u8, pub value: ManagementDeviceAddressType, } impl fmt::Debug for ManagementDeviceAddressTypeData { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_s...
match raw { 0x01 => ManagementDeviceType::Other, 0x02 => ManagementDeviceType::Unknown, 0x03 => ManagementDeviceType::NationalSemiconductorLM75, 0x04 => ManagementDeviceType::NationalSemiconductorLM78, 0x05 => ManagementDeviceType::National...
if_condition
[ { "content": "/// Returns smbios raw data\n\npub fn raw_smbios_from_device() -> Result<Vec<u8>, Error> {\n\n Ok(try_load_macos_table()?)\n\n}\n", "file_path": "src/macos/platform.rs", "rank": 0, "score": 186846.18458766805 }, { "content": "/// Returns smbios raw data\n\npub fn raw_smbios_...
Rust
utils/validation/src/abi.rs
dimension-labs/dimension-node
9d07c74f99b6e88e1e1921458310d1099d0fc45c
use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use dimension_types::{ bytesrepr::{self, ToBytes}, CLValue, Key, StoredValue, Transform, U512, }; use crate::test_case::{Error, TestCase}; #[derive(Serialize, Deserialize, Debug, From)] #[serde(tag = "type", content = "value")] pub enum In...
use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use dimension_types::{ bytesrepr::{self, ToBytes}, CLValue, Key, StoredValue, Transform, U512, }; use crate::test_case::{Error, TestCase}; #[derive(Serialize, Deserialize, Debug, From)] #[serde(tag = "type", content = "value")] pub enum In...
} #[derive(Serialize, Deserialize, Debug)] pub struct ABITestCase { input: Vec<Input>, #[serde( deserialize_with = "hex::deserialize", serialize_with = "hex::serialize" )] output: Vec<u8>, } impl ABITestCase { pub fn from_inputs(inputs: Vec<Input>) -> Result<ABITestCase, bytesrepr...
fn serialized_length(&self) -> usize { match self { Input::U8(value) => value.serialized_length(), Input::U16(value) => value.serialized_length(), Input::U32(value) => value.serialized_length(), Input::U64(value) => value.serialized_length(), Input::St...
function_block-full_function
[ { "content": "pub fn u512_arb() -> impl Strategy<Value = U512> {\n\n vec(any::<u8>(), 0..64).prop_map(|b| U512::from_little_endian(b.as_slice()))\n\n}\n\n\n", "file_path": "types/src/gens.rs", "rank": 0, "score": 384990.8515566985 }, { "content": "pub fn key_arb() -> impl Strategy<Value =...
Rust
execution/executor-benchmark/src/lib.rs
BlockSuite/libra
27c125594ee82c8edb361f0c4cf79c9fa101dd68
use diem_config::{ config::{NodeConfig, RocksdbConfig}, utils::get_genesis_txn, }; use diem_crypto::{ ed25519::{Ed25519PrivateKey, Ed25519PublicKey}, hash::HashValue, PrivateKey, SigningKey, Uniform, }; use diem_logger::prelude::*; use diem_transaction_builder::stdlib::{ encode_create_parent_v...
use diem_config::{ config::{NodeConfig, RocksdbConfig}, utils::get_genesis_txn, }; use diem_crypto::{ ed25519::{Ed25519PrivateKey, Ed25519PublicKey}, hash::HashValue, PrivateKey, SigningKey, Uniform, }; use diem_logger::prelude::*; use diem_transaction_builder::stdlib::{ encode_create_parent_v...
ript( xus_tag(), receiver.address, 1, /* amount */ vec![], vec![], ), ); transactions.push(txn); self.accounts[sender_idx].sequence...
Arc}, time::Instant, }; use storage_client::StorageClient; use storage_interface::{DbReader, DbReaderWriter}; use storage_service::start_storage_service_with_db; struct AccountData { private_key: Ed25519PrivateKey, public_key: Ed25519PublicKey, address: AccountAddress, sequence_number: u64, } impl...
random
[ { "content": "type TransactionScriptDecoderMap = std::collections::HashMap<Vec<u8>, Box<dyn Fn(&Script) -> Option<ScriptCall> + std::marker::Sync + std::marker::Send>>;\n\n\n\nstatic TRANSACTION_SCRIPT_DECODER_MAP: once_cell::sync::Lazy<TransactionScriptDecoderMap> = once_cell::sync::Lazy::new(|| {{\"#\n\n ...
Rust
compiler/rustc_builtin_macros/src/test_harness.rs
Clownsw/rust
fdca237d5194bf8a1c9b437ebd2114d1c2ba6195
use rustc_ast as ast; use rustc_ast::entry::EntryPointType; use rustc_ast::mut_visit::{ExpectOne, *}; use rustc_ast::ptr::P; use rustc_ast::{attr, ModKind}; use rustc_expand::base::{ExtCtxt, ResolverExpand}; use rustc_expand::expand::{AstFragment, ExpansionConfig}; use rustc_feature::Features; use rustc_session::Sess...
use rustc_ast as ast; use rustc_ast::entry::EntryPointType; use rustc_ast::mut_visit::{ExpectOne, *}; use rustc_ast::ptr::P; use rustc_ast::{attr, ModKind}; use rustc_expand::base::{ExtCtxt, ResolverExpand}; use rustc_expand::expand::{AstFragment, ExpansionConfig}; use rustc_feature::Features; use rustc_session::Sess...
struct TestHarnessGenerator<'a> { cx: TestCtxt<'a>, tests: Vec<Test>, } impl TestHarnessGenerator<'_> { fn add_test_cases(&mut self, node_id: ast::NodeId, span: Span, prev_tests: Vec<Test>) { let mut tests = mem::replace(&mut self.tests, prev_tests); if !tests.is_empty() { ...
nic=abort is not supported \ without `-Zpanic_abort_tests`", ); } PanicStrategy::Unwind } (PanicStrategy::Unwind, _) => PanicStrategy::Unwind, }; generate_test_harness( sess, ...
function_block-function_prefixed
[]
Rust
crates/tools/src/deposit_ckb.rs
RetricSu/godwoken
88df30ffad824b3b3b2980d67ece79ca31ab0b47
use crate::account::{privkey_to_eth_address, read_privkey}; use crate::deploy_scripts::ScriptsDeploymentResult; use crate::godwoken_rpc::GodwokenRpcClient; use crate::hasher::CkbHasher; use crate::utils::{get_network_type, read_config, run_cmd, wait_for_tx}; use ckb_fixed_hash::H256; use ckb_jsonrpc_types::JsonBytes; u...
use crate::account::{privkey_to_eth_address, read_privkey}; use crate::deploy_scripts::ScriptsDeploymentResult; use crate::godwoken_rpc::GodwokenRpcClient; use crate::hasher::CkbHasher; use crate::utils::{get_network_type, read_config, run_cmd, wait_for_tx}; use ckb_fixed_hash::H256; use ckb_jsonrpc_types::JsonBytes; u...
; log::info!("eth address: 0x{:#x}", eth_address_bytes); let rollup_type_hash = &config.genesis.rollup_type_hash; let owner_lock_hash = Byte32::from_slice(privkey_to_lock_hash(&privkey)?.as_bytes()) .map_err(|err| err.to_string())?; let l2_code_hash = &deployment_result.eth_account_lock....
match eth_address { Some(addr) => { let mut b: [u8; 20] = [0u8; 20]; b.copy_from_slice(&addr.as_bytes()[2..]); CKBBytes::from(b.to_vec()) } None => privkey_to_eth_address(&privkey)?, }
if_condition
[ { "content": "pub fn read_privkey(privkey_path: &Path) -> Result<H256, String> {\n\n let privkey_string = fs::read_to_string(privkey_path)\n\n .map_err(|err| err.to_string())?\n\n .split_whitespace()\n\n .next()\n\n .map(ToOwned::to_owned)\n\n .ok_or_else(|| \"Privkey file ...
Rust
necsim/impls/no-std/src/cogs/event_sampler/unconditional.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
use core::marker::PhantomData; use necsim_core::{ cogs::{ Backup, CoalescenceRngSample, CoalescenceSampler, DispersalSampler, EmigrationExit, EventSampler, Habitat, LineageReference, LocallyCoherentLineageStore, RngCore, SpeciationProbability, TurnoverRate, }, event::{DispersalEvent...
use core::marker::PhantomData; use necsim_core::{ cogs::{ Backup, CoalescenceRngSample, CoalescenceSampler, DispersalSampler, EmigrationExit, EventSampler, Habitat, LineageReference, LocallyCoherentLineageStore, RngCore, SpeciationProbability, TurnoverRate, }, event::{DispersalEvent...
let (dispersal_target, interaction) = simulation .coalescence_sampler .sample_interaction_at_location( dispersal_target, &simulation.habitat, &simulation.lineage_store, CoalescenceRngSample::new...
let (lineage_reference, dispersal_origin, dispersal_target, prior_time, event_time) = simulation.with_mut_split_emigration_exit(|emigration_exit, simulation| { emigration_exit.optionally_emigrate( lineage_reference, dispersal_origin, ...
assignment_statement
[ { "content": "#[contract_trait]\n\npub trait EmigrationExit<H: Habitat, G: RngCore, R: LineageReference<H>, S: LineageStore<H, R>>:\n\n crate::cogs::Backup + core::fmt::Debug\n\n{\n\n #[must_use]\n\n #[debug_ensures(match &ret {\n\n Some((\n\n ret_lineage_reference,\n\n ret...
Rust
age/src/cli_common/file_io.rs
therealyingtong/rage
cb37391b81f2b69e75edde7bb04b14974a10e339
use std::fmt; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; use crate::{fl, util::LINE_ENDING, wfl, wlnfl}; const SHORT_OUTPUT_LENGTH: usize = 20 * 80; #[derive(Debug)] struct DenyBinaryOutputError; impl fmt::Display for DenyBinaryOutputEr...
use std::fmt; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; use crate::{fl, util::LINE_ENDING, wfl, wlnfl}; const SHORT_OUTPUT_LENGTH: usize = 20 * 80; #[derive(Debug)] struct DenyBinaryOutputError; impl fmt::Display for DenyBinaryOutputEr...
(LINE_ENDING.as_bytes())?; self.inner.write_all(b"[")?; self.inner.write_all(fl!("cli-truncated-tty").as_bytes())?; self.inner.write_all(b"]")?; self.inner.write_all(LINE_ENDING.as_bytes())?; self.tru...
s_bytes())?; self.inner.write_all(b"]")?; self.inner.write_all(LINE_ENDING.as_bytes())?; self.truncated = true; } return io::sink().write(data); } let mut to_write = SHORT_OU...
random
[ { "content": "#[cfg(fuzzing)]\n\npub fn fuzz_header(data: &[u8]) {\n\n if let Ok(header) = format::Header::read(data) {\n\n let mut buf = Vec::with_capacity(data.len());\n\n header.write(&mut buf).expect(\"can write header\");\n\n assert_eq!(&buf[..], &data[..buf.len()]);\n\n }\n\n}\n...
Rust
examples/advanced_params.rs
spivachuk/didcomm-rust
9a24b3b60f07a11822666dda46e5616a138af056
#[allow(unused_imports, dead_code)] #[path = "../src/test_vectors/mod.rs"] mod test_vectors; pub(crate) use didcomm; use didcomm::{ algorithms::{AnonCryptAlg, AuthCryptAlg}, did::resolvers::ExampleDIDResolver, protocols::routing::try_parse_forward, secrets::resolvers::ExampleSecretsResolver, Messa...
#[allow(unused_imports, dead_code)] #[path = "../src/test_vectors/mod.rs"] mod test_vectors; pub(crate) use didcomm; use didcomm::{ algorithms::{AnonCryptAlg, AuthCryptAlg}, did::resolvers::ExampleDIDResolver, protocols::routing::try_parse_forward, secrets::resolvers::ExampleSecretsResolver, Messa...
let secrets_resolver = ExampleSecretsResolver::new(MEDIATOR1_SECRETS.clone()); let (msg, metadata) = Message::unpack( &msg, &did_resolver, &secrets_resolver, &UnpackOptions::default(), ) .await .expect("Unable unpack"); println!("Mediator1 received message is ...
let did_resolver = ExampleDIDResolver::new(vec![ ALICE_DID_DOC.clone(), BOB_DID_DOC.clone(), MEDIATOR1_DID_DOC.clone(), ]);
assignment_statement
[ { "content": "/// Tries to parse plaintext message into `ParsedForward` structure if the message is Forward.\n\n/// (https://identity.foundation/didcomm-messaging/spec/#messages)\n\n///\n\n/// # Parameters\n\n/// - `msg` plaintext message to try to parse into `ParsedForward` structure\n\n///\n\n/// # Returns\n\...
Rust
src/tools/clippy/clippy_lints/src/manual_strip.rs
ankushduacodes/rust
d3163e96553ae8cb1fca0e62084b124e8b98310b
use crate::consts::{constant, Constant}; use crate::utils::usage::mutated_variables; use crate::utils::{ eq_expr_value, higher, match_def_path, meets_msrv, multispan_sugg, paths, qpath_res, snippet, span_lint_and_then, }; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_hir::def::Res; use rustc_hir::...
use crate::consts::{constant, Constant}; use crate::utils::usage::mutated_variables; use crate::utils::{ eq_expr_value, higher, match_def_path, meets_msrv, multispan_sugg, paths, qpath_res, snippet, span_lint_and_then, }; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_hir::def::Res; use rustc_hir::...
fn eq_pattern_length<'tcx>(cx: &LateContext<'tcx>, pattern: &Expr<'_>, expr: &'tcx Expr<'_>) -> bool { if let ExprKind::Lit(Spanned { node: LitKind::Int(n, _), .. }) = expr.kind { constant_length(cx, pattern).map_or(false, |length| length == n) } else { len_arg(cx, expr...
ant::Str(value) => Some(value.len() as u128), Constant::Char(value) => Some(value.len_utf8() as u128), _ => None, } }
function_block-function_prefixed
[]
Rust
src/core/manager/clients.rs
Danacus/penrose
4fd4ade09a38946c35f57be5e16d15e2fe151445
use crate::{ core::{ client::Client, data_types::Region, hooks::HookName, layout::LayoutConf, manager::{event::EventAction, util::pad_region}, ring::Selector, workspace::ArrangeActions, xconnection::{ Atom, ClientMessageKind, Prop, XClient...
use crate::{ core::{ client::Client, data_types::Region, hooks::HookName, layout::LayoutConf, manager::{event::EventAction, util::pad_region}, ring::Selector, workspace::ArrangeActions, xconnection::{ Atom, ClientMessageKind, Prop, XClient...
pub fn client_mut(&mut self, selector: &Selector<'_, Client>) -> Option<&mut Client> { match selector { Selector::Focused | Selector::Any => self.focused_client_mut(), Selector::WinId(id) => self.inner.get_mut(&id), Selector::Condition(f) => self.inner.iter_mut().f...
pub fn client(&self, selector: &Selector<'_, Client>) -> Option<&Client> { match selector { Selector::Focused | Selector::Any => self.focused_client(), Selector::WinId(id) => self.inner.get(&id), Selector::Condition(f) => self.inner.iter().find(|(_, v)| f(v)).map(|(_, v)| v),...
function_block-full_function
[ { "content": "#[stubbed_companion_trait(doc_hidden = \"true\")]\n\npub trait XClientConfig {\n\n /// Configure the on screen appearance of a client window\n\n #[stub(Ok(()))]\n\n fn configure_client(&self, id: Xid, data: &[ClientConfig]) -> Result<()>;\n\n\n\n /// Set client attributes such as event...
Rust
tests/all/utils/fixture.rs
goto-bus-stop/wasm-pack
d4144d301945ed69b5b5d78f46684ab28dfae5f4
use std::env; use std::fs; use std::io; use std::mem::ManuallyDrop; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::{Once, ONCE_INIT}; use std::thread; use wasm_pack; use tempfile::TempDir; fn hard_link_or_copy<P1: AsRef<Path>, P2: AsRef<Path>>(from: P1, to: P2) -> io::Result<()> { ...
use std::env; use std::fs; use std::io; use std::mem::ManuallyDrop; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::{Once, ONCE_INIT}; use std::thread; use wasm_pack; use tempfile::TempDir; fn hard_link_or_copy<P1: AsRef<Path>, P2: AsRef<Path>>(from: P1, to: P2) -> io::Result<()> { ...
pub fn readme(&self) -> &Self { self.file( "README.md", r#" # Fixture! > an example rust -> wasm project "#, ) } pub fn cargo_toml(&self, name: &str) -> &Self { self.file( ...
pub fn file<P: AsRef<Path>, C: AsRef<[u8]>>(&self, path: P, contents: C) -> &Self { assert!(path.as_ref().is_relative()); let path = self.path.join(path); if let Some(parent) = path.parent() { fs::create_dir_all(parent).unwrap(); } fs::write(path, contents).unwrap(); ...
function_block-full_function
[ { "content": "/// Get the path for a crate's directory of locally-installed binaries.\n\n///\n\n/// This does not check whether or ensure that the directory exists.\n\npub fn local_bin_dir(crate_path: &Path) -> PathBuf {\n\n crate_path.join(\"bin\")\n\n}\n\n\n", "file_path": "src/binaries.rs", "rank"...
Rust
marwood/src/vm/builtin/char.rs
ratherlargerobot/lisp
78a26d7e49341e11816d07e73611279166cb006b
use crate::number::Number; use crate::vm::builtin::{pop_argc, pop_char, pop_integer}; use crate::vm::vcell::VCell; use crate::vm::Error::InvalidSyntax; use crate::vm::{Error, Vm}; pub fn load_builtins(vm: &mut Vm) { vm.load_builtin("char->integer", char_to_integer); vm.load_builtin("char-alphabetic?", is_alpha...
use crate::number::Number; use crate::vm::builtin::{pop_argc, pop_char, pop_integer}; use crate::vm::vcell::VCell; use crate::vm::Error::InvalidSyntax; use crate::vm::{Error, Vm}; pub fn load_builtins(vm: &mut Vm) { vm.load_builtin("char->integer", char_to_integer); vm.load_builtin("char-alphabetic?", is_alpha...
pub fn char_downcase(vm: &mut Vm) -> Result<VCell, Error> { pop_argc(vm, 1, Some(1), "char-downcase")?; let c = pop_char(vm)?; if c.is_ascii() { Ok(c.to_ascii_lowercase().into()) } else if c.to_lowercase().into_iter().count() == 1 { Ok(c.to_lowercase().into_iter().next().unwrap().into(...
else if c.to_uppercase().into_iter().count() == 1 { Ok(c.to_uppercase().into_iter().next().unwrap().into()) } else { Ok(c.into()) } }
function_block-function_prefix_line
[ { "content": "pub fn num_equal(vm: &mut Vm) -> Result<VCell, Error> {\n\n num_comp(vm, \"=\", |x, y| x == y)\n\n}\n\n\n", "file_path": "marwood/src/vm/builtin/number.rs", "rank": 0, "score": 357008.1276462554 }, { "content": "pub fn plus(vm: &mut Vm) -> Result<VCell, Error> {\n\n let a...
Rust
exonum/benches/criterion/transactions.rs
0nkery/exonum
cdbed0ce14119f28f049cbe3d0d6130211a0338c
const MESSAGES_COUNT: usize = 1_000; const SAMPLE_SIZE: usize = 20; use criterion::{ AxisScale, Bencher, Criterion, ParameterizedBenchmark, PlotConfiguration, Throughput, }; use futures::{stream, sync::mpsc::Sender, sync::oneshot, Future, Sink}; use tokio_core::reactor::Core; use std::{ sync::{Arc, RwLock},...
const MESSAGES_COUNT: usize = 1_000; const SAMPLE_SIZE: usize = 20; use criterion::{ AxisScale, Bencher, Criterion, ParameterizedBenchmark, PlotConfiguration, Throughput, }; use futures::{stream, sync::mpsc::Sender, sync::oneshot, Future, Sink}; use tokio_core::reactor::Core; use std::{ sync::{Arc, RwLock},...
} } fn gen_messages(count: usize, tx_size: usize) -> Vec<Vec<u8>> { use exonum::storage::StorageValue; let (p, s) = crypto::gen_keypair(); (0..count) .map(|_| { let msg = Message::new( RawTransaction::new( 0, ServiceTransactio...
if let Event::Internal(InternalEvent::MessageVerified(_)) = event { assert!(!self.is_finished(), "unexpected `MessageVerified`"); self.txs_count += 1; if self.txs_count == self.expected_count { self.finish_signal .take() .unwr...
if_condition
[ { "content": "fn bench_hash(b: &mut Bencher, &count: &usize) {\n\n let data = (0..count).map(|x| (x % 255) as u8).collect::<Vec<u8>>();\n\n b.iter(|| hash(&data))\n\n}\n\n\n", "file_path": "exonum/benches/criterion/crypto.rs", "rank": 0, "score": 285236.78293542226 }, { "content": "fn ...
Rust
src/platform_impl/linux/x11/monitor.rs
tomaka/winit
64c1d4c5bbcde5e6d30d9c8182bde7a0cfbb9244
use std::os::raw::*; use once_cell::sync::Lazy; use parking_lot::Mutex; use super::{ ffi::{ RRCrtc, RRCrtcChangeNotifyMask, RRMode, RROutputPropertyNotifyMask, RRScreenChangeNotifyMask, True, Window, XRRCrtcInfo, XRRScreenResources, }, util, XConnection, XError, }; use crate::{ dpi::{P...
use std::os::raw::*; use once_cell::sync::Lazy; use parking_lot::Mutex; use super::{ ffi::{ RRCrtc, RRCrtcChangeNotifyMask, RRMode, RROutputPropertyNotifyMask, RRScreenChangeNotifyMask, True, Window, XRRCrtcInfo, XRRScreenResources, }, util, XConnection, XError, }; use crate::{ dpi::{P...
} } matched_monitor.to_owned() } fn query_monitor_list(&self) -> Vec<MonitorHandle> { unsafe { let mut major = 0; let mut minor = 0; (self.xrandr.XRRQueryVersion)(self.display, &mut major, &mut minor); let root = (self.xlib.XDefault...
ct.get_overlapping_area(&monitor.rect); if overlapping_area > largest_overlap { largest_overlap = overlapping_area; matched_monitor = monitor;
function_block-random_span
[ { "content": "pub fn adjust_size(hwnd: HWND, size: PhysicalSize<u32>) -> PhysicalSize<u32> {\n\n let (width, height): (u32, u32) = size.into();\n\n let rect = RECT {\n\n left: 0,\n\n right: width as i32,\n\n top: 0,\n\n bottom: height as i32,\n\n };\n\n let rect = adjust_...
Rust
src/solution/data_structures/array/operations.rs
smallswan/leetcode-rust
9b8bb3f91bec613de61f1cfdd203dd9eeda23ebe
use std::collections::HashMap; pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut nums_map = HashMap::<i32, i32>::new(); for (idx, num) in nums.into_iter().enumerate() { let complement = target - num; let j = idx as i32; if let Some(idx) = nums_map.get(&complement) { ...
use std::collections::HashMap; pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut nums_map = HashMap::<i32, i32>::new(); for (idx, num) in nums.into_iter().enumerate() { let complement = target - num; let j = idx as i32; if let Some(idx) = nums_map.get(&complement) { ...
pub fn min_cost(costs: Vec<Vec<i32>>) -> i32 { let (mut first, mut second, mut third) = (-1, -1, -1); let len = costs.len(); for cost in costs.iter().take(len) { if first == -1 { first = cost[0]; second = cost[1]; third = cost[2]; } else { le...
attend_meetings(intervals: Vec<Vec<i32>>) -> bool { let len = intervals.len(); if len <= 1 { return true; } let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); for i in 0..len - 1 { if intervals[i][1] > intervals[i + 1][0] { return false; ...
function_block-function_prefixed
[ { "content": "fn less_than_thousand(num: i32, result: &mut String) {\n\n const SINGLES: [&str; 19] = [\n\n \"One\",\n\n \"Two\",\n\n \"Three\",\n\n \"Four\",\n\n \"Five\",\n\n \"Six\",\n\n \"Seven\",\n\n \"Eight\",\n\n \"Nine\",\n\n \"Ten\...
Rust
src/two_operand.rs
jrozner/msp430-dis
ac3dda973e5b5562d28fb6d8ed36553a582a70dd
use std::fmt; use crate::emulate; use crate::emulate::Emulate; use crate::instruction::Instruction; use crate::operand::{Operand, OperandWidth}; pub trait TwoOperand { fn mnemonic(&self) -> &str; fn source(&self) -> &Operand; fn destination(&self) -> &Operand; fn size(&self) -> usi...
use std::fmt; use crate::emulate; use crate::emulate::Emulate; use crate::instruction::Instruction; use crate::operand::{Operand, OperandWidth}; pub trait TwoOperand { fn mnemonic(&self) -> &str; fn source(&self) -> &Operand; fn destination(&self) -> &Operand; fn size(&self) -> usi...
} two_operand!(Cmp, "cmp"); impl Emulate for Cmp { fn emulate(&self) -> Option<Instruction> { if self.source == Operand::Constant(0) { Some(Instruction::Tst(emulate::Tst::new( Some(self.destination), Some(self.operand_width), *self, ...
me(self.destination), Some(self.operand_width), *self, ))) } else if self.source == Operand::Constant(2) { Some(Instruction::Decd(emulate::Decd::new( Some(self.destination), Some(self.operand_width), *self, ...
function_block-function_prefixed
[ { "content": "/// All emulated instructions implement this trait to provide a common\n\n/// interface and polymorphism\n\npub trait Emulated {\n\n /// Return the mnemonic for the instruction. This is operand width aware\n\n fn mnemonic(&self) -> &str;\n\n /// Returns the destination operand\n\n fn d...
Rust
src/system/keys/filestorage.rs
ChristianVisintin/termscp
0c8144aaa8bddf2452011612ac52c896a3977c66
/** * MIT License * * termscp - Copyright (c) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights ...
/** * MIT License * * termscp - Copyright (c) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights ...
fn is_supported(&self) -> bool { true } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; #[test] fn test_system_keys_filestorage_make_dir() { let storage: FileStorage = FileStorage::new(&Path::new("/tmp/")); assert_eq!( ...
write(true) .create(true) .truncate(true) .open(key_file.as_path()) { Ok(mut file) => { if file.write_all(key.as_bytes()).is_err() { return Err(KeyStorageError::ProviderError); } ...
function_block-function_prefix_line
[ { "content": "/// ### import_theme\n\n///\n\n/// Import theme at provided path into termscp\n\npub fn import_theme(p: &Path) -> Result<(), String> {\n\n if !p.exists() {\n\n return Err(String::from(\n\n \"Could not import theme: No such file or directory\",\n\n ));\n\n }\n\n //...
Rust
src/calculator.rs
JakeStanger/eno-number
76d125734be0e751b1149b0cd524e05036438081
use std::collections::HashMap; use std::time::Instant; use rocket_contrib::databases::postgres; use crate::database::{get_artist_by_id, get_associated_artists}; use crate::path_vec::PathVec; use crate::server::CalculateResponseBody; use crate::structs::{Artist, ArtistNode}; fn format_path(path: Vec<Artist>) -> Strin...
use std::collections::HashMap; use std::time::Instant; use rocket_contrib::databases::postgres; use crate::database::{get_artist_by_id, get_associated_artists}; use crate::path_vec::PathVec; use crate::server::CalculateResponseBody; use crate::structs::{Artist, ArtistNode}; fn format_path(path: Vec<Artist>) -> Strin...
; let elapsed_time = start_time.elapsed().as_secs_f32(); println!("===RESULTS==="); println!( "Found {} paths in {:.2} seconds", paths.paths.len(), elapsed_time ); println!("Paths:"); for path in paths.paths.clone() { println!("{}", format_path(path)); } ...
get_associations( &start_node, &destination, &mut paths, &mut explored, database, )
call_expression
[ { "content": "pub fn associated_acts(artist: &Artist) -> String {\n\n format!(\n\n \"SELECT DISTINCT artist.id, artist.name\n\n FROM l_artist_artist\n\n INNER JOIN artist ON\n\n (artist.id = l_artist_artist.entity1)\n\n OR (artist.id = l_artist_artist.entity0)\n\n ...
Rust
rubble/src/gatt/mod.rs
chris-ricketts/rubble
c061a45f245ad0e9cd0cc259b9a75a0f09e1ef10
pub mod characteristic; use { crate::{ att::{AttUuid, Attribute, AttributeProvider, Handle, HandleRange}, utils::HexSlice, uuid::{Uuid, Uuid16}, Error, }, core::{cmp, slice}, }; pub struct BatteryServiceAttrs { attributes: [Attribute<'static>; 3], } impl BatteryServi...
pub mod characteristic; use { crate::{ att::{AttUuid, Attribute, AttributeProvider, Handle, HandleRange}, utils::HexSlice, uuid::{Uuid, Uuid16}, Error, }, core::{cmp, slice}, }; pub struct BatteryServiceAttrs { attributes: [Attribute<'static>; 3], } impl BatteryServi...
0x77, ]), }, Attribute { att_type: AttUuid::Uuid128(Uuid::from_bytes([ 0xF3, 0x6B, 0x10, 0x9D, 0x66, 0xF2, /*-*/ 0xA9, 0xA1, /*-*/ 0x12, 0x41, /*-*/ ...
0xA9, 0xA1, /*-*/ 0x12, 0x41, /*-*/ 0x68, 0x38, /*-*/ 0xDB, 0xE5, 0x72,
function_block-random_span
[ { "content": "/// Runs Rubble's packet queue testsuite against the given `PacketQueue`.\n\n///\n\n/// This can be used when implementing your own packet queue. Simply create a `#[test]` function as\n\n/// usual and call `run_tests` from there. The function will panic when any test fails.\n\n///\n\n/// The passe...
Rust
stack_collapse/src/stack_collapse.rs
Atul9/measureme
8bd1782148a54a7fc81b5c9c79cd05796357eb04
use std::collections::HashMap; use std::time::{Duration, SystemTime}; use measureme::{Event, TimestampKind}; pub fn collapse_stacks<'a>(events: impl Iterator<Item = Event<'a>>, first_event_time: SystemTime, interval: u64) -> HashMap<String, usize> { let mut recorded_stacks = HashMap::<String, usize>::new(); ...
use std::collections::HashMap; use std::time::{Duration, SystemTime}; use measureme::{Event, TimestampKind}; pub fn collapse_stacks<'a>(events: impl Iterator<Item = Event<'a>>, first_event_time: SystemTime, interval: u64) -> HashMap<String, usize> { let mut recorded_stacks = HashMap::<String, usize>::new(); ...
#[cfg(test)] mod test { use std::collections::HashMap; use std::time::{Duration, SystemTime}; use measureme::{Event, TimestampKind}; #[test] fn basic_test() { let events = [ Event { event_kind: "Query".into(), label: "EventA".into(), ...
q!(previous_event.timestamp_kind, TimestampKind::Start); }, TimestampKind::Instant => { }, } } recorded_stacks }
function_block-function_prefixed
[ { "content": "pub fn read_file_header(\n\n bytes: &[u8],\n\n expected_magic: &[u8; 4]\n\n) -> Result<u32, Box<dyn Error>> {\n\n // The implementation here relies on FILE_HEADER_SIZE to have the value 8.\n\n // Let's make sure this assumption cannot be violated without being noticed.\n\n assert_eq...
Rust
dbcrossbarlib/src/drivers/postgres_shared/schema/schema_sql.rs
faradayio/schemaconv
eeb808354af7d58f1782927eaa9e754d59544011
use super::super::{ PgColumn, PgCreateTable, PgCreateType, PgCreateTypeDefinition, PgDataType, PgName, PgScalarDataType, PgSchema, }; use crate::schema::Srid; pub(crate) use schema_grammar::schema as parse; pub(self) enum Definition { Type(PgCreateType), Table(PgCreateTable), } pub(self) ...
use super::super::{ PgColumn, PgCreateTable, PgCreateType, PgCreateTypeDefinition, PgDataType, PgName, PgScalarDataType, PgSchema, }; use crate::schema::Srid; pub(crate) use schema_grammar::schema as parse; pub(self) enum Definition { Type(PgCreateType), Table(PgCreateTable), } pub(self) ...
peg::parser! { grammar schema_grammar() for str { pub(crate) rule schema() -> PgSchema = ws()? defs:definition() ** (ws()? ";" ws()?) (";" ws()?)? { let (types, tables) = group_definitions(defs); PgSchema { types, tables } } ...
n::Type(ty) => types.push(ty), Definition::Table(table) => tables.push(table), } } (types, tables) }
function_block-function_prefixed
[ { "content": "#[derive(Clone, Copy)]\n\nenum CreateTableType {\n\n /// Regular `CREATE TABLE`.\n\n Plain,\n\n /// `CREATE TABLE IF NOT EXISTS`.\n\n IfNotExists,\n\n /// `CREATE OR REPLACE TABLE`.\n\n OrReplace,\n\n}\n\n\n\nimpl fmt::Display for CreateTableType {\n\n fn fmt(&self, f: &mut fm...
Rust
vrp-core/src/construction/heuristics/context.rs
dooley/vrp
0007543128fcf6d261c1e08be4a006aaa90a331f
#[cfg(test)] #[path = "../../../tests/unit/construction/heuristics/context_test.rs"] mod context_test; use crate::construction::constraints::{TOTAL_DISTANCE_KEY, TOTAL_DURATION_KEY}; use crate::construction::heuristics::factories::*; use crate::models::common::Cost; use crate::models::problem::*; use crate::models::so...
#[cfg(test)] #[path = "../../../tests/unit/construction/heuristics/context_test.rs"] mod context_test; use crate::construction::constraints::{TOTAL_DISTANCE_KEY, TOTAL_DURATION_KEY}; use crate::construction::heuristics::factories::*; use crate::models::common::Cost; use crate::models::problem::*; use crate::models::so...
pub fn deep_copy(&self) -> Self { Self { required: self.required.clone(), ignored: self.ignored.clone(), unassigned: self.unassigned.clone(), locked: self.locked.clone(), routes: self.routes.iter().map(|rc| rc.deep_copy()).collect(), ...
routes: self.routes.iter().map(|rc| rc.route.deep_copy()).collect(), unassigned: self.unassigned.iter().map(|(job, code)| (job.clone(), *code)).collect(), extras, } }
function_block-function_prefix_line
[ { "content": "/// Creates initial solution using cheapest insertion\n\npub fn create_with_cheapest(problem: Arc<Problem>, random: Arc<dyn Random + Send + Sync>) -> InsertionContext {\n\n RecreateWithCheapest::default()\n\n .run(&mut create_default_refinement_ctx(problem.clone()), InsertionContext::new...
Rust
src/error.rs
ccakes/openid
6c411715b122136eb60ba2ee314aa64e9333eab1
use serde::Deserialize; use std::{error, fmt}; #[derive(Deserialize, Debug)] pub struct OAuth2Error { pub error: OAuth2ErrorCode, pub error_description: Option<String>, pub error_uri: Option<String>, } impl fmt::Display for OAuth2Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result...
use serde::Deserialize; use std::{error, fmt}; #[derive(Deserialize, Debug)] pub struct OAuth2Error { pub error: OAuth2ErrorCode, pub error_de
rror> { match *self { ClientError::Io(ref err) => Some(err), ClientError::Url(ref err) => Some(err), ClientError::Reqwest(ref err) => Some(err), ClientError::Json(ref err) => Some(err), ClientError::OAuth2(ref err) => Some(err), } ...
scription: Option<String>, pub error_uri: Option<String>, } impl fmt::Display for OAuth2Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{:?}", self.error)?; if let Some(ref description) = self.error_description { write!(f, ": {}", descripti...
random
[ { "content": "#[derive(Serialize, Deserialize, Debug)]\n\nstruct Failure {\n\n error: String,\n\n}\n\n\n\n#[get(\"/oauth2/authorization/oidc\")]\n\nasync fn authorize(oidc_client: web::Data<DiscoveredClient>) -> impl Responder {\n\n let auth_url = oidc_client.auth_url(&Options {\n\n scope: Some(\"e...
Rust
crate/loading/src/loading_state.rs
Lighty0410/autexousious
99d142d8fdbf2076f3fd929f61b8140d47cf6b86
use std::{fmt::Debug, marker::PhantomData, time::Duration}; use amethyst::{ core::Stopwatch, ecs::{Read, WorldExt}, GameData, State, StateData, Trans, }; use application_event::AppEvent; use application_state::AutexState; use application_ui::ThemeLoader; use asset_model::loaded::{AssetIdMappings, AssetType...
use std::{fmt::Debug, marker::PhantomData, time::Duration}; use amethyst::{ core::Stopwatch, ecs::{Read, WorldExt}, GameData, State, StateData, Trans, }; use application_event::AppEvent; use application_state::AutexState; use application_ui::ThemeLoader; use asset_model::loaded::{AssetIdMappings, AssetType...
} Err(()) } }) .is_ok(); asset_loading_complete }; if loading_statuses_complete && asset_load_stagees_complete { Trans::Switch(Box::new( self.next_state ...
if !warnings_reported { self.warnings_reported = true; warn!( "Asset `{}` has not completed loading. Load stage: `{:?}`", asset_slug, load_stage ); ...
if_condition
[ { "content": "/// Asserts that the `Trans` objects contained in the `Option`s, disregarding their `State`, are\n\n/// equal.\n\n///\n\n/// This `panic!`s with a readable error message when the assertion fails.\n\n///\n\n/// # Parameters\n\n///\n\n/// * `expected`: The `Option<Trans>` that is desired.\n\n/// * `...
Rust
boards/nucleo_f103/src/main.rs
tock/tock-stm32
2470101c423cdc935728b8d78dfb381d7aeb6fe7
#![no_std] #![no_main] #![feature(asm, const_fn, lang_items)] extern crate capsules; extern crate cortexm3; #[allow(unused_imports)] #[macro_use(debug, static_init)] extern crate kernel; extern crate stm32; extern crate stm32f1; use capsules::virtual_alarm::{MuxAlarm, VirtualMuxAlarm}; use kernel::hil; use kernel::hi...
#![no_std] #![no_main] #![feature(asm, const_fn, lang_items)] extern crate capsules; extern crate cortexm3; #[allow(unused_imports)] #[macro_use(debug, static_init)] extern crate kernel; extern crate stm32; extern crate stm32f1; use capsules::virtual_alarm::{MuxAlarm, VirtualMuxAlarm}; use kernel::hil; use kernel::hi...
&stm32::gpio::PB[5], &stm32::gpio::PB[4], &stm32::gpio::PB[10], &stm32::gpio::PA[8], &stm32::gpio::PA[9], &stm32::gpio::PC[7], &stm32::gpio::PB[6], &stm32::gpio::PA[7], &stm32::gpio::PA[6], ...
static_init!( [(&'static stm32::gpio::GPIOPin, capsules::button::GpioMode); 1], [( &stm32::gpio::PC[13], capsules::button::GpioMode::LowWhenPressed )] ); let button = static_init!( capsules::button::Button<'static, stm32::gpio::GPIOPin>, capsules::...
random
[ { "content": "pub fn syscfg() -> &'static Registers {\n\n unsafe { &*(BASE_ADDRESS as *const Registers) }\n\n}\n", "file_path": "chips/stm32f4/src/syscfg.rs", "rank": 0, "score": 137426.88586235885 }, { "content": "#[repr(C, packed)]\n\nstruct Registers {\n\n pub cr: [VolatileCell<u32>...
Rust
crates/codegen/src/domtree.rs
fe-lang/sonatina
bfdbac2f01d2dd85afd1d8633b7379cc53c48d2e
use std::collections::BTreeSet; use cranelift_entity::{packed_option::PackedOption, SecondaryMap}; use crate::ir::Block; use super::cfg::ControlFlowGraph; #[derive(Default, Debug)] pub struct DomTree { doms: SecondaryMap<Block, PackedOption<Block>>, rpo: Vec<Block>, } impl DomTree { pub fn new() -> S...
use std::collections::BTreeSet; use cranelift_entity::{packed_option::PackedOption, SecondaryMap}; use crate::ir::Block; use super::cfg::ControlFlowGraph; #[derive(Default, Debug)] pub struct DomTree { doms: SecondaryMap<Block, PackedOption<Block>>, rpo: Vec<Block>, } impl DomTree { pub fn new() -> S...
pub fn compute(&mut self, cfg: &ControlFlowGraph) { self.clear(); self.rpo = cfg.post_order().collect(); self.rpo.reverse(); let block_num = self.rpo.len(); if self.doms.capacity() < block_num { self.doms = SecondaryMap::with_capacity(block_num); } el...
pub fn dominates(&self, block1: Block, block2: Block) -> bool { if block1 == block2 { return true; } self.strictly_dominates(block1, block2) }
function_block-full_function
[ { "content": "pub fn simplify_insn(\n\n dfg: &mut DataFlowGraph,\n\n isa: &TargetIsa,\n\n insn: Insn,\n\n) -> Option<SimplifyResult> {\n\n if dfg.is_phi(insn) {\n\n return simplify_phi(dfg, dfg.insn_data(insn));\n\n }\n\n\n\n let mut ctx = SimplifyContext::new(dfg, isa);\n\n let expr...
Rust
src/simple_logger.rs
Co-Epi/app-backend-rust
b332afe7e92caf2703334c00dabf72fb4f279869
#[cfg(test)] use chrono::Local; #[cfg(not(test))] use chrono::Utc; use log::*; use std::fmt; use std::sync::{mpsc::Sender, Once}; static INIT: Once = Once::new(); pub static mut SENDER: Option<Sender<CoreLogMessageThreadSafe>> = None; #[allow(dead_code)] #[repr(u8)] #[derive(Debug, Clone, Copy)] pub enum CoreLogLeve...
#[cfg(test)] use chrono::Local; #[cfg(not(test))] use chrono::Utc; use log::*; use std::fmt; use std::sync::{mpsc::Sender, Once}; static INIT: Once = Once::new(); pub static mut SENDER: Option<Sender<CoreLogMessageThreadSafe>> = None; #[allow(dead_code)] #[repr(u8)] #[derive(Debug, Clone, Copy)] pub enum CoreLogLeve...
fn flush(&self) {} } #[cfg(not(test))] impl SimpleLogger { fn log_message_to_app(log_message: CoreLogMessageThreadSafe) { unsafe { if let Some(s) = &SENDER { s.send(log_message).expect("Couldn't send"); } else { println!("No SENDER!"); ...
let lmts = CoreLogMessageThreadSafe { level: lvl, text: arg_string, time: Utc::now().timestamp(), }; SimpleLogger::log_message_to_app(lmts); } }}; } #[cfg(test)] macro_rules! log_test { ($sel: ident, $record: ident) => { ...
random
[ { "content": "pub fn bootstrap(db_path: &str) -> Result<(), ServicesError> {\n\n info!(\"Bootstrapping with db path: {:?}\", db_path);\n\n\n\n let sqlite_path = format!(\"{}/db.sqlite\", db_path);\n\n debug!(\"Sqlite path: {:?}\", sqlite_path);\n\n\n\n let connection_res = Connection::open(sqlite_pa...
Rust
src/commands/mod.rs
tktcorporation/discord-speech-bot
9375a1c9e2ec78bad9234f9d4828787c083b1716
use std::{sync::Arc, time::Duration}; use serenity::{ async_trait, client::Context, framework::standard::{ macros::{command, group}, Args, CommandResult, }, http::Http, model::{channel::Message, prelude::ChannelId}, }; use songbird::{ input::{self}, Event, EventContext,...
use std::{sync::Arc, time::Duration}; use serenity::{ async_trait, client::Context, framework::standard::{ macros::{command, group}, Args, CommandResult, }, http::Http, model::{channel::Message, prelude::ChannelId}, }; use songbird::{ input::{self}, Event, EventContext,...
} let input = get_bgm_input().await.unwrap(); let guild = msg.guild(&ctx.cache).await.unwrap(); let guild_id = guild.id; let manager = songbird::get(ctx) .await .expect("Songbird Voice client placed in at initialisation.") .clone(); if let Some(handler_lock) = manager...
match Restartable::ytdl(url, true).await { Ok(source) => Ok(source.into()), Err(why) => { println!("Err get input source: {:?}", why); Err(why) } }
if_condition
[ { "content": "fn added_queue_embed(m: &mut serenity::builder::CreateMessage, np: songbird::input::Metadata) {\n\n m.embed(|e| {\n\n e.title(\"Added Queue\");\n\n e.field(\"Title\", np.title.clone().unwrap(), false);\n\n // if let Some(t) = np.source_url {\n\n // e.field(\"URL\...
Rust
src/actor/im.rs
rconan/dos-actors
356228a3fbe4430671ec1225952789d620914ec9
use super::{Task, Update}; use crate::{io::*, ActorError, ActorOutputBuilder, Result, UniqueIdentifier, Who}; use async_trait::async_trait; use futures::future::join_all; use std::{fmt, ops::DerefMut, sync::Arc}; use tokio::sync::Mutex; #[derive(Debug, Hash)] #[doc(hidden)] pub struct PlainIO { pub name: String, ...
use super::{Task, Update}; use crate::{io::*, ActorError, ActorOutputBuilder, Result, UniqueIdentifier, Who}; use async_trait::async_trait; use futures::future::join_all; use std::{fmt, ops::DerefMut, sync::Arc}; use tokio::sync::Mutex; #[derive(Debug, Hash)] #[doc(hidden)] pub struct PlainIO { pub name: String, ...
fn check_inputs(&self) -> Result<()> { match self.inputs { Some(_) if NI == 0 => Err(ActorError::SomeInputsZeroRate(Who::who(self))), None if NI > 0 => Err(ActorError::NoInputsPositiveRate(Who::who(self))), _ => Ok(()), } } fn check_outputs(&self) -> Resu...
async fn async_run(&mut self) -> Result<()> { match (self.inputs.as_ref(), self.outputs.as_ref()) { (Some(_), Some(_)) => { if NO >= NI { loop { for _ in 0..NO / NI { self.collect().await?; ...
function_block-full_function
[ { "content": "// Unique hash for a pair of input/output\n\nfn hasio<CO, const NO: usize, const NI: usize>(output_actor: &mut Actor<CO, NI, NO>) -> u64\n\nwhere\n\n CO: Update + Send,\n\n{\n\n let mut hasher = DefaultHasher::new();\n\n output_actor.who().hash(&mut hasher);\n\n let output = output_act...
Rust
src/optimizer/core/src/code_move.rs
Dkendal/qwik
ff632b1cc25229d47d084a26a59dcdad936e1adc
use crate::collector::{new_ident_from_id, GlobalCollect, Id, ImportKind}; use crate::parse::{emit_source_code, HookAnalysis, PathData, TransformModule, TransformOutput}; use crate::transform::{create_internal_call, create_synthetic_wildcard_import}; use crate::words::*; use std::collections::HashMap; use std::path::Pa...
use crate::collector::{new_ident_from_id, GlobalCollect, Id, ImportKind}; use crate::parse::{emit_source_code, HookAnalysis, PathData, TransformModule, TransformOutput}; use crate::transform::{create_internal_call, create_synthetic_wildcard_import}; use crate::words::*; use std::collections::HashMap; use std::path::Pa...
, }, ))); } else if let Some(export) = global.exports.get(id) { let imported = if export == &id.0 { None } else { Some(ast::Ident::new(export.clone(), DUMMY_SP)) }; module .body ...
obal.imports.len() + global.exports.len(); let mut module = ast::Module { span: DUMMY_SP, body: Vec::with_capacity(max_cap), shebang: None, }; module.body.push(create_synthetic_wildcard_import( &QWIK_INTERNAL, &BUILDER_IO_QWIK, )); for id in local_ident...
function_block-random_span
[ { "content": "pub fn parse_path(src: &str) -> Result<PathData, Error> {\n\n let path = Path::new(src);\n\n let file_stem = path\n\n .file_stem()\n\n .and_then(OsStr::to_str)\n\n .map(Into::into)\n\n .with_context(|| format!(\"Computing file stem for {}\", path.to_string_lossy()...
Rust
clearing-house-app/ch-lib/src/model/ids/mod.rs
LaudateCorpus1/ids-clearing-house-service
6e5f8ecdee5bd8a17f0cc8864a9e92520126cb58
use chrono::prelude::*; use std::fmt; use std::fmt::{Display, Formatter, Result}; pub mod message; pub mod request; pub mod response; #[cfg(test)] mod tests; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct InfoModelComplexId { #[serde(rename = "@id", alias="id", skip_serializing_if = "O...
use chrono::prelude::*; use std::fmt; use std::fmt::{Display, Formatter, Result}; pub mod message; pub mod request; pub mod response; #[cfg(test)] mod tests; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct InfoModelComplexId { #[serde(rename = "@id", alias="id", skip_serializing_if = "O...
} impl Display for InfoModelTimeStamp { fn fmt(&self, f: &mut Formatter<'_>) -> Result { match serde_json::to_string(&self) { Ok(result) => write!(f, "{}", result), Err(e) => { error!("could not convert DateTimeStamp to json: {}", e); write!(f, "") ...
ult() -> Self { InfoModelTimeStamp { format: Some("http://www.w3.org/2001/XMLSchema#dateTimeStamp".to_string()), value: Local::now() } }
function_block-function_prefixed
[ { "content": "fn insert_test_doc_type_into_keyring(token: &String, pid: &String, dt_id: &String) -> Result<bool>{\n\n let client = Client::new();\n\n let dt_url = format!(\"http://localhost:8002{}\", ROCKET_DOC_TYPE_API);\n\n\n\n let json_data = create_dt_json(dt_id, pid);\n\n\n\n println!(\"json_da...
Rust
src/oid.rs
ximon18/bcder
2bcdcbba0b7b21e8fbbde196d6405d40b9f9388d
use std::{fmt, hash, io}; use bytes::Bytes; use crate::{decode, encode}; use crate::decode::Source; use crate::mode::Mode; use crate::tag::Tag; #[derive(Clone, Debug)] pub struct Oid<T: AsRef<[u8]>=Bytes>(pub T); pub type ConstOid = Oid<&'static [u8]>; impl Oid<Bytes> { pub fn skip_in<...
use std::{fmt, hash, io}; use bytes::Bytes; use crate::{decode, encode}; use crate::decode::Source; use crate::mode::Mode; use crate::tag::Tag; #[derive(Clone, Debug)] pub struct Oid<T: AsRef<[u8]>=Bytes>(pub T); pub type ConstOid = Oid<&'static [u8]>; impl Oid<Bytes> { pub fn skip_in<...
} impl<T: AsRef<[u8]>> encode::PrimitiveContent for Oid<T> { const TAG: Tag = Tag::OID; fn encoded_len(&self, _: Mode) -> usize { self.0.as_ref().len() } fn write_encoded<W: io::Write>( &self, _: Mode, target: &mut W ) -> Result<(), io::Error> { target.wri...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut components = self.iter(); write!(f, "{}", components.next().unwrap().to_u32().unwrap())?; for component in components { if let Some(val) = component.to_u32() { ...
function_block-full_function
[]
Rust
dasp_slice/src/lib.rs
poww10s/dasp
769b02d3ddb78ce8f5aae68031cd05ec377b45c3
#![cfg_attr(not(feature = "std"), no_std)] use dasp_frame::Frame; use dasp_sample::Sample; #[cfg(feature = "boxed")] pub use boxed::{ from_boxed_frame_slice, from_boxed_sample_slice, to_boxed_frame_slice, to_boxed_sample_slice, DuplexBoxedFrameSlice, DuplexBoxedSampleSlice, DuplexBoxedSlice, FromBoxedFrameS...
#![cfg_attr(not(feature = "std"), no_std)] use dasp_frame::Frame; use dasp_sample::Sample; #[cfg(feature = "boxed")] pub use boxed::{ from_boxed_frame_slice, from_boxed_sample_slice, to_boxed_frame_slice, to_boxed_sample_slice, DuplexBoxedFrameSlice, DuplexBoxedSampleSlice, DuplexBoxedSlice, FromBoxedFrameS...
#[inline] pub fn equilibrium<F>(a: &mut [F]) where F: Frame, { map_in_place(a, |_| F::EQUILIBRIUM) } #[inline] pub fn zip_map_in_place<FA, FB, M>(a: &mut [FA], b: &[FB], zip_map: M) where FA: Frame, FB: Frame, M: FnMut(FA, FB) -> FA, { assert_eq!(a.len(), b.len()); unsafe { ...
pub fn map_in_place<F, M>(a: &mut [F], mut map: M) where M: FnMut(F) -> F, F: Frame, { for f in a { *f = map(*f); } }
function_block-full_function
[ { "content": "/// For converting to and from a mutable slice of `Frame`s.\n\npub trait DuplexFrameSliceMut<'a, F>: FromFrameSliceMut<'a, F> + ToFrameSliceMut<'a, F>\n\nwhere\n\n F: Frame,\n\n{\n\n}\n\n\n\nimpl<'a, F> FromFrameSlice<'a, F> for &'a [F]\n\nwhere\n\n F: Frame,\n\n{\n\n #[inline]\n\n fn ...
Rust
src/canvas/widgets/battery_display.rs
andys8/bottom
554505b221ae385769f6b5534bf03d5f0f3e8a11
use std::cmp::max; use crate::{ app::App, canvas::{drawing_utils::calculate_basic_use_bars, Painter}, constants::*, }; use tui::{ backend::Backend, layout::{Constraint, Rect}, terminal::Frame, widgets::{Block, Borders, Paragraph, Row, Table, Tabs, Text}, }; pub trait BatteryDisplayWidget ...
use std::cmp::max; use crate::{ app::App, canvas::{drawing_utils::calculate_basic_use_bars, Painter}, constants::*, }; use tui::{ backend::Backend, layout::{Constraint, Rect}, terminal::Frame, widgets::{Block, Borders, Paragraph, Row, Table, Tabs, Text}, }; pub trait BatteryDisplayWidget ...
, ["Health %", &battery_details.health], ]; let battery_rows = battery_items.iter().enumerate().map(|(itx, item)| { Row::StyledData( item.iter(), if itx == 0 { let colour_...
.border_style(self.colours.highlighted_border_style) } else { Block::default().borders(Borders::NONE) }; if let Some(battery_details) = app_state .canvas_data .battery_data .get(battery_widget_state.currently_sele...
random
[ { "content": "fn update_final_process_list(app: &mut App, widget_id: u64) {\n\n use utils::gen_util::get_exact_byte_values;\n\n let is_invalid_or_blank = match app.proc_state.widget_states.get(&widget_id) {\n\n Some(process_state) => process_state\n\n .process_search_state\n\n ...
Rust
Chapter09/feruscore/src/bin/fuzz_target.rs
PacktPublishing/Hands-On-Concurrency-with-Rust
0540a7c04584e5dbd482aa498b045c6516bd62c5
extern crate byteorder; extern crate feruscore; use byteorder::{BigEndian, ReadBytesExt}; use feruscore::individual::*; use feruscore::instruction::*; use feruscore::mars::*; use std::io::{self, Cursor, Read}; #[derive(Debug)] struct Config { pub rounds: u16, pub core_size: u16, pub cycles: u16, pub p...
extern crate byteorder; extern crate feruscore; use byteorder::{BigEndian, ReadBytesExt}; use feruscore::individual::*; use feruscore::instruction::*; use feruscore::mars::*; use std::io::{self, Cursor, Read}; #[derive(Debug)] struct Config { pub rounds: u16, pub core_size: u16, pub cycles: u16, pub p...
fn adjust_pos(core_size: u16, mut pos: u16, space: u16) -> u16 { pos %= core_size; if (pos + space) > core_size { let past = (pos + space) - core_size; pos - past } else { pos } } fn mk_individual( rdr: &mut Cursor<Vec<u8>>, ...
s, max_warrior_length, left_chromosome_size, right_chromosome_size, left, right, left_pos, right_pos, }) }
function_block-function_prefixed
[ { "content": "pub fn dwarf(chromosome_sz: u16) -> Individual {\n\n let mut chromosome = vec![\n\n // ADD.AB #4, $3\n\n Some(Instruction {\n\n opcode: OpCode::Add,\n\n modifier: Modifier::AB,\n\n a_mode: Mode::Immediate,\n\n a_offset: Offset { offset...
Rust
src/renderer/shadow/point.rs
MGlolenstine/rg3d
e02b00577c39aef4ab87adc4b06ca0f6bedb02f1
use crate::renderer::shadow::cascade_size; use crate::{ core::{ algebra::{Matrix4, Point3, Vector3}, color::Color, math::{frustum::Frustum, Rect}, scope_profile, }, renderer::framework::{ error::FrameworkError, framebuffer::{Attachment, AttachmentKind, CullFac...
use crate::renderer::shadow::cascade_size; use crate::{ core::{ algebra::{Matrix4, Point3, Vector3}, color::Color, math::{frustum::Frustum, Rect}, scope_profile, }, renderer::framework::{ error::FrameworkError, framebuffer::{Attachment, AttachmentKind, CullFac...
, MinificationFilter::Nearest, MagnificationFilter::Nearest, 1, None, )?; texture .bind_mut(state, 0) .set_minification_filter(MinificationFilter::Nearest) ...
match precision { ShadowMapPrecision::Full => PixelKind::D32F, ShadowMapPrecision::Half => PixelKind::D16, }
if_condition
[ { "content": "fn image_3d_size_bytes(pixel_kind: PixelKind, width: usize, height: usize, depth: usize) -> usize {\n\n let pixel_count = width * height * depth;\n\n match pixel_kind {\n\n PixelKind::RGBA32F => 16 * pixel_count,\n\n PixelKind::RGBA16 | PixelKind::RGBA16F => 8 * pixel_count,\n\...
Rust
src/session.rs
Nokkasiili/warp-diesel-ructe-sample
0f4e15bf1d79e4d668021105f2b9c165667671f8
use crate::models::User; use diesel::pg::PgConnection; use diesel::prelude::*; use diesel::r2d2::{ConnectionManager, Pool, PooledConnection}; use log::{debug, error}; use rand::distributions::Alphanumeric; use rand::thread_rng; use rand::Rng; use warp::filters::{cookie, BoxedFilter}; use warp::{self, Filter}; type Poo...
use crate::models::User; use diesel::pg::PgConnection; use diesel::prelude::*; use diesel::r2d2::{ConnectionManager, Pool, PooledConnection}; use log::{debug, error}; use rand::distributions::Alphanumeric; use rand::thread_rng; use rand::Rng; use warp::filters::{cookie, BoxedFilter}; use warp::{self, Filter}; type Poo...
pub fn create_session_filter(db_url: &str) -> BoxedFilter<(Session,)> { let pool = pg_pool(db_url); warp::any() .and(cookie::optional("EXAUTH")) .and_then(move |key: Option<String>| { let pool = pool.clone(); async move { let key = key.as_ref().map(|s| &...
fn random_key(len: usize) -> String { thread_rng() .sample_iter(&Alphanumeric) .map(char::from) .take(len) .collect() }
function_block-full_function
[]
Rust
qkernel/src/guestfdnotifier.rs
qingqu/Quark
10f1c6e509d9aa047dbad066ca3f54aa322c055d
use alloc::collections::btree_map::BTreeMap; use ::qlib::mutex::*; use core::ops::Deref; use super::Kernel::HostSpace; use super::kernel::waiter::*; use super::fs::host::hostinodeop::*; use super::qlib::common::*; use super::qlib::linux_def::*; use super::qlib::singleton::*; use super::SHARESPACE; use super::IOURING...
use alloc::collections::btree_map::BTreeMap; use ::qlib::mutex::*; use core::ops::Deref; use super::Kernel::HostSpace; use super::kernel::waiter::*; use super::fs::host::hostinodeop::*; use super::qlib::common::*; use super::qlib::linux_def::*; use super::qlib::singleton::*; use super::SHARESPACE; use super::IOURING...
(&self, fd: i32) -> Result<()> { let op; let mask = { let mut n = self.lock(); let fi = match n.fdMap.get_mut(&fd) { None => { return Ok(()) } Some(fi) => fi, }; let mask = fi.queue.Event...
else { if mask | fi.mask == fi.mask { return Ok(()) } op = LibcConst::EPOLL_CTL_MOD; } } fi.mask = mask; mask }; IOURING.EpollCtl(epollfd, fd, op as i32, mask as u3...
random
[ { "content": "pub fn UpdateFD(_fd: i32) -> Result<()> { return Err(Error::None) }\n\n\n", "file_path": "qvisor/src/guestfdnotifier.rs", "rank": 0, "score": 650523.5117746135 }, { "content": "pub fn FdNotify(fd: i32, mask: EventMask) {\n\n SHARE_SPACE.AQHostInputCall(&HostInputMsg::FdNotif...
Rust
src/issue.rs
caranatar/tweec
901ade8593224260aeda813a41d347af8bde3c46
use crate::Config; use crate::StoryFiles; use crate::StoryResult; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::files::Files; use std::cmp::Ordering; use std::io::Write; use std::ops::Range; use termcolor::{Color, ColorSpec, StandardStream, WriteColor}; use tweep::FullContext; use t...
use crate::Config; use crate::StoryFiles; use crate::StoryResult; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::files::Files; use std::cmp::Ordering; use std::io::Write; use std::ops::Range; use termcolor::{Color, ColorSpec, StandardStream, WriteColor}; use tweep::FullContext; use t...
candidates.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal)); candidates.into_iter().map(|(_, pv)| pv).collect() } pub fn filter_and_sort_issues( story_result: &StoryResult, mut warnings: Vec<Warning>, config: &Config, ) -> (Vec<Issue>, bool) { let mut issues = Vec::new(); l...
let mut candidates: Vec<(f64, String)> = possible_values .into_iter() .map(|pv| (strsim::jaro_winkler(v, pv.as_ref()), pv.as_ref().to_owned())) .filter(|(confidence, _)| *confidence > 0.8) .collect();
assignment_statement
[ { "content": "/// Gets the contents of a `TwinePassage`\n\npub fn get_content(twine: &TwinePassage) -> &str {\n\n twine.content.content.as_str()\n\n}\n", "file_path": "src/utils.rs", "rank": 0, "score": 91216.73563708425 }, { "content": "fn default_name() -> String {\n\n \"Untitled Sto...
Rust
src/i18n.rs
lislis/www.rust-lang.org
44e361ec96c72ff16f1716c09b9b83bc310bea10
use handlebars::{ Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderError, Renderable, }; use handlebars::template::{Parameter, TemplateElement}; use rocket::http::RawStr; use rocket::request::FromParam; use serde_json::Value as Json; use std::collections::HashMap; use std::fs:...
use handlebars::{ Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderError, Renderable, }; use handlebars::template::{Parameter, TemplateElement}; use rocket::http::RawStr; use rocket::request::FromParam; use serde_json::Value as Json; use std::collections::HashMap; use std::fs:...
pub fn lookup_no_english( &self, lang: &str, text_id: &str, args: Option<&HashMap<&str, FluentValue>>, ) -> Option<String> { for l in self.fallbacks.get(lang).expect("language not found") { if let Some(val) = self.lookup_single_language(l, text_id, args...
args: Option<&HashMap<&str, FluentValue>>, ) -> String { for l in self.fallbacks.get(lang).expect("language not found") { if let Some(val) = self.lookup_single_language(l, text_id, args) { return val; } } if lang != "en-US" { if let Some(va...
function_block-function_prefix_line
[ { "content": "fn baseurl(lang: &str) -> String {\n\n if lang == \"en-US\" {\n\n String::new()\n\n } else {\n\n format!(\"/{}\", lang)\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 1, "score": 124408.23230299319 }, { "content": "fn kind_to_str(kind: TeamKind) -...
Rust
base/src/windows/win/ioctl.rs
0xgpapad/crosvm
37f02e9b1f9c966b79719c61e6eebdf5faee88dc
use std::{mem::size_of, os::raw::*, ptr::null_mut}; use crate::descriptor::AsRawDescriptor; pub use winapi::um::winioctl::{CTL_CODE, FILE_ANY_ACCESS, METHOD_BUFFERED}; use winapi::um::{errhandlingapi::GetLastError, ioapiset::DeviceIoControl}; #[macro_export] macro_rules! device_io_control_expr { ...
use std::{mem::size_of, os::raw::*, ptr::null_mut}; use crate::descriptor::AsRawDescriptor; pub use winapi::um::winioctl::{CTL_CODE, FILE_ANY_ACCESS, METHOD_BUFFERED}; use winapi::um::{errhandlingapi::GetLastError, ioapiset::DeviceIoControl}; #[macro_export] macro_rules! device_io_control_expr { ...
pub unsafe fn ioctl_with_ref<T>(handle: &dyn AsRawDescriptor, nr: IoctlNr, arg: &T) -> c_int { ioctl_with_ptr(handle, nr, arg) } pub unsafe fn ioctl_with_mut_ref<T>( handle: &dyn AsRawDescriptor, nr: IoctlNr, arg: &mut T, ) -> c_int { ioctl_with_mut_ptr(handle, nr, arg) } pub unsafe fn ioctl_wit...
pub unsafe fn ioctl_with_val(handle: &dyn AsRawDescriptor, nr: IoctlNr, mut arg: c_ulong) -> c_int { let mut byte_ret: c_ulong = 0; let ret = DeviceIoControl( handle.as_raw_descriptor(), nr, &mut arg as *mut c_ulong as *mut c_void, size_of::<c_ulong>() as u32, null_mut()...
function_block-full_function
[]
Rust
staked-relayer/src/oracle.rs
sander2/polkabtc-clients
395798cd9c0d1acd5a62b3586df89e49edf2f2e0
use super::Error; use crate::utils; use log::info; use runtime::{ ErrorCode, ExchangeRateOraclePallet, SecurityPallet, StakedRelayerPallet, TimestampPallet, }; use std::sync::Arc; use std::time::Duration; pub async fn report_offline_oracle< P: TimestampPallet + ExchangeRateOraclePallet + StakedRelayerPallet + ...
use super::Error; use crate::utils; use log::info; use runtime::{ ErrorCode, ExchangeRateOraclePallet, SecurityPallet, StakedRelayerPallet, TimestampPallet, }; use std::sync::Arc; use std::time::Duration; pub async fn report_offline_oracle< P: TimestampPallet + ExchangeRateOraclePallet + StakedRelayerPallet + ...
#[tokio::test] async fn test_report_oracle_offline_not_reported() { let mut parachain = MockProvider::default(); parachain .expect_get_active_stake() .once() .returning(|| Ok(MINIMUM_STAKE)); parachain .expect_get_exchange_rate_...
OracleMonitor::new(Arc::new(parachain)) .is_offline() .await .unwrap(), false ); }
function_block-function_prefix_line
[ { "content": "/// Take the `percentage` of an `amount`\n\nfn calculate_for(amount: u128, percentage: FixedU128) -> Result<u128, Error> {\n\n // we add 0.5 before we do the final integer division to round the result we return.\n\n // note that unwrapping is safe because we use a constant\n\n let roundin...
Rust
check/src/substitution.rs
hwchen/gluon
b7c88ed2bc283508d1f8100334066a660bbddce8
use std::cell::RefCell; use std::default::Default; use std::fmt; use union_find::{QuickFindUf, Union, UnionByRank, UnionFind, UnionResult}; use base::fixed::{FixedMap, FixedVec}; use base::types; use base::types::{ArcType, Type, Walker}; #[derive(Debug, PartialEq)] pub enum Error<T> { Occurs(T, T), } impl<T> fm...
use std::cell::RefCell; use std::default::Default; use std::fmt; use union_find::{QuickFindUf, Union, UnionByRank, UnionFind, UnionResult}; use base::fixed::{FixedMap, FixedVec}; use base::types; use base::types::{ArcType, Type, Walker}; #[derive(Debug, PartialEq)] pub enum Error<T> { Occurs(T, T), } impl<T> fm...
#[derive(Debug)] struct UnionByLevel { rank: UnionByRank, level: u32, } impl Default for UnionByLevel { fn default() -> UnionByLevel { UnionByLevel { rank: UnionByRank::default(), level: ::std::u32::MAX, } } } impl Union for UnionByLevel { #[inline] fn...
impl<'a, 't, T> Walker<'t, T> for Occurs<'a, T> where T: Substitutable, { fn walk(&mut self, typ: &'t T) { if self.occurs { return; } let typ = self.subs.real(typ); if let Some(other) = typ.get_var() { if self.var.ge...
function_block-function_prefix_line
[ { "content": "pub fn walk_type_mut<I, T, F: ?Sized>(typ: &mut T, f: &mut F)\n\nwhere\n\n F: WalkerMut<T>,\n\n T: DerefMut<Target = Type<I, T>>,\n\n{\n\n match **typ {\n\n Type::Forall(_, ref mut typ, _) => f.walk_mut(typ),\n\n Type::Function(_, ref mut arg, ref mut ret) => {\n\n ...
Rust
pyd4/src/builder.rs
Clinical-Genomics/d4-format
b36b441f652b1caa3d8ce49b880a0dc853547de3
use d4::{Chrom, D4FileBuilder, D4FileWriter, D4FileWriterExt, Dictionary, ptab::PTablePartitionWriter, stab::SecondaryTablePartWriter}; use pyo3::{exceptions::PyKeyError, prelude::*}; use rayon::prelude::*; #[pyclass(subclass)] pub struct D4Builder { genome_size: Vec<(String, usize)>, dictionary: Dictionary, ...
use d4::{Chrom, D4FileBuilder, D4FileWriter, D4FileWriterExt, Dictionary, ptab::PTablePartitionWriter, stab::SecondaryTablePartWriter}; use pyo3::{exceptions::PyKeyError, prelude::*}; use rayon::prelude::*; #[pyclass(subclass)] pub struct D4Builder { genome_size: Vec<(String, usize)>, dictionary: Dictionary, ...
fn set_compression(&mut self, level: i32) -> PyResult<()> { if level < 0 { self.compression = None; } else { self.compression = Some(level as u32); } Ok(()) } fn into_writer(&mut self, path: &str) -> PyResult<D4Writer> { let mut writer : D4Fil...
fn dup_seqs(&mut self, that: &super::D4File) -> PyResult<()> { let reader = that.open()?.into_local_reader()?; self.genome_size = reader.header() .chrom_list() .iter() .map(|chrom| (chrom.name.clone(), chrom.size)) .collect(); Ok(()) }
function_block-full_function
[ { "content": "#[no_mangle]\n\npub fn d4_task_range(task: *const d4_task_part_t, left_buf: *mut u32, right_buf: *mut u32) -> i32 {\n\n if null() == task {\n\n return set_einval(-1);\n\n }\n\n let handle: &TaskHandle = unsafe { std::mem::transmute(task) };\n\n let (_, l, r) = handle.range();\n\...
Rust
src/main.rs
elaineo/token-rs
cf7e6647b0103f9fb761673547b9db6a92f5482d
extern crate serde; extern crate serde_json; extern crate gethrpc; extern crate shapeshift; extern crate emerald_core as emerald; #[macro_use] extern crate nickel; #[macro_use] extern crate serde_derive; extern crate bincode; extern crate leveldb; extern crate hyper; extern crate time; extern crate hex; use bincode...
extern crate serde; extern crate serde_json; extern crate gethrpc; extern crate shapeshift; extern crate emerald_core as emerald; #[macro_use] extern crate nickel; #[macro_use] extern crate serde_derive; extern crate bincode; extern crate leveldb; extern crate hyper; extern crate time; extern crate hex; use bincode...
"./tokendb"; const ICO_MACHINE: &'static str = "0x2f846034a256f51ae51249b61f4c92bcf4b0a3d8"; const RELAY_ACCOUNT: &'static str = "0xE4cf8aE5E9Cdc78d0d339877f05CD190Cc6f4d54"; const PK: &'static str = "beaed1cc16e409c72918ed71fdb11df055a3f787534d7a6946770f7e18697496"; fn enable_cors<'mw>(_req: &mut Request, ...
Headers, AccessControlAllowMethods, ContentType}; use hyper::method::Method; use std::thread; mod raw_body; mod token_db; use raw_body::*; use token_db::{TokenDB, ShapeshiftDeposit}; use gethrpc::{GethRPCClient}; use shapeshift::{ShapeshiftClient, ShapeshiftStatus}; use emerald::util::{to_arr, align_bytes}; use eme...
random
[ { "content": "#[derive(Serialize, Deserialize)]\n\nstruct RPCRequest {\n\n jsonrpc: String,\n\n method: String,\n\n params: Vec<String>,\n\n id: usize,\n\n}\n\n\n", "file_path": "shapeshift/src/lib.rs", "rank": 0, "score": 36351.4935534281 }, { "content": "#[derive(Serialize, Des...
Rust
third_party/rust_crates/ask2patch/memchr/src/memmem/x86/avx.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
#[cfg(not(feature = "std"))] pub(crate) use self::nostd::Forward; #[cfg(feature = "std")] pub(crate) use self::std::Forward; #[cfg(feature = "std")] mod std { use core::arch::x86_64::{__m128i, __m256i}; use crate::memmem::{genericsimd, NeedleInfo}; #[derive(Clone, Copy, Debug)] pub(crate) s...
#[cfg(not(feature = "std"))] pub(crate) use self::nostd::Forward; #[cfg(feature = "std")] pub(crate) use self::std::Forward; #[cfg(feature = "std")] mod std { use core::arch::x86_64::{__m128i, __m256i}; use crate::memmem::{genericsimd, NeedleInfo}; #[derive(Clone, Copy, Debug)] pub(crate) s...
t.haystack.len() >= fwd.min_haystack_len() }) } } }
let fwd = match super::Forward::new(&t.ninfo, &t.needle) { None => return false, Some(fwd) => fwd, };
assignment_statement
[]
Rust
hypervisor/src/arch/emulator/mod.rs
vineethrp/cloud-hypervisor
d370ea585be9829b5bdb6c8234d6b7d2ca9740be
extern crate thiserror; use core::fmt::Debug; use std::fmt::{self, Display}; use thiserror::Error; #[derive(Clone, Copy, Error, Debug)] pub struct Exception<T: Debug> { vector: T, ip: u64, error: Option<u32>, payload: Option<u64>, } impl<T: Debug> Display for Exception<T> { fn fmt(&self, f: &mu...
extern crate thiserror; use core::fmt::Debug; use std::fmt::{self, Display}; use thiserror::Error; #[derive(Clone, Copy, Error, Debug)] pub struct Except
CPU Mode: {0}")] UnsupportedCpuMode(#[source] anyhow::Error), #[error("Invalid instruction operand: {0}")] InvalidOperand(#[source] anyhow::Error), } #[derive(Error, Debug)] pub enum EmulationError<T: Debug> { #[error("Unsupported instruction: {0}")] UnsupportedInstruction(#[source] anyhow::Error)...
ion<T: Debug> { vector: T, ip: u64, error: Option<u32>, payload: Option<u64>, } impl<T: Debug> Display for Exception<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Exception {:?} at IP {:#x}", self.vector, self.ip) } } #[derive(Error, Debug)] pub enum PlatformEr...
random
[ { "content": "#[derive(Serialize, Deserialize)]\n\n#[serde(remote = \"GuestAddress\")]\n\nstruct GuestAddressDef(pub u64);\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n/// A virtio queue's parameters.\n\npub struct Queue {\n\n /// The maximal size in elements offered by the device\n\n pub max_size: ...
Rust
core/lib/src/form/name/view.rs
GHGHGHKO/Rocket
ae0ccf43f11be5c00bb9cd49996c8bb06a7e1651
use crate::form::name::*; #[derive(Copy, Clone)] pub struct NameView<'v> { name: &'v Name, start: usize, end: usize, } impl<'v> NameView<'v> { pub fn new<N: Into<&'v Name>>(name: N) -> Self { let mut view = NameView { name: name.into(...
use crate::form::name::*; #[derive(Copy, Clone)] pub struct NameView<'v> { name: &'v Name, start: usize, end: usize, } impl<'v> NameView<'v> { pub fn new<N: Into<&'v Name>>(name: N) -> Self { let mut view = NameView { name: name.into(...
pub fn source(&self) -> &'v Name { self.name } fn is_at_last(&self) -> bool { self.end == self.name.len() } pub(crate) fn exhausted(&self) -> bool { self.start == self...
pub fn parent(&self) -> Option<&'v Name> { if self.start > 0 { Some(&self.name[..self.start]) } else { None } }
function_block-full_function
[]
Rust
src/check/monad/error.rs
ice1000/narc-rs
ed0a4537051ee0b5c906f1366e473db855b2bc45
use std::fmt::{Display, Error as FmtError, Formatter}; use voile_util::{ level::Level, loc::{Ident, Loc, ToLoc}, meta::MI, }; use crate::{ check::pats::Blocked, syntax::{ abs::{Abs, AbsCopat}, core::{Elim, Term, Val}, }, }; #[derive(Debug)] pub enum TCE { Textual(String), ...
use std::fmt::{Display, Error as FmtError, Formatter}; use voile_util::{ level::Level, loc::{Ident, Loc, ToLoc}, meta::MI, }; use crate::{ check::pats::Blocked, syntax::{ abs::{Abs, AbsCopat}, core::{Elim, Term, Val}, }, }; #[derive(Debug)] pub enum TCE { Textual(String), ...
}
n {}.", expr, expected_to_be_small, big ), TCE::DifferentFieldCodata(loc, field, codata) => write!( f, "Codata `{}` does not have field `{}` (at {}).", codata, field, loc ), TCE::DifferentTerm(a, b) => write!...
function_block-function_prefixed
[ { "content": "/// Application on a definition.\n\n/// [Agda](https://hackage.haskell.org/package/Agda-2.6.0.1/docs/src/Agda.TypeChecking.Substitute.html#defApp).\n\npub fn def_app(f: GI, id: Ident, mut a: Vec<Elim>, mut args: Vec<Elim>) -> Term {\n\n /* // Does not support projection using application syntax...
Rust
src/tree/tree_options.rs
drahnr/broot
546890a5557e4ab289e220f1303457048f843a96
use { super::Sort, crate::pattern::*, clap::ArgMatches, }; #[derive(Debug, Clone)] pub struct TreeOptions { pub show_hidden: bool, pub only_folders: bool, pub show_counts: bool, pub show_dates: bool, pub show_sizes: bool, pub show_git_file_info: bool, pub show_root_fs: b...
use { super::Sort, crate::pattern::*, clap::ArgMatches, }; #[derive(Debug, Clone)] pub struct TreeOptions { pub show_hidden: bool, pub only_folders: bool, pub show_counts: bool, pub show_dates: bool, pub show_sizes: bool, pub show_git_file_info: bool, pub show_root_fs: b...
} impl Default for TreeOptions { fn default() -> Self { Self { show_hidden: false, only_folders: false, show_counts: false, show_dates: false, show_sizes: false, show_git_file_info: false, show_root_fs: false, ...
rue; self.show_hidden = true; } if cli_args.is_present("hidden") { self.show_hidden = true; } else if cli_args.is_present("no-hidden") { self.show_hidden = false; } if cli_args.is_present("dates") { self.show_dates = true; }...
function_block-function_prefixed
[ { "content": "/// find the list of optional features which are enabled\n\npub fn list() -> Vec<(&'static str, &'static str)> {\n\n #[allow(unused_mut)]\n\n let mut features: Vec<(&'static str, &'static str)> = Vec::new();\n\n\n\n #[cfg(not(any(target_family=\"windows\",target_os=\"android\")))]\n\n ...
Rust
src/index/id_map.rs
justinaustin/faiss-rs
1a647963490ade8095877ac60827b0191a356cbc
use error::Result; use faiss_sys::*; use index::{ AssignSearchResult, ConcurrentIndex, CpuIndex, FromInnerPtr, Idx, Index, NativeIndex, RangeSearchResult, SearchResult, }; use selector::IdSelector; use std::marker::PhantomData; use std::mem; use std::ptr; #[derive(Debug)] pub struct IdMap<I> { inner: *m...
use error::Result; use faiss_sys::*; use index::{ AssignSearchResult, ConcurrentIndex, CpuIndex, FromInnerPtr, Idx, Index, NativeIndex, RangeSearchResult, SearchResult, }; use selector::IdSelector; use std::marker::PhantomData; use std::mem; use std::ptr; #[derive(Debug)] pub struct IdMap<I> { inner: *m...
} impl<I> ConcurrentIndex for IdMap<I> where I: ConcurrentIndex, { fn assign(&self, query: &[f32], k: usize) -> Result<AssignSearchResult> { unsafe { let nq = query.len() / self.d() as usize; let mut out_labels = vec![0 as Idx; k * nq]; faiss_try!(faiss_Index_assign...
fn remove_ids(&mut self, sel: &IdSelector) -> Result<(i64)> { unsafe { let mut n_removed = 0; faiss_try!(faiss_Index_remove_ids( self.inner_ptr(), sel.inner_ptr(), &mut n_removed )); Ok(n_removed) } }
function_block-full_function
[ { "content": "/// Simplified interface for k-means clustering.\n\n///\n\n/// - `d`: dimension of the data\n\n/// - `k`: nb of output centroids\n\n/// - `x`: training set (size `n * d`)\n\n///\n\n/// The number of points is inferred from `x` and `k`.\n\n///\n\n/// Returns the final quantization error and centroi...
Rust
benchmark/src/benchmark.rs
cronosun/abin
ec10d5918d42d6a9221d9ec97d5021bd5b7ee1c7
use core::iter; use std::collections::VecDeque; use std::marker::PhantomData; use std::thread; use enum_iterator::IntoEnumIterator; use crate::BenchStr; pub fn run_benchmark<TBenchStr: BenchStr>( number_of_threads: usize, test_set: &'static [&'static str], ) { if number_of_threads == 1 { run_benc...
use core::iter; use std::collections::VecDeque; use std::marker::PhantomData; use std::thread; use enum_iterator::IntoEnumIterator; use crate::BenchStr; pub fn run_benchmark<TBenchStr: BenchStr>( number_of_threads: usize, test_set: &'static [&'static str], ) { if number_of_threads == 1 { run_benc...
fn perform_with_test_set(&mut self, items: &[&'static str]) { if items.is_empty() { return; } for item in items { self.join_single(item); self.do_clone(item); self.slice(item); } self.join(items); } fn join(&mut self,...
n 0..50 { self.perform_with_test_set(&smallest); self.perform_with_test_set(self.test_set); self.perform_with_test_set(&smallest); self.perform_with_test_set(&smallest); } }
function_block-function_prefixed
[ { "content": "pub fn benchmark_test_set() -> &'static [&'static str] {\n\n TEST_SET\n\n}\n", "file_path": "benchmark/src/test_set.rs", "rank": 1, "score": 259003.78508813225 }, { "content": "fn perform<TBenchStr: BenchStr>() {\n\n run_benchmark::<TBenchStr>(2, benchmark_test_set());\n\...
Rust
lib/tests/test_revset_graph_iterator.rs
clayne/jj
051c01491c32dcc6865d8ac84b6bd240148624c2
use itertools::Itertools; use jujutsu_lib::revset::revset_for_commits; use jujutsu_lib::revset_graph_iterator::RevsetGraphEdge; use jujutsu_lib::testutils; use jujutsu_lib::testutils::{CommitGraphBuilder, TestRepo}; use test_case::test_case; #[test_case(false ; "keep transitive edges")] #[test_case(true ; "skip tran...
use itertools::Itertools; use jujutsu_lib::revset::revset_for_commits; use jujutsu_lib::revset_graph_iterator::RevsetGraphEdge; use jujutsu_lib::testutils; use jujutsu_lib::testutils::{CommitGraphBuilder, TestRepo}; use test_case::test_case; #[test_case(false ; "keep transitive edges")] #[test_case(true ; "skip tran...
assert_eq!( commits[1].1, vec![ RevsetGraphEdge::direct(pos_c), RevsetGraphEdge::missing(pos_b), ] ); assert_eq!(commits[2].1, vec![RevsetGraphEdge::missing(pos_a)]); } #[test_case(false ; "keep transitive edges")] #[test_case(true ; "skip transitive edges")...
if skip_transitive_edges { assert_eq!(commits[0].1, vec![RevsetGraphEdge::direct(pos_d)]); } else { assert_eq!( commits[0].1, vec![ RevsetGraphEdge::direct(pos_d), RevsetGraphEdge::indirect(pos_c), ] ); }
if_condition
[ { "content": "#[must_use]\n\nfn child_commit(settings: &UserSettings, repo: &ReadonlyRepo, commit: &Commit) -> CommitBuilder {\n\n testutils::create_random_commit(settings, repo).set_parents(vec![commit.id().clone()])\n\n}\n\n\n", "file_path": "lib/tests/test_index.rs", "rank": 6, "score": 328114...
Rust
luminance-derive/src/semantics.rs
SpacialCircumstances/luminance-rs
ecdd660cf3780d7dd8d25232c7e58ffac450d2cf
use crate::attrib::{get_field_attr_once, AttrError}; use proc_macro::TokenStream; use quote::quote; use std::fmt; use syn::{Attribute, DataEnum, Ident, Type}; const KNOWN_SUBKEYS: &[&str] = &["name", "repr", "wrapper"]; #[derive(Debug)] pub(crate) enum SemanticsImplError { AttributeErrors(Vec<AttrError>), NoField...
use crate::attrib::{get_field_attr_once, AttrError}; use proc_macro::TokenStream; use quote::quote; use std::fmt; use syn::{Attribute, DataEnum, Ident, Type}; const KNOWN_SUBKEYS: &[&str] = &["name", "repr", "wrapper"]; #[derive(Debug)] pub(crate) enum SemanticsImplError { AttributeErrors(Vec<AttrError>), NoField...
elf::Sem = #ident::#sem_var; } unsafe impl luminance::vertex::VertexAttrib for #ty_name { const VERTEX_ATTRIB_DESC: luminance::vertex::VertexAttribDesc = <#repr_ty_name as luminance::vertex::VertexAttrib>::VERTEX_ATTRIB_DESC; } }; fiel...
function_block-function_prefixed
[ { "content": "fn uniform_type_match(program: GLuint, name: &str, ty: UniformType) -> Result<(), UniformWarning> {\n\n let mut size: GLint = 0;\n\n let mut glty: GLuint = 0;\n\n\n\n unsafe {\n\n // get the max length of the returned names\n\n let mut max_len = 0;\n\n gl::GetProgramiv(program, gl::ACT...
Rust
src/round.rs
Cykooz/scorched_earth
0297d0610ab1955dcf9718f9497f6e4b555289b0
use ggez::audio::SoundSource; use rand::rngs::ThreadRng; use rand::seq::SliceRandom; use rand::Rng; use crate::explosion::Explosion; use crate::landscape::Landscape; use crate::missile::Missile; use crate::tank::{Tank, TankState}; use crate::types::Vector2; use crate::world::World; use crate::{G, MAX_PLAYERS_COUNT}; ...
use ggez::audio::SoundSource; use rand::rngs::ThreadRng; use rand::seq::SliceRandom; use rand::Rng; use crate::explosion::Explosion; use crate::landscape::Landscape; use crate::missile::Missile; use crate::tank::{Tank, TankState}; use crate::types::Vector2; use crate::world::World; use crate::{G, MAX_PLAYERS_COUNT}; ...
fn update_landscape(&mut self) { if let GameState::Subsidence = self.state { if self.landscape.update() { let live_tanks = self.tanks.iter_mut().filter(|t| !t.dead); for tank in live_tanks { tank.throw_down(None); } ...
fn update_explosions(&mut self) { if let GameState::Exploding(ref mut explosions) = self.state { let landscape = &mut self.landscape; let count_not_finished_explosions = explosions .iter_mut() .filter_map(|e| { if e.update(landscape) { ...
function_block-full_function
[ { "content": "#[derive(Debug, Clone)]\n\nstruct TankThrowing {\n\n start_height: f32,\n\n ballistics: Ballistics,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Tank {\n\n pub player_number: u8,\n\n pub rect: graphics::Rect,\n\n body_bounds: Vec<Ellipse>,\n\n gun_bounds: Vec<Ellipse>,\n\n ...
Rust
azure-functions/src/bindings/durable_orchestration_context.rs
MutedExclamation/azure-functions-rs
bb1c7457ccfa65d8b29c74902eae1b61706f2033
use crate::{ durable::{ Action, ActionFuture, EventType, HistoryEvent, JoinAll, OrchestrationFuture, OrchestrationState, RetryOptions, SelectAll, }, rpc::{typed_data::Data, TypedData}, }; use chrono::{DateTime, Utc}; use serde::Deserialize; use serde_json::{from_str, Value}; use std::{cell::...
use crate::{ durable::{ Action, ActionFuture, EventType, HistoryEvent, JoinAll, OrchestrationFuture, OrchestrationState, RetryOptions, SelectAll, }, rpc::{typed_data::Data, TypedData}, }; use chrono::{DateTime, Utc}; use serde::Deserialize; use serde_json::{from_str, Value}; use std::{cell::...
} pub fn is_replaying(&self) -> bool { self.state.borrow().is_replaying() } pub fn current_time(&self) -> DateTime<Utc> { self.state.borrow().current_time() } pub fn set_custom_status<S>(&self, status: S) where S: Into<Value>, { self.sta...
match &data.data { Some(Data::String(s)) => { let data: BindingData = from_str(s).expect("failed to parse orchestration context data"); DurableOrchestrationContext { instance_id: data.instance_id, parent_instance_id...
if_condition
[ { "content": "pub fn to_camel_case(input: &str) -> String {\n\n let mut result = String::new();\n\n let mut capitalize = false;\n\n let mut first = true;\n\n for ch in input.chars() {\n\n if ch == '_' {\n\n capitalize = true;\n\n } else {\n\n result.push(if capita...
Rust
src/cpu_scs/mvfr1.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register MVFR1"] pub type R = crate::R<u32, super::MVFR1>; #[doc = "Writer for register MVFR1"] pub type W = crate::W<u32, super::MVFR1>; #[doc = "Register MVFR1 `reset()`'s with value 0x1100_0011"] impl crate::ResetValue for super::MVFR1 { type Type = u32; #[inline(always)] fn reset_valu...
#[doc = "Reader of register MVFR1"] pub type R = crate::R<u32, super::MVFR1>; #[doc = "Writer for register MVFR1"] pub type W = crate::W<u32, super::MVFR1>; #[doc = "Register MVFR1 `reset()`'s with value 0x1100_0011"] impl crate::ResetValue for super::MVFR1 { type Type = u32; #[inline(always)] fn reset_valu...
f) -> D_NAN_MODE_R { D_NAN_MODE_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 0:3 - 3:0\\] Indicates whether the FP hardware implementation supports only the Flush-to-Zero mode of operation. The value of this field is: 0b0001 - hardware supports full denormalized number arithmetic."] #[inl...
self.w } } #[doc = "Reader of field `FP_HPFP`"] pub type FP_HPFP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `FP_HPFP`"] pub struct FP_HPFP_W<'a> { w: &'a mut W, } impl<'a> FP_HPFP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/carrier.rs
KaoImin/rustracing
51a6915f2b0ec834f802c0febdf97e7fad07fd52
use crate::span::SpanContext; use crate::Result; use std::collections::{BTreeMap, HashMap}; use std::hash::{BuildHasher, Hash}; use std::io::{Read, Write}; pub trait InjectToTextMap<T>: Sized where T: TextMap, { fn inject_to_text_map(context: &SpanContext<Self>, carrier: &mut T) -> Result<()>; } pub tr...
use crate::span::SpanContext; use crate::Result; use std::collections::{BTreeMap, HashMap}; use std::hash::{BuildHasher, Hash}; use std::io::{Read, Write}; pub trait InjectToTextMap<T>: Sized where T: TextMap, { fn inject_to_text_map(context: &SpanContext<Self>, carrier: &mut T) -> Result<()>; } pub tr...
derField for HashMap<String, String, S> { fn set_http_header_field(&mut self, name: &str, value: &str) -> Result<()> { self.insert(name.to_owned(), value.to_owned()); Ok(()) } } pub trait IterHttpHeaderFields<'a> { type Fields: Iterator<Item = (&'a str, &'a [u8])>; fn fields(...
ned(), value.to_owned()); } fn get(&self, key: &str) -> Option<&str> { self.get(key).map(|v| v.as_ref()) } } impl TextMap for BTreeMap<String, String> { fn set(&mut self, key: &str, value: &str) { self.insert(key.to_owned(), value.to_owned()); } fn get(&self, key: &str) -> Opti...
random
[ { "content": "/// A cheap reference-to-reference conversion that has a possibility to fail.\n\npub trait MaybeAsRef<T: ?Sized> {\n\n /// Performs the conversion.\n\n fn maybe_as_ref(&self) -> Option<&T>;\n\n}\n\n\n\nimpl<T, U> MaybeAsRef<T> for Option<U>\n\nwhere\n\n U: MaybeAsRef<T>,\n\n{\n\n fn ma...
Rust
src/lib.rs
metinc/godot-tts
691997023a80d061ea8cef8a6d74933e9398149a
use std::sync::mpsc::{channel, Receiver}; use gdnative::prelude::*; use tts::{Features, UtteranceId, TTS as Tts}; #[derive(NativeClass)] #[inherit(Reference)] struct Utterance(pub(crate) Option<UtteranceId>); #[methods] impl Utterance { fn new(_owner: &Reference) -> Self { Self(None) } ...
use std::sync::mpsc::{channel, Receiver}; use gdnative::prelude::*; use tts::{Features, UtteranceId, TTS as Tts}; #[derive(NativeClass)] #[inherit(Reference)] struct Utterance(pub(crate) Option<UtteranceId>); #[methods] impl Utterance { fn new(_owner: &Reference) -> Self { Self(None) } ...
ame: "utterance", default: Variant::default(), export_info: ExportInfo::new(VariantType::Object), usage: PropertyUsage::DEFAULT, }], }); builder.add_signal(Signal { name: "utterance_end", args: &[SignalArgument {...
te() } else { 0. } }) .done(); builder .add_property("can_detect_screen_reader") .with_getter(|_: &TTS, _| cfg!(all(windows, features = "use_tolk"))) .done(); #[allow(unreachable_cod...
random
[ { "content": " private float rate = 1f;\n", "file_path": "src/main/java/games/lightsout/godot/tts/TTS.java", "rank": 3, "score": 29309.817895607863 }, { "content": " private Integer utteranceId = 0;\n", "file_path": "src/main/java/games/lightsout/godot/tts/TTS.java", "rank": 4,...
Rust
base_layer/core/src/base_node/sync/header_sync/validator.rs
DenisKolodin/tari
f8eeebf63124124722959b79b9238f086b4eddeb
use crate::{ base_node::sync::BlockHeaderSyncError, blocks::BlockHeader, chain_storage::{ async_db::AsyncBlockchainDb, BlockHeaderAccumulatedData, BlockchainBackend, ChainHeader, ChainStorageError, TargetDifficulties, }, common::rolling_vec::RollingV...
use crate::{ base_node::sync::BlockHeaderSyncError, blocks::BlockHeader, chain_storage::{ async_db::AsyncBlockchainDb, BlockHeaderAccumulatedData, BlockchainBackend, ChainHeader, ChainStorageError, TargetDifficulties, }, common::rolling_vec::RollingV...
lt(); let db = create_new_blockchain(); ( BlockHeaderSyncValidator::new(db.clone().into(), rules, randomx_factory), db.into(), ) } async fn setup_with_headers( n: usize, ) -> ( BlockHeaderSyncValidator<TempDatabase>, AsyncBlockchainDb<...
e(State { current_height: start_header.height, timestamps, target_difficulties, previous_accum, valid_headers: Vec::with_capacity(1000), }); Ok(()) } pub fn current_valid_chain_tip_header(&self) -> Option<&ChainHeader> { ...
random
[ { "content": "/// Fetches all the size of all key/values in the given DB. Returns the number of entries, the total size of all the\n\n/// keys and values in bytes.\n\npub fn fetch_db_entry_sizes(txn: &ConstTransaction<'_>, db: &Database) -> Result<(u64, u64, u64), ChainStorageError> {\n\n let access = txn.ac...
Rust
src/hstring.rs
danielframpton/winrt-rs
1b96fff8ca7f25f012097fe8ec44e26d6576ecff
use crate::*; #[repr(transparent)] pub struct HString { ptr: *mut Header, } impl HString { pub fn new() -> HString { Self { ptr: std::ptr::null_mut(), } } pub fn is_empty(&self) -> bool { self.ptr.is_null() } pub fn len(&s...
use crate::*; #[repr(transparent)] pub struct HString { ptr: *mut Header, } impl HString { pub fn new() -> HString { Self { ptr: std::ptr::null_mut(), } } pub fn is_empty(&self) -> bool { self.ptr.is_null() } pub fn len(&s...
} impl From<String> for HString { fn from(value: String) -> Self { value.as_str().into() } } impl From<&String> for HString { fn from(value: &String) -> Self { value.as_str().into() } } impl PartialEq for HString { fn eq(&self, other: &Self) -> bool { self.as_wide() == ot...
fn from(value: &str) -> Self { if value.is_empty() { return HString::new(); } let mut ptr = Header::alloc(value.len() as u32); for (index, wide) in value.encode_utf16().enumerate() { unsafe { std::ptr::write((*ptr).data.add(inde...
function_block-function_prefix_line
[ { "content": "pub fn default_gen_debug(type_name: &TypeName) -> TokenStream {\n\n let name = &type_name.name;\n\n let implementation =\n\n quote! { \"{}({:?})\", #name, <Self as ::winrt::AbiTransferable>::get_abi(self) };\n\n\n\n gen(type_name, &implementation)\n\n}\n\n\n", "file_path": "cra...
Rust
src/lib.rs
daaku/actix-clean-path
d35ba066962a7953e3a7e41aedf93b6f9b73ec7b
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform}; use actix_web::http::{self, PathAndQuery, Uri}; use actix_web::{Error, HttpResponse}; use futures_util::future::{ok, Either, LocalBoxFuture, Ready}; use std::task::{Context, Poll}; #[derive(Default, Clone, Copy)] pub struct CleanPath; impl<S...
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform}; use actix_web::http::{self, PathAndQuery, Uri}; use actix_web::{Error, HttpResponse}; use futures_util::future::{ok, Either, LocalBoxFuture, Ready}; use std::task::{Context, Poll}; #[derive(Default, Clone, Copy)] pub struct CleanPath; impl<S...
dy(cx) } fn call(&mut self, req: ServiceRequest) -> Self::Future { let original_path = req.uri().path(); let trailing_slash = original_path.ends_with('/'); if !original_path.contains("/.") && !original_path.contains("//") && (has_ext(original_path) ^ tr...
t; type Response = ServiceResponse<B>; type Error = Error; type InitError = (); type Transform = CleanPathNormalization<S>; type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ok(CleanPathNormalization { service }) } }...
random
[ { "content": "actix-clean-path\n\n================\n\n\n\n[![Build](https://github.com/daaku/actix-clean-path/workflows/build/badge.svg)](https://github.com/daaku/actix-clean-path/actions?query=workflow%3Abuild)\n\n[![Crates.io](https://img.shields.io/crates/v/actix-clean-path)](https://crates.io/crates/actix-c...
Rust
src/sparkles.rs
MakotoE/prettier-print
8d24ada3a041920de5bc080fb52f81ed269e9984
use crate::game_of_life::{Board, Cell}; use crate::prettier_printer::{PrettierPrinter, Seed}; use crossterm::cursor; use crossterm::cursor::{MoveTo, MoveToNextLine}; use crossterm::event::poll; use crossterm::style::{Color, Colors, Print, SetBackgroundColor, SetColors}; use crossterm::terminal::{disable_raw_mode, enabl...
use crate::game_of_life::{Board, Cell}; use crate::prettier_printer::{PrettierPrinter, Seed}; use crossterm::cursor; use crossterm::cursor::{MoveTo, MoveToNextLine}; use crossterm::event::poll; use crossterm::style::{Color, Colors, Print, SetBackgroundColor, SetColors}; use crossterm::terminal::{disable_raw_mode, enabl...
char; fn next(&mut self) -> Option<Self::Item> { const SPACE: char = ' '; let result = if self.curr_index / self.terminal_size.0 < self.top_margin_length { SPACE } else if self.curr_index % self.terminal_size.0 < self.left_margin_length { s...
use std::fmt::Debug; use std::io::{StdoutLock, Write}; use std::iter::once; use std::str::Chars; use std::thread::sleep; use std::time::Duration; pub struct Sparkles<'stream> { rng: SmallRng, stdout: StdoutLock<'stream>, } impl<'stream> Sparkles<'stream> { pub fn new(stdout: StdoutLock<'stream>) -> S...
random
[ { "content": "#![no_main]\n\nuse arbitrary::Arbitrary;\n\nuse libfuzzer_sys::fuzz_target;\n\nuse prettier_print::prettier_printer::{PrettierPrintDisplayer, Seed};\n\n\n\n#[derive(Debug, Arbitrary)]\n", "file_path": "fuzz/fuzz_targets/prettier_print_displayer.rs", "rank": 0, "score": 16561.5064490338...
Rust
examples/chat/src/session.rs
planet-s/actix
2bb4e09a43aa7bccc804327e05509dae94c37244
use std::io; use std::time::{Instant, Duration}; use tokio_core::net::TcpStream; use actix::prelude::*; use server::{self, ChatServer}; use codec::{ChatRequest, ChatResponse, ChatCodec}; pub struct Message(pub String); pub struct ChatSession { id: usize, addr: Address<ChatServer>, hb: In...
use std::io; use std::time::{Instant, Duration}; use tokio_core::net::TcpStream; use actix::prelude::*; use server::{self, ChatServer}; use codec::{ChatRequest, ChatResponse, ChatCodec}; pub struct Message(pub String); pub struct ChatSession { id: usize, addr: Address<ChatServer>, hb: In...
} impl ResponseType<Message> for ChatSession { type Item = (); type Error = (); } impl ChatSession { pub fn new(addr: Address<ChatServer>) -> ChatSession { ChatSession {id: 0, addr: addr, hb: Instant::now(), room: "Main".to_owned()} } fn hb(&self, ctx: &mut FramedCont...
fn handle(&mut self, msg: Message, ctx: &mut FramedContext<Self>) -> Response<Self, Message> { let _ = ctx.send(ChatResponse::Message(msg.0)); Self::empty() }
function_block-full_function
[ { "content": "type Item<A> = (SpawnHandle, Box<ActorFuture<Item=(), Error=(), Actor=A>>);\n\n\n\npub struct ActorItemsCell<A> where A: Actor, A::Context: AsyncContext<A> {\n\n index: SpawnHandle,\n\n items: Vec<Item<A>>,\n\n}\n\n\n\nimpl<A> Default for ActorItemsCell<A> where A: Actor, A::Context: AsyncCo...
Rust
src/controlregs.rs
jounathaen/rust-x86
bc724a380c32dfb68c6c3ad90b4a4f1b701a55e0
use bitflags::*; use crate::arch::{_xgetbv, _xsetbv}; bitflags! { pub struct Cr0: usize { const CR0_ENABLE_PAGING = 1 << 31; const CR0_CACHE_DISABLE = 1 << 30; const CR0_NOT_WRITE_THROUGH = 1 << 29; const CR0_ALIGNMENT_MASK = 1 << 18; const CR0_WRITE_PROTECT = 1 << 16; ...
use bitflags::*; use crate::arch::{_xgetbv, _xsetbv}; bitflags! { pub struct Cr0: usize { const CR0_ENABLE_PAGING = 1 << 31; const CR0_CACHE_DISABLE = 1 << 30; const CR0_NOT_WRITE_THROUGH = 1
const CR4_DEBUGGING_EXTENSIONS = 1 << 3; const CR4_TIME_STAMP_DISABLE = 1 << 2; const CR4_VIRTUAL_INTERRUPTS = 1 << 1; const CR4_ENABLE_VME = 1 << 0; } } bitflags! { pub struct Xcr0: u64 { const XCR0_PKRU_STATE = 1 << 9; const XCR0_...
<< 29; const CR0_ALIGNMENT_MASK = 1 << 18; const CR0_WRITE_PROTECT = 1 << 16; const CR0_NUMERIC_ERROR = 1 << 5; const CR0_EXTENSION_TYPE = 1 << 4; const CR0_TASK_SWITCHED = 1 << 3; const CR0_EMULATE_COPROCESSOR = 1 << 2; const CR0_MONITOR_COPROCESSOR = 1 << 1; ...
random
[ { "content": "/// Summary display at the end of the test run.\n\npub fn test_summary(passed: usize, failed: usize, ignored: usize) {\n\n println!(\n\n \"\\ntest result: {} {} passed; {} failed; {} ignored\",\n\n if failed == 0 { \"OK\" } else { \"FAILED\" },\n\n passed,\n\n failed...
Rust
library/core/tests/num/bignum.rs
ohno418/rust
395a09c3dafe0c7838c9ca41d2b47bb5e79a5b6d
use core::num::bignum::tests::Big8x3 as Big; use core::num::bignum::Big32x40; #[test] #[should_panic] fn test_from_u64_overflow() { Big::from_u64(0x1000000); } #[test] fn test_add() { assert_eq!(*Big::from_small(3).add(&Big::from_small(4)), Big::from_small(7)); assert_eq!(*Big::from_small(3).add(&Big::fro...
use core::num::bignum::tests::Big8x3 as Big; use core::num::bignum::Big32x40; #[test] #[should_panic] fn test_from_u64_overflow() { Big::from_u64(0x1000000); } #[test] fn test_add() { assert_eq!(*Big::from_small(3).add(&Big::from_small(4)), Big::from_small(7)); assert_eq!(*Big::from_small(3).add(&Big::fro...
#[test] fn test_is_zero() { assert!(Big::from_small(0).is_zero()); assert!(!Big::from_small(3).is_zero()); assert!(!Big::from_u64(0x123).is_zero()); assert!(!Big::from_u64(0xffffff).sub(&Big::from_u64(0xfffffe)).is_zero()); assert!(Big::from_u64(0xffffff).sub(&Big::from_u64(0xffffff)).is_zero()); ...
assert_eq!(div_rem(45, 9), (Big::from_small(5), Big::from_small(0))); assert_eq!(div_rem(103, 9), (Big::from_small(11), Big::from_small(4))); assert_eq!(div_rem(123456, 77), (Big::from_u64(1603), Big::from_small(25))); assert_eq!(div_rem(0xffff, 1), (Big::from_u64(0xffff), Big::from_small(0))); assert_e...
function_block-function_prefix_line
[]
Rust
src/services/download/sentry.rs
samsartor/symbolicator
7d7bcffe7571b56c09f74241bb820ff6b279aed7
use std::fmt; use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::prelude::*; use parking_lot::Mutex; use reqwest::StatusCode; use serde::Deserialize; use thiserror::Error; use url::Url; use super::{DownloadError, DownloadStatus, RemoteDif, RemoteDifUri, USER_AGENT}; use cra...
use std::fmt; use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::prelude::*; use parking_lot::Mutex; use reqwest::StatusCode; use serde::Deserialize; use thiserror::Error; use url::Url; use super::{DownloadError, DownloadStatus, RemoteDif, RemoteDifUri, USER_AGENT}; use cra...
}
id: SourceId::new("test"), url: Url::parse("https://example.net/endpoint/").unwrap(), token: "token".into(), }; let file_source = SentryRemoteDif::new(Arc::new(source), SentryFileId("abc123".into())); let uri = file_source.uri(); assert_eq!(uri, RemoteDifUri::new(...
function_block-function_prefix_line
[ { "content": "/// Entry function for the cleanup command.\n\n///\n\n/// This will clean up all caches based on configured cache retention.\n\npub fn cleanup(config: Config) -> Result<()> {\n\n Caches::from_config(&config)?.cleanup()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use ...
Rust
common/src/rpc/de.rs
IDAPluginProject/lumen
df00d4eca3b61036d715003c6e5ac046fb8ef5a0
use serde::Deserialize; use serde::de::{self, DeserializeSeed, SeqAccess, Visitor}; use super::Error; struct Deserializer<'de> { input: &'de [u8], } impl<'de> Deserializer<'de> { fn from_bytes(b: &'de [u8]) -> Self { Self { input: b, } } fn unpack_dd(&mu...
use serde::Deserialize; use serde::de::{self, DeserializeSeed, SeqAccess, Visitor}; use super::Error; struct Deserializer<'de> { input: &'de [u8], } impl<'de> Deserializer<'de> { fn from_bytes(b: &'de [u8]) -> Self { Self { input: b, } } fn unpack_dd(&mu...
fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> { visitor.visit_borrowed_str(self.unpack_cstr()?) } fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> { let v = self.unpack_var_bytes()?; visitor.v...
fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> { let len = self.unpack_dd()?; visitor.visit_seq(Access { len: len as usize, de: &mut *self, }) }
function_block-function_prefix_line
[ { "content": "/// packs a dd into `buf` returning amout of bytes written.\n\n/// Returns 0 if buffer is too small\n\npub fn pack_dd(v: u32, buf: &mut [u8]) -> usize {\n\n let bytes = v.to_le_bytes();\n\n match v {\n\n 0..=0x7f => { // 0..0XXXXXXX (7 bits)\n\n if buf.is_empty() {\n\n ...
Rust
nrf52-hal-common/src/spim.rs
jacobrosenthal/nrf52-hal
ebe3c90b52b6dab9d057e70b8e772109f1af7313
use core::ops::Deref; use core::sync::atomic::{compiler_fence, Ordering::SeqCst}; use crate::target::{ spim0, SPIM0, SPIM1, SPIM2, }; use crate::prelude::*; use crate::gpio::{ p0::P0_Pin, Floating, Input, Output, PushPull, }; pub trait SpimExt : Deref<Target=spim0::RegisterBlock...
use core::ops::Deref; use core::sync::atomic::{compiler_fence, Ordering::SeqCst}; use crate::target::{ spim0, SPIM0, SPIM1, SPIM2, }; use crate::prelude::*; use crate::gpio::{ p0::P0_Pin, Floating, Input, Output, PushPull, }; pub trait SpimExt : Deref<Target=spim0::RegisterBlock...
pub sck: P0_Pin<Output<PushPull>>, pub mosi: P0_Pin<Output<PushPull>>, pub miso: P0_Pin<Input<Floating>>, } #[derive(Debug)] pub enum Error { TxBufferTooLong, RxBufferTooLong, Transmit, Receive, }
w.connect().connected() }); spim.enable.write(|w| w.enable().enabled() ); spim.config.write(|w| w .order().msb_first() .cpha().leading() .cpol().active_high() ); spi...
random
[ { "content": "/// Extension trait to split a GPIO peripheral in independent pins and registers\n\npub trait GpioExt {\n\n /// The to split the GPIO into\n\n type Parts;\n\n\n\n /// Splits the GPIO block into independent pins and registers\n\n fn split(\n\n self,\n\n // apb2: &mut APB2\...
Rust
src/swarm.rs
dignifiedquire/rust-drand
57cd6bcb459fb3fca1deb11c5a789c413ee308e2
use anyhow::Result; use async_std::prelude::*; use async_std::{ io, sync::{channel, Receiver, Sender}, task, }; use futures::StreamExt; use libp2p::{ core, core::muxing::StreamMuxerBox, core::transport::boxed::Boxed, floodsub::{self, Floodsub, FloodsubEvent}, identity, mplex, noise, ...
use anyhow::Result; use async_std::prelude::*; use async_std::{ io, sync::{channel, Receiver, Sender}, task, }; use futures::StreamExt; use libp2p::{ core, core::muxing::StreamMuxerBox, core::transport::boxed::Boxed, floodsub::{self, Floodsub, FloodsubEvent}, identity, mplex, noise, ...
pub async fn run(&mut self) -> Result<()> { let mut stdin = io::BufReader::new(io::stdin()).lines(); let (sender, receiver) = channel(10); task::spawn(async move { while let Some(Ok(line)) = stdin.next().await { sender.send(line).await; ...
ut swarm, listen_addr)?; Ok(Node { swarm, topic, dkg_topic, event_sender, action_receiver, }) }
function_block-function_prefixed
[ { "content": "fn serialize_peer_id<S>(id: &PeerId, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let raw = id.to_string();\n\n serializer.serialize_str(&raw)\n\n}\n\n\n", "file_path": "src/key/key.rs", "rank": 3, "score": 147580.35724311013 }, { "con...
Rust
net_util/src/queue_pair.rs
thillux/cloud-hypervisor
f7f2f25a574b1b2dba22c094fc8226d404157d15
use super::{register_listener, unregister_listener, vnet_hdr_len, Tap}; use crate::GuestMemoryMmap; use rate_limiter::{RateLimiter, TokenType}; use std::io; use std::num::Wrapping; use std::os::unix::io::{AsRawFd, RawFd}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use vm_memory::{Bytes, GuestAd...
use super::{register_listener, unregister_listener, vnet_hdr_len, Tap}; use crate::GuestMemoryMmap; use rate_limiter::{RateLimiter, TokenType}; use std::io; use std::num::Wrapping; use std::os::unix::io::{AsRawFd, RawFd}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use vm_memory::{Bytes, GuestAd...
.map_err(NetQueuePairError::UnregisterListener)?; self.tx_tap_listening = false; info!("Writing to TAP succeeded. No longer listening for TAP to become writable."); } self.counters .tx_bytes .fetch_add(self.tx.counter_bytes.0, Ordering::AcqRe...
unregister_listener( self.epoll_fd.unwrap(), self.tap_for_write_epoll.as_raw_fd(), epoll::Events::EPOLLOUT, u64::from(self.tap_tx_event_id), )
call_expression
[]
Rust
cap-primitives/src/posish/linux/fs/procfs.rs
olivierlemasle/cap-std
fc53b00cabbacff2c0a67f7ec1b802a62a25231e
use crate::fs::{ errors, open, open_unchecked, read_link_unchecked, set_times_follow_unchecked, FollowSymlinks, Metadata, OpenOptions, SystemTimeSpec, }; use once_cell::sync::Lazy; use posish::{ fs::{chmodat, fstatfs, major, renameat, Mode, OFlags, PROC_SUPER_MAGIC}, io::Errno, path::DecInt, p...
use crate::fs::{ errors, open, open_unchecked, read_link_unchecked, set_times_follow_unchecked, FollowSymlinks, Metadata, OpenOptions, SystemTimeSpec, }; use once_cell::sync::Lazy; use posish::{ fs::{chmodat, fstatfs, major, renameat, Mode, OFlags, PROC_SUPER_MAGIC}, io::Errno, path::DecInt, p...
th, OpenOptions::new() .read(true) .custom_flags(OFlags::PATH.bits() as i32), )?; let dirfd = proc_self_fd()?; set_times_follow_unchecked(dirfd, &DecInt::from_fd(&opath), atime, mtime) }
k(dir_metadata) } fn check_procfs(file: &fs::File) -> io::Result<()> { let statfs = fstatfs(file)?; let f_type = statfs.f_type; if f_type != PROC_SUPER_MAGIC { return Err(io::Error::new( io::ErrorKind::Other, format!("unexpected filesystem type in /proc ({:#x})", f_type), ...
random
[ { "content": "#[cfg(target_os = \"wasi\")]\n\n#[inline]\n\nfn metadata_from(file: &std::fs::File) -> io::Result<Metadata> {\n\n file.metadata()\n\n}\n\n\n", "file_path": "cap-async-std/src/fs/file.rs", "rank": 0, "score": 371803.43662341626 }, { "content": "fn open_from(start: &fs::File, ...
Rust
src/widgets/canvas/mod.rs
KlossPeter/tui-rs
56fc43400a7df36ff2421392742fb9087cd27698
mod line; mod map; mod points; mod world; pub use self::line::Line; pub use self::map::{Map, MapResolution}; pub use self::points::Points; use buffer::Buffer; use layout::Rect; use style::{Color, Style}; use widgets::{Block, Widget}; pub const DOTS: [[u16; 2]; 4] = [ [0x0001, 0x0008], [0x0002, 0x0010], [...
mod line; mod map; mod points; mod world; pub use self::line::Line; pub use self::map::{Map, MapResolution}; pub use self::points::Points; use buffer::Buffer; use layout::Rect; use style::{Color, Style}; use widgets::{Block, Widget}; pub const DOTS: [[u16; 2]; 4] = [ [0x0001, 0x0008], [0x0002, 0x0010], [...
let width = canvas_area.width as usize; let height = canvas_area.height as usize; if let Some(ref painter) = self.painter { let mut ctx = Context { x_bounds: self.x_bounds, y_bounds: self.y_bounds, width: canvas_area.wid...
let canvas_area = match self.block { Some(ref mut b) => { b.draw(area, buf); b.inner(area) } None => area, };
assignment_statement
[ { "content": "/// Base requirements for a Widget\n\npub trait Widget {\n\n /// Draws the current state of the widget in the given buffer. That the only method required to\n\n /// implement a custom widget.\n\n fn draw(&mut self, area: Rect, buf: &mut Buffer);\n\n /// Helper method to quickly set the...
Rust
fyrox-ui/src/inspector/editors/array.rs
jackos/Fyrox
4b293733bda8e1a0a774aaf82554ac8930afdd8b
use crate::{ border::BorderBuilder, brush::Brush, core::{color::Color, inspect::Inspect, pool::Handle}, expander::ExpanderBuilder, inspector::{ editors::{ PropertyEditorBuildContext, PropertyEditorDefinition, PropertyEditorDefinitionContainer, PropertyEditorInstance, ...
use crate::{ border::BorderBuilder, brush::Brush, core::{color::Color, inspect::Inspect, pool::Handle}, expander::ExpanderBuilder, inspector::{ editors::{ PropertyEditorBuildContext, PropertyEditorDefinition, PropertyEditorDefinitionContainer, PropertyEditorInstance, ...
None } }
if message.direction() == MessageDirection::FromWidget { if let Some(collection_changed) = message.data::<CollectionChanged>() { return Some(PropertyChanged { name: name.to_string(), owner_type_id, value: FieldKind::Collection(Box::...
if_condition
[ { "content": "pub fn make_dropdown_list_option(ctx: &mut BuildContext, name: &str) -> Handle<UiNode> {\n\n DecoratorBuilder::new(BorderBuilder::new(\n\n WidgetBuilder::new().with_height(26.0).with_child(\n\n TextBuilder::new(WidgetBuilder::new())\n\n .with_vertical_text_align...
Rust
shotover-proxy/src/transforms/load_balance.rs
benbromhead/shotover-proxy
3ea7fbb53c954c5c0bf03b72f96ac70dcc69b4de
use crate::config::topology::TopicHolder; use crate::error::ChainResponse; use crate::transforms::chain::{BufferedChain, TransformChain}; use crate::transforms::{ build_chain_from_config, Transform, Transforms, TransformsConfig, Wrapper, }; use anyhow::Result; use async_trait::async_trait; use serde::Deserialize; u...
use crate::config::topology::TopicHolder; use crate::error::ChainResponse; use crate::transforms::chain::{BufferedChain, TransformChain}; use crate::transforms::{ build_chain_from_config, Transform, Transforms, TransformsConfig, Wrapper, }; use anyhow::Result; use async_trait::async_trait; use serde::Deserialize; u...
} } #[derive(Debug)] pub struct ConnectionBalanceAndPool { pub active_connection: Option<BufferedChain>, pub max_connections: usize, pub all_connections: Arc<Mutex<Vec<BufferedChain>>>, pub chain_to_clone: TransformChain, } impl Clone for ConnectionBalanceAndPool { fn clone(&self) -> Self { ...
Ok(Transforms::PoolConnections(ConnectionBalanceAndPool { active_connection: None, max_connections: self.max_connections, all_connections: Arc::new(Mutex::new(Vec::with_capacity(self.max_connections))), chain_to_clone: chain, }))
call_expression
[ { "content": "// TODO: Replace with trait_alias (rust-lang/rust#41517).\n\npub trait Token: Send + Sync + std::hash::Hash + Eq + Clone + fmt::Debug {}\n\nimpl<T: Send + Sync + std::hash::Hash + Eq + Clone + fmt::Debug> Token for T {}\n\n\n\n#[derive(Clone, Derivative)]\n\n#[derivative(Debug)]\n\npub struct Conn...
Rust
src/structs/command.rs
Katsutoshii/kataru
d029f728a4fa976778ac25cb07d6acfe38d65361
use linear_map::LinearMap; use super::QualifiedName; use crate::{traits::CopyMerge, Bookmark, Error, Map, Result, Story, Value}; use serde::{Deserialize, Serialize}; pub type Params = LinearMap<String, Value>; pub type RawCommand = Map<String, Params>; #[derive(Debug, Default, Clone, PartialEq, Deserialize, Serializ...
use linear_map::LinearMap; use super::QualifiedName; use crate::{traits::CopyMerge, Bookmark, Error, Map, Result, Story, Value}; use serde::{Deserialize, Serialize}; pub type Params = LinearMap<String, Value>; pub type RawCommand = Map<String, Params>; #[derive(Debug, Default, Clone, PartialEq, Deserialize, Serializ...
merged_params.insert(param.clone(), value); } Ok(merged_params) } } impl MergeParams for Params { fn merge_params(&self, default_params: &Params) -> Result<Params> { self.copy_merge(default_params) } } pub trait CommandGetters<ParamsT: MergeParams>: Sized where for...
let value = if let Some(positional_value) = it.next() { positional_value.clone() } else { default_value.clone() };
assignment_statement
[ { "content": "fn run_command(runner: &mut Runner, command: &str, _params: &LinearMap<String, Value>) {\n\n match command {\n\n \"ClearScreen\" => print!(\"{}[2J\", 27 as char),\n\n \"SaveSnapshot\" => {\n\n runner.save_snapshot(\"test\");\n\n println!(\"Snapshot saved.\");...
Rust
components/butterfly/src/rumor/election.rs
jsirex/habitat
6c2289b2769ec5d7c8e29652bbac15638441b6c5
pub use crate::protocol::newscast::{election::Status as ElectionStatus, Election as ProtoElection}; use crate::{error::{Error, Result}, protocol::{self, newscast::{self, Rumor as ProtoRumor}, ...
pub use crate::protocol::newscast::{election::Status as ElectionStatus, Election as ProtoElection}; use crate::{error::{Error, Result}, protocol::{self, newscast::{self, Rumor as ProtoRumor}, ...
y() } } impl ConstIdRumor for ElectionUpdate { fn const_id() -> &'static str { "election" } } #[cfg(test)] mod tests { use crate::rumor::{election::{Election, ElectionUpdate, Term}, ConstIdRumor as _, ...
lection { pub member_id: String, pub service_group: String, pub term: u64, pub suitability: u64, pub status: ElectionStatus, pub votes: Vec<String>, } impl fmt::Display for Election { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, ...
random
[ { "content": "pub trait ConstIdRumor: Rumor {\n\n fn const_id() -> &'static str;\n\n}\n\n\n\nimpl<'a, T: Rumor> From<&'a T> for RumorKey {\n\n fn from(rumor: &'a T) -> RumorKey { RumorKey::new(rumor.kind(), rumor.id(), rumor.key()) }\n\n}\n\n\n", "file_path": "components/butterfly/src/rumor.rs", "...
Rust
rust/pact_consumer/src/builders/request_builder.rs
milleniumbug/pact-reference
e96dca8186e21829eb1ddbf1b5b6d27684625a06
use pact_matching::models::*; use pact_matching::models::matchingrules::MatchingRules; #[cfg(test)] use regex::Regex; use std::collections::HashMap; #[cfg(test)] #[allow(unused_imports)] use env_logger; use prelude::*; use util::GetDefaulting; pub struct RequestBuilder { request: Request, } impl RequestBuilder ...
use pact_matching::models::*; use pact_matching::models::matchingrules::MatchingRules; #[cfg(test)] use regex::Regex; use std::collections::HashMap; #[cfg(test)] #[allow(unused_imports)] use env_logger; use prelude::*; use util::GetDefaulting; pub struct RequestBuilder { request: Request, } impl RequestBuilder ...
#[test] fn query_param_with_underscore() { let pattern = PactBuilder::new("C", "P") .interaction("get a user", |i| { i.request .path("/users") .query_param("user_id", term!("^[0-9]+$", "1")); }) .build(); let...
let pattern = PactBuilder::new("C", "P") .interaction("I", |i| { i.request.query_param("greeting", term!("^h.*$", "hello")); }) .build(); let good = PactBuilder::new("C", "P") .interaction("I", |i| { i.request.query_param("greeting", "hi"); }) .build(); let ba...
function_block-function_prefix_line
[ { "content": "/// Given a `serde_json::Value`, walk it recursively, removing any null fields,\n\n/// and return the updated value. Because of how this is normally called, it\n\n/// consumes its input value and returns the stripped value.\n\n///\n\n/// This function is most useful when serializing Rust types to ...
Rust
kailua_langsvr/src/ops/signature.rs
nxgtri/kailua
17eb0750ff8bbe4237d75f31f9b8aa23170c3c28
use std::sync::Arc; use std::collections::HashSet; use kailua_env::Pos; use kailua_diag::{Localize, Localized}; use kailua_syntax::lex::{Tok, Punct, NestedToken}; use kailua_types::ty::{TypeContext, Display, Nil, Functions, Function}; use kailua_check::env::Output; use protocol::*; use message as m; use super::{get...
use std::sync::Arc; use std::collections::HashSet; use kailua_env::Pos; use kailua_diag::{Localize, Localized}; use kailua_syntax::lex::{Tok, Punct, NestedToken}; use kailua_types::ty::{TypeContext, Display, Nil, Functions, Function}; use kailua_check::env::Output; use protocol::*; use message as m; use super::{get...
let mut label = format!("{}(", if is_method { "method" } else { "function" }); let mut params = Vec::new(); let types = output.types() as &TypeContext; let mut first = true; let mut names = func.argnames.iter(); for t in &func.args.head { let implicit; if first { ...
s: &mut String, mut n: usize) { s.push('\u{2060}'); while n > 0 { s.push(['\u{200b}', '\u{200c}', '\u{200d}'][n % 3]); n /= 3; } }
function_block-function_prefixed
[ { "content": "pub fn help<F>(outputs: &[Arc<Output>], pos: Pos, source: &Source, mut localize: F) -> Option<Hover>\n\n where F: for<'a> FnMut(&'a Localize) -> Localized<'a, Localize>\n\n{\n\n // for multiple outputs, we deduplicate the identical types\n\n let mut hover_range = None;\n\n let mut cont...
Rust
powersoftau/src/bin/compute_constrained.rs
maticnetwork/avail-srs
766cff39e0fbf308ffe0ac5556fd721963fc378e
extern crate bellman; extern crate blake2; extern crate byteorder; extern crate memmap; extern crate powersoftau; extern crate rand; use powersoftau::batched_accumulator::BachedAccumulator; use powersoftau::keypair::keypair; use powersoftau::parameters::{CheckForCorrectness, UseCompression}; use powersoftau::small_bls...
extern crate bellman; extern crate blake2; extern crate byteorder; extern crate memmap; extern crate powersoftau; extern crate rand; use powersoftau::batched_accumulator::BachedAccumulator; use powersoftau::keypair::keypair; use powersoftau::parameters::{CheckForCorrectness, UseCompression}; use powersoftau::small_bls...
In total will generate up to {} powers", Bls12CeremonyParameters::TAU_POWERS_G1_LENGTH ); let mut rng = { use blake2::{Blake2b, Digest}; use byteorder::{BigEndian, ReadBytesExt}; use rand::chacha::ChaChaRng; use rand::{OsRng, Rng, SeedableRng}; let h = { ...
function_block-function_prefix_line
[ { "content": "/// Verifies a transformation of the `Accumulator` with the `PublicKey`, given a 64-byte transcript `digest`.\n\npub fn verify_transform<E: Engine, P: PowersOfTauParameters>(\n\n before: &Accumulator<E, P>,\n\n after: &Accumulator<E, P>,\n\n key: &PublicKey<E>,\n\n digest: &[u8],\n\n) ...
Rust
src/session/transcoders.rs
claudiosdc/rust-internet2
e4c741cd0579d5f03f81f3f6a0ca57ee0a9bb56e
use amplify::Bipolar; use std::borrow::Borrow; use crate::transport::{ Error, FRAME_PREFIX_SIZE, FRAME_SUFFIX_SIZE, MAX_FRAME_SIZE, }; #[cfg(feature = "lightning")] use lightning::ln::peers::{ encryption::{Decryptor, Encryptor}, handshake::CompletedHandshakeInfo, }; #[cfg(feature = "lightning")] pub str...
use amplify::Bipolar; use std::borrow::Borrow; use crate::transport::{ Error, FRAME_PREFIX_SIZE, FRAME_SUFFIX_SIZE, MAX_FRAME_SIZE, }; #[cfg(feature = "lightning")] use lightning::ln::peers::{ encryption::{Decryptor, Encryptor}, handshake::CompletedHandshakeInfo, }; #[cfg(feature = "lightning")] pub str...
} #[cfg(feature = "lightning")] impl Transcode for Transcoder { type Encryptor = Encryptor; type Decryptor = Decryptor; } #[cfg(feature = "lightning")] impl Bipolar for Transcoder { type Left = <Self as Transcode>::Encryptor; type Right = <Self as Transcode>::Decryptor; fn join(encryptor: S...
fn decrypt( &mut self, buffer: impl Borrow<[u8]>, ) -> Result<Vec<u8>, Self::Error> { match self.0.decryptor.decrypt_next(buffer.borrow()) { Ok((Some(data), _)) => Ok(data), _ => Err(DecryptionError), } }
function_block-full_function
[ { "content": "/// Marker traits for service bus identifiers\n\npub trait BusId: Copy + Eq + Hash + Display {}\n\n\n\npub struct BusConfig<A>\n\nwhere\n\n A: ServiceAddress,\n\n{\n\n pub carrier: zmqsocket::Carrier,\n\n pub router: Option<A>,\n\n /// Indicates whether the messages must be queued, or ...
Rust
src/message.rs
jbit/ubus-rs
f38156225aad8abdd258fe6bec5b0c0e756fc844
use crate::{Blob, BlobBuilder, BlobIter, BlobMsg, BlobTag, Error, IO}; use core::convert::TryInto; use core::mem::{size_of, transmute}; use storage_endian::{BEu16, BEu32}; values!(pub MessageVersion(u8) { CURRENT = 0x00, }); values!(pub MessageType(u8) { HELLO = 0x00, STATUS = 0x01, ...
use crate::{Blob, BlobBuilder, BlobIter, BlobMsg, BlobTag, Error, IO}; use core::convert::TryInto; use core::mem::{size_of, transmute}; use storage_endian::{BEu16, BEu32}; values!(pub MessageVersion(u8) { CURRENT = 0x00, }); values!(pub MessageType(u8) { HELLO = 0x00, STATUS = 0x01, ...
} }
match blob.tag.id().into() { MessageAttrId::STATUS => MessageAttr::Status(blob.try_into().unwrap()), MessageAttrId::OBJPATH => MessageAttr::ObjPath(blob.try_into().unwrap()), MessageAttrId::OBJID => MessageAttr::ObjId(blob.try_into().unwrap()), MessageAttrId::METHOD => Me...
if_condition
[ { "content": "pub trait IOError {}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 61368.607232113594 }, { "content": "pub trait IO {\n\n type Error: IOError;\n\n fn put(&mut self, data: &[u8]) -> Result<(), Error<Self::Error>>;\n\n fn get(&mut self, data: &mut [u8]) -> Resul...
Rust
structdoc-derive/src/lib.rs
vorner/structdoc
1a5477f228e60ab6b28f0090dbf7f86facc50648
#![doc( html_root_url = "https://docs.rs/structdoc-derive/0.1.4/structdoc-derive/", test(attr(deny(warnings))) )] #![forbid(unsafe_code)] extern crate proc_macro; use std::iter; use either::Either; use itertools::Itertools; use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::punctuated::Punctuat...
#![doc( html_root_url = "https://docs.rs/structdoc-derive/0.1.4/structdoc-derive/", test(attr(deny(warnings))) )] #![forbid(unsafe_code)] extern crate proc_macro; use std::iter; use either::Either; use itertools::Itertools; use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::punctuated::Punctuat...
fn derive_transparent(field: &Field) -> TokenStream { let ty = &field.ty; quote!(<#ty as ::structdoc::StructDoc>::document()) } #[proc_macro_derive(StructDoc, attributes(structdoc))] pub fn structdoc_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let mut input: DeriveInput = syn::par...
n(), ); } } }; quote! { let mut variant = #constructor; #mods let variant = ::structdoc::Field::new(variant, #doc); variants.push((#name.into(), variant)); } }); #[rustfmt::skip] let tag...
function_block-function_prefixed
[ { "content": "#[derive(Clone, StructDoc, Deserialize)]\n\nstruct Inner {\n\n /// A bool\n\n c: bool,\n\n}\n\n\n", "file_path": "examples/document.rs", "rank": 20, "score": 85991.08070017755 }, { "content": "#[derive(StructDoc)]\n\nstruct A<T: Default = ()>(T);\n\n\n", "file_path": ...
Rust
src/gpu/surface.rs
not-wlan/nx
77acb7ec70b7489b4bb0b5417cbf124c2ed862e9
use super::*; use crate::{ gpu::{binder, ioctl}, ipc::cmif::sf, mem, results, service::cmif::{dispdrv, nv, vi}, svc, }; use core::{mem as cmem, ptr}; extern crate alloc; const MAX_BUFFERS: usize = 8; pub type LayerDestroyFn = fn(vi::LayerId, mem::Shared<vi::ApplicationDisplayService>) -> Result<(...
use super::*; use crate::{ gpu::{binder, ioctl}, ipc::cmif::sf, mem, results, service::cmif::{dispdrv, nv, vi}, svc, }; use core::{mem as cmem, ptr}; extern crate alloc; const MAX_BUFFERS: usize = 8; pub type LayerDestroyFn = fn(vi::LayerId, mem::Shared<vi::ApplicationDisplayService>) -> Result<(...
pub fn queue_buffer(&mut self, slot: i32, fences: MultiFence) -> Result<()> { let mut qbi: QueueBufferInput = Default::default(); qbi.swap_interval = 1; qbi.fences = fences; mem::flush_data_cache( self.buffer_data, self.single_buffer_size * self.buffer_coun...
pub fn dequeue_buffer( &mut self, is_async: bool, ) -> Result<(*mut u8, usize, i32, bool, MultiFence)> { let slot: i32; let has_fences: bool; let fences: MultiFence; if is_async { self.wait_buffer_event(-1)?; loop { match self.b...
function_block-full_function
[ { "content": "pub fn allocate(size: usize) -> Result<*mut u8> {\n\n unsafe {\n\n let _ = sync::ScopedLock::new(&mut G_LOCK);\n\n\n\n let mut address = G_CURRENT_ADDRESS;\n\n\n\n loop {\n\n address += mem::PAGE_ALIGNMENT;\n\n\n\n if !G_ADDRESS_SPACE.contains(address)...
Rust
src/event_message/mod.rs
35359595/keriox
62528c164c26f6aa9fcf1ee0e41b34f0e7c45e0b
use crate::{ derivation::{attached_signature_code::get_sig_count, self_addressing::SelfAddressing}, error::Error, event::{ event_data::{inception::InceptionEvent, DelegatedInceptionEvent, DummyEvent, EventData}, Event, }, prefix::{AttachedSignaturePrefix, BasicPrefix, IdentifierPrefi...
use crate::{ derivation::{attached_signature_code::get_sig_count, self_addressing::SelfAddressing}, error::Error, event::{ event_data::{inception::InceptionEvent, DelegatedInceptionEvent, DummyEvent, EventData}, Event, }, prefix::{AttachedSignaturePrefix, BasicPrefix, IdentifierPrefi...
#[test] fn self_addressing_create() -> Result<(), Error> { let ed = ed25519::Ed25519Sha512::new(); let (sig_key_0, sig_priv_0) = ed .keypair(Option::None) .map_err(|e| Error::CryptoError(e))?; let (sig_key_1, sig_priv_1) = ed .keypair(Optio...
let signed_event = icp_m.sign(vec![attached_sig]); let s_ = IdentifierState::default(); let s0 = s_.apply(&signed_event)?; assert!(s0.current.verify(&ser, &signed_event.signatures)?); assert_eq!(s0.prefix, IdentifierPrefix::Basic(pref0.clone())); assert_eq!(s0.sn, 0); ...
function_block-function_prefix_line
[ { "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<EventType>) -> Result<TestStateData, Error> {\n\n let mut st = get_initial_test_data();\n\n...
Rust
engine/matcher/src/matcher/operator/regex.rs
danielsvitols/tornado
9553c38226b9f4964acd146adeb7dd6838178b0a
use crate::accessor::Accessor; use crate::error::MatcherError; use crate::matcher::operator::Operator; use crate::model::InternalEvent; use regex::Regex as RustRegex; use std::collections::HashMap; use tornado_common_api::{cow_to_str, Value}; const OPERATOR_NAME: &str = "regex"; #[derive(Debug)] pub struct Regex { ...
use crate::accessor::Accessor; use crate::error::MatcherError; use crate::matcher::operator::Operator; use crate::model::InternalEvent; use regex::Regex as RustRegex; use std::collections::HashMap; use tornado_common_api::{cow_to_str, Value}; const OPERATOR_NAME: &str = "regex"; #[derive(Debug)] pub struct Regex { ...
rap(); let mut event = Event::new("test_type"); event.payload.insert("value".to_owned(), Value::Bool(true)); assert!(!operator.evaluate(&InternalEvent::new(event), None)); } #[test] fn should_evaluate_to_false_if_value_of_type_number() { let operator = Regex::build( ...
ue = self.target.get(event, extracted_vars); cow_to_str(&cow_value).map_or(false, |text| self.regex.is_match(text)) } } #[cfg(test)] mod test { use super::*; use crate::accessor::AccessorBuilder; use std::collections::HashMap; use tornado_common_api::*; #[test] fn should_return_th...
random
[ { "content": "pub fn read_event_from_file(path: &str) -> Event {\n\n let event_body =\n\n fs::read_to_string(path).unwrap_or_else(|_| panic!(\"Unable to open the file [{}]\", path));\n\n serde_json::from_str(&event_body).unwrap()\n\n}\n\n\n", "file_path": "engine/matcher/benches/utils/mod.rs", ...
Rust
raw/src/types/chat.rs
r4start/telegram-bot
32e682c8dfc77cb89f1b465956f99bbab5a49922
use serde::de::{Deserialize, Deserializer, Error}; use crate::types::*; #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Deserialize)] pub struct User { pub id: UserId, pub first_name: String, pub last_name: Option<String>, pub username: Option<String>, pub is_...
use serde::de::{Deserialize, Deserializer, Error}; use crate::types::*; #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Deserialize)] pub struct User { pub id: UserId, pub first_name: String, pub last_name: Option<String>, pub username: Option<String>, pub is_...
} impl<'de> Deserialize<'de> for Chat { fn deserialize<D>(deserializer: D) -> Result<Chat, D::Error> where D: Deserializer<'de>, { let raw: RawChat = Deserialize::deserialize(deserializer)?; macro_rules! required_field { ($name:ident) => {{ match raw.$n...
pub fn id(&self) -> ChatId { match *self { Chat::Private(ref x) => x.id.into(), Chat::Group(ref x) => x.id.into(), Chat::Supergroup(ref x) => x.id.into(), Chat::Channel(ref x) => x.id.into(), Chat::Unknown(ref x) => x.id.into(), } }
function_block-full_function
[ { "content": "/// Obtains URL to the Telegram Bot API. You're able to change this URL to point to fake Telegram server\n\n/// for E2E-testing by setting `TELEGRAM_API_URL` environment variable.\n\npub fn telegram_api_url() -> String {\n\n match env::var(\"TELEGRAM_API_URL\") {\n\n Ok(url) => url,\n\n ...
Rust
src/buffers/disk/leveldb_buffer.rs
szibis/vector
fa371f5c3a4835f5169eb380e5dec290b718682a
use crate::event::{proto, Event}; use futures01::{ task::{self, AtomicTask, Task}, Async, AsyncSink, Poll, Sink, Stream, }; use leveldb::database::{ batch::{Batch, Writebatch}, compaction::Compaction, iterator::{Iterable, LevelDBIterator}, kv::KV, options::{Options, ReadOptions, WriteOptions...
use crate::event::{proto, Event}; use futures01::{ task::{self, AtomicTask, Task}, Async, AsyncSink, Poll, Sink, Stream, }; use leveldb::database::{ batch::{Batch, Writebatch}, compaction::Compaction, iterator::{Iterable, LevelDBIterator}, kv::KV, options::{Options, ReadOptions, WriteOptions...
}
n()).sum(); let current_size = Arc::new(AtomicUsize::new(initial_size)); let write_notifier = Arc::new(AtomicTask::new()); let blocked_write_tasks = Arc::new(Mutex::new(Vec::new())); let ack_counter = Arc::new(AtomicUsize::new(0)); let acker = Acker::Disk(Arc::clone(&ack_count...
function_block-function_prefixed
[ { "content": "fn random_events(size: usize) -> impl Stream<Item = Event, Error = ()> {\n\n use rand::distributions::Alphanumeric;\n\n use rand::{rngs::SmallRng, thread_rng, Rng, SeedableRng};\n\n\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n\n\n let lines = std::iter::repeat(()).m...
Rust
src/iter/grid_iter.rs
jomsch/gridit
e217f35426cc9eb4ca768e18a7178125fa3443a8
use super::{Positions, PositionsEnumerator}; pub struct GridIter<'a, T> { pub(crate) grid_iter: std::slice::Iter<'a, T>, pub(crate) width: usize, } impl<'a, T> Iterator for GridIter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.grid_iter.next() } } impl<'a, T...
use super::{Positions, PositionsEnumerator}; pub struct GridIter<'a, T> { pub(crate) grid_iter: std::slice::Iter<'a, T>, pub(crate) width: usize, } impl<'a, T> Iterator for GridIter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.grid_iter.next() } } impl<'a, T...
} pub struct GridIterMut<'a, T> { pub(crate) grid_iter: std::slice::IterMut<'a, T>, pub(crate) width: usize, } impl<'a, T> Iterator for GridIterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.grid_iter.next() } } impl<'a, T: 'static> PositionsEnumerato...
Positions { inner: self, prev_position: None, next_pos: |inner, prev_pos| { let (px, py) = match prev_pos { Some(xy) => xy.into(), None => return (0, 0).into(), }; let (x, y) = match px == (inner....
function_block-function_prefix_line
[ { "content": "/// Enumerates the positions of the grid.\n\n/// # Example\n\n/// ```\n\n/// # use gridit::Grid;\n\n/// use gridit::PositionsEnumerator;\n\n/// let grid = Grid::from(vec![1, 2, 1, 2], 2, 2);\n\n/// let mut iter = grid.iter()\n\n/// .grid_positions()\n\n/// .filter(|...
Rust
primitives/sm2/src/rt_sig.rs
hammeWang/substrate-sm2
b0b5715f20fbb3ec70bce203f180dc98ece9d4c0
use sp_std::prelude::*; use sp_std::convert::{Into, TryFrom}; pub use sp_core::{TypeId, crypto::{key_types, KeyTypeId, CryptoType, AccountId32}}; pub use sp_application_crypto::{RuntimeAppPublic, BoundToRuntimeAppPublic}; pub use sp_core::{crypto::{self, Public}, ed25519, sr25519, ecdsa, hash::{H256, H512}}; pub use ...
use sp_std::prelude::*; use sp_std::convert::{Into, TryFrom}; pub use sp_core::{TypeId, crypto::{key_types, KeyTypeId, CryptoType, AccountId32}}; pub use sp_application_crypto::{RuntimeAppPublic, BoundToRuntimeAppPublic}; pub use sp_core::{crypto::{self, Public}, ed25519, sr25519, ecdsa, hash::{H256, H512}}; pub use ...
} } impl From<ed25519::Public> for MultiSigner { fn from(x: ed25519::Public) -> Self { MultiSigner::Ed25519(x) } } impl TryFrom<MultiSigner> for ed25519::Public { type Error = (); fn try_from(m: MultiSigner) -> Result<Self, Self::Error> { if let MultiSigner::Ed25519(x) = m { Ok(x) } else { Err(()) } } } i...
match self { MultiSigner::Ed25519(who) => <[u8; 32]>::from(who).into(), MultiSigner::Sr25519(who) => <[u8; 32]>::from(who).into(), MultiSigner::Ecdsa(who) => sp_io::hashing::blake2_256(&who.as_ref()[..]).into(), MultiSigner::Sm2(who) => sp_io::hashing::blake2_256(&who.as_ref()[..]).into(), }
if_condition
[ { "content": "/// Helper function to generate an account ID from seed\n\npub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId where\n\n\tAccountPublic: From<<TPublic::Pair as Pair>::Public>\n\n{\n\n\tAccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()\n\n}\n\n\n", "file_p...
Rust
src/media/rtp/rtp_receiver/rtp_receiver_test.rs
mpromonet/webrtc
354c943e0ded28c88616b1ae444ff0b56666b380
use super::*; use crate::api::media_engine::MIME_TYPE_OPUS; use crate::media::rtp::rtp_codec::RTPHeaderExtensionParameter; use crate::media::rtp::RTCPFeedback; use crate::media::track::track_local::track_local_static_sample::TrackLocalStaticSample; use crate::media::track::track_local::TrackLocal; use crate::media::Sam...
use super::*; use crate::api::media_engine::MIME_TYPE_OPUS; use crate::media::rtp::rtp_codec::RTPHeaderExtensionParameter; use crate::media::rtp::RTCPFeedback; use crate::media::track::track_local::track_local_static_sample::TrackLocalStaticSample; use crate::media::track::track_local::TrackLocal; use crate::media::Sam...
/*TODO: // Assert that SetReadDeadline works as expected // This test uses VNet since we must have zero loss func Test_RTPReceiver_SetReadDeadline()->Result<()> { lim := test.TimeOut(time.Second * 30) defer lim.Stop() report := test.CheckRoutines(t) defer report() sender, receiver, wan := create...
let seen_packet_tx2 = Arc::clone(&seen_packet_tx); Box::pin(async move { if let Some(r) = &receiver { r.set_rtp_parameters(P.clone()).await; if let Some(t) = r.track().await { let incoming_track_codecs = t.c...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_codecs_from_media_description() -> Result<()> {\n\n //\"Codec Only\"\n\n {\n\n let codecs = codecs_from_media_description(&sdp::media_description::MediaDescription {\n\n media_name: MediaName {\n\n media: \"audio\".to_owned(),\n\n ...