lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/service.rs
redcar-io/redcar
042bd007aef9343a9d0626e94f9101e1254694e4
use std::sync::Arc; use std::pin::Pin; use proto::service::health_check_response; use proto::service::health_server; use proto::service::{HealthCheckRequest, HealthCheckResponse}; use async_stream; use futures::Stream; use tonic::{IntoRequest, IntoStreamingRequest, Request, Response, Streaming}; use tonic::Status; us...
use std::sync::Arc; use std::pin::Pin; use proto::service::health_check_response; use proto::service::health_server; use proto::service::{HealthCheckRequest, HealthCheckResponse}; use async_stream; use futures::Stream; use tonic::{IntoRequest, IntoStreamingRequest, Request, Response, Streaming}; use tonic::Status; us...
S_CHANNEL_SIZE:usize = 265; pub struct Service { pub ws: WatcherService, pub ts: TriggerService, pub ls: LeaserService, pub hs: HealthService, } impl Service { pub fn new(c: Config, rt: Runtime) -> (Result<Service, Error>, Runtime) { println!("build service"); let (ktx, rx) = broad...
untime::Runtime; use tokio::sync::Mutex as Mtx; use proto::service::watch_request::WatchType; use tokio::time::sleep; use bus::{Bus}; use proto::txn::CloudEvent; use crate::ServingStatus; use crate::leaser::{LeaserService}; use crate::trigger::{TriggerService}; use crate::store::Store; use crate::watcher::WatcherServ...
random
[]
Rust
crypto/signature/sm2/src/lib.rs
julyawang/WeDPR-Lab-Crypto
79f87ce94cf7eb239afab0a43a9b949df3f0320e
#[allow(unused_imports)] #[macro_use] extern crate wedpr_l_macros; #[macro_use] extern crate lazy_static; use wedpr_l_utils::{error::WedprError, traits::Signature}; use wedpr_l_libsm::sm2::signature::{SigCtx, Signature as sm2Signature}; lazy_static! { static ref SM2_CTX: SigCtx = SigCtx::new(); } #[deriv...
#[allow(unused_imports)] #[macro_use] extern crate wedpr_l_macros; #[macro_use] extern crate lazy_static; use wedpr_l_utils::{error::WedprError, traits::Signature}; use wedpr_l_libsm::sm2::signature::{SigCtx, Signature as sm2Signature}; lazy_static! { static ref SM2_CTX: SigCtx = SigCtx::new(); } #[deriv...
} #[cfg(test)] mod tests { use super::*; use wedpr_l_utils::constant::tests::BASE64_ENCODED_TEST_MESSAGE; #[test] fn test_sm2() { let sm2_sign = WedprSm2p256v1::default(); let msg_hash = BASE64_ENCODED_TEST_MESSAGE; let (public_key, private_key) = sm2_sign....
pub fn derive_public_key<T: ?Sized + AsRef<[u8]>>( &self, private_key: &T, ) -> Result<Vec<u8>, WedprError> { let secret_key = match SM2_CTX.load_seckey(&private_key.as_ref()) { Ok(v) => v, Err(_) => { return Err(WedprError::FormatError); }...
function_block-full_function
[ { "content": "/// FISCO BCOS precompiled alt_bn128_G1_mul function,\n\n/// returns an error object if any points in pairing_data does not\n\n/// belong the BN128 curve.\n\n// TODO: Add detailed explanation for pairing_data format.\n\npub fn alt_bn128_g1_mul<T: ?Sized + AsRef<[u8]>>(\n\n pairing_data: &T,\n\n...
Rust
src/lib.rs
archisgore/rmesg
5f8e758f5a7d0e90624bc8454f8c8cbc0e8debd9
mod common; pub mod entry; pub mod error; pub mod klogctl; pub mod kmsgfile; #[cfg(feature = "sync")] use std::iter::Iterator; #[cfg(feature = "async")] use core::pin::Pin; #[cfg(feature = "async")] use futures::stream::Stream; #[cfg(feature = "async")] use futures::task::{Context, Poll}; #[cfg(feature = "async")]...
mod common; pub mod entry; pub mod error; pub mod klogctl; pub mod kmsgfile; #[cfg(feature = "sync")] use std::iter::Iterator; #[cfg(feature = "async")] use core::pin::Pin; #[cfg(feature = "async")] use futures::stream::Stream; #[cfg(feature = "async")] use futures::task::{Context, Poll}; #[cfg(feature = "async")]...
/**********************************************************************************/ #[cfg(all(test, target_os = "linux"))] mod test { use super::*; #[cfg(feature = "async")] use tokio_stream::StreamExt; #[test] fn test_log_entries() { let entries = log_entries(Backend::Default, false); ...
eprintln!("WARNING: Timestamps are disabled but tailing/following logs (as you've requested) requires them."); eprintln!("Aboring program."); eprintln!("You can enable timestamps by running the following: "); eprintln!(" echo Y > /sys/module/printk/parameters/time"); return Err(error::R...
function_block-function_prefix_line
[ { "content": "/// This is the key safe function that makes the klogctl syslog call with parameters.\n\n/// While the internally used function supports all klogctl parameters, this function\n\n/// only provides one bool parameter which indicates whether the buffer is to be cleared\n\n/// or not, after its conten...
Rust
src/shape/trimesh.rs
Cupnfish/parry
d193b1010bb8bf33f429e6a91523ff04278a51e1
use crate::bounding_volume::AABB; use crate::math::{Isometry, Point, Real}; use crate::partitioning::SimdQuadTree; use crate::shape::composite_shape::SimdCompositeShape; #[cfg(feature = "dim3")] use crate::shape::{Cuboid, HeightField}; use crate::shape::{Shape, Triangle, TypedSimdCompositeShape}; #[derive(Clone)] #[cf...
use crate::bounding_volume::AABB; use crate::math::{Isometry, Point, Real}; use crate::partitioning::SimdQuadTree; use crate::shape::composite_shape::SimdCompositeShape; #[cfg(feature = "dim3")] use crate::shape::{Cuboid, HeightField}; use crate::shape::{Shape, Triangle, TypedSimdCompositeShape}; #[derive(Clone)] #[cf...
let mut quadtree = SimdQuadTree::new(); quadtree.clear_and_rebuild(data, 0.0); Self { quadtree, vertices, indices, } } pub fn aabb(&self, pos: &Isometry<Real>) -> AABB { self.quadtree.root_aabb().transform_by(...
let data = indices.iter().enumerate().map(|(i, idx)| { let aabb = Triangle::new( vertices[idx[0] as usize], vertices[idx[1] as usize], vertices[idx[2] as usize], ) .local_aabb(); (i as u32, aabb) });
assignment_statement
[ { "content": "#[inline]\n\npub fn center(pts: &[Point<Real>]) -> Point<Real> {\n\n assert!(\n\n pts.len() >= 1,\n\n \"Cannot compute the center of less than 1 point.\"\n\n );\n\n\n\n let denom: Real = na::convert::<f64, Real>(1.0 / (pts.len() as f64));\n\n\n\n let mut piter = pts.iter(...
Rust
rust/src/methods/import/elife.rs
stencila/stencila
bff4faceb1460a84b096e9e45f4a4580a0156295
use std::{fs, path::Path}; use crate::{files::File, sources::Elife, utils::http::download}; use eyre::{bail, Result}; use futures::future::join_all; use minidom::Element; pub async fn import( project: &Path, source: &Elife, destination: Option<String>, ) -> Result<Vec<File>> { let url = format!("https...
use std::{fs, path::Path}; use crate::{files::File, sources::Elife, utils::http::download}; use eyre::{bail, Result}; use futures::future::join_all; use minidom::Element; pub async fn import( project: &Path, source: &Elife, destination: Option<String>, ) -> Result<Vec<File>> { let url = format!("https...
t_dir = destination.parent().expect("Should always have a parent"); let file_name = destination .file_name() .expect("Should always have a file name") .to_string_lossy() .to_string(); let media_dir = format!("{}.media", file_name); fn walk(article: u32, media_dir: ...
ace("<article ", "<article xmlns=\"article\""); let mut root: Element = xml.parse()?; let destination = project.join(destination.unwrap_or_else(|| format!("elife-{}.xml", source.article))); let paren
function_block-random_span
[ { "content": "/// Compile a node\n\n///\n\n/// Compiling a document involves walking over the node tree and compiling each\n\n/// individual node so that it is ready to be built & executed. This includes\n\n/// (but is not limited to):\n\n///\n\n/// - for those node types needing to be accesses directly (e.g. e...
Rust
src/eusci_a3/ucax_mctlw.rs
klanmiko/msp432p401r
f21410cf79fa268fe78714b7e8a367c10374055a
#[doc = "Reader of register UCAxMCTLW"] pub type R = crate::R<u16, super::UCAXMCTLW>; #[doc = "Writer for register UCAxMCTLW"] pub type W = crate::W<u16, super::UCAXMCTLW>; #[doc = "Register UCAxMCTLW `reset()`'s with value 0"] impl crate::ResetValue for super::UCAXMCTLW { type Type = u16; #[inline(always)] ...
#[doc = "Reader of register UCAxMCTLW"] pub type R = crate::R<u16, super::UCAXMCTLW>; #[doc = "Writer for register UCAxMCTLW"] pub type W = crate::W<u16, super::UCAXMCTLW>; #[doc = "Register UCAxMCTLW `reset()`'s with value 0"] impl crate::ResetValue for su
riant as u8 != 0 } } #[doc = "Reader of field `UCOS16`"] pub type UCOS16_R = crate::R<bool, UCOS16_A>; impl UCOS16_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> UCOS16_A { match self.bits { false => UCOS16_A::UCOS16_0, true => UC...
per::UCAXMCTLW { type Type = u16; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Oversampling mode enabled\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum UCOS16_A { #[doc = "0: Disabled"] UCOS16_0 = 0, #[doc = "1: Enabled"] UCOS16_1 = ...
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
runtime/test/src/common.rs
victaphu/graph-node
252f8203496c333c52c5cb7d9d16a12993ca9f61
use ethabi::Contract; use graph::components::store::DeploymentLocator; use graph::data::subgraph::*; use graph::ipfs_client::IpfsClient; use graph::prelude::*; use graph_chain_ethereum::{ Chain, DataSource, DataSourceTemplate, Mapping, MappingABI, TemplateSource, }; use graph_runtime_wasm::{HostExports, MappingCont...
use ethabi::Contract; use graph::components::store::DeploymentLocator; use graph::data::subgraph::*; use graph::ipfs_client::IpfsClient; use graph::prelude::*; use graph_chain_ethereum::{ Chain, DataSource, DataSourceTemplate, Mapping, MappingABI, TemplateSource, }; use graph_runtime_wasm::{HostExports, MappingCont...
pub fn mock_data_source(path: &str, api_version: Version) -> DataSource { let runtime = std::fs::read(path).unwrap(); DataSource { kind: String::from("ethereum/contract"), name: String::from("example data source"), network: Some(String::from("mainnet")), source: Source { ...
pub fn mock_context( deployment: DeploymentLocator, data_source: DataSource, store: Arc<impl SubgraphStore>, api_version: Version, ) -> MappingContext<Chain> { MappingContext { logger: Logger::root(slog::Discard, o!()), block_ptr: BlockPtr { hash: Default::default(), ...
function_block-full_function
[ { "content": "fn mock_abi() -> MappingABI {\n\n MappingABI {\n\n name: \"mock_abi\".to_string(),\n\n contract: Contract::load(\n\n r#\"[\n\n {\n\n \"inputs\": [\n\n {\n\n \"name\": \"a\",\n\n \...
Rust
tests/test_rendering.rs
scott113341/osm-renderer
2045375eee6bd0b627b2b003734687463f997bf2
mod common; use renderer::draw::png_writer::rgb_triples_to_png; use renderer::draw::tile_pixels::{RgbTriples, TilePixels}; use renderer::mapcss::parser::parse_file; use renderer::mapcss::styler::{StyleType, Styler}; use std::collections::BTreeMap; use std::fs::File; use std::io::Write; use std::path::Path; const RED_...
mod common; use renderer::draw::png_writer::rgb_triples_to_png; use renderer::draw::tile_pixels::{RgbTriples, TilePixels}; use renderer::mapcss::parser::parse_file; use renderer::mapcss::styler::{StyleType, Styler}; use std::collections::BTreeMap; use std::fs::File; use std::io::Write; use std::path::Path; const RED_...
iples::new(); let mut raw_pixels = vec![0; reader.output_buffer_size()]; let info = reader.next_frame(&mut raw_pixels).unwrap(); result.extend(raw_pixels[..info.buffer_size()].chunks(3).map(|v| (v[0], v[1], v[2]))); (result, info) } fn compare_png_outputs(zoom: u8, suffix: &str) { let (expected, ex...
Triples, png::OutputInfo) { let decoder = png::Decoder::new(File::open(file_name).unwrap()); let mut reader = decoder.read_info().unwrap(); let mut result = RgbTr
function_block-random_span
[]
Rust
src/auto/favicon_database.rs
antoyo/webkit2-rs
f889cd127472b17e3eb87c9a45ed29e11a7718bb
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use std::pin::Pin; use std::ptr; glib::wrapper! { #[doc(alias = "WebKitFaviconDatabase")] pub struct Fav...
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use std::pin::Pin; use std::ptr; glib::wrapper! { #[doc(alias = "WebKitFaviconDatabase")] pub struct Fav...
fn favicon_uri(&self, page_uri: &str) -> Option<glib::GString> { unsafe { from_glib_full(ffi::webkit_favicon_database_get_favicon_uri( self.as_ref().to_glib_none().0, page_uri.to_glib_none().0, )) } } fn connect_favicon_changed<F: Fn(&Self, &str, &str) + 'static>(&self, f: F...
page_uri: &str, ) -> Pin<Box_<dyn std::future::Future<Output = Result<cairo::Surface, glib::Error>> + 'static>> { let page_uri = String::from(page_uri); Box_::pin(gio::GioFuture::new(self, move |obj, cancellable, send| { obj.favicon(&page_uri, Some(cancellable), move |res| { send.resolve(res);...
function_block-function_prefix_line
[ { "content": "pub trait HitTestResultExt: 'static {\n\n #[doc(alias = \"webkit_hit_test_result_context_is_editable\")]\n\n fn context_is_editable(&self) -> bool;\n\n\n\n #[doc(alias = \"webkit_hit_test_result_context_is_image\")]\n\n fn context_is_image(&self) -> bool;\n\n\n\n #[doc(alias = \"webkit_hit_te...
Rust
banks-server/src/send_transaction_service.rs
charles-e/Safecoin
cab0ae7f4abf357b4555f37dea36c5d20ac960ea
use log::*; use solana_metrics::{datapoint_warn, inc_new_counter_info}; use solana_runtime::{bank::Bank, bank_forks::BankForks}; use safecoin_sdk::signature::Signature; use std::{ collections::HashMap, net::{SocketAddr, UdpSocket}, sync::{ mpsc::{Receiver, RecvTimeoutError}, Arc, RwLock, ...
use log::*; use solana_metrics::{datapoint_warn, inc_new_counter_info}; use solana_runtime::{bank::Bank, bank_forks::BankForks}; use safecoin_sdk::signature::Signature; use std::{ collections::HashMap, net::{SocketAddr, UdpSocket}, sync::{ mpsc::{Receiver, RecvTimeoutError}, Arc, RwLock, ...
fn process_transactions( working_bank: &Arc<Bank>, root_bank: &Arc<Bank>, send_socket: &UdpSocket, tpu_address: &SocketAddr, transactions: &mut HashMap<Signature, TransactionInfo>, ) -> ProcessTransactionsResult { let mut result = ProcessTransactionsResult::defa...
let _result = Self::process_transactions( &working_bank, &root_bank, &send_socket, &tpu_address, &mut transactions, ); } ...
function_block-function_prefix_line
[]
Rust
src/paramcli.rs
cyrille-blanchet-1974/grep
2660ef818bcfdce12b31c6dbcb208f79526ad942
use std::env; #[derive(Debug)] pub struct Paramcli { pub input: String, pub search: String, pub before: u8, pub after: u8, pub case_sensitive: bool, pub inverse_search: bool, pub recurse: bool, } impl Default for Paramcli { fn default() -> Self { Paramcli::new()...
use std::env; #[derive(Debug)] pub struct Paramcli { pub input: String, pub search: String, pub before: u8, pub after: u8, pub case_sensitive: bool, pub inverse_search: bool, pub recurse: bool, } impl Default for Paramcli { fn default() -> Self { Paramcli::new()...
} fn get_param(arg: &str, switch: String) -> Option<String> { if arg.to_lowercase().starts_with(&switch) { let mut a = String::from(arg); return Some(a.split_off(switch.len())); } None } fn help(name: &str) { println!("{} 1.0 (2020)", name); println!("syntax : {} 'what to search' ...
y() { search.push_str(&arg); continue; } if input.is_empty() { input.push_str(&arg); continue; } } help(&name); } if !case_sensitive { ...
function_block-function_prefixed
[ { "content": "pub fn traitement(p: &Paramcli) {\n\n //MPSC chanels\n\n let (to_aggregate, from_read) = channel();\n\n let (to_compute, from_aggregate) = channel();\n\n\n\n let hread = start_thread_read(to_aggregate, p);\n\n let haggregate = start_thread_aggregate(from_read, to_compute, &p);\n\n ...
Rust
daemon/src/database/helpers/grid_schemas.rs
B3n3d1k7B/grid
43044ee53c46cc896ee81d1882346186aa65559a
/* * Copyright 2019 Cargill Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or a...
/* * Copyright 2019 Cargill Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or a...
if let Some(service_id) = service_id { query = query.filter(grid_schema::service_id.eq(service_id)); } else { query = query.filter(grid_schema::service_id.is_null()); } query.load::<GridSchema>(conn) } pub fn list_grid_property_definitions( conn: &PgConnection, service_id: Op...
let mut query = grid_schema::table .into_boxed() .select(grid_schema::all_columns) .filter(grid_schema::end_commit_num.eq(MAX_COMMIT_NUM));
assignment_statement
[ { "content": "/// Computes the address a Grid Schema is stored at based on its name\n\npub fn compute_schema_address(name: &str) -> String {\n\n let mut sha = Sha512::new();\n\n sha.input(name.as_bytes());\n\n\n\n String::from(GRID_NAMESPACE) + GRID_SCHEMA_NAMESPACE + &sha.result_str()[..62].to_string(...
Rust
core/http/src/uri/uri.rs
dgriffen/Rocket
7fb6ba9be5dc2c3f032b5d1006d25587bb1543c7
use std::fmt::{self, Display}; use std::convert::From; use std::borrow::Cow; use std::str::Utf8Error; use std::convert::TryFrom; use ext::IntoOwned; use parse::Indexed; use uri::{Origin, Authority, Absolute, Error}; #[derive(Debug, PartialEq, Clone)] pub enum Uri<'a> { Origin(Origin<'a>), Authority(...
use std::fmt::{self, Display}; use std::convert::From; use std::borrow::Cow; use std::str::Utf8Error; use std::convert::TryFrom; use ext::IntoOwned; use parse::Indexed; use uri::{Origin, Authority, Absolute, Error}; #[derive(Debug, PartialEq, Clone)] pub enum Uri<'a> { Origin(Origin<'a>), Authority(...
} impl<'a> TryFrom<&'a str> for Uri<'a> { type Error = Error<'a>; #[inline] fn try_from(string: &'a str) -> Result<Uri<'a>, Self::Error> { Uri::parse(string) } } impl TryFrom<String> for Uri<'static> { type Error = Error<'static>; #[inline] fn try_from(string: String) -> Result<...
match input { Cow::Borrowed(bytes) => Cow::Borrowed(::std::str::from_utf8_unchecked(bytes)), Cow::Owned(bytes) => Cow::Owned(String::from_utf8_unchecked(bytes)) }
if_condition
[]
Rust
crates/sui-open-rpc/src/lib.rs
huitseeker/sui
c5b77c8585ac87063933847b82177eec32ade23b
use std::collections::BTreeMap; use schemars::gen::{SchemaGenerator, SchemaSettings}; use schemars::schema::SchemaObject; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone)] pub struct Project { openrpc: String, info: Info, methods: Vec<Method>, co...
use std::collections::BTreeMap; use schemars::gen::{SchemaGenerator, SchemaSettings}; use schemars::schema::SchemaObject; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone)] pub struct Project { openrpc: String, info: Info, methods: Vec<Method>, co...
Self { proj_name: proj_name.to_string(), namespace: namespace.to_string(), version: env!("CARGO_PKG_VERSION").to_owned(), openrpc: "1.2.6".to_string(), schema_generator, methods: vec![], content_descriptors: BTreeMap::new(), ...
let schema_generator = SchemaSettings::default() .with(|s| { s.definitions_path = "#/components/schemas/".to_string(); }) .into_generator();
assignment_statement
[ { "content": "fn unwrap_or<'a>(val: &'a Option<String>, default: &'a str) -> &'a str {\n\n match val {\n\n Some(v) => v,\n\n None => default,\n\n }\n\n}\n\n\n", "file_path": "crates/sui/src/wallet_commands.rs", "rank": 0, "score": 248761.3030145525 }, { "content": "pub fn...
Rust
common/src/border.rs
AdrianDanis/prototty
544abb85efacb49bdd87a0be4382b08c7bad32a2
use prototty::*; use decorated::Decorated; use defaults::*; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BorderChars { pub top: char, pub bottom: char, pub left: char, pub right: char, pub top_left: char, pub top_right: char, pub bottom_left: char, pub bottom_right: char, ...
use prototty::*; use decorated::Decorated; use defaults::*; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BorderChars { pub top: char, pub bottom: char, pub left: char, pub right: char, pub top_left: char, pub top_right: char, pub bottom_left: char, pub bottom_right: char, ...
} #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct BorderPadding { pub top: u32, pub bottom: u32, pub left: u32, pub right: u32, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Border { pub title: Option<String>, pub padding: BorderPadding, pub chars: Borde...
fn default() -> Self { Self { top: '─', bottom: '─', left: '│', right: '│', top_left: '┌', top_right: '┐', bottom_left: '└', bottom_right: '┘', before_title: '┤', after_title: '├', } ...
function_block-full_function
[ { "content": "struct Timeout {\n\n pub remaining: Duration,\n\n}\n\n\n\nimpl Timeout {\n\n pub fn from_millis(millis: u64) -> Self {\n\n Self::new(Duration::from_millis(millis))\n\n }\n\n pub fn zero() -> Self {\n\n Self::from_millis(0)\n\n }\n\n pub fn new(remaining: Duration) -...
Rust
src/developer/ffx/plugins/target/flash/src/args.rs
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
use { argh::FromArgs, ffx_core::ffx_command, ffx_fastboot::common::cmd::{Command, ManifestParams, OemFile}, std::default::Default, std::path::PathBuf, }; #[ffx_command()] #[derive(FromArgs, Default, Debug, PartialEq)] #[argh( subcommand, name = "flash", description = "Flash an image t...
use { argh::FromArgs, ffx_core::ffx_command, ffx_fastboot::common::cmd::{Command, ManifestParams, OemFile}, std::default::Default, std::path::PathBuf, }; #[ffx_command()] #[derive(FromArgs, Default, Debug, PartialEq)] #[argh( subcommand, name = "flash", description = "Flash an image t...
arams.oem_stage[0].command(), test_oem_cmd); Ok(()) } }
manifest: self.manifest, product: self.product, product_bundle: self.product_bundle, oem_stage: self.oem_stage, skip_verify: self.skip_verify, no_bootloader_reboot: self.no_bootloader_reboot, op: Command::Flash, ..Default::default(...
random
[]
Rust
src/lib.rs
kalix-systems/semalock
e7ea49921e3da16e464cdd73e94fdcdc26c1d8ca
extern crate errno; /* @TODO really need a dep for this? */ extern crate libc; extern crate tempfile; use std::collections::hash_map::DefaultHasher; use std::error::Error; use std::ffi::CString; use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; use std::os::unix::io::AsRawFd; use std::path::Path; use st...
extern crate errno; /* @TODO really need a dep for this? */ extern crate libc; extern crate tempfile; use std::collections::hash_map::DefaultHasher; use std::error::Error; use std::ffi::CString; use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; use std::os::unix::io::AsRawFd; use std::path::Path; use st...
} #[test] fn basic_usage() { use std::fs::remove_file; use std::io::prelude::*; use tempfile::NamedTempFile; let file = NamedTempFile::new().unwrap(); let path = file.path(); let mut lock = Semalock::new(path).unwrap(); lock.with(|lock| { lock.file.write_all(b"hello world!").unwr...
if sem_getvalue_code != 0 { let e = errno::errno(); return Err(format!("sem_getvalue {}: {}", e.0, e)); } if sem_value == 0 { let sem_post_code = unsafe { libc::sem_post(self.sem) }; if sem_post_code != 0 { let e = errno::errno()...
function_block-function_prefix_line
[ { "content": "# semalock\n\n\n\n[![Crates.io](https://img.shields.io/crates/v/semalock.svg?style=flat-square)](https://crates.io/crates/semalock)\n\n[![Crates.io](https://img.shields.io/crates/d/semalock.svg?style=flat-square)](https://crates.io/crates/semalock)\n\n[![Travis](https://img.shields.io/travis/longs...
Rust
src/fsevent.rs
fossabot/fsevent-better
ef43e72718aeb7cc904ba7b8ec7a6c050fa95793
use std::ffi::{c_void, CStr}; use std::io; use std::os::raw::c_char; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::mpsc::channel; use std::task::{Context, Poll}; use std::thread; use std::time::Duration; use core_foundation::runloop::{kCFRunLoopBeforeWaiting, kCFRunLoopDefaultMode, CFRunLoop}; us...
use std::ffi::{c_void, CStr}; use std::io; use std::os::raw::c_char; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::mpsc::channel; use std::task::{Context, Poll}; use std::thread; use std::time::Duration; use core_foundation::runloop::{kCFRunLoopBeforeWaiting, kCFRunLoopDefaultMode, CFRunLoop}; us...
extern "C" fn callback( stream_ref: fs::FSEventStreamRef, info: *mut c_void, num_events: usize, event_paths: *mut c_void, event_flags: *const fs::FSEventStreamEventFlags, event_ids: *const fs::FSEventStreamEventId, ) { unsafe { ...
runloop_rx.recv().expect("receive runloop from worker").0, thread_handle, stream_handle, )), }, )) }
function_block-function_prefix_line
[ { "content": "pub fn create_oneshot_observer(\n\n interest: CFRunLoopActivity,\n\n tx: Sender<CFRunLoopActivity>,\n\n) -> CFRunLoopObserver {\n\n let ctx = Box::into_raw(Box::new(CFRunLoopObserverContext {\n\n version: 0,\n\n info: Box::into_raw(Box::new(ObserverContextInfo { interest, tx...
Rust
src/desktop/inhibit.rs
A6GibKm/ashpd
a45ef79faa8b052764e9e9667777c7ef927c06a2
use enumflags2::BitFlags; use futures::TryFutureExt; use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; use zvariant::OwnedObjectPath; use zvariant_derive::{DeserializeDict, SerializeDict, Type, TypeDict}; use super::{HandleToken, SessionProxy, DESTINATION, PATH}; use crate::{ ...
use enumflags2::BitFlags; use futures::TryFutureExt; use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; use zvariant::OwnedObjectPath; use zvariant_derive::{DeserializeDict, SerializeDict, Type, TypeDict}; use super::{HandleToken, SessionProxy, DESTINATION, PATH}; use crate::{ ...
#[doc(alias = "StateChanged")] pub async fn receive_state_changed(&self) -> Result<InhibitState, Error> { receive_signal(&self.0, "StateChanged").await } #[doc(alias = "QueryEndResponse")] pub async ...
t( &self, identifier: &WindowIdentifier, flags: BitFlags<InhibitFlags>, reason: &str, ) -> Result<(), Error> { let options = InhibitOptions::default().reason(reason); call_basic_response_method( &self.0, &options.handle_token, "Inhi...
function_block-function_prefixed
[ { "content": "/// Check whether the application is running inside a sandbox.\n\n///\n\n/// **Note** The check is very stupid as is for now.\n\npub fn is_sandboxed() -> bool {\n\n std::path::Path::new(\"/.flatpak-info\").exists()\n\n}\n\n\n\npub use self::error::Error;\n", "file_path": "src/lib.rs", "...
Rust
crates/net/src/http/mod.rs
minauteur/gloo
8467f47d110f5f526404d7b8a4bc3d791d77b87e
mod headers; use crate::{js_to_error, Error}; use js_sys::{ArrayBuffer, Uint8Array}; use serde::Serialize; use std::fmt; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; #[cfg(feature = "json")] #[cfg_attr(docsrs, doc(cfg(feature = "json")))] use serde::de::DeserializeOwne...
mod headers; use crate::{js_to_error, Error}; use js_sys::{ArrayBuffer, Uint8Array}; use serde::Serialize; use std::fmt; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; #[cfg(feature = "json")] #[cfg_attr(docsrs, doc(cfg(feature = "json")))] use serde::de::DeserializeOwne...
dow().fetch_with_request(&request); let response = JsFuture::from(promise).await.map_err(js_to_error)?; match response.dyn_into::<web_sys::Response>() { Ok(response) => Ok(Response { response: response.unchecked_into(), }), Err(e) => panic!("fetch retu...
quest = web_sys::Request::new_with_str_and_init(&self.url, &self.options) .map_err(js_to_error)?; let promise = gloo_utils::win
function_block-random_span
[ { "content": "/// Calls the `prompt` function.\n\n///\n\n/// A default value can be supplied which will be returned if the user doesn't input anything.\n\n/// This function will return `None` if the value of `default` is `None` and the user cancels\n\n/// the operation.\n\n///\n\n/// [MDN Documentation](https:/...
Rust
probe-rs-cli-util/src/lib.rs
twelho/probe-rs
679c98535076c9cae52ed93b0a9876335f97aabf
pub mod argument_handling; pub mod common_options; pub mod flash; pub mod logging; use cargo_toml::Manifest; use serde::Deserialize; use thiserror::Error; use cargo_metadata::Message; use std::{ path::{Path, PathBuf}, process::{Command, Stdio}, }; pub use indicatif; pub use log; pub use structopt; #[derive(...
pub mod argument_handling; pub mod common_options; pub mod flash; pub mod logging; use cargo_toml::Manifest; use serde::Deserialize; use thiserror::Error; use cargo_metadata::Message; use std::{ path::{Path, PathBuf}, process::{Command, Stdio}, }; pub use indicatif; pub use log; pub use structopt; #[derive(...
pub fn build_artifact(work_dir: &Path, args: &[String]) -> Result<PathBuf, ArtifactError> { let work_dir = dunce::canonicalize(work_dir).map_err(|e| ArtifactError::Canonicalize { source: e, work_dir: format!("{}", work_dir.display()), })?; let cargo_executable = std::env::var("CARGO").unw...
pub fn read_metadata(work_dir: &Path) -> Result<Metadata, ArtifactError> { let cargo_toml = work_dir.join("Cargo.toml"); let cargo_toml_content = std::fs::read(&cargo_toml).map_err(|e| ArtifactError::CargoToml { source: e, path: format!("{}", cargo_toml.display()), })?; let meta = matc...
function_block-full_function
[ { "content": "/// Captures an anyhow error with sentry and sends all previously captured logs.\n\npub fn capture_anyhow(metadata: &Metadata, error: &anyhow::Error) {\n\n let _guard = sentry::init(sentry_config(metadata.release.clone()));\n\n set_metadata(metadata);\n\n send_logs();\n\n let uuid = se...
Rust
vulkano/src/command_buffer/submit/queue_present.rs
one-bit/vulkano
a939adc3432b367bcfb6fc92c7d994a945ce3df3
use smallvec::SmallVec; use std::error; use std::fmt; use std::marker::PhantomData; use std::ptr; use device::DeviceOwned; use device::Queue; use swapchain::PresentRegion; use swapchain::Swapchain; use sync::Semaphore; use check_errors; use vk; use Error; use OomError; use SynchronizedVulkanObject; use VulkanObject...
use smallvec::SmallVec; use std::error; use std::fmt; use std::marker::PhantomData; use std::ptr; use device::DeviceOwned; use device::Queue; use swapchain::PresentRegion; use swapchain::Swapchain; use sync::Semaphore; use check_errors; use vk; use Error; use OomError; use SynchronizedVulkanObject; use VulkanObject...
pub fn submit(mut self, queue: &Queue) -> Result<(), SubmitPresentError> { unsafe { debug_assert_eq!(self.swapchains.len(), self.image_indices.len()); assert!( !self.swapchains.is_empty(), "Tried to submit a present comm...
gions.push(vk_present_region); } self.swapchains.push(swapchain.internal_object()); self.image_indices.push(image_num); }
function_block-function_prefixed
[ { "content": "/// Checks whether the dispatch dimensions are supported by the device.\n\npub fn check_dispatch(device: &Device, dimensions: [u32; 3]) -> Result<(), CheckDispatchError> {\n\n let max = device\n\n .physical_device()\n\n .limits()\n\n .max_compute_work_group_count();\n\n\n\n...
Rust
src/records/bgp4mp.rs
rrybarczyk/bgpdump-rs
87f784661f4160fccd8973b7c542902728f126fe
use byteorder::{BigEndian, ReadBytesExt}; use std::io::{Error, ErrorKind, Read}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use crate::Header; use crate::AFI; #[derive(Debug)] #[allow(non_camel_case_types)] pub enum BGP4MP { STATE_CHANGE(STATE_CHANGE), MESSAGE(MESSAGE), ENTRY(ENTRY), ...
use byteorder::{BigEndian, ReadBytesExt}; use std::io::{Error, ErrorKind, Read}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use crate::Header; use crate::AFI; #[derive(Debug)] #[allow(non_camel_case_types)] pub enum BGP4MP { STATE_CHANGE(STATE_CHANGE), MESSAGE(MESSAGE), ENTRY(ENTRY), ...
stream.read_u32::<BigEndian>()?; let interface = stream.read_u16::<BigEndian>()?; let afi = stream.read_u16::<BigEndian>()?; let peer_address = match AFI::from(afi)? { AFI::IPV4 => IpAddr::V4(Ipv4Addr::from(stream.read_u32::<BigEndian>()?)), AFI::IPV6 => IpAddr::V6(Ipv6Ad...
= header.length - (8 + 2 * AFI::from(afi)?.size()); let mut message = vec![0; length as usize]; stream.read_exact(&mut message)?; Ok(MESSAGE { peer_as, local_as, interface, peer_address, local_address, message, }) ...
random
[ { "content": "///\n\n/// # Summary\n\n/// Used to parse ISIS MRT records.\n\n///\n\n/// # Panics\n\n/// This function does not panic.\n\n///\n\n/// # Errors\n\n/// Any IO error will be returned while reading from the stream.\n\n/// If an ill-formatted stream or header is provided behavior will be undefined.\n\n...
Rust
demos/examples/druid_3d_shapes.rs
dyaso/klein-ported-to-rust
8e41d185276680610f74403ae623c1bd865eafb1
#![cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use druid::kurbo::{BezPath}; use druid::piet::{FontFamily, FontStyle, ImageFormat, InterpolationMode}; use druid::kurbo; use druid::widget::prelude::*; use druid::{ Affine, AppLauncher, ArcStr, Color, Data, FontDescriptor, LocalizedString, MouseEvent, ...
#![cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use druid::kurbo::{BezPath}; use druid::piet::{FontFamily, FontStyle, ImageFormat, InterpolationMode}; use druid::kurbo; use druid::widget::prelude::*; use druid::{ Affine, AppLauncher, ArcStr, Color, Data, FontDescriptor, LocalizedString, MouseEvent, ...
pub fn set_window_boundary_planes(&mut self, _state: &State, window: &kurbo::Size) { let desired_width = self.right_x - self.left_x; let desired_height = self.upper_y - self.lower_y; let desired_aspect_ratio = desired_width / desired_height; let center_x = (self.right_x + self.left...
fn new() -> CustomWidget { CustomWidget { lower_y: -2., upper_y: 2., left_x: -2., right_x: 2., ..Default::default() } }
function_block-full_function
[ { "content": "pub fn origin() -> Point {\n\n Point::new(0., 0., 0.)\n\n}\n\n\n\n// // trait AsRef<T: ?Sized> {\n\n// // fn as_ref(&self) -> &T;\n\n// // }\n\n// impl AsRef<Point> for Point {\n\n// fn as_ref(&self) -> &Point {\n\n// &(&self)\n\n// }\n\n// }\n\n\n\nuse std::fmt;\n\n\n\nimpl...
Rust
tokweb/src/system.rs
john-sharratt/ate
f9982e4d2b210942e6aa39aa03c1f3e72acb55e9
use async_trait::async_trait; use js_sys::Promise; use std::cell::RefCell; use std::future::Future; use std::pin::Pin; use std::rc::Rc; use term_lib::api::abi::SystemAbi; use tokio::sync::mpsc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasm_bindgen::prelude::*; use wasm_bin...
use async_trait::async_trait; use js_sys::Promise; use std::cell::RefCell; use std::future::Future; use std::pin::Pin; use std::rc::Rc; use term_lib::api::abi::SystemAbi; use tokio::sync::mpsc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasm_bindgen::prelude::*; use wasm_bin...
; let ok = resp.ok(); let redirected = resp.redirected(); let status = resp.status(); let status_text = resp.status_text(); let data = match crate::common::get_response_data(resp).await { Ok(a) => a, ...
match crate::common::fetch(url.as_str(), method.as_str(), headers, data) .await { Ok(a) => a, Err(err) => { let _ = tx.send(Err(err)).await; return; } }
if_condition
[ { "content": "fn canonicalize(path: &str) -> String {\n\n let mut ret = String::with_capacity(path.len());\n\n\n\n let mut comps = Vec::new();\n\n for comp in path.split(\"/\") {\n\n if comp.len() <= 0 {\n\n continue;\n\n }\n\n if comp == \".\" {\n\n continue;...
Rust
language/move-prover/bytecode/src/data_invariant_instrumentation.rs
awelc/move
2f0d73d518c9dc178d02592e665e78fd391d9dc9
use crate::{ function_data_builder::FunctionDataBuilder, function_target::FunctionData, function_target_pipeline::{FunctionTargetProcessor, FunctionTargetsHolder}, options::ProverOptions, stackless_bytecode::{Bytecode, Operation, PropKind}, }; use move_model::{ ast, ast::{ConditionKind, E...
use crate::{ function_data_builder::FunctionDataBuilder, function_target::FunctionData, function_target_pipeline::{FunctionTargetProcessor, FunctionTargetsHolder}, options::ProverOptions, stackless_bytecode::{Bytecode, Operation, PropKind}, }; use move_model::{ ast, ast::{ConditionKind, E...
fn translate_invariant(&self, deep: bool, value: Exp) -> Vec<(Loc, Exp)> { let ty = self.builder.global_env().get_node_type(value.node_id()); match ty.skip_reference() { Type::Struct(mid, sid, targs) => { let struct_env = self.builder.global_env().get_module(*mid).into_...
fn emit_data_invariant_for_temp(&mut self, deep: bool, kind: PropKind, temp: TempIndex) { let temp_exp = self.builder.mk_temporary(temp); for (loc, inv) in self.translate_invariant(deep, temp_exp) { self.builder.set_next_debug_comment(format!( "data invariant {}", ...
function_block-full_function
[]
Rust
execution-engine/engine-tests/src/test/system_contracts/proof_of_stake/finalize_payment.rs
RitaatCasperLabs/CasperLabs
a81ce10078664d7ef68f4c55157b9afc5be45f3a
use std::convert::TryInto; use contract_ffi::{ key::Key, value::{ account::{Account, PublicKey, PurseId}, U512, }, }; use engine_core::engine_state::{ genesis::{POS_PAYMENT_PURSE, POS_REWARDS_PURSE}, CONV_RATE, }; use engine_shared::{gas::Gas, motes::Motes}; use crate::{ suppor...
use std::convert::TryInto; use contract_ffi::{ key::Key, value::{ account::{Account, PublicKey, PurseId}, U512, }, }; use engine_core::engine_state::{ genesis::{POS_PAYMENT_PURSE, POS_REWARDS_PURSE}, CONV_RATE, }; use engine_shared::{gas::Gas, motes::Motes}; use crate::{ suppor...
#[ignore] #[test] fn finalize_payment_should_not_be_run_by_non_system_accounts() { let mut builder = initialize(); let payment_amount = U512::from(300); let spent_amount = U512::from(75); let refund_purse: Option<PurseId> = None; let args = ( payment_amount, refund_purse, S...
builder .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit(); builder }
function_block-function_prefix_line
[ { "content": "pub fn contract_hash(builder: &mut TestBuilder, account: [u8; 32], name: &str) -> [u8; 32] {\n\n let account_key = Key::Account(account);\n\n let value: Value = builder.query(None, account_key, &[name]).unwrap();\n\n if let Value::Key(Key::Hash(contract_hash)) = value {\n\n contrac...
Rust
gio/src/auto/network_service.rs
YaLTeR/gtk-rs
b10a29d60458d33642c05421b0ece8d67582229e
use crate::SocketConnectable; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::glib_wrapper! { pub struct NetworkService(Object<ffi::GNetworkService, f...
use crate::SocketConnectable; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::glib_wrapper! { pub struct NetworkService(Object<ffi::GNetworkService, f...
fn connect_property_scheme_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_scheme_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::GNetworkService, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where ...
e { ffi::g_network_service_set_scheme( self.as_ref().to_glib_none().0, scheme.to_glib_none().0, ); } }
function_block-function_prefixed
[ { "content": "pub fn version() -> &'static str {\n\nif cfg!(feature = \"v3_24\") {\n\n \"3.24\"\n\n } else if cfg!(feature = \"v3_22\") {\n\n \"3.22\"\n\n } else if cfg!(feature = \"v3_20\") {\n\n \"3.20\"\n\n } else if cfg!(feature = \"v3_18\") {\n\n \"3.18\"\n\n } else ...
Rust
probe-rs/examples/tcp_itm.rs
bfrog/probe-rs
4d8058d1bcb1c0b348717a7d375fc7d736fafeb6
use probe_rs::architecture::arm::swo::{ Decoder, SwoConfig, SwoPublisher, TracePacket, UpdaterChannel, }; use probe_rs::Error; use serde::{Deserialize, Serialize}; use std::io::prelude::*; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::mpsc::{channel, Sender}; use std::thread::{sleep, spawn, Joi...
use probe_rs::architecture::arm::swo::{ Decoder, SwoConfig, SwoPublisher, TracePacket, UpdaterChannel, }; use probe_rs::Error; use serde::{Deserialize, Serialize}; use std::io::prelude::*; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::mpsc::{channel, Sender}; use std::thread::{sleep, spawn, Joi...
} } } } for i in to_remove.into_iter().rev() { sockets.swap_remove(i); } } } impl SwoPublisher for TcpPublisher { fn start< I: Serialize + Send + Sync + 'static, O: Deserialize<'static> + Send + Sync + 'static, ...
) => (), Err(err) => { if err.kind() == std::io::ErrorKind::WouldBlock { } else { to_remove.push(i); log::error!("Writing to a tcp socket experienced an error: {:?}", err)
function_block-random_span
[ { "content": "/// This is the main entrypoint which we will call to start the GDB stub.\n\npub fn run(connection_string: Option<impl Into<String>>, session: Session) -> Result<()> {\n\n let connection_string = connection_string\n\n .map(|cs| cs.into())\n\n .unwrap_or_else(|| CONNECTION_STRING.t...
Rust
src/compute/take/list.rs
abreis/arrow2
982454620d1db7964a4e272b3f74745563b6ba5a
use crate::{ array::{ growable::{Growable, GrowableList}, Array, ListArray, Offset, PrimitiveArray, }, error::Result, }; use super::maybe_usize; pub fn take<I: Offset, O: Offset>( values: &ListArray<I>, indices: &PrimitiveArray<O>, ) -> Result<ListArray<I>> { let mut capacity...
use crate::{ array::{ growable::{Growable, GrowableList}, Array, ListArray, Offset, PrimitiveArray, }, error::Result, }; use super::maybe_usize; pub fn take<I: Offset, O: Offset>( values: &ListArray<I>, indices: &PrimitiveArray<O>, ) -> Result<ListArray<I>> { let mut capacity...
#[test] fn list_both_validity() { let values = vec![ Some(vec![Some(2i32), Some(3), Some(4), Some(5)]), None, Some(vec![Some(9i32)]), Some(vec![Some(6i32), Some(7), Some(8)]), ]; let array: ListPrimitive<i32, Primitive<i32>, i32> = values...
c![Some(2i32), Some(3), Some(4), Some(5)]), Some(vec![Some(6i32), Some(7), Some(8)]), ]; let expected: ListPrimitive<i32, Primitive<i32>, i32> = data_expected.into_iter().collect(); let expected = expected.to(ListArray::<i32>::default_datatype(DataType::Int32)); assert_eq!(r...
function_block-function_prefixed
[ { "content": "pub fn take<O: Offset>(values: &dyn Array, indices: &PrimitiveArray<O>) -> Result<Box<dyn Array>> {\n\n if indices.len() == 0 {\n\n return Ok(new_empty_array(values.data_type().clone()));\n\n }\n\n\n\n match values.data_type() {\n\n DataType::Null => Ok(Box::new(NullArray::f...
Rust
src/video_hashing/search.rs
abanoubha/vid_dup_finder_lib
ef427f40d4c3731c95ddd9938e9da4117dfb2fa4
use crate::*; #[derive(Debug, Default)] struct Entry { matched: bool, value: VideoHash, } impl From<VideoHash> for Entry { fn from(val: VideoHash) -> Self { Self { matched: false, value: val, } } } #[derive(Debug, Default)] pub struct Search { entries: Vec<E...
use crate::*; #[derive(Debug, Default)] struct Entry { matched: bool, value: VideoHash, } impl From<VideoHash> for Entry { fn from(val: VideoHash) -> Self { Self { matched: false, value: val, } } } #[derive(Debug, Default)] pub struct Search { entries: Vec<E...
} if !match_vec.is_empty() { match_vec.push(target.value.clone()); ret.push(match_vec); } } if let Some(next_lhs) = advance_lhs(lhs, &self.entries) { lhs = next_lhs; } else { ...
if !cand.matched && tolerance.contains(&target.value.levenshtein_distance(&cand.value)) { match_vec.push(cand.value.clone()); cand.matched = true; }
if_condition
[]
Rust
src/utils.rs
argmin-rs/modcholesky
6f63a293311ac3f15e4174f74d5142b6c8127ee6
use ndarray_rand::RandomExt; use rand::distributions::Uniform; use rand::prelude::*; pub fn eigenvalues_2x2(mat: &ndarray::ArrayView2<f64>) -> (f64, f64) { let a = mat[(0, 0)]; let b = mat[(0, 1)]; let c = mat[(1, 0)]; let d = mat[(1, 1)]; let tmp = ((-(a + d) / 2.0).powi(2) - a * d + b * c).sqrt...
use ndarray_rand::RandomExt; use rand::distributions::Uniform; use rand::prelude::*; pub fn eigenvalues_2x2(mat: &ndarray::ArrayView2<f64>) -> (f64, f64) { let a = mat[(0, 0)]; let b = mat[(0, 1)]; let c = mat[(
28); let res: ndarray::Array2<f64> = ndarray::arr2(&[[-0.49803921207376156, 0.0], [0.0, 0.0039215684018965025]]); assert!(d.abs_diff_eq(&res, 1e-19)); } }
1, 0)]; let d = mat[(1, 1)]; let tmp = ((-(a + d) / 2.0).powi(2) - a * d + b * c).sqrt(); let l1 = (a + d) / 2.0 + tmp; let l2 = (a + d) / 2.0 - tmp; if l1 > l2 { (l1, l2) } else { (l2, l1) } } pub fn swap_columns<T>(mat: &mut ndarray::Array2<T>, idx1: usize, idx2: usize) wh...
random
[ { "content": "/// Gershgorin circles\n\n///\n\n/// # References\n\n///\n\n/// * Semyon Aranovich Gerschgorin.\n\n/// Über die Abgrenzung der Eigenwerte einer Matrix.\n\n/// Izv. Akad. Nauk. USSR Otd. Fiz.-Mat. Nauk, 6: 749–754, 1931.\n\npub trait GershgorinCircles {\n\n /// Computes the Gershgorin Circle...
Rust
libtiny_tui/src/lib.rs
jbg/tiny
7eb82b7e5bc355d4a8e913174e99ce7d9d155540
#![cfg_attr(test, feature(test))] #![allow(clippy::too_many_arguments)] #![allow(clippy::cognitive_complexity)] mod config; mod exit_dialogue; mod messaging; #[doc(hidden)] pub mod msg_area; mod notifier; mod statusline; mod tab; mod termbox; mod text_field; mod trie; mod tui; mod utils; mod widget; pub use crate::t...
#![cfg_attr(test, feature(test))] #![allow(clippy::too_many_arguments)] #![allow(clippy::cognitive_complexity)] mod config; mod exit_dialogue; mod messaging; #[doc(hidden)] pub mod msg_area; mod notifier; mod statusline; mod tab; mod termbox; mod text_field; mod trie; mod tui; mod utils; mod widget; pub use crate::t...
async fn input_handler( tui: Rc<RefCell<tui::TUI>>, mut snd_ev: mpsc::Sender<Event>, mut snd_abort: mpsc::Sender<()>, ) { let mut input = Input::new(); while let Some(mb_ev) = input.next().await { use tui::TUIRet::*; match mb_ev { Err(io_err) => { debug!...
Err(err) => { debug!("Can't install SIGWINCH handler: {:?}", err); return; } Ok(stream) => stream, }; let mut stream_fused = stream.fuse(); let mut rcv_abort_fused = rcv_abort.fuse(); loop { select! { _ = stream_fused.next() => { ...
function_block-function_prefix_line
[ { "content": "fn draw(tui: &mut Termbox, fg: bool) {\n\n tui.clear();\n\n\n\n let row = 0;\n\n let row = draw_range(tui, 0, 16, row, fg);\n\n let row = draw_range(tui, 16, 232, row + 1, fg);\n\n let _ = draw_range(tui, 232, 256, row + 1, fg);\n\n\n\n tui.present();\n\n}\n\n\n", "file_path"...
Rust
src/matrix.rs
doxxx/raytracer
21c92437ffd07d0434f8e095ce787fe23f42658c
use std::cmp::PartialEq; use std::ops::{Index, IndexMut, Mul}; use direction::Direction; use point::Point; #[derive(Debug, Clone, Copy)] pub struct Matrix44f(pub [[f64; 4]; 4]); impl Matrix44f { pub fn zero() -> Matrix44f { Matrix44f([ [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], ...
use std::cmp::PartialEq; use std::ops::{Index, IndexMut, Mul}; use direction::Direction; use point::Point; #[derive(Debug, Clone, Copy)] pub struct Matrix44f(pub [[f64; 4]; 4]); impl Matrix44f { pub fn zero() -> Matrix44f { Matrix44f([ [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], ...
} impl Mul<Matrix44f> for Direction { type Output = Direction; fn mul(self, rhs: Matrix44f) -> Self::Output { Direction::new( self.x * rhs[0][0] + self.y * rhs[1][0] + self.z * rhs[2][0], self.x * rhs[0][1] + self.y * rhs[1][1] + self.z * rhs[2][1], self.x * rh...
fn mul(self, rhs: Matrix44f) -> Self::Output { let mut v = Point::new( self.x * rhs[0][0] + self.y * rhs[1][0] + self.z * rhs[2][0] + rhs[3][0], self.x * rhs[0][1] + self.y * rhs[1][1] + self.z * rhs[2][1] + rhs[3][1], self.x * rhs[0][2] + self.y * rhs[1][2] + self.z * rhs[2]...
function_block-full_function
[ { "content": "pub fn combine_transforms(transforms: Vec<Matrix44f>) -> Matrix44f {\n\n transforms.iter().fold(Matrix44f::identity(), |acc, &m| acc * m)\n\n}\n", "file_path": "src/sdl.rs", "rank": 0, "score": 140925.18886915388 }, { "content": "fn plane_intersect(o: Point, n: Direction, ra...
Rust
safe-cli/tests/cli_seq.rs
theWebalyst/safe-api
c0b73f8cfbd578e7165c724613ac8f0829f158d0
extern crate safe_cmd_test_utilities; #[macro_use] extern crate duct; use assert_cmd::prelude::*; use predicates::prelude::*; use safe_api::xorurl::XorUrlEncoder; use safe_cmd_test_utilities::{ get_random_nrs_string, parse_cat_seq_output, parse_seq_store_output, CLI, SAFE_PROTOCOL, }; use std::{env, process::Co...
extern crate safe_cmd_test_utilities; #[macro_use] extern crate duct; use assert_cmd::prelude::*; use predicates::prelude::*; use safe_api::xorurl::XorUrlEncoder; use safe_cmd_test_utilities::{ get_random_nrs_string, parse_cat_seq_output, parse_seq_store_output, CLI, SAFE_PROTOCOL, }; use std::{env, process::Co...
N_EXE_safe"), "cat", &seq_url, "--json") .read() .unwrap(); let (_url, data) = parse_cat_seq_output(&seq_cat); assert_eq!(data, content_v1.as_bytes()); xorurl_encoder.set_content_version(Some(0)); let seq_cat = cmd!( env!("CARGO_BIN_EXE_safe"), "cat", &xorurl_en...
(_url, data) = parse_cat_seq_output(&seq_cat); assert_eq!(data, content_v0.as_bytes()); } #[test] fn calling_safe_seq_priv_append() { let content_v0 = "first item"; let seq_store = cmd!( env!("CARGO_BIN_EXE_safe"), "seq", "store", content_v0, "--private", "--...
random
[ { "content": "#[allow(dead_code)]\n\npub fn parse_seq_store_output(output: &str) -> String {\n\n serde_json::from_str(output).expect(\"Failed to parse output of `safe seq store`\")\n\n}\n\n\n", "file_path": "safe-cmd-test-utilities/src/lib.rs", "rank": 0, "score": 375608.9247387373 }, { "...
Rust
src/sources/kubernetes_logs/k8s_paths_provider.rs
mdfranz/vector
8e7a3674ffca11b13a3a87dcf69d7254f2083e98
#![deny(missing_docs)] use super::path_helpers::build_pod_logs_directory; use crate::kubernetes as k8s; use evmap::ReadHandle; use file_source::paths_provider::PathsProvider; use k8s_openapi::api::core::v1::Pod; use std::path::PathBuf; pub struct K8sPathsProvider { pods_state_reader: ReadHandle<String, k8s::sta...
#![deny(missing_docs)] use super::path_helpers::build_pod_logs_directory; use crate::kubernetes as k8s; use evmap::ReadHandle; use file_source::paths_provider::PathsProvider; use k8s_openapi::api::core::v1::Pod; use std::path::PathBuf; pub struct K8sPathsProvider { pods_state_reader: ReadHandle<String, k8s::sta...
fn real_glob(pattern: &str) -> impl Iterator<Item = PathBuf> { glob::glob(pattern) .expect("the pattern is supposed to always be correct") .flat_map(|paths| paths.into_iter()) } #[cfg(test)] mod tests { use super::{extract_pod_logs_directory, list_pod_log_paths}; use k8s_openapi::{api::co...
fn list_pod_log_paths<'a, G, GI>(mut glob_impl: G, pod: &Pod) -> impl Iterator<Item = PathBuf> + 'a where G: FnMut(&str) -> GI + 'a, GI: Iterator<Item = PathBuf> + 'a, { extract_pod_logs_directory(pod) .into_iter() .flat_map(move |dir| { glob_impl( ...
function_block-full_function
[ { "content": "/// Checks whether a field specified by a given path is present.\n\npub fn contains(fields: &BTreeMap<String, Value>, path: &str) -> bool {\n\n let mut path_iter = PathIter::new(path);\n\n\n\n match path_iter.next() {\n\n Some(PathComponent::Key(key)) => match fields.get(&key) {\n\n ...
Rust
src/operation/count_documents/test.rs
moy2010/mongo-rust-driver
dc085119dac3943773115bf4a0f923d17156dd06
use crate::{ bson::doc, bson_util, cmap::StreamDescription, coll::Namespace, concern::ReadConcern, operation::{ test::{self, handle_response_test}, Operation, }, options::{CountOptions, Hint}, }; use super::CountDocuments; #[cfg_attr(feature = "tokio-runtime", tokio::te...
use crate::{ bson::doc, bson_util, cmap::StreamDescription, coll::Namespace, concern::ReadConcern, operation::{ test::{self, handle_response_test}, Operation, }, options::{CountOptions, Hint}, }; use super::CountDocuments; #[cfg_attr(feature = "tokio-runtime", tokio::te...
None, None).unwrap(); let n = 26; let response = doc! { "ok": 1.0, "cursor": { "id": 0, "ns": "test_db.test_coll", "firstBatch": [ { "_id": 1, "n": n as i32 } ], } }; let actual_values = handle_response_test(&count_op, response).unwrap(); ...
_eq!(cmd_doc, expected_body); } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn op_selection_criteria() { test::op_selection_criteria(|selection_criteria| { let options = CountOptions { selection_criteria, ..De...
random
[ { "content": "fn parse_i64_ext_json(doc: &Document) -> Option<i64> {\n\n let number_string = doc.get(\"$numberLong\").and_then(Bson::as_str)?;\n\n number_string.parse::<i64>().ok()\n\n}\n\n\n", "file_path": "src/test/util/matchable.rs", "rank": 0, "score": 257883.71142427178 }, { "cont...
Rust
ictarus/src/network/receiver.rs
Alex6323/Ictarus
1ff63da37c0746de7af38daca1107ac6d351d5b9
use std::cmp::Reverse; use std::collections::{HashMap, HashSet, VecDeque}; use std::io; use std::net::SocketAddr; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::*; use log::*; use rand::Rng; use tokio::net::UdpSocket; use super::listener::SharedListeners; use super::neighbor::SharedNeighbors; us...
use std::cmp::Reverse; use std::collections::{HashMap, HashSet, VecDeque}; use std::io; use std::net::SocketAddr; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::*; use log::*; use rand::Rng; use tokio::net::UdpSocket; use super::listener::SharedListeners; use super::neighbor::SharedNeighbors; us...
; let cloneable_tx_key = { let tx_trits = trits::from_tx_bytes_2enc9(&self.buffer[..TRANSACTION_SIZE_BYTES]); let hash_trits = curl::curl_tx(tx_trits, CURL_ROUNDS_TRANSACTION_HASH); Arc::new(Key81::from(trytes::from_trit...
match num_bytes { PACKET_SIZE_WITH_REQUEST => { Some(self.get_shareable_key81_from_buffer(REQUEST_HASH.4, REQUEST_HASH.5)) } PACKET_SIZE => None, _ => { self.warn_on_unknown_packet_size(num_bytes, &s...
if_condition
[ { "content": "// Helper function to quickly create local nodes\n\nfn get_config(port: u16, neighbors: Vec<u16>) -> SharedConfig {\n\n let mut builder = ConfigBuilder::default().port(port);\n\n for port in neighbors {\n\n builder = builder.neighbor(&format!(\"127.0.0.1:{}\", port));\n\n }\n\n ...
Rust
alvr/experiments/gui/src/dashboard/components/settings_controls/choice.rs
morphline/ALVR
1f74eb0871d63813251edc406da8c1d554d6302d
use crate::{dashboard::basic_components, translation::TranslationBundle, LocalizedId}; use super::{ EmptyContainer, EmptyControl, SettingContainer, SettingControl, SettingsContext, SettingsResponse, }; use egui::Ui; use serde_json as json; use settings_schema::EntryData; use std::collections::HashMap; pub str...
use crate::{dashboard::basic_components, translation::TranslationBundle, LocalizedId}; use super::{ EmptyContainer, EmptyControl, SettingContainer, SettingControl, SettingsContext, SettingsResponse, }; use egui::Ui; use serde_json as json; use settings_schema::EntryData; use std::collections::HashMap; pub str...
}) .collect(), } } } impl SettingContainer for ChoiceContainer { fn ui( &mut self, ui: &mut Ui, session_fragment: json::Value, context: &SettingsContext, ) -> Option<SettingsResponse> { let mut session_variants = j...
if let Some(data) = data { ( id.clone(), ( super::create_setting_container( data.content, session_variants.remove(&id).unwrap(), ...
if_condition
[ { "content": "// Due to the nature of immediate mode GUIs, the parent containers cannot conditionally render based\n\n// on the presence of the child container, so it is the child responsibility to format the container\n\npub fn container<R>(ui: &mut Ui, content: impl FnOnce(&mut Ui) -> R) -> R {\n\n ui.hori...
Rust
devtools/x/src/nextest.rs
awelc/move
2f0d73d518c9dc178d02592e665e78fd391d9dc9
use crate::{ cargo::{build_args::BuildArgs, selected_package::SelectedPackageArgs, CargoCommand}, context::XContext, Result, }; use anyhow::{bail, Context}; use camino::Utf8PathBuf; use clap::Parser; use nextest_config::{NextestConfig, StatusLevel, TestOutputDisplay}; use nextest_runner::{ partition::...
use crate::{ cargo::{build_args::BuildArgs, selected_package::SelectedPackageArgs, CargoCommand}, context::XContext, Result, }; use anyhow::{bail, Context}; use camino::Utf8PathBuf; use clap::Parser; use nextest_config::{NextestConfig, StatusLevel, TestOutputDisplay}; use nextest_runner::{ partition::...
if let Some(status_level) = self.status_level { builder.set_status_level(status_level); } builder } } pub fn run(args: Args, xctx: XContext) -> Result<()> { let config = xctx.config(); let mut packages = args.package_args.to_selected_packages(&xctx)?; if args.unit {...
lf.failure_output { builder.set_failure_output(failure_output); } if let Some(success_output) = self.success_output { builder.set_success_output(success_output); }
function_block-random_span
[]
Rust
src/connection.rs
abetterinternet/crustls
fbbf99b839a610216607e6e4512f7cf5db4ce169
use std::io::{ErrorKind, Read, Write}; use std::{ffi::c_void, ptr::null}; use std::{ptr::null_mut, slice}; use libc::{size_t, EIO}; use rustls::{ Certificate, ClientConnection, ServerConnection, SupportedCipherSuite, ALL_CIPHER_SUITES, }; use crate::io::{ rustls_write_vectored_callback, CallbackReader, Callba...
use std::io::{ErrorKind, Read, Write}; use std::{ffi::c_void, ptr::null}; use std::{ptr::null_mut, slice}; use libc::{size_t, EIO}; use rustls::{ Certificate, ClientConnection, ServerConnection, SupportedCipherSuite, ALL_CIPHER_SUITES, }; use crate::io::{ rustls_write_vectored_callback, CallbackReader, Callba...
Some(p) => { *protocol_out = p.as_ptr(); *protocol_out_len = p.len(); }, None => { *protocol_out = null(); *protocol_out_len = 0; } } } } ...
log_callback: rustls_log_callback, } impl Connection { pub(crate) fn from_client(conn: ClientConnection) -> Self { Connection { conn: conn.into(), userdata: null_mut(), log_callback: None, } } pub(crate) fn from_server(conn: ServerConnection) -> Self { ...
random
[ { "content": "enum rustls_result rustls_connection_read(struct rustls_connection *conn,\n\n uint8_t *buf,\n\n size_t count,\n", "file_path": "src/rustls.h", "rank": 0, "score": 83745.24569326376 }, { "content":...
Rust
src/lib.rs
starkat99/bevy-console
35729503988081f85d79677db8f913b9a2c1a7a9
use bevy::input::keyboard::KeyboardInput; use bevy::prelude::*; use bevy_egui::egui::{Align, ScrollArea, TextEdit}; use bevy_egui::{egui, EguiContext, EguiPlugin}; pub struct ConsolePlugin; impl Plugin for ConsolePlugin { fn build(&self, app: &mut AppBuilder) { app.insert_resource(ConsoleState::default())...
use bevy::input::keyboard::KeyboardInput; use bevy::prelude::*; use bevy_egui::egui::{Align, ScrollArea, TextEdit}; use bevy_egui::{egui, EguiContext, EguiPlugin}; pub struct ConsolePlugin; impl Plugin for ConsolePlugin { fn build(&self, app: &mut AppBuilder) { app.insert_resource(ConsoleState::default())...
} #[derive(Default)] struct ConsoleState { buf: String, show: bool, scrollback: Vec<String>, } #[derive(Copy, Clone)] pub enum ToggleConsoleKey { KeyCode(KeyCode), ScanCode(u32), } #[derive(Clone)] pub struct ConsoleConfiguration { pub keys: Vec<ToggleConsoleKey>, pub left_pos: f32, ...
fn from(str: String) -> Self { let separator = str.find(' '); let index = match separator { None => { return Self { command: str, args: "".to_string(), }; } Some(index) => index, }; ...
function_block-full_function
[]
Rust
sdk/finspacedata/src/json_ser.rs
ymwjbxxq/aws-sdk-rust
f2b4361b004ee822960ea9791f566fd4eb6d1aba
pub fn serialize_structure_crate_input_create_changeset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateChangesetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_1) = &input.change_type { object.key("changeType")....
pub fn serialize_structure_crate_input_create_changeset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateChangesetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_1) = &input.change_type { object.key("changeType")....
pub fn serialize_structure_crate_model_column_definition( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::ColumnDefinition, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_73) = &input.data_type { object.key("dataType").string(var_...
ey_columns { let mut array_71 = object.key("primaryKeyColumns").start_array(); for item_72 in var_70 { { array_71.value().string(item_72); } } array_71.finish(); } Ok(()) }
function_block-function_prefixed
[]
Rust
src/colors.rs
eytans/egg-1
f4194a56cf63bd16fa4450b46432cc2b2177b72b
pub use crate::{Id, EGraph, Language, Analysis, ColorId}; use crate::UnionFind; use std::collections::{HashSet, HashMap}; use smallvec::SmallVec; use std::iter; use std::iter::FromIterator; pub type ColorParents = smallvec::SmallVec<[ColorId; 3]>; global_counter!(COLOR_IDS, usize, usize::default()); #[derive(Clone, ...
pub use crate::{Id, EGraph, Language, Analysis, ColorId}; use crate::UnionFind; use std::collections::{HashSet, HashMap}; use smallvec::SmallVec; use std::iter; use std::iter::FromIterator; pub type ColorParents = smallvec::SmallVec<[ColorId; 3]>; global_counter!(COLOR_IDS, usize, usize::default()); #[derive(Clone, ...
pub fn black_ids(&self, id: Id) -> Option<&HashSet<Id>> { self.union_map.get(&self.union_find.find(id)) } pub fn merge_uf(&mut self, other: &mut Self, new_id: ColorId) -> Self { let mut res = self.clone(); res.dirty_unions.extend_from_slice(&other.dirty_unions); for (black...
for (id1, id2) in to_union.drain(..) { self.colored_union(id1, id2); } } assert!(self.dirty_unions.is_empty()); assert!(to_union.is_empty()); }
function_block-function_prefix_line
[ { "content": "fn is_const(v: Var) -> impl Fn(&mut EGraph, Id, &Subst) -> bool {\n\n move |egraph, _, subst| egraph[subst[v]].data.constant.is_some()\n\n}\n\n\n", "file_path": "tests/lambda.rs", "rank": 0, "score": 209245.03580402836 }, { "content": "fn is_const(var: &str) -> impl Fn(&mut ...
Rust
src/bin/rdcore/rootmap.rs
eriksjolund/coreos-installer
be52902e1f92b8f34a03132f62f84f6821627347
use anyhow::{bail, Context, Result}; use nix::mount; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::process::Command; use libcoreinst::blockdev::*; use libcoreinst::install::*; use libcoreinst::util::*; use libcoreinst::runcmd_output; use crate::cmdline::*; pub fn rootmap(config: &RootMap...
use anyhow::{bail, Context, Result}; use nix::mount; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::process::Command; use libcoreinst::blockdev::*; use libcoreinst::install::*; use libcoreinst::util::*; use libcoreinst::runcmd_output; use crate::cmdline::*; pub fn rootmap(config: &RootMap...
fn get_luks_name(device: &Path) -> Result<String> { Ok(runcmd_output!( "dmsetup", "info", "--columns", "--noheadings", "-o", "name", device )? .trim() .into()) } fn get_luks_uuid(device: &Path) -> Result<String> { Ok(runcmd_output!("cryptset...
fn crypttab_device_has_netdev(root: &Mount, dmname: &str) -> Result<bool> { let crypttab_path = root.mountpoint().join("etc/crypttab"); let crypttab = std::fs::read_to_string(&crypttab_path) .with_context(|| format!("opening {}", crypttab_path.display()))?; for line in crypttab.lines() { le...
function_block-full_function
[ { "content": "/// Runs the provided Command object, captures its stdout, and swallows its stderr except on\n\n/// failure. Returns a Result<String> describing whether the command failed, and if not, its\n\n/// standard output. Output is assumed to be UTF-8. Errors are adequately prefixed with the full\n\n/// co...
Rust
src/lexeme/lexemes/association.rs
mangolang/compiler
a33d5886c7536fa7d3c0365879fd8e250a8d84f4
use ::std::hash; use crate::common::debug::ToText; use crate::common::error::{ErrMsg, MsgResult}; use crate::io::slice::{SourceLocation, SourceSlice}; use crate::ir::codeparts::Symbol; use crate::lexeme::Lexeme; #[derive(Debug, Eq, Clone)] pub struct AssociationLexeme { symbol: Option<Symbol>, source: So...
use ::std::hash; use crate::common::debug::ToText; use crate::common::error::{ErrMsg, MsgResult}; use crate::io::slice::{SourceLocation, SourceSlice}; use crate::ir::codeparts::Symbol; use crate::lexeme::Lexeme; #[derive(Debug, Eq, Clone)] pub struct AssociationLexeme { symbol: Option<Symbol>, source: So...
exeme::from_str("===", SourceSlice::mock()).is_err()); assert!(AssociationLexeme::from_str("<=", SourceSlice::mock()).is_err()); assert!(AssociationLexeme::from_str(">=", SourceSlice::mock()).is_err()); assert!(AssociationLexeme::from_str("<==", SourceSlice::mock()).is_err()); assert!(As...
} impl ToText for AssociationLexeme { fn to_text(&self) -> String { match self.symbol { Option::None => "=".to_owned(), Option::Some(ref sym) => format!("{}=", sym), } } } #[cfg(test)] mod from_str { use crate::common::tests::assert_panic_silent; use s...
random
[ { "content": "pub fn association(txt: &str, source: SourceSlice) -> MsgResult<Lexeme> {\n\n Ok(Lexeme::Association(AssociationLexeme::from_str(txt, source)?))\n\n}\n\n\n", "file_path": "src/lexeme/collect/short.rs", "rank": 0, "score": 286120.79757015436 }, { "content": "pub fn associatio...
Rust
node/src/utils/external.rs
arcolife/casper-node
82c95c06a1b762304ff8c766ac7473dee819b337
use std::{ fmt::{Debug, Display}, path::{Path, PathBuf}, }; use datasize::DataSize; use openssl::{ pkey::{PKey, Private}, x509::X509, }; use serde::{Deserialize, Serialize}; use thiserror::Error; use super::{read_file, ReadFileError}; use crate::{ crypto::{self, asymmetric_key::SecretKey}, t...
use std::{ fmt::{Debug, Display}, path::{Path, PathBuf}, }; use datasize::DataSize; use openssl::{ pkey::{PKey, Private}, x509::X509, }; use serde::{Deserialize, Serialize}; use thiserror::Error; use super::{read_file, ReadFileError}; use crate::{ crypto::{self, asymmetric_key::SecretKey}, t...
: AsRef<Path>>(path: P) -> Result<Self, Self::Error> { tls::load_private_key(path) } } impl Loadable for SecretKey { type Error = crypto::Error; fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Self::Error> { SecretKey::from_file(path) } } impl Loadable for Vec<u8> { type Err...
type Error: Debug + Display; fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Self::Error>; #[cfg(test)] fn from_resources<P: AsRef<Path>>(rel_path: P) -> Self { Self::from_file(RESOURCES_PATH.join(rel_path)).expect("could not load resources from local") } } impl<T> De...
random
[ { "content": "pub trait NodeIdT: Clone + Display + Debug + Send + Eq + Hash + 'static {}\n\nimpl<I> NodeIdT for I where I: Clone + Display + Debug + Send + Eq + Hash + 'static {}\n\n\n\n/// A validator identifier.\n\npub(crate) trait ValidatorIdT: Eq + Ord + Clone + Debug + Hash {}\n\nimpl<VID> ValidatorIdT for...
Rust
src/lib.rs
Dandandan/datafusion-tokomak
29abcd5f232018007ee81bc3455fc0a5b9a89741
use std::vec; use datafusion::{ logical_plan::LogicalPlan, optimizer::optimizer::OptimizerRule, scalar::ScalarValue, }; use datafusion::{logical_plan::Operator, optimizer::utils}; use datafusion::error::Result as DFResult; use datafusion::logical_plan::Expr; use egg::{rewrite as rw, *}; pub struct Tokomak {} im...
use std::vec; use datafusion::{ logical_plan::LogicalPlan, optimizer::optimizer::OptimizerRule, scalar::ScalarValue, }; use datafusion::{logical_plan::Operator, optimizer::utils}; use datafusion::error::Result as DFResult; use datafusion::logical_plan::Expr; use egg::{rewrite as rw, *}; pub struct Tokomak {} im...
Expr::Between{ expr: Box::new(left), negated: false, low: Box::new(low_expr), high: Box::new(high_expr), } } TokomakExpr::Multiply(ids) => { let l = to_exprs(&rec_expr, ids[0]); let r = to_e...
se-gt"; "(> ?x ?y)"=> "(< ?x ?y)"), rw!("converse-gte"; "(>= ?x ?y)"=> "(<= ?x ?y)"), rw!("converse-lt"; "(< ?x ?y)"=> "(> ?x ?y)"), rw!("converse-lte"; "(<= ?x ?y)"=> "(>= ?x ?y)"), rw!("add-0"; "(+ ?x 0)" => "?x"), rw!("add-assoc"; "(+ (+ ?a ?b) ?c)" => "(+ ?a (+ ?b ?c))"), ...
random
[ { "content": "# datafusion-tokomak\n\nExperimental pluggable optimizer for DataFusion using graph rewriting.\n\n\n\nThe goal is to allow experimenting with the [Egg](https://github.com/egraphs-good/egg) library,\n\nand experiment with a maintainable and aggresive optimization framework.\n\n\n\nThe optimizer is ...
Rust
tests/serde.rs
Fenex/bson-rs
3654859aa8c72f646a7e03d7922e2d7a36c92c9c
use bson::{Bson, Decoder, Encoder, bson, doc}; use serde::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize}; use std::collections::BTreeMap; #[test] fn test_ser_vec() { let vec = vec![1, 2, 3]; let encoder = Encoder::new(); let result = vec.serialize(encoder).unwrap(); let expecte...
use bson::{Bson, Decoder, Encoder, bson, doc}; use serde::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize}; use std::collections::BTreeMap; #[test] fn test_ser_vec() { let vec = vec![1, 2, 3]; let encoder = Encoder::new(); let result = vec.serialize(encoder).unwrap(); let expecte...
assert_eq!(p2, Point::ThreeDim(x2, y2, z2)); }
} #[test] fn test_serde_bytes() { #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] pub struct Foo { #[serde(with = "serde_bytes")] data: Vec<u8>, } let x = Foo { data: b"12345abcde".to_vec(), }; let b = bson::to_bson(&x).unwrap(); assert_eq!(b.as_document(...
random
[ { "content": "/// Decode a BSON `Value` into a `T` Deserializable.\n\npub fn from_bson<'de, T>(bson: Bson) -> DecoderResult<T>\n\n where T: Deserialize<'de>\n\n{\n\n let de = Decoder::new(bson);\n\n Deserialize::deserialize(de)\n\n}\n", "file_path": "src/decoder/mod.rs", "rank": 0, "score":...
Rust
webkit2gtk/src/auto/cookie_manager.rs
vhdirk/webkit2gtk-rs
2d1b0fd6896b9ab8da62138245b8cf9d4b5e560c
use crate::CookieAcceptPolicy; use crate::CookiePersistentStorage; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use std::pin::Pin; use std::ptr; glib::wrappe...
use crate::CookieAcceptPolicy; use crate::CookiePersistentStorage; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use std::pin::Pin; use std::ptr; glib::wrappe...
let callback = domains_with_cookies_trampoline::<P>; unsafe { ffi::webkit_cookie_manager_get_domains_with_cookies( self.as_ref().to_glib_none().0, cancellable.map(|p| p.as_ref()).to_glib_none().0, Some(callback), Box_::into_raw...
error = ptr::null_mut(); let ret = ffi::webkit_cookie_manager_get_domains_with_cookies_finish( _source_object as *mut _, res, &mut error, ); let result = if error.is_null() { Ok(FromGlibPtrContainer::from_glib_full(ret))...
function_block-function_prefixed
[ { "content": "pub trait WebsitePoliciesExt: 'static {\n\n #[cfg(any(feature = \"v2_30\", feature = \"dox\"))]\n\n #[cfg_attr(feature = \"dox\", doc(cfg(feature = \"v2_30\")))]\n\n #[doc(alias = \"webkit_website_policies_get_autoplay_policy\")]\n\n #[doc(alias = \"get_autoplay_policy\")]\n\n fn au...
Rust
angelscript/src/engine.rs
dsobotta/rust-angelscript
095dc2bafc60fcc5557d26d96b87a7560640912d
use angelscript_sys::c_types::*; use angelscript_sys::c_engine::*; use crate::types::*; use crate::read_cstring; use crate::module::ScriptModule; use crate::context::ScriptContext; use std::ffi::CString; use std::ffi::c_void; use std::os::raw::c_int; pub struct MessageInfo { pub section: String, pub row: u3...
use angelscript_sys::c_types::*; use angelscript_sys::c_engine::*; use crate::types::*; use crate::read_cstring; use crate::module::ScriptModule; use crate::context::ScriptContext; use std::ffi::CString; use std::ffi::c_void; use std::os::raw::c_int; pub struct MessageInfo { pub section: String, pub row: u3...
pub fn get_module(&mut self, module: &str, flag: EGMFlags) -> Option<ScriptModule> { let c_module_name = CString::new(module).unwrap(); let c_script_module = unsafe { asEngine_GetModule(self.engine, c_module_name.as_ptr(), flag.to_u32()) }; return ScriptModule::new(c_script_module...
pub fn send_message(&mut self, section: &str, row: u32, col: u32, msg_type: EMsgType, message: &str) -> EReturnCodes { let c_section = CString::new(section).unwrap(); let c_message = CString::new(message).unwrap(); let result = unsafe { asEngine_WriteMessage(self.engine, c_section.as_ptr(), row...
function_block-full_function
[ { "content": "fn test_callback(mut engine: &mut ScriptEngine) {\n\n\n\n let r = engine.set_message_callback(msg_callback);\n\n check_ok!(r);\n\n\n\n let r = engine.send_message(\"section\", 0, 1, EMsgType::Warning, \"direct engine message\");\n\n check_ok!(r);\n\n\n\n as_log_debug!(engine, \"macr...
Rust
rust/experimental/lang/src/language/rust.rs
jeremywiebe/xi-editor
1c95252fa39e225dcfa4fd93b04111921d1ccf0d
use std::io::{stdin, Read}; use crate::parser::Parser; use crate::peg::*; use crate::statestack::{Context, State}; use crate::ScopeId; static ALL_SCOPES: &[&[&str]] = &[ &["source.rust"], &["source.rust", "string.quoted.double.rust"], &["source.rust", "string.quoted.single.rust"], &["source.rust", "...
use std::io::{stdin, Read}; use crate::parser::Parser; use crate::peg::*; use crate::statestack::{Context, State}; use crate::ScopeId; static ALL_SCOPES: &[&[&str]] = &[ &["source.rust"], &["source.rust", "string.quoted.double.rust"], &["source.rust", "string.quoted.single.rust"], &["source.rust", "...
b'\\', Alt3( OneOf(b"\\\'\"0nrt"), (b'x', Repeat(OneByte(is_hex_digit), 2)), ("u{", Repeat(OneByte(is_hex_digit), 1..7), b'}'), ), ) .p(s) } fn char_literal(s: &[u8]) -> Option<usize> { (b'\'', Alt(OneChar(|c| c != '\\' && c != '\''), escape), b'\...
return (i + 1, self.ctx.push(state, StateEl::Invalid), len, state); } } i += 1; } (0, state, i, state) } } impl Parser for RustParser { fn has_offset(&mut self) -> bool { self.scope_offset.is_some() } fn set_scope_offset(&mut self, o...
random
[ { "content": "/// Given the inital byte of a UTF-8 codepoint, returns the number of\n\n/// bytes required to represent the codepoint.\n\n/// RFC reference : https://tools.ietf.org/html/rfc3629#section-4\n\npub fn len_utf8_from_first_byte(b: u8) -> usize {\n\n match b {\n\n b if b < 0x80 => 1,\n\n ...
Rust
automerge/benches/save_load.rs
dvc94ch/automerge-rs
78dc394a7a20cfbaa9d430f90056d25b9e1c3d49
use automerge::{Backend, Frontend, InvalidChangeRequest, LocalChange, Path, Primitive, Value}; use criterion::{black_box, criterion_group, criterion_main, Criterion}; fn small_change_backend() -> Backend { let mut frontend = Frontend::new(); let mut backend = Backend::new(); let (_, change) = frontend ...
use automerge::{Backend, Frontend, InvalidChangeRequest, LocalChange, Path, Primitive, Value}; use criterion::{black_box, criterion_group, criterion_main, Criterion}; fn small_change_backend() -> Backend { let mut frontend = Frontend::new(); let mut backend = Backend::new(); let (_, change) = frontend ...
fn save_small(c: &mut Criterion) { c.bench_function("save a small history backend", |b| { b.iter_batched( small_change_backend, |b| black_box(b.save().unwrap()), criterion::BatchSize::SmallInput, ) }); } fn save_medium(c: &mut Criterion) { c.bench_funct...
fn save_empty(c: &mut Criterion) { c.bench_function("save an empty backend", |b| { b.iter_batched( Backend::new, |b| black_box(b.save().unwrap()), criterion::BatchSize::SmallInput, ) }); }
function_block-full_function
[ { "content": "/// Asserts that the changes are equal without respect to order of the hashes\n\n/// in the change dependencies\n\nfn assert_changes_equal(mut change1: amp::Change, change2: amp::Change) {\n\n let change2_clone = change2.clone();\n\n let deps1: HashSet<&ChangeHash> = change1.deps.iter().coll...
Rust
sdl_viewer/src/graphic/program.rs
googlecartographer/point_cloud_viewer
189a81d53b3f674c7738a6a16d9674c20fc7c106
use crate::opengl; use crate::opengl::types::{GLchar, GLenum, GLint, GLuint}; use std::ffi::CString; use std::ptr; use std::rc::Rc; use std::str; pub struct GlProgramBuilder<'a> { gl: Rc<opengl::Gl>, vertex_shader: &'a str, geometry_shader: Option<&'a str>, fragment_shader: Option<&'a str>, } impl<'a>...
use crate::opengl; use crate::opengl::types::{GLchar, GLenum, GLint, GLuint}; use std::ffi::CString; use std::ptr; use std::rc::Rc; use std::str; pub struct GlProgramBuilder<'a> { gl: Rc<opengl::Gl>, vertex_shader: &'a str, geometry_shader: Option<&'a str>, fragment_shader: Option<&'a str>, } impl<'a>...
pub fn geometry_shader(mut self, geometry_shader: &'a str) -> Self { self.geometry_shader = Some(geometry_shader); self } pub fn fragment_shader(mut self, fragment_shader: &'a str) -> Self { self.fragment_shader = Some(fragment_shader); self } pub fn build(self) -> G...
r { gl, vertex_shader, geometry_shader: None, fragment_shader: None, } }
function_block-function_prefixed
[ { "content": "// TODO(nnmm): Remove\n\npub fn attribute_extension(attribute: &str) -> &str {\n\n match attribute {\n\n \"position\" => \"xyz\",\n\n \"color\" => \"rgb\",\n\n _ => attribute,\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 1, "score": 197605.6242280639...
Rust
linkerd/opencensus/src/lib.rs
shirshak55/linkerd2-proxy
aabf49113f6b1477522dd5729f0be7a68df2dfd9
#![deny( warnings, rust_2018_idioms, clippy::disallowed_methods, clippy::disallowed_types )] #![forbid(unsafe_code)] pub mod metrics; use futures::stream::{Stream, StreamExt}; use http_body::Body as HttpBody; use linkerd_error::Error; use metrics::Registry; pub use opencensus_proto as proto; use openc...
#![deny( warnings, rust_2018_idioms, clippy::disallowed_methods, clippy::disallowed_types )] #![forbid(unsafe_code)] pub mod metrics; use futures::stream::{Stream, StreamExt}; use http_body::Body as HttpBody; use linkerd_error::Error; use metrics::Registry; pub use opencensus_proto as proto; use openc...
struct SpanExporter<T, S> { client: T, node: Node, spans: S, metrics: Registry, } #[derive(Debug)] struct SpanRxClosed; impl<T, S> SpanExporter<T, S> where T: GrpcService<BoxBody>, T::Error: Into<Error>, <T::ResponseBody as HttpBody>::Error: Into<Error> + Send + Sync, T::ResponseBody...
pub async fn export_spans<T, S>(client: T, node: Node, spans: S, metrics: Registry) where T: GrpcService<BoxBody> + Clone, T::Error: Into<Error>, <T::ResponseBody as HttpBody>::Error: Into<Error> + Send + Sync, T::ResponseBody: Send + Sync + 'static, S: Stream<Item = Span> + Unpin, { debug!("Spa...
function_block-full_function
[ { "content": "pub fn metric(name: impl Into<String>) -> MetricMatch {\n\n MetricMatch::new(name)\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/metrics.rs", "rank": 0, "score": 169559.12140093878 }, { "content": "pub fn new() -> (Registry, grpc::Server) {\n\n let registry = Reg...
Rust
src/sources/mysqld/slave_status.rs
f1shl3gs/vertex
8911e1956ee5ed5ba0d7123d775df315f13ca7be
use std::collections::BTreeMap; use chrono::NaiveDateTime; use event::{tags, Metric}; use regex::Regex; use sqlx::mysql::MySqlRow; use sqlx::{Column, FromRow, MySqlPool, Row, ValueRef}; use crate::sources::mysqld::Error; #[derive(Default, Debug)] struct Record { master_uuid: String, master_host: String, ...
use std::collections::BTreeMap; use chrono::NaiveDateTime; use event::{tags, Metric}; use regex::Regex; use sqlx::mysql::MySqlRow; use sqlx::{Column, FromRow, MySqlPool, Row, ValueRef}; use crate::sources::mysqld::Error; #[derive(Default, Debug)] struct Record { master_uuid: String, master_host: String, ...
}
0)), ("Connecting", Some(0.0)), ("Primary", Some(1.0)), ("non-Primary", Some(0.0)), ("disconnected", Some(0.0)), ("2006-01-02 15:04:05", Some(1136214245.0)), ("Jan 02 15:04:05 2006 MST", Some(1136214245.0)), ("Mar 05 03:00:45 2009 CST",...
function_block-function_prefixed
[ { "content": "pub fn sanitize_metric_name(name: &str) -> String {\n\n // The first character must be [a-zA-Z_:], and all subsequent characters must be [a-zA-Z0-9_:].\n\n name.replacen(invalid_metric_name_start_character, \"_\", 1)\n\n .replace(invalid_metric_name_character, \"_\")\n\n}\n\n\n\nimpl ...
Rust
src/address.rs
iqlusioninc/deep_space
5e2584392b8430f79a6fa0ffb491014974df9f78
use failure::{ensure, Error}; use serde::Serialize; use serde::Serializer; use std::fmt::{self, Display}; use subtle_encoding::bech32::{self}; #[derive(Default, Debug, PartialEq, Eq, Copy, Clone)] pub struct Address([u8; 20]); #[derive(Default, Debug, PartialEq, Eq, Copy, Clone)] pub struct CosmosValidatorOperatorA...
use failure::{ensure, Error}; use serde::Serialize; use serde::Serializer; use std::fmt::{self, Display}; use subtle_encoding::bech32::{self}; #[derive(Default, Debug, PartialEq, Eq, Copy, Clone)] pub struct Address([u8; 20]); #[derive(Default, Debug, PartialEq, Eq, Copy, Clone)] pub struct CosmosValidatorOperatorA...
lize_str(&s) } } #[test] fn test_bech32() { let address = Address::default(); assert_eq!( address.to_bech32("cosmos"), "cosmos1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqnrql8a" ); let decoded = Address::from_bech32("cosmos1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqnrql8a".to_string()) .expect(...
lizer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let s = self.0.to_bech32("cosmosvaloper"); serializer.serialize_str(&s) } } impl Serialize for TerraAddress { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, ...
random
[ { "content": "/// Creates a canonical JSON representation of any serializable objects.\n\npub fn to_canonical_json(s: impl Serialize) -> Result<Vec<u8>, Error> {\n\n // Serialize any object to String first\n\n let s = to_string(&s)?;\n\n // Deserialize into Value which would order keys\n\n let v: Va...
Rust
virtio-devices/src/vsock/unix/muxer_rxq.rs
corvinux/cloud-hypervisor
7936bfe6804a2914d67dfdce1d1e976064350664
use std::collections::{HashMap, VecDeque}; use super::super::VsockChannel; use super::defs; use super::muxer::{ConnMapKey, MuxerRx}; use super::MuxerConnection; pub struct MuxerRxQ { q: VecDeque<MuxerRx>, synced: bool, } impl MuxerRxQ { const SIZE: usize = defs::MUXER_RXQ_SIZE; ...
use std::collections::{HashMap, VecDeque}; use super::super::VsockChannel; use super::defs; use super::muxer::{ConnMapKey, MuxerRx}; use super::MuxerConnection; pub struct MuxerRxQ { q: VecDeque<MuxerRx>, synced: bool, } impl MuxerRxQ { const SIZE: usize = defs::MUXER_RXQ_SIZE; ...
pub fn push(&mut self, rx: MuxerRx) -> bool { if self.is_synced() && !self.is_full() { self.q.push_back(rx); return true; } match rx { MuxerRx::RstPkt { .. } => { ...
rom_conn_map(conn_map: &HashMap<ConnMapKey, MuxerConnection>) -> Self { let mut q = VecDeque::new(); let mut synced = true; for (key, conn) in conn_map.iter() { if !conn.has_pending_rx() { continue; } if q.len() >= Self::SIZE { ...
function_block-function_prefixed
[ { "content": "/// Check if io_uring for block device can be used on the current system, as\n\n/// it correctly supports the expected io_uring features.\n\npub fn block_io_uring_is_supported() -> bool {\n\n let error_msg = \"io_uring not supported:\";\n\n\n\n // Check we can create an io_uring instance, wh...
Rust
src/binder/statement/select.rs
skyzh/risinglight
404bf4aa1dd76856ab8317e157a76bcd3b5b5454
use super::BoundExpr::*; use super::{BoundExpr, BoundTableRef, *}; use crate::parser::{Query, SelectItem, SetExpr}; use crate::types::DataValue::Bool; #[derive(Debug, PartialEq, Clone)] pub struct BoundSelect { pub select_list: Vec<BoundExpr>, pub from_table: Option<BoundTableRef>, pub where_clause: Option...
use super::BoundExpr::*; use super::{BoundExpr, BoundTableRef, *}; use crate::parser::{Query, SelectItem, SetExpr}; use crate::types::DataValue::Bool; #[derive(Debug, PartialEq, Clone)] pub struct BoundSelect { pub select_list: Vec<BoundExpr>, pub from_table: Option<BoundTableRef>, pub where_clause: Option...
fn bind_select_internal(&mut self, query: &Query) -> Result<Box<BoundSelect>, BindError> { let select = match &query.body { SetExpr::Select(select) => &**select, _ => todo!("not select"), }; let mut from_table = if select.from.is_empty() { None...
y) -> Result<Box<BoundSelect>, BindError> { self.push_context(); let ret = self.bind_select_internal(query); self.pop_context(); ret }
function_block-function_prefixed
[ { "content": "pub fn path_of_data_column(base: impl AsRef<Path>, column_info: &ColumnCatalog) -> PathBuf {\n\n path_of_column(base, column_info, \".col\")\n\n}\n\n\n", "file_path": "src/storage/secondary/rowset/rowset_builder.rs", "rank": 0, "score": 131354.18076245338 }, { "content": "pu...
Rust
src/storage/src/source/pubnub.rs
jwills/materialize
9be06cc96d81628ba131d14624420a8336acbe1f
use std::pin::Pin; use std::time::Duration; use async_trait::async_trait; use futures::StreamExt; use pubnub_hyper::core::data::{channel, message::Type}; use pubnub_hyper::{Builder, DefaultRuntime, DefaultTransport, PubNub}; use timely::scheduling::SyncActivator; use tracing::info; use mz_dataflow_types::sources::{...
use std::pin::Pin; use std::time::Duration; use async_trait::async_trait; use futures::StreamExt; use pubnub_hyper::core::data::{channel, message::Type}; use pubnub_hyper::{Builder, DefaultRuntime, DefaultTransport, PubNub}; use timely::scheduling::SyncActivator; use tracing::info; use mz_dataflow_types::sources::{...
} } None => { info!( "pubnub channel {:?} disconnected. reconnecting", self.channel.to_string() ); self.stream.take(); tokio::time::sleep(timestamp_frequen...
ernalSourceConnector, _aws_external_id: AwsExternalId, _restored_offsets: Vec<(PartitionId, Option<MzOffset>)>, _encoding: SourceDataEncoding, _metrics: SourceBaseMetrics, ) -> Result<Self, anyhow::Error> { let pubnub_conn = match connector { ExternalSourceConnect...
random
[ { "content": "/// Converts a Materialize row into a vector of PostgreSQL values.\n\n///\n\n/// Calling this function is equivalent to mapping [`Value::from_datum`] over\n\n/// every datum in `row`.\n\npub fn values_from_row(row: Row, typ: &RelationType) -> Vec<Option<Value>> {\n\n row.iter()\n\n .zip(...
Rust
src/sys/pkg/bin/omaha-client/src/configuration.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
use crate::channel::ChannelConfigs; use anyhow::{anyhow, Error}; use fidl_fuchsia_boot::{ArgumentsMarker, ArgumentsProxy}; use log::{error, info, warn}; use omaha_client::{ common::{App, AppSet, UserCounting, Version}, configuration::{Config, Updater}, protocol::{request::OS, Cohort}, }; use std::fs; use ...
use crate::channel::ChannelConfigs; use anyhow::{anyhow, Error}; use fidl_fuchsia_boot::{ArgumentsMarker, ArgumentsProxy}; use log::{error, info, warn}; use omaha_client::{ common::{App, AppSet, UserCounting, Version}, configuration::{Config, Updater}, protocol::{request::OS, Cohort}, }; use std::fs; use ...
pub fn get_config(version: &str) -> Config { let service_url = fs::read_to_string("/config/data/omaha_url") .unwrap_or("https://clients2.google.com/service/update2/fuchsia/json".to_string()); Config { updater: Updater { name: "Fuchsia".to_string(), version: Version::from([0, 0, 1, 0]) }, ...
id = appid.unwrap_or_else(|| match fs::read_to_string("/config/data/omaha_app_id") { Ok(id) => id, Err(e) => { error!("Unable to read omaha app id from config/data: {:?}", e); String::new() } }); let version = match version.parse::<Version>() { Ok(version)...
function_block-function_prefixed
[]
Rust
crates/stun-types/src/attributes/integrity.rs
kbalt/ezk
6886981a5d13954fb8536cf69d83b147551fd55c
use super::Attribute; use crate::builder::MessageBuilder; use crate::parse::{ParsedAttr, ParsedMessage}; use crate::Error; use hmac::digest::generic_array::ArrayLength; use hmac::digest::{BlockInput, Digest, FixedOutput, Reset, Update}; use hmac::{Hmac, Mac, NewMac}; use sha1::Sha1; use sha2::Sha256; use std::borrow::C...
use super::Attribute; use crate::builder::MessageBuilder; use crate::parse::{ParsedAttr, ParsedMessage}; use crate::Error; use hmac::digest::generic_array::ArrayLength; use hmac::digest::{BlockInput, Digest, FixedOutput, Reset, Update}; use hmac::{Hmac, Mac, NewMac}; use sha1::Sha1; use sha2::Sha256; use std::borrow::C...
fn encode(&self, ctx: Self::Context, builder: &mut MessageBuilder) -> Result<(), Error> { let hmac: Hmac<Sha1> = Hmac::new_from_slice(&ctx.0).map_err(|_| Error::InvalidData("invalid key length"))?; message_integrity_encode(hmac, builder); Ok(()) } fn encode_len(&self...
fn decode( ctx: Self::Context, msg: &mut ParsedMessage, attr: ParsedAttr, ) -> Result<Self, Error> { let hmac: Hmac<Sha1> = Hmac::new_from_slice(&ctx.0).map_err(|_| Error::InvalidData("invalid key length"))?; message_integrity_decode(hmac, msg, attr)?; O...
function_block-full_function
[ { "content": "type HashFn = fn(&[u8]) -> String;\n\n\n", "file_path": "crates/sip-auth/src/digest.rs", "rank": 0, "score": 234088.31462810654 }, { "content": "/// Inspect the given input to find out if it contains a STUN message.\n\n///\n\n/// Does not perform any kind of searching, to detec...
Rust
src/config.rs
enjmiah/nog
0528ff83797273eb778d4a8c66bba134bc2cff58
use crate::keybindings::keybinding::Keybinding; use bar_config::BarConfig; use log::error; use rule::Rule; use std::{collections::HashMap, time::Duration}; use update_channel::UpdateChannel; use workspace_setting::WorkspaceSetting; pub mod bar_config; pub mod hot_reloading; pub mod rhai; pub mod rule; pub mod update_c...
use crate::keybindings::keybinding::Keybinding; use bar_config::BarConfig; use log::error; use rule::Rule; use std::{collections::HashMap, time::Duration}; use update_channel::UpdateChannel; use workspace_setting::WorkspaceSetting; pub mod bar_config; pub mod hot_reloading; pub mod rhai; pub mod rule; pub mod update_c...
pub fn set_bool_field(self: &mut Self, field: &str, value: bool) { match field { "use_border" => self.use_border = value, "light_theme" => self.light_theme = value, "launch_on_startup" => self.launch_on_startup = value, "remove_title_bar" => self.remove_titl...
ve_task_bar = !self.remove_task_bar, "display_app_bar" => self.display_app_bar = !self.display_app_bar, _ => error!("Attempt to toggle unknown field: {}", field), } }
function_block-function_prefixed
[]
Rust
core/src/avm2/globals/flash/display/loaderinfo.rs
dumpmemory/ruffle
dde21a2a606c479e96b454e9eba54084ae173b85
use crate::avm2::activation::Activation; use crate::avm2::bytearray::Endian; use crate::avm2::class::{Class, ClassAttributes}; use crate::avm2::method::{Method, NativeMethodImpl}; use crate::avm2::names::{Namespace, QName}; use crate::avm2::object::{loaderinfo_allocator, DomainObject, LoaderStream, Object, TObject}; ...
use crate::avm2::activation::Activation; use crate::avm2::bytearray::Endian; use crate::avm2::class::{Class, ClassAttributes}; use crate::avm2::method::{Method, NativeMethodImpl}; use crate::avm2::names::{Namespace, QName}; use crate::avm2::object::{loaderinfo_allocator, DomainObject, LoaderStream, Object, TObject}; ...
root.version().into()); } } } } Ok(Value::Undefined) } pub fn url<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { if let Some(loader_stream) ...
LoaderStream::Stage => { return Err("Error: The stage's loader info does not have a SWF version".into()) } LoaderStream::Swf(root, _) => { return Ok(
function_block-random_span
[ { "content": "pub fn root_error_handler<'gc>(activation: &mut Activation<'_, 'gc, '_>, error: Error<'gc>) {\n\n match &error {\n\n Error::ThrownValue(value) => {\n\n let message = value\n\n .coerce_to_string(activation)\n\n .unwrap_or_else(|_| \"undefined\".int...
Rust
src/workspace.rs
Zynapse500/rust-rpm
9f94077bdc16ffd9750b6b6fe833f69925b45696
use std::fs; use std::path::{Path, PathBuf}; use std::io::{Write, Read, ErrorKind}; use project::{Project, ProjectList}; use serde_json; #[derive(Clone, Serialize, Deserialize)] pub struct Workspace { name: String, path: String } const WORKSPACE_PREFERENCE_FOLDER_NAME: &'static str = ".workspace"; const WORKSPAC...
use std::fs; use std::path::{Path, PathBuf}; use std::io::{Write, Read, ErrorKind}; use project::{Project, ProjectList}; use serde_json; #[derive(Clone, Serialize, Deserialize)] pub struct Workspace { name: String, path: String } const WORKSPACE_PREFERENCE_FOLDER_NAME: &'static str = ".workspace"; const WORKSPAC...
fn add_to_workspace_list(&self) -> Result<(), String> { let mut workspaces = match WorkspaceList::get() { Ok(workspace) => workspace, Err(e) => return Err(e), }; if let Ok(_) = workspaces.lookup_index(&self.name) { return Err(format!("Workspace with the name '{}' already exists", self.na...
pub fn new(name: &str, path: &str) -> Result<Workspace, String> { let workspace = Workspace { name: name.to_owned(), path: path.to_owned() }; if let Err(e) = workspace.add_to_workspace_list() { return Err(e); } if let Err(_) = fs::create_dir_all(path) { return Err("Failed to create workspace...
function_block-full_function
[ { "content": "fn new_workspace(name: &str, path: &str) {\n\n\tlet workspace = try_fatal!(Workspace::new(name, path));\n\n\ttry_fatal!(workspace.set_active());\n\n}\n\n\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 114705.85107066372 }, { "content": "fn new_project(name: &str) {\n\n...
Rust
sync_app_lib/src/sync_client.rs
ddboline/sync_app_rust
e82c086793f1bf09f50ab88563521631bc5a7dc2
use anyhow::{format_err, Error}; use chrono::{DateTime, Utc}; use log::debug; use maplit::hashmap; use reqwest::{ header::{HeaderMap, HeaderName, HeaderValue}, redirect::Policy, Client, Response, Url, }; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::path::Path; use tempfile::NamedTempF...
use anyhow::{format_err, Error}; use chrono::{DateTime, Utc}; use log::debug; use maplit::hashmap; use reqwest::{ header::{HeaderMap, HeaderName, HeaderValue}, redirect::Policy, Client, Response, Url, }; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::path::Path; use tempfile::NamedTempF...
+ Send + 'static>( &self, table: &str, start_timestamp: Option<DateTime<Utc>>, ) -> Result<Vec<T>, Error> { let data = self .local_session .run_command_export(table, start_timestamp) .await?; if data.is_empty() { Ok(Vec::new()) ...
ser: {:?}", user.email); Ok(()) } pub async fn shutdown(&self) -> Result<(), Error> { let from_url = self.get_url()?; let url = from_url.join("api/auth")?; self.remote_session .delete(&url, &HeaderMap::new()) .await? .error_for_status()?; ...
random
[ { "content": "pub fn convert_str_to_datetime(s: &str) -> Result<DateTime<Utc>, Error> {\n\n DateTime::parse_from_rfc3339(&s.replace(\"Z\", \"+00:00\"))\n\n .map(|x| x.with_timezone(&Utc))\n\n .map_err(Into::into)\n\n}\n\n\n", "file_path": "sync_app_lib/src/iso_8601_datetime.rs", "rank":...
Rust
src/bits/chunk_iterator.rs
gitter-badger/arrow2
7cd81f9db6c22bc24a97fd538179d0735f32c4f0
use super::bytes_for; #[derive(Debug)] pub struct BitChunks<'a> { buffer: &'a [u8], bit_offset: usize, chunk_len: usize, remainder_len: usize, } impl<'a> BitChunks<'a> { pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self { assert!(offset + len <= buffer.len() ...
use super::bytes_for; #[derive(Debug)] pub struct BitChunks<'a> { buffer: &'a [u8], bit_offset: usize, chunk_len: usize, remainder_len: usize, } impl<'a> BitChunks<'a> { pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self { assert!(offset + len <= buffer.len() ...
#[test] fn test_iter_unaligned_remainder_bits_large() { let input: &[u8] = &[ 0b11111111, 0b00000000, 0b11111111, 0b00000000, 0b11111111, 0b00000000, 0b11111111, 0b00000000, 0b11111111, ]; let bitchunks = BitChunks::new(&input, 2, 63); assert_eq!(63, bi...
fn test_iter_unaligned_remainder_bits_across_bytes() { let input: &[u8] = &[0b00111111, 0b11111100]; let bitchunks = BitChunks::new(&input, 6, 7); assert_eq!(7, bitchunks.remainder_len()); assert_eq!(0b1110000, bitchunks.remainder()); }
function_block-full_function
[ { "content": "#[inline]\n\npub fn check_offsets_and_utf8<O: Offset>(offsets: &Buffer<O>, values: &Buffer<u8>) -> usize {\n\n let len = check_offsets(offsets, values.len());\n\n offsets.as_slice().windows(2).for_each(|window| {\n\n let start = window[0]\n\n .to_usize()\n\n .exp...
Rust
src/lib.rs
menmos/menmos-sdk
851575326f4132ebbc5cc133d5b92e979e78ee6d
pub mod fs; mod metadata_detector; mod profile; pub mod push; mod typing; mod util; pub use menmos_client::Query; pub use profile::{Config, Profile}; pub use typing::{FileMetadata, UploadRequest}; use metadata_detector::{MetadataDetector, MetadataDetectorRC}; use typing::*; use std::sync::Arc; use std::time; use as...
pub mod fs; mod metadata_detector; mod profile; pub mod push; mod typing; mod util; pub use menmos_client::Query; pub use profile::{Config, Profile}; pub use typing::{FileMetadata, UploadRequest}; use metadata_detector::{MetadataDetector, MetadataDetectorRC}; use typing::*; use std::sync::Arc; use std::time; use as...
#[must_use] pub fn with_request_timeout(mut self, request_timeout: time::Duration) -> Self { self.request_timeout = Some(request_timeout); self } #[must_use] pub fn with_max_retry_count(mut self, max_retry_count: usize) -> Self { self.max_retry_count = Some(max_retry_count...
w(profile: String) -> Self { Self { profile, request_timeout: None, max_retry_count: None, retry_interval: None, } }
function_block-function_prefixed
[ { "content": "/// Scrolls a given query until the end of results and returns the output lazily as a stream.\n\npub fn scroll_query(\n\n query: Query,\n\n client: &ClientRC,\n\n) -> impl TryStream<Ok = Hit, Error = UtilError> + Unpin {\n\n Box::pin(futures::stream::try_unfold(\n\n (query, Vec::<H...
Rust
src/lib.rs
paunstefan/sernet
fa71e873733f72dc08f083637b8f2e434b5a47a7
use std::io; use std::{ io::{Read, Write}, sync::Arc, thread, }; use tun_tap::{Iface, Mode}; mod errors; use errors::SernetError; const IP_MAX_LEN: usize = 65535; #[derive(Debug, PartialEq)] enum EtherType { IpV4, IpV6, Unsupported, } impl From<u16> for EtherType { fn from(ethertype: u...
use std::io; use std::{ io::{Read, Write}, sync::Arc, thread, }; use tun_tap::{Iface, Mode}; mod errors; use errors::SernetError; const IP_MAX_LEN: usize = 65535; #[derive(Debug, PartialEq)] enum EtherType { IpV4, IpV6, Unsupported, } impl From<u16> for EtherType { fn from(ethertype: u...
fn fwd_ser_ip(&self, mut reader: impl Read) { let mut buffer = vec![0; IP_MAX_LEN]; loop { let size = match read_ip_packet(&mut buffer, &mut reader) { Ok(size) => size, Err(e) => { eprintln!("{:?}", e); contin...
e); continue; } }; if size < 4 { continue; } let _flags = u16::from_be_bytes([buffer[0], buffer[1]]); let proto = EtherType::from(u16::from_be_bytes([buffer[2], buffer[3]])); if pro...
function_block-function_prefixed
[ { "content": "pub fn new_serial(path: &str, baud: u32) -> (impl Read, impl Write) {\n\n let reader = serialport::new(path, baud)\n\n .timeout(Duration::from_millis(1000))\n\n .open_native()\n\n .expect(\"Failed to open port\");\n\n\n\n let writer = reader.try_clone().expect(\"Failed t...
Rust
src/core/engine.rs
Cosmian/abe_gpsw
1ad9aed9ab49af6b7e6fb740a3b18bda698e222e
use sha3::{ digest::{ExtendableOutput, Update, XofReader}, Shake256, }; use crate::{ core::{ gpsw::{AbeScheme, AsBytes}, policy::{AccessPolicy, Attribute, Policy}, }, error::FormatErr, }; #[derive(Clone)] pub struct Engine<S: AbeScheme> { sch: S, } impl<S: AbeScheme> Engine<S>...
use sha3::{ digest::{ExtendableOutput, Update, XofReader}, Shake256, }; use crate::{ core::{ gpsw::{AbeScheme, AsBytes}, policy::{AccessPolicy, Attribute, Policy}, }, error::FormatErr, }; #[derive(Clone)] pub struct Engine<S: AbeScheme> { sch: S, } impl<S: AbeScheme> Engine<S>...
} } impl<S: AbeScheme> Default for Engine<S> { fn default() -> Self { Self::new() } }
Ok(Shake256::default() .chain(&random.try_into_bytes()?) .finalize_xof() .read_boxed(symmetric_key_len) .into_vec())
call_expression
[ { "content": "#[pyfunction]\n\npub fn decrypt(user_decryption_key_bytes: Vec<u8>, encrypted_bytes: Vec<u8>) -> PyResult<Vec<u8>> {\n\n let header_size = get_encrypted_header_size(encrypted_bytes.clone())?;\n\n let header = &encrypted_bytes[4..4 + header_size as usize];\n\n let ciphertext = &encrypted_b...
Rust
src/parse.rs
bitsapien/shell-hist
158de8c3908b49530ecd76bf6e65c210f351ef82
use std::{ cmp::Ordering, collections::{BinaryHeap, BTreeMap}, fs::File, io::{self, prelude::*, BufReader}, path::PathBuf, }; use dirs::home_dir; use regex::Regex; use crate::opts::HistoryFlavor; #[derive(Eq, Debug)] pub struct CtNode { pub count: usize, pub full_text: String, } impl Ord...
use std::{ cmp::Ordering, collections::{BinaryHeap, BTreeMap}, fs::File, io::{self, prelude::*, BufReader}, path::PathBuf, }; use dirs::home_dir; use regex::Regex; use crate::opts::HistoryFlavor; #[derive(Eq, Debug)] pub struct CtNode { pub count: usize, pub full_text: String, } impl Ord...
tree }
let _: io::Result<()> = f .lines() .filter_map(|line| line.ok()) .filter_map(|line| Some( re .captures(&line)? .get(idx)? .as_str() .to_string() ) ) .try_for_each(|lineout| { let t...
assignment_statement
[ { "content": "fn pct_to_bar(pct: f64, width: usize) -> String {\n\n let mult = (BARS.len() - 1) * width;\n\n let ct = pct * (mult as f64);\n\n let ct = ct.round();\n\n let mut ct = ct as usize;\n\n\n\n let mut out = String::with_capacity(width);\n\n\n\n for _ in 0..width {\n\n let idx =...
Rust
src/registers/control.rs
Freax13/x86_64
8060f05c1314467520052a8d70f9de8ef80e4aa0
pub use super::model_specific::{Efer, EferFlags}; use bitflags::bitflags; #[derive(Debug)] pub struct Cr0; bitflags! { pub struct Cr0Flags: u64 { const PROTECTED_MODE_ENABLE = 1; const MONITOR_COPROCESSOR = 1 << 1; const EMULATE...
pub use super::model_specific::{Efer, EferFlags}; use bitflags::bitflags; #[derive(Debug)] pub struct Cr0; bitflags! { pub struct Cr0Flags: u64 { const PROTECTED_MODE_ENABLE = 1; const MONITOR_COPROCESSOR = 1 << 1; const EMULATE...
#[inline] pub unsafe fn update<F>(f: F) where F: FnOnce(&mut Cr0Flags), { let mut flags = Self::read(); f(&mut flags); Self::write(flags); } } impl C...
cfg(feature = "inline_asm")] asm!("mov cr0, {}", in(reg) value, options(nostack, preserves_flags)); #[cfg(not(feature = "inline_asm"))] crate::asm::x86_64_asm_write_cr0(value); }
function_block-function_prefix_line
[ { "content": "#[cfg(feature = \"inline_asm\")]\n\n#[cfg_attr(docsrs, doc(cfg(any(feature = \"nightly\", feature = \"inline_asm\"))))]\n\n#[inline(always)]\n\npub fn read_rip() -> crate::VirtAddr {\n\n let rip: u64;\n\n unsafe {\n\n asm!(\"lea {}, [rip]\", out(reg) rip, options(nostack, nomem, prese...
Rust
src/connectivity/lowpan/drivers/lowpan-ot-driver/src/driver/connectivity_state.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use crate::prelude::*; use fidl_fuchsia_lowpan::{ConnectivityState, Role}; pub trait ConnectivityStateExt { fn is_ready(&self) -> bool; fn is_active(&self) -> bool; fn is_active_and_ready(&self) -> bool; fn is_commissioning(&self) -> bool; fn is_invalid_during_in...
use crate::prelude::*; use fidl_fuchsia_lowpan::{ConnectivityState, Role}; pub trait ConnectivityStateExt { fn is_ready(&self) -> bool; fn is_active(&self) -> bool; fn is_active_and_ready(&self) -> bool; fn is_commissioning(&self) -> bool; fn is_invalid_during_in...
} fn is_active_and_ready(&self) -> bool { self.is_active() && self.is_ready() } fn is_invalid_during_initialization(&self) -> bool { self.is_online() } fn is_commissioning(&self) -> bool { *self == ConnectivityState::Commissioning } fn is_online(&self) -> boo...
match self { ConnectivityState::Inactive => false, ConnectivityState::Ready => false, ConnectivityState::Offline => true, ConnectivityState::Attaching => true, ConnectivityState::Attached => true, ConnectivityState::Isolated => true, C...
if_condition
[]
Rust
scipio/src/pollable.rs
monocodus-demonstrations/scipio
dbd22e5b701254d87dafb661242d2392820a20ac
use std::future::Future; use std::io::{self, IoSlice, IoSliceMut, Read, Write}; use std::os::unix::io::{AsRawFd, RawFd}; use std::pin::Pin; use std::task::{Context, Poll}; use futures_lite::io::{AsyncRead, AsyncWrite}; use futures_lite::{future, pin}; use crate::parking::Reactor; use crate::sys::{self, Source}; #[...
use std::future::Future; use std::io::{self, IoSlice, IoSliceMut, Read, Write}; use std::os::unix::io::{AsRawFd, RawFd}; use std::pin::Pin; use std::task::{Context, Poll}; use futures_lite::io::{AsyncRead, AsyncWrite}; use futures_lite::{future, pin}; use crate::parking::Reactor; use crate::sys::{self, Source}; #[...
optimistic(self.readable()).await?; } } pub async fn read_with_mut<R>( &mut self, op: impl FnMut(&mut T) -> io::Result<R>, ) -> io::Result<R> { let mut ...
match op(self.get_ref()) { Err(err) if err.kind() == io::ErrorKind::WouldBlock => {} res => return res, }
if_condition
[ { "content": "/// Shuts down the write side of a socket.\n\n///\n\n/// If this source is not a socket, the `shutdown()` syscall error is ignored.\n\npub fn shutdown_write(raw: RawFd) -> io::Result<()> {\n\n // This may not be a TCP stream, but that's okay. All we do is call `shutdown()` on the raw\n\n // ...
Rust
wheel/src/service.rs
MrCroxx/RunKV
0770ce449363a98814c80e343a4e6e6a029e5f6b
use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Instant; use async_trait::async_trait; use itertools::Itertools; use lazy_static::lazy_static; use runkv_common::channel_pool::ChannelPool; use runkv_common::config::Node; use runkv_common::notify_pool::Not...
use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Instant; use async_trait::async_trait; use itertools::Itertools; use lazy_static::lazy_static; use runkv_common::channel_pool::ChannelPool; use runkv_common::config::Node; use runkv_common::notify_pool::Not...
mpl Into<Box<dyn std::error::Error>>) -> Status { Status::internal(e.into().to_string()) } pub struct WheelOptions { pub node: u64, pub meta_store: MetaStoreRef, pub channel_pool: ChannelPool, pub raft_network: GrpcRaftNetwork, pub raft_manager: RaftManager, pub txn_notify_pool: NotifyPool<...
ATENCY_HISTOGRAM_VEC .get_metric_with_label_values(&["txn", &node.to_string()]) .unwrap(), kv_service_propose_latency_histogram: KV_SERVICE_LATENCY_HISTOGRAM_VEC .get_metric_with_label_values(&["propose", &node.to_string()]) .unwrap(), ...
random
[ { "content": "#[allow(clippy::type_complexity)]\n\nfn build_dataset(args: &Args) -> Vec<Vec<Vec<(u64, u64, u64, Vec<u8>, Vec<u8>)>>> {\n\n const TERM: u64 = 1;\n\n let mut rng = ChaCha8Rng::seed_from_u64(args.seed);\n\n\n\n let mut dataset = Vec::with_capacity(args.groups);\n\n\n\n for group in 1..=...
Rust
src/solution/s0094_binary_tree_inorder_traversal.rs
tan-wei/my-leetcode-rust
3d7892a42294fe4891db396573b8ba81e9294380
/** * [94] Binary Tree Inorder Traversal * * Given the root of a binary tree, return the inorder traversal of its nodes' values. * * Example 1: * <img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" style="width: 202px; height: 324px;" /> * Input: root = [1,null,2,3] * Output: [1,3,2...
/** * [94] Binary Tree Inorder Traversal * * Given the root of a binary tree, return the inorder traversal of its nodes' values. * * Example 1: * <img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" style="width: 202px; height: 324px;" /> * Input: root = [1,null,2,3] * Output: [1,3,2...
#[test] fn test_0094_example_2() { let root = tree![]; let result = vec![]; assert_eq!(Solution::inorder_traversal(root), result); let root = tree![]; let result = vec![]; assert_eq!(Solution::inorder_traversal_v2(root), result); } #[test] fn tes...
assert_eq!(Solution::inorder_traversal(root), result); let root = tree![1, null, 2, 3]; let result = vec![1, 3, 2]; assert_eq!(Solution::inorder_traversal_v2(root), result); }
function_block-function_prefix_line
[ { "content": "pub fn to_tree(vec: Vec<Option<i32>>) -> Option<Rc<RefCell<TreeNode>>> {\n\n use std::collections::VecDeque;\n\n let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap()))));\n\n let mut queue = VecDeque::new();\n\n queue.push_back(head.as_ref().unwrap().clone());\n\n\n\n ...
Rust
core/src/result.rs
sanjsingh07/Domi-chain
ee256fdf16a1e594b2eed683864b583c7736cb92
use analog_gossip::{cluster_info, gossip_error::GossipError}; use analog_ledger::blockstore; #[derive(Debug)] pub enum Error { Io(std::io::Error), Recv(std::sync::mpsc::RecvError), CrossbeamRecvTimeout(crossbeam_channel::RecvTimeoutError), ReadyTimeout, RecvTimeout(std::sync::mpsc::RecvTimeoutErr...
use analog_gossip::{cluster_info, gossip_error::GossipError}; use analog_ledger::blockstore; #[derive(Debug)] pub enum Error { Io(std::io::Error), Recv(std::sync::mpsc::RecvError), CrossbeamRecvTimeout(crossbeam_channel::RecvTimeoutError), ReadyTimeout, RecvTimeout(std::sync::mpsc::RecvTimeoutErr...
}
p(); write!( io::sink(), "{:?}", Error::from(io::Error::new(io::ErrorKind::NotFound, "hi")) ) .unwrap(); }
function_block-function_prefixed
[ { "content": "/// Reads a JSON-encoded `Keypair` from a `Reader` implementor\n\npub fn read_keypair<R: Read>(reader: &mut R) -> Result<Keypair, Box<dyn error::Error>> {\n\n let bytes: Vec<u8> = serde_json::from_reader(reader)?;\n\n let dalek_keypair = ed25519_dalek::Keypair::from_bytes(&bytes)\n\n ...
Rust
src/server/mod.rs
ivan-ochc/actix-web
c04b4678f136b118fef40b979c0df90402a8e0e4
use std::net::{Shutdown, SocketAddr}; use std::rc::Rc; use std::{io, time}; use bytes::{BufMut, BytesMut}; use futures::{Async, Poll}; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_tcp::TcpStream; pub use actix_net::server::{PauseServer, ResumeServer, StopServer}; pub(crate) mod acceptor; pub(crate) mod builder...
use std::net::{Shutdown, SocketAddr}; use std::rc::Rc; use std::{io, time}; use bytes::{BufMut, BytesMut}; use futures::{Async, Poll}; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_tcp::TcpStream; pub use actix_net::server::{PauseServer, ResumeServer, StopServer}; pub(crate) mod acceptor; pub(crate) mod builder...
} #[doc(hidden)] #[derive(Debug)] pub enum WriterState { Done, Pause, } #[doc(hidden)] pub trait Writer { fn written(&self) -> u64; #[doc(hidden)] fn set_date(&mut self); #[doc(hidden)] fn buffer(&mut self) -> &mut BytesMut; fn start( &mut self, req: &Request, resp: &...
fn from(keepalive: Option<usize>) -> Self { if let Some(keepalive) = keepalive { KeepAlive::Timeout(keepalive) } else { KeepAlive::Disabled } }
function_block-full_function
[ { "content": "/// This trait indicates types that can create acceptor service for http server.\n\npub trait AcceptorServiceFactory: Send + Clone + 'static {\n\n type Io: IoStream + Send;\n\n type NewService: NewService<Request = TcpStream, Response = Self::Io>;\n\n\n\n fn create(&self) -> Self::NewServ...
Rust
src/backend/primitives/path_find.rs
jesse99/1k-deaths
473107dffcb68e3edd5352c7e5ba98d9ccc5716d
#[cfg(test)] use super::super::time; #[cfg(test)] use super::super::Time; #[cfg(test)] use super::vec2d::Vec2d; use super::Point; #[cfg(test)] use super::Size; use fnv::FnvHashMap; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::ops::{Add, AddAssign}; pub struct PathFind<C, S> where C:...
#[cfg(test)] use super::super::time; #[cfg(test)] use super::super::Time; #[cfg(test)] use super::vec2d::Vec2d; use super::Point; #[cfg(test)] use super::Size; use fnv::FnvHashMap; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::ops::{Add, AddAssign}; pub struct PathFind<C, S> where C:...
#[test] fn test_column() { #[rustfmt::skip] let rows = vec![ "............", "............", "......#.....", "......#.....", "......#.....", ".S....#..T..", "......#.....", ".........
k = |loc: Point, neighbors: &mut Vec<(Point, Time)>| successors(&map, loc, neighbors); let find = PathFind::new(start, start, callback); let actual = find.path(); let expected = vec![Point::new(1, 5)]; assert_eq!(*actual, expected); }
function_block-function_prefixed
[ { "content": "fn successors(game: &Game, ch: &Object, loc: Point, target: &Point, neighbors: &mut Vec<(Point, Time)>) {\n\n let deltas = vec![(-1, -1), (-1, 1), (-1, 0), (1, -1), (1, 1), (1, 0), (0, -1), (0, 1)];\n\n for delta in deltas {\n\n let new_loc = Point::new(loc.x + delta.0, loc.y + delta....
Rust
src/models/r5/CapabilityStatement_Rest.rs
itsbalamurali/rust-fhir
be43a387214586b6d8c5c5bf1d1f082a15c362b0
#![allow(unused_imports, non_camel_case_types)] use crate::models::r5::CapabilityStatement_Interaction1::CapabilityStatement_Interaction1; use crate::models::r5::CapabilityStatement_Operation::CapabilityStatement_Operation; use crate::models::r5::CapabilityStatement_Resource::CapabilityStatement_Resource; use crate::m...
#![allow(unused_imports, non_camel_case_types)] use crate::models::r5::CapabilityStatement_Interaction1::CapabilityStatement_Interaction1; use crate::models::r5::CapabilityStatement_Operation::CapabilityStatement_Operation; use crate::models::r5::CapabilityStatement_Resource::CapabilityStatement_Resource; use crate::m...
pub fn resource<'a>( &'a mut self, val: Vec<CapabilityStatement_Resource>, ) -> &'a mut CapabilityStatement_RestBuilder { self.value["resource"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn search_param<'a>( &'a mut self,...
val: Vec<CapabilityStatement_Operation>, ) -> &'a mut CapabilityStatement_RestBuilder { self.value["operation"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; }
function_block-function_prefix_line
[ { "content": "fn write_string_to_file(contents: &str, path_string: &str) -> bool {\n\n if contents.len() == 0 {\n\n return false;\n\n }\n\n let path = Path::new(&path_string);\n\n // Open a file in write-only mode, returns `io::Result<File>`\n\n let mut file = match File::create(&path) {\n...
Rust
zebra-state/src/service/finalized_state/disk_format.rs
preston-evans98/zebra-btc
7b67007d9e24d05bfd33d967115972d29d8faa3f
use std::{convert::TryInto, fmt::Debug, sync::Arc}; use bytes::BytesMut; use zebra_chain::{ block, block::Block, serialization::{BitcoinDeserialize, BitcoinDeserializeInto, BitcoinSerialize}, transaction, transparent, }; use crate::Utxo; #[derive(Debug, Clone, Copy, PartialEq)] pub struct Transactio...
use std::{convert::TryInto, fmt::Debug, sync::Arc}; use bytes::BytesMut; use zebra_chain::{ block, block::Block, serialization::{BitcoinDeserialize, BitcoinDeserializeInto, BitcoinSerialize}, transaction, transparent, }; use crate::Utxo; #[derive(Debug, Clone, Copy, PartialEq)] pub struct Transactio...
} fn assert_round_trip_ref<T>(input: &T) where T: IntoDisk + FromDisk + Clone + PartialEq + std::fmt::Debug, { let before = input; let after = round_trip_ref(input); assert_eq!(before, &after); } fn round_trip_arc<T>(input: Arc<T>) -> T where T: IntoDisk...
isk, { fn from_bytes(bytes: impl AsRef<[u8]>) -> Self { Arc::new(T::from_bytes(bytes)) } } impl IntoDisk for Block { type Bytes = Vec<u8>; fn as_bytes(&self) -> Self::Bytes { self.bitcoin_serialize_to_vec() .expect("serialization to vec doesn't fail") } } impl FromDisk...
random
[ { "content": "/// Get the heights of the blocks for constructing a block_locator list\n\npub fn block_locator_heights(tip_height: block::Height) -> Vec<block::Height> {\n\n // Stop at the reorg limit, or the genesis block.\n\n let min_locator_height = tip_height\n\n .0\n\n .saturating_sub(co...
Rust
derive/src/validators.rs
Emilgardis/async-graphql
3e586a0f1162b0d98226b6b1342ff2b2a57e735d
use darling::util::SpannedValue; use darling::FromMeta; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{Error, Expr, Lit, Result}; #[derive(Clone)] pub enum Number { F64(f64), I64(i64), } impl FromMeta for Number { fn from_value(value: &Lit) -> darling::Result<Self> { match v...
use darling::util::SpannedValue; use darling::FromMeta; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{Error, Expr, Lit, Result}; #[derive(Clone)] pub enum Number { F64(f64), I64(i64), } impl FromMeta for Number { fn from_value(value: &Lit) -> darling::Result<Self> { match v...
} #[derive(FromMeta, Default, Clone)] pub struct Validators { #[darling(default)] multiple_of: Option<Number>, #[darling(default)] maximum: Option<Number>, #[darling(default)] minimum: Option<Number>, #[darling(default)] max_length: Option<usize>, #[darling(default)] min_length...
fn to_tokens(&self, tokens: &mut TokenStream) { match self { Number::F64(n) => tokens.extend(quote!(#n as f64)), Number::I64(n) => tokens.extend(quote!(#n as i64)), } }
function_block-function_prefix_line
[ { "content": "/// Parse a value as an enum value.\n\n///\n\n/// This can be used to implement `InputType::parse`.\n\npub fn parse_enum<T: EnumType + InputType>(value: Value) -> InputValueResult<T> {\n\n let value = match &value {\n\n Value::Enum(s) => s,\n\n Value::String(s) => s.as_str(),\n\n ...
Rust
unic/normal/src/decompose.rs
rust-han/rust-unic
4d82460788b2f58d0f7fd4573c6616f9067d64d1
use std::collections::VecDeque; use std::fmt::{self, Write}; use unic_ucd_normal::{decompose_canonical, decompose_compatible, CanonicalCombiningClass}; fn canonical_sort(comb: &mut VecDeque<(char, CanonicalCombiningClass)>) { let len = comb.len(); for i in 0..len { let mut swapped = false; f...
use std::collections::VecDeque; use std::fmt::{self, Write}; use unic_ucd_normal::{decompose_canonical, decompose_compatible, CanonicalCombiningClass}; fn canonical_sort(comb: &mut VecDeque<(char, CanonicalCombiningClass)>) { let len = comb.len(); for i in 0..len { let mut swapped = false; f...
al, } } #[inline] pub fn new_compatible<I: Iterator<Item = char>>(iter: I) -> Decompositions<I> { Decompositions { iter, buffer: VecDeque::new(), sorted: false, kind: self::DecompositionType::Compatible, } } impl<I: Iterator<Item = char>> Iterator for Decompositions<I> { ...
itions { iter, buffer: VecDeque::new(), sorted: false, kind: self::DecompositionType::Canonic
function_block-random_span
[ { "content": "/// Check if the Unicode code-point provided is a *Unicode Private-Use Character*.\n\n///\n\n/// - https://www.unicode.org/faq/private_use.html#private_use\n\npub fn is_private_use(codepoint: char) -> bool {\n\n match codepoint {\n\n '\\u{e000}'...'\\u{f8ff}' // 6,400 Plane 0 (BMP) chars...
Rust
src/platform_impl/web/window.rs
willcrichton/win
5fac5afb726a7a159eaea86027a4872dafb20f81
use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; use crate::error::{ExternalError, NotSupportedError, OsError as RootOE}; use crate::event; use crate::icon::Icon; use crate::monitor::MonitorHandle as RootMH; use crate::window::{ CursorIcon, Fullscreen, UserAttentionType, WindowAttribut...
use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; use crate::error::{ExternalError, NotSupportedError, OsError as RootOE}; use crate::event; use crate::icon::Icon; use crate::monitor::MonitorHandle as RootMH; use crate::window::{ CursorIcon, Fullscreen, UserAttentionType, WindowAttribut...
#[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { self.canvas.borrow().size() } #[inline] pub fn outer_size(&self) -> PhysicalSize<u32> { self.inner_size() } #[inline] pub fn set_inner_size(&self, size: Size) { let old_size = self.inner_size()...
pub fn set_outer_position(&self, position: Position) { let position = position.to_logical::<f64>(self.scale_factor()); let canvas = self.canvas.borrow(); canvas.set_attribute("position", "fixed"); canvas.set_attribute("left", &position.x.to_string()); canvas.set_attribute("top",...
function_block-full_function
[]
Rust
tests/json.rs
juliotpaez/jpar
f90e55236de738af1dc05d2beda28ef9aa526f85
use std::collections::HashMap; use jpar::branch::alternative; use jpar::characters::{ read_any, read_any_quantified, read_char, read_none_of, read_text, ucd_whitespace0, }; use jpar::combinator::verify; use jpar::helpers::{and_then, map_result}; use jpar::numbers::read_float; use jpar::sequence::{delimited, preced...
use std::collections::HashMap; use jpar::branch::alternative; use jpar::characters::{ read_any, read_any_quantified, read_char, read_none_of, read_text, ucd_whitespace0, }; use jpar::combinator::verify; use jpar::helpers::{and_then, map_result}; use jpar::numbers::read_float; use jpar::sequence::{delimited, preced...
) }), preceded(read_char('u'), unicode_escape), ))(input) } else { Ok(c) } } fn string<Err>(input: &mut ParserInput<Err>) -> ParserResult<String, Err> { delimited( read_char('"'), repeat_and_fold( .., String::new(), ...
match c { '"' | '\\' | '/' => c, 'b' => '\x08', 'f' => '\x0C', 'n' => '\n', 'r' => '\r', 't' => '\t', _ => return Err(ParserResultError::NotFound), }
if_condition
[ { "content": "/// It is ok only at the end of the input.\n\npub fn end<C, Err>(reader: &mut ParserInput<Err, C>) -> ParserResult<(), Err> {\n\n if reader.is_end() {\n\n Ok(())\n\n } else {\n\n Err(ParserResultError::NotFound)\n\n }\n\n}\n\n\n", "file_path": "src/parsers/combinator.rs"...
Rust
src/lib/diagnostics/inspect/runtime/rust/src/service.rs
Prajwal-Koirala/fuchsia
ca7ae6c143cd4c10bad9aa1869ffcc24c3e4b795
use anyhow::{Context as _, Error}; use fidl; use fidl_fuchsia_inspect::{ TreeContent, TreeNameIteratorRequest, TreeNameIteratorRequestStream, TreeRequest, TreeRequestStream, }; use fidl_fuchsia_mem::Buffer; use fuchsia_async as fasync; use fuchsia_inspect::{reader::ReadableTree, Inspector}; use fuchsia_zircon...
use anyhow::{Context as _, Error}; use fidl; use fidl_fuchsia_inspect::{ TreeContent, TreeNameIteratorRequest, TreeNameIteratorRequestStream, TreeRequest, TreeRequestStream, }; use fidl_fuchsia_mem::Buffer; use fuchsia_async as fasync; use fuchsia_inspect::{reader::ReadableTree, Inspector}; use fuchsia_zircon...
) } }; let buffer_data = vmo.and_then(|vmo| vmo.get_size().ok().map(|size| (vmo, size))); let content = TreeContent { buffer: buffer_data.map(|data| Buffer { vmo: data.0, size: data.1 }), ..TreeContent::EMPTY ...
match **failure { TreeServerSendPreference::DeepCopy => inspector.copy_vmo(), TreeServerSendPreference::Live => inspector.duplicate_vmo(), _ => None, }
if_condition
[]
Rust
isucondition-axum/src/routes/authorization_routes.rs
walf443/isucon11-qualify-rust-axum
535118cb0cd57ea6e8d59fb35483f0de69b8b594
use crate::requests::current_user_id::SESSION_USER_ID; use crate::requests::session::{SessionID, SESSION_KEY}; use async_redis_session::RedisSessionStore; use async_session::{Session, SessionStore}; use axum::extract::{Extension, TypedHeader}; use axum::headers::authorization::Bearer; use axum::http::StatusCode; use ax...
use crate::requests::current_user_id::SESSION_USER_ID; use crate::requests::session::{SessionID, SESSION_KEY}; use async_redis_session::RedisSessionStore; use async_session::{Session, SessionStore}; use axum::extract::{Extension, TypedHeader}; use axum::headers::authorization::Bearer; use axum::http::StatusCode; use ax...
pub async fn post_signout( cookies: Cookies, Extension(store): Extension<RedisSessionStore>, session_id: SessionID, ) -> impl IntoResponse { cookies.remove(Cookie::new("jia_user_id", "")); if session_id.is_none() { return (StatusCode::OK, Json("OK")); } let session_id = session_id....
let claims: Claims = token.claims; let jia_user_id = claims.jia_user_id; repo.user_repository() .insert(jia_user_id.to_string()) .await .map_err(|e| { log::error!("user insert failed: {:?}", e); ( StatusCode::INTERNAL_SERVER_ERROR, ...
function_block-function_prefix_line
[ { "content": "pub fn run<R: 'static + RepositoryManager, S: 'static + ServiceManager, Store: SessionStore>(\n\n listener: TcpListener,\n\n repo_manager: Arc<R>,\n\n service_manager: Arc<S>,\n\n session_store: Store,\n\n) -> Result<impl Future<Output = hyper::Result<()>>, hyper::Error> {\n\n let r...
Rust
src/language.rs
mullroy/tiny-bip39
c6428c43d34b8f8ef5a9f28e77da25e8f73b2a69
use crate::error::ErrorKind; use crate::util::{Bits, Bits11}; use rustc_hash::FxHashMap; pub struct WordMap { inner: FxHashMap<&'static str, Bits11>, } pub struct WordList { inner: Vec<&'static str>, } impl WordMap { pub fn get_bits(&self, word: &str) -> Result<Bits11, ErrorKind> { match self.inn...
use crate::error::ErrorKind; use crate::util::{Bits, Bits11}; use rustc_hash::FxHashMap; pub struct WordMap { inner: FxHashMap<&'static str, Bits11>, } pub struct WordList { inner: Vec<&'static str>, } impl WordMap { pub fn get_bits(&self, word: &str) -> Result<Bits11, ErrorKind> { match self.inn...
gs/japanese.txt"))); #[cfg(feature = "korean")] pub static WORDLIST_KOREAN: Lazy<WordList> = Lazy::new(|| gen_wordlist(include_str!("langs/korean.txt"))); #[cfg(feature = "spanish")] pub static WORDLIST_SPANISH: Lazy<WordList> = Lazy::new(|| gen_wordlist(include_str!("langs/spanish.txt")...
SE_SIMPLIFIED: Lazy<WordList> = Lazy::new(|| gen_wordlist(include_str!("langs/chinese_simplified.txt"))); #[cfg(feature = "chinese-traditional")] pub static WORDLIST_CHINESE_TRADITIONAL: Lazy<WordList> = Lazy::new(|| gen_wordlist(include_str!("langs/chinese_traditional.txt"))); #[cfg(feature...
random
[ { "content": "fn test_word_count(expected_word_count: usize) {\n\n let mnemonic_type = MnemonicType::for_word_count(expected_word_count).unwrap();\n\n\n\n let mnemonic = Mnemonic::new(mnemonic_type, Language::English);\n\n let actual_word_count = mnemonic.phrase().split(\" \").count();\n\n\n\n asser...
Rust
demos/todo-app/src/ui/components/app_bar.rs
zicklag/raui
bdabe92953c80ea52e67ffd9f8006807d79eb292
use crate::ui::components::app::{AppMessage, AppSharedProps, ThemeModeProps}; use raui_core::prelude::*; use raui_material::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct AppBarState { pub creating_task: bool, pub new_task_name: String, } im...
use crate::ui::components::app::{AppMessage, AppSharedProps, ThemeModeProps}; use raui_core::prelude::*; use raui_material::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct AppBarState { pub creating_task: bool, pub new_task_name: String, } im...
n_paper: {create_props.clone()}) } } } ]) { if creating_task { widget! { (#{"task-bar"} horizontal_box: {line_props} [ (#{"name"} text_field_paper: {name_props}) ...
avItemActive) .with(ButtonNotifyProps(id.to_owned().into())) .with(TextInputNotifyProps(id.to_owned().into())); let theme_props = Props::new(FlexBoxItemLayout { fill: 0.0, grow: 0.0, shrink: 0.0, align: 0.5, ..Default::default() }) .with(IconPaperProps { ...
random
[ { "content": "#[pre_hooks(use_task)]\n\npub fn task(mut context: WidgetContext) -> WidgetNode {\n\n let WidgetContext { id, key, props, .. } = context;\n\n\n\n let data = props.read_cloned_or_default::<TaskProps>();\n\n let checkbox_props = Props::new(FlexBoxItemLayout {\n\n fill: 0.0,\n\n ...
Rust
xtask/coverage/src/compare.rs
iamsaquib8/rome
425301c0293dbd884da9ed757b60b0e90ce9ccb7
use std::char::decode_utf16; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use xtask::project_root; use crate::results::emit_compare; use crate::TestResults; const BASE_RESULT_FILE: &str = "base_results.json"; const NEW_RESULT_FILE: &str = "new_results.json"; p...
use std::char::decode_utf16; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use xtask::project_root; use crate::results::emit_compare; use crate::TestResults; const BASE_RESULT_FILE: &str = "base_results.json"; const NEW_RESULT_FILE: &str = "new_results.json"; p...
fn read_test_results(path: &Path, name: &'static str) -> HashMap<String, TestResults> { let mut file = File::open(path) .unwrap_or_else(|err| panic!("Can't read the file of the {} results: {:?}", name, err)); let mut buffer = Vec::new(); file.read_to_end(&mut buffer) .unwrap_or_else(|err|...
n(NEW_RESULT_FILE) }; if !base_result_dir.exists() { panic!( "The path to the base results doesn't exist: {:?}", base_result_dir ); } if !&new_result_dir.exists() { panic!( "The path to the new results doesn't exist: {:?}", new_re...
function_block-function_prefixed
[]
Rust
src/hss/mod.rs
hieronymusma/hbs-lms-rust
ef3954c8acb49c2d76ff8176259cd7b2a77f6e91
pub mod aux; pub mod definitions; pub mod parameter; pub mod reference_impl_private_key; mod seed_derive; pub mod signing; pub mod verify; use arrayvec::ArrayVec; use crate::{ constants::{MAX_HASH_SIZE, MAX_HSS_SIGNATURE_LENGTH, REFERENCE_IMPL_PRIVATE_KEY_SIZE}, extract_or, extract_or_return, hasher::Hash...
pub mod aux; pub mod definitions; pub mod parameter; pub mod reference_impl_private_key; mod seed_derive; pub mod signing; pub mod verify; use arrayvec::ArrayVec; use crate::{ constants::{MAX_HASH_SIZE, MAX_HSS_SIGNATURE_LENGTH, REFERENCE_IMPL_PRIVATE_KEY_SIZE}, extract_or, extract_or_return, hasher::Hash...
#[cfg(feature = "fast_verify")] pub fn hss_sign_mut<H: 'static + Hasher>( message: &mut [u8], private_key: &[u8], private_key_update_function: &mut dyn FnMut(&[u8]) -> bool, aux_data: Option<&mut &mut [u8]>, ) -> Option<(ArrayVec<u8, MAX_HSS_SIGNATURE_LENGTH>, Option<u16>)> { hss_sign_core::<H>( ...
8]>, ) -> Option<ArrayVec<u8, MAX_HSS_SIGNATURE_LENGTH>> { let (signature, _) = hss_sign_core::<H>( Some(message), None, private_key, private_key_update_function, aux_data, )?; Some(signature) }
function_block-function_prefixed
[ { "content": "pub fn hss_is_aux_data_used(aux_data: &[u8]) -> bool {\n\n aux_data[AUX_DATA_MARKER] != NO_AUX_DATA\n\n}\n\n\n", "file_path": "src/hss/aux.rs", "rank": 1, "score": 306364.19943773607 }, { "content": "fn compute_hmac<H: Hasher>(dest: &mut [u8], key: &mut [u8], data: &[u8]) {\...
Rust
src/sources/fs.rs
jwmcglynn/font-kit
640745f42187d38494fc9a5b2b3957c8a3ff793d
use std::fs::File; use std::path::PathBuf; use walkdir::WalkDir; #[cfg(not(any(target_os = "android", target_family = "windows")))] use dirs; #[cfg(target_family = "windows")] use std::ffi::OsString; #[cfg(target_family = "windows")] use std::os::windows::ffi::OsStringExt; #[cfg(target_family = "windows")] use winap...
use std::fs::File; use std::path::PathBuf; use walkdir::WalkDir; #[cfg(not(any(target_os = "android", target_family = "windows")))] use dirs; #[cfg(target_family = "windows")] use std::ffi::OsString; #[cfg(target_family = "windows")] use std::os::windows::ffi::OsStringExt; #[cfg(target_family = "windows")] use winap...
} } FsSource { mem_source: MemSource::from_fonts(fonts.into_iter()).unwrap(), } } pub fn all_fonts(&self) -> Result<Vec<Handle>, SelectionError> { self.mem_source.all_fonts() } pub fn all_families(&self) -> Result<Vec<String>, Selecti...
match Font::analyze_file(&mut file) { Err(_) => continue, Ok(FileType::Single) => fonts.push(Handle::from_path(path.to_owned(), 0)), Ok(FileType::Collection(font_count)) => { for font_index in 0..font_count { ...
if_condition
[ { "content": "#[test]\n\npub fn load_font_from_file() {\n\n let mut file = File::open(TEST_FONT_FILE_PATH).unwrap();\n\n let font = Font::from_file(&mut file, 0).unwrap();\n\n assert_eq!(font.postscript_name().unwrap(), TEST_FONT_POSTSCRIPT_NAME);\n\n}\n\n\n", "file_path": "tests/tests.rs", "ra...
Rust
examples/winit.rs
Veykril/d3d11-glyph
5875e7061c6042679b57618632836888a72ff203
use std::time::Instant; use std::{mem, ptr}; use d3d11_glyph::{ab_glyph, GlyphBrushBuilder, Section, Text}; use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; use winapi::shared::dxgi::*; use winapi::shared::dxgiformat::*; use winapi::shared::dxgitype::*; use winapi::shared::minwindef::{FALSE, TRUE}; use w...
use std::time::Instant; use std::{mem, ptr}; use d3d11_glyph::{ab_glyph, GlyphBrushBuilder, Section, Text}; use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; use winapi::shared::dxgi::*; use winapi::shared::dxgiformat::*; use winapi::shared::dxgitype::*; use winapi::shared::minwindef::{FALSE, TRUE}; use w...
unsafe fn create_render_target( swapchain: &ComPtr<IDXGISwapChain>, device: &ComPtr<ID3D11Device>, ) -> ( ComPtr<ID3D11RenderTargetView>, ComPtr<ID3D11DepthStencilView>, ) { let mut back_buffer = ptr::null_mut::<ID3D11Texture2D>(); let mut main_rtv = ptr::null_mut(); swapchain.GetBuffer( ...
unsafe fn create_device( hwnd: HWND, ) -> Option<( ComPtr<IDXGISwapChain>, ComPtr<ID3D11Device>, ComPtr<ID3D11DeviceContext>, )> { let sc_desc = DXGI_SWAP_CHAIN_DESC { BufferDesc: DXGI_MODE_DESC { Width: 0, Height: 0, RefreshRate: DXGI_RATIONAL { ...
function_block-full_function
[ { "content": "pub use builder::GlyphBrushBuilder;\n\npub use glyph_brush::ab_glyph;\n\npub use glyph_brush::{\n\n BuiltInLineBreaker, Extra, FontId, GlyphCruncher, GlyphPositioner, HorizontalAlign, Layout,\n\n LineBreak, LineBreaker, Section, SectionGeometry, SectionGlyph, SectionGlyphIter, SectionText,\n...
Rust
src/human/test_value.rs
AljoschaMeyer/valuable-value-rs
9e0691fc5bcfc2a60d34e24bbd82f8815275adf2
use std::collections::BTreeMap; use arbitrary::Arbitrary; use atm_parser_helper_common_syntax::testing::*; use crate::value::Value; #[derive(Arbitrary, Debug)] pub enum TestValue { Nil(Spaces), Bool(Spaces, bool), Int(Spaces, Int), Float(Spaces, Float), ByteString(Spaces, ByteString), Utf8St...
use std::collections::BTreeMap; use arbitrary::Arbitrary; use atm_parser_helper_common_syntax::testing::*; use crate::value::Value; #[derive(Arbitrary, Debug)] pub enum TestValue { Nil(Spaces), Bool(Spaces, bool), Int(Spaces, Int), Float(Spaces, Float), ByteString(Spaces, ByteString), Utf8St...
pub fn encode(&self, out: &mut Vec<u8>) { out.extend_from_slice(b"["); let len = self.values.len(); for (i, (s1, v, s2)) in self.values.iter().enumerate() { s1.encode(out); v.encode(out); s2.encode(out); if i + 1 == len { mat...
pub fn to_value(&self) -> Value { let mut arr = Vec::with_capacity(self.values.len()); for (_, v, _) in self.values.iter() { arr.push(v.to_value()); } Value::Array(arr) }
function_block-full_function
[ { "content": "fn test(b: bool, v: &Value, w: &Value, msg: &'static str) {\n\n if !b {\n\n println!(\"v: {:?}\", v);\n\n println!(\"w: {:?}\", w);\n\n panic!(\"{}\", msg);\n\n }\n\n}\n", "file_path": "fuzz/fuzz_targets/partial_order.rs", "rank": 0, "score": 109545.090220795...
Rust
src/spacework/history.rs
m-rsha/spacework
323a5c7cedf4dfbb9fb1f3ba0195e368c5f1904e
use std::env::{self, VarError}; use std::error::Error; use std::fs::{self, File, OpenOptions}; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; use std::str; use chrono::prelude::*; pub struct History { histfile: PathBuf, } impl History { const HISTFILE: &'static str = ".spacework_history"; ...
use std::env::{self, VarError}; use std::error::Error; use std::fs::{self, File, OpenOptions}; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; use std::str; use chrono::prelude::*; pub struct History { histfile: PathBuf, } impl History { const HISTFILE: &'static str = ".spacework_history"; ...
fn create_history_file(filepath: &Path) -> Result<(), Box<dyn Error>> { match File::create(filepath) { Ok(_) => { Self::write( &Self{ histfile: filepath.into() }, "Hello hello, world!", )?; println!( ...
pub fn write<'a>(&self, text: &'a str) -> Result<&'a str, Box<dyn Error>> { match self .file()? .write_all( format!("{} {}\n", self.timestamp(), text).as_bytes()) { Ok(_) => Ok(text), Err(e) => Err( format!("Unable to write to h...
function_block-full_function
[ { "content": "pub fn workspace_dir() -> Result<PathBuf, &'static str> {\n\n let home_dir = match env::var(\"HOME\") {\n\n Ok(home) => home,\n\n Err(e) => match e {\n\n VarError::NotPresent =>\n\n return Err(\"HOME environment variable not found. \\\n\n ...
Rust
src/utils/serde.rs
dmitmel/crosscode-localization-engine
b8c69c81feb203e28ba3b0761588efbb95ab0825
use serde::de::{self, Deserialize, DeserializeSeed, Deserializer, Error as DeError}; use serde::ser::{Error as SerError, Serialize, SerializeMap as _, SerializeSeq as _, Serializer}; use std::borrow::Cow; use std::cell::{Ref, RefCell, RefMut}; use std::convert::TryFrom; use std::fmt; use std::marker::PhantomData; use...
use serde::de::{self, Deserialize, DeserializeSeed, Deserializer, Error as DeError}; use serde::ser::{Error as SerError, Serialize, SerializeMap as _, SerializeSeq as _, Serializer}; use std::borrow::Cow; use std::cell::{Ref, RefCell, RefMut}; use std::convert::TryFrom; use std::fmt; use std::marker::PhantomData; use...
), }, Err(_) => Err(de_error(format_args!( "length doesn't match: expected {}, found {}", super::COMPACT_UUID_BYTE_LEN, value.len(), ))), } } fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<Uuid, E> { ...
de_error(format_args!( "invalid byte {:?} at index {}", bytes[error_idx] as char, error_idx ))
call_expression
[ { "content": "pub fn escape_str(text: &str, out: &mut String) {\n\n out.reserve(text.len());\n\n let mut literal_text_start = 0;\n\n\n\n for (i, &b) in text.as_bytes().iter().enumerate() {\n\n let escape_type = ESCAPE_TYPE_TABLE[b as usize];\n\n if escape_type == 0 {\n\n continue;\n\n }\n\n\n\n...
Rust
gensokyo-vulkan/src/pipeline/state/depth_stencil/depth.rs
Usami-Renko/hakurei
cccc69fe71d6efd75089d1c03c9c49fefde8e2ca
use ash::vk; use crate::pipeline::state::dynamic::DynamicableValue; use crate::types::{ vkfloat, vkbool, VK_TRUE, VK_FALSE }; pub struct DepthTest { pub test_enable: vkbool, pub write_enable: vkbool, pub compare_op: vk::CompareOp, pub depth_bound: DynamicableValue<DepthBoundInf...
use ash::vk; use crate::pipeline::state::dynamic::DynamicableValue; use crate::types::{ vkfloat, vkbool, VK_TRUE, VK_FALSE }; pub struct DepthTest { pub test_enable: vkbool, pub write_enable: vkbool, pub compare_op: vk::CompareOp, pub depth_bound: DynamicableValue<DepthBoundInf...
pub fn disable() -> DepthTest { DepthTest { ..Default::default() } } pub fn set_depth_bound(&mut self, bound: DynamicableValue<DepthBoundInfo>) { self.depth_bound = bound; } pub(crate) fn is_dynamic_depthbound(&self) -> bool { self.depth_bound.is_dynamic() } } impl D...
pub fn enable(wirte_enable: bool, compare_op: vk::CompareOp, bounds_enable: bool) -> DepthTest { DepthTest { test_enable: VK_TRUE, write_enable: if wirte_enable { VK_TRUE } else { VK_FALSE }, compare_op, depth_bound: if bounds_enable { DynamicableV...
function_block-full_function
[]
Rust
modules/src/ics04_channel/handler/timeout_on_close.rs
mkaczanowski/ibc-rs
75d4dd81262cab979b1bf286b0b462297825ab65
use crate::events::IbcEvent; use crate::handler::{HandlerOutput, HandlerResult}; use crate::ics04_channel::channel::State; use crate::ics04_channel::channel::{ChannelEnd, Counterparty, Order}; use crate::ics04_channel::events::TimeoutOnClosePacket; use crate::ics04_channel::handler::verify::verify_channel_proofs; use c...
use crate::events::IbcEvent; use crate::handler::{HandlerOutput, HandlerResult}; use crate::ics04_channel::channel::State; use crate::ics04_channel::channel::{ChannelEnd, Counterparty, Order}; use crate::ics04_channel::events::TimeoutOnClosePacket; use crate::ics04_channel::handler::verify::verify_channel_proofs; use c...
#[cfg(test)] mod tests { use crate::events::IbcEvent; use crate::ics02_client::height::Height; use crate::ics03_connection::connection::ConnectionEnd; use crate::ics03_connection::connection::Counterparty as ConnectionCounterparty; use crate::ics03_connection::connection::State as ConnectionState...
pub fn process( ctx: &dyn ChannelReader, msg: MsgTimeoutOnClose, ) -> HandlerResult<PacketResult, Error> { let mut output = HandlerOutput::builder(); let packet = &msg.packet; let source_channel_end = ctx .channel_end(&(packet.source_port.clone(), packet.source_channel.clone())) .o...
function_block-full_function
[ { "content": "// TODO: Memoize this result\n\nfn get_counterparty_chain(\n\n src_chain: &dyn ChainHandle,\n\n src_channel_id: &ChannelId,\n\n src_port_id: &PortId,\n\n) -> Result<ChainId, BoxError> {\n\n info!(\n\n chain_id = %src_chain.id(),\n\n src_channel_id = %src_channel_id,\n\n ...
Rust
src/factory/mod.rs
mskorkowski/relm4
c1deccc1e6e46ab790d99108b2481ea5afdf4146
use gtk::glib::Sender; use gtk::prelude::WidgetExt; pub mod collections; pub mod positions; mod widgets; pub use collections::*; pub trait FactoryPrototype: Sized { type Factory: Factory<Self, Self::View>; type Widgets: std::fmt::Debug; type Root: WidgetExt; type Vi...
use gtk::glib::Sender; use gtk::prelude::WidgetExt; pub mod collections; pub mod positions; mod widgets; pub use collections::*; pub trait FactoryPrototype: Sized { type Factory: Factory<Self, Self::View>; type Widgets: std::fmt::Debug; type Root: WidgetExt; type Vi...
get: &Widget) -> Self::Root; }
s. trait SimpleFactoryView<Widget: std::fmt::Debug> { /// Position type used by this widget. /// /// For example [`GridPosition`] for [`gtk::Grid`] or `()` for [`gtk::Box`] type Position; /// Adds a new widget to self at the end. fn add(&self, widget: &Widget, position: &Self::Position); /...
random
[ { "content": "/// Define behavior to turn the data of you model into widgets.\n\n///\n\n/// This trait and the associated struct can also be implemented by the `relm4-macros::widget` macro.\n\n///\n\n/// This trait has two generic types, its own model and the model of the parent (which can be `()`).\n\n/// This...
Rust
src/dhcp/clientv4.rs
loriopatrick/smoltcp
1bff999a6f3f7adf623d837ea96cc807e1b3a470
use crate::{Result, Error}; use crate::wire::{IpVersion, IpProtocol, IpEndpoint, IpAddress, Ipv4Cidr, Ipv4Address, Ipv4Packet, Ipv4Repr, UdpPacket, UdpRepr, DhcpPacket, DhcpRepr, DhcpMessageType}; use crate::wire::dhcpv4::field as dhcpv4_field; use crate::socket::{SocketSet, SocketHandl...
use crate::{Result, Error}; use crate::wire::{IpVersion, IpProtocol, IpEndpoint, IpAddress, Ipv4Cidr, Ipv4Address, Ipv4Packet, Ipv4Repr, UdpPacket, UdpRepr, DhcpPacket, DhcpRepr, DhcpMessageType}; use crate::wire::dhcpv4::field as dhcpv4_field; use crate::socket::{SocketSet, SocketHandl...
}; if config.is_some() { Ok(config) } else { if raw_socket.can_send() && now >= self.next_egress { self.egress(iface, &mut *raw_socket, &checksum_caps, now) } else { Ok(None) ...
match raw_socket.recv() .and_then(|packet| parse_udp(packet, &checksum_caps)) { Ok((IpEndpoint { addr: IpAddress::Ipv4(src_ip), port: UDP_SERVER_PORT, }, IpEndpoint { addr: _, ...
if_condition
[ { "content": "// We use our own RNG to stay compatible with #![no_std].\n\n// The use of the RNG below has a slight bias, but it doesn't matter.\n\nfn xorshift32(state: &mut u32) -> u32 {\n\n let mut x = *state;\n\n x ^= x << 13;\n\n x ^= x >> 17;\n\n x ^= x << 5;\n\n *state = x;\n\n x\n\n}\n\...