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/cli/utils.rs
lmapii/run_clang_format
153a3fd24813ce4ea8846bf38f1263dcb4f044db
use std::{fs, path}; use color_eyre::{eyre::eyre, eyre::WrapErr}; pub fn path_or_err<P>(path: P) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_as_buf = path::PathBuf::from(path.as_ref()); if !path_as_buf.exists() { return Err(eyre!("Path not found or permission denied")) ...
use std::{fs, path}; use color_eyre::{eyre::eyre, eyre::WrapErr}; pub fn path_or_err<P>(path: P) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_as_buf = path::PathBuf::from(path.as_ref()); if !path_as_buf.exists() { return Err(eyre!("Path not found or permission denied")) ...
rcase()); } }
fn test_path() { let path = path::Path::new("some/path/to/.clang-format"); let file_name = path.file_name().and_then(std::ffi::OsStr::to_str).unwrap(); assert_eq!(".clang-format", file_name.to_lowe
function_block-random_span
[ { "content": "fn crate_root_rel(path: &str) -> path::PathBuf {\n\n crate_root().join(path)\n\n}\n\n\n", "file_path": "tests/invoke.rs", "rank": 5, "score": 193585.52881078637 }, { "content": "pub fn match_paths<P>(\n\n candidates: Vec<globmatch::Matcher<P>>,\n\n filter: Option<Vec<g...
Rust
base_layer/core/src/covenants/output_set.rs
AaronFeickert/tari
5e55bf22110ac40ffc0dea88d88ba836982591eb
use std::{ cmp::Ordering, collections::BTreeSet, iter::FromIterator, ops::{Deref, DerefMut}, }; use crate::{covenants::error::CovenantError, transactions::transaction_components::TransactionOutput}; #[derive(Debug, Clone)] pub struct OutputSet<'a>(BTreeSet<Indexed<&'a TransactionOutput>>); impl<'a>...
use std::{ cmp::Ordering, collections::BTreeSet, iter::FromIterator, ops::{Deref, DerefMut}, }; use crate::{covenants::error::CovenantError, transactions::transaction_components::TransactionOutput}; #[derive(Debug, Clone)] pub struct OutputSet<'a>(BTreeSet<Indexed<&'a TransactionOutput>>); impl<'a>...
pub fn clear(&mut self) { self.0.clear(); } #[cfg(test)] pub(super) fn get(&self, index: usize) -> Option<&TransactionOutput> { self.0 .iter() .find(|output| output.index == index) .map(|output| **output) } #[cfg(test)] pub(super) fn ge...
pub fn find_inplace<F>(&mut self, mut pred: F) where F: FnMut(&TransactionOutput) -> bool { match self.0.iter().find(|indexed| pred(&**indexed)) { Some(output) => { let output = *output; self.clear(); self.0.insert(output); }, ...
function_block-full_function
[ { "content": "/// Is this position a leaf in the MMR?\n\n/// We know the positions of all leaves based on the postorder height of an MMR of any size (somewhat unintuitively\n\n/// but this is how the PMMR is \"append only\").\n\npub fn is_leaf(pos: usize) -> bool {\n\n bintree_height(pos) == 0\n\n}\n\n\n", ...
Rust
polars/polars-lazy/src/physical_plan/expressions/aggregation.rs
qiemem/polars
48ea1ed035a44d188d17f2d01ee07f671df27360
use crate::physical_plan::state::ExecutionState; use crate::physical_plan::PhysicalAggregation; use crate::prelude::*; use polars_arrow::export::arrow::{array::*, compute::concatenate::concatenate}; use polars_arrow::prelude::QuantileInterpolOptions; use polars_core::frame::groupby::{fmt_groupby_column, GroupByMethod, ...
use crate::physical_plan::state::ExecutionState; use crate::physical_plan::PhysicalAggregation; use crate::prelude::*; use polars_arrow::export::arrow::{array::*, compute::concatenate::concatenate}; use polars_arrow::prelude::QuantileInterpolOptions; use polars_core::frame::groupby::{fmt_groupby_column, GroupByMethod, ...
GroupByMethod::Mean => { let series = self.expr.evaluate(final_df, state)?; let count_name = format!("{}__POLARS_MEAN_COUNT", series.name()); let new_name = fmt_groupby_column(series.name(), self.agg_type); let count = final_df.column(&count_nam...
into_series() }); Ok(opt_agg) } GroupByMethod::List => { let agg = ac.aggregated(); Ok(rename_option_series(Some(agg), &new_name)) } GroupByMethod::Groups => { let mut column: ListChunked = ac...
random
[ { "content": "/// Create a Column Expression based on a column name.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `name` - A string slice that holds the name of the column\n\n///\n\n/// # Examples\n\n///\n\n/// ```ignore\n\n/// // select a column name\n\n/// col(\"foo\")\n\n/// ```\n\n///\n\n/// ```ignore\n\n/// /...
Rust
daemon/state_helper.rs
slooppe/pueue
ee71ad7c6eb05788af063fd98a649b02c006cbb1
use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; use std::sync::MutexGuard; use std::time::SystemTime; use anyhow::{Context, Result}; use chrono::prelude::*; use log::{debug, info}; use pueue_lib::state::{GroupStatus, State}; use pueue_lib::task::{TaskResult, TaskStatus}; pub type LockedS...
use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; use std::sync::MutexGuard; use std::time::SystemTime; use anyhow::{Context, Result}; use chrono::prelude::*; use log::{debug, info}; use pueue_lib::state::{GroupStatus, State}; use pueue_lib::task::{TaskResult, TaskStatus}; pub type LockedS...
pub fn restore_state(pueue_directory: &Path) -> Result<Option<State>> { let path = pueue_directory.join("state.json"); if !path.exists() { info!( "Couldn't find state from previous session at location: {:?}", path ); return Ok(None); } info!("Start...
fn save_state_to_file(state: &State, log: bool) -> Result<()> { let serialized = serde_json::to_string(&state).context("Failed to serialize state:"); let serialized = serialized.unwrap(); let path = state.settings.shared.pueue_directory(); let (temp, real) = if log { let path = path.join("log")...
function_block-full_function
[ { "content": "/// Print a local log file.\n\n/// This is usually either the stdout or the stderr\n\nfn print_local_file(stdout: &mut Stdout, file: &mut File, lines: &Option<usize>, text: String) {\n\n if let Ok(metadata) = file.metadata() {\n\n if metadata.len() != 0 {\n\n // Don't print a ...
Rust
macros/src/parser/mod.rs
ryan-summers/smlang-rs
9f4567b6fb05bd867363bb46385f4c33704fe304
pub mod data; pub mod event; pub mod input_state; pub mod output_state; pub mod state_machine; pub mod transition; use data::DataDefinitions; use event::EventMapping; use state_machine::StateMachine; use input_state::InputState; use proc_macro2::Span; use std::collections::HashMap; use syn::{parse, Ident, Type}; use...
pub mod data; pub mod event; pub mod input_state; pub mod output_state; pub mod state_machine; pub mod transition; use data::DataDefinitions; use event::EventMapping; use state_machine::StateMachine; use input_state::InputState; use proc_macro2::Span; use std::collections::HashMap; use syn::{parse, Ident, Type}; use...
in_state, event: transition.event.clone(), guard: transition.guard.clone(), action: transition.action.clone(), out_state: transition.out_state.clone(), }; ...
ansition, transition_map: &mut TransitionMap, state_data: &DataDefinitions, ) -> Result<(), parse::Error> { let p = transition_map .get_mut(&transition.in_state.ident.to_string()) .unwrap(); if !p.contains_key(&transition.event.ident.to_string()) { let mapping = EventMapping { ...
random
[ { "content": "// helper function for extracting a vector of lifetimes from a Type\n\nfn get_lifetimes(data_type: &Type) -> Result<Lifetimes, parse::Error> {\n\n let mut lifetimes = Lifetimes::new();\n\n match data_type {\n\n Type::Reference(tr) => {\n\n if let Some(lifetime) = &tr.lifeti...
Rust
futures-util/src/future/try_join.rs
zhanghanyun/futures-rs
f1f28da9bdf4bd5ac1182d6adf9ad71d29bfe728
#![allow(non_snake_case)] use crate::future::{TryMaybeDone, try_maybe_done}; use core::fmt; use core::pin::Pin; use futures_core::future::{Future, TryFuture}; use futures_core::task::{Context, Poll}; use pin_project::pin_project; macro_rules! generate { ($( $(#[$doc:meta])* ($Join:ident, <Fut1, $(...
#![allow(non_snake_case)] use crate::future::{TryMaybeDone, try_maybe_done}; use core::fmt; use core::pin::Pin; use futures_core::future::{Future, TryFuture}; use futures_core::task::{Context, Poll}; use pin_project::pin_project; macro_rules! generate { ($( $(#[$doc:meta])* ($Join:ident, <Fut1, $(...
1, Fut2, Fut3, Fut4, Fut5> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, Fut3: TryFuture<Error = Fut1::Error>, Fut4: TryFuture<Error = Fut1::Error>, Fut5: TryFuture<Error = Fut1::Error>, { TryJoin5::new(future1, future2, future3, future4, future5) }
>, Fut3: TryFuture<Error = Fut1::Error>, { TryJoin3::new(future1, future2, future3) } pub fn try_join4<Fut1, Fut2, Fut3, Fut4>( future1: Fut1, future2: Fut2, future3: Fut3, future4: Fut4, ) -> TryJoin4<Fut1, Fut2, Fut3, Fut4> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, ...
random
[ { "content": "/// Same as [`join`](join()), but with more futures.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # futures::executor::block_on(async {\n\n/// use futures::future;\n\n///\n\n/// let a = async { 1 };\n\n/// let b = async { 2 };\n\n/// let c = async { 3 };\n\n/// let d = async { 4 };\n\n/// let...
Rust
src/revaultd/config.rs
KRD1/revault-gui
5eb9b2fee0c78d63cc5f4b7bb93d1f99c4bb8fb0
use bitcoin::{util::bip32, Network}; use serde::Deserialize; use std::{ net::SocketAddr, path::{Path, PathBuf}, }; #[derive(Debug, Clone, Deserialize)] pub struct BitcoindConfig { pub network: Network, pub cookie_path: PathBuf, pub addr: SocketAddr, pub poll_interval_secs: O...
use bitcoin::{util::bip32, Network}; use serde::Deserialize; use std::{ net::SocketAddr, path::{Path, PathBuf}, }; #[derive(Debug, Clone, Deserialize)] pub struct BitcoindConfig { pub network: Network, pub cookie_path: PathBuf, pub addr: SocketAddr, pub poll_interval_secs: O...
figuration file: {}", e)) }) })?; Ok(config) } pub fn socket_path(&self) -> Result<PathBuf, ConfigError> { let mut path = if let Some(ref datadir) = self.data_dir { datadir.clone() } else { default_datadir().map_err(|_| { ...
ig>, pub emergency_address: String, } #[derive(Debug, Clone, Deserialize)] pub struct CosignerConfig { pub host: String, pub noise_key: String, } #[derive(Debug, Clone, Deserialize)] pub struct ManagerConfig { pub xpub: bip32::ExtendedPubKey, pub cosigners: Vec<CosignerConfig>, } #[derive(Debug, ...
random
[ { "content": "pub fn clipboard<'a, T: 'a + Clone>(\n\n state: &'a mut button::State,\n\n message: T,\n\n) -> button::Button<'a, T> {\n\n button::Button::new(state, clipboard_icon().size(15))\n\n .on_press(message)\n\n .style(ClipboardButtonStyle {})\n\n}\n\n\n", "file_path": "src/ui/c...
Rust
src/components/boid.rs
Luke-Draper/Boids
5ddfe3ecc3e34721ed3c6df7dc92cff41fd1e015
use super::player_control::PlayerControl; use super::velocity::Velocity; use amethyst::{ assets::AssetLoaderSystemData, core::{math::Vector3, transform::Transform}, ecs::{prelude::EntityBuilder, Component, VecStorage, World}, prelude::*, renderer::{ rendy::mesh::{Normal, Position, Tangent, T...
use super::player_control::PlayerControl; use super::velocity::Velocity; use amethyst::{ assets::AssetLoaderSystemData, core::{math:
f64, pub step_time: f64, pub hunger: f32, pub flock_id: u8, } impl Component for Boid { type Storage = VecStorage<Self>; } pub fn initialize_boid_default(world: &mut World) { initialize_boid( world, Vector3::new(0.0, 0.0, 0.0), Velocity { velocity: 0.0, ...
:Vector3, transform::Transform}, ecs::{prelude::EntityBuilder, Component, VecStorage, World}, prelude::*, renderer::{ rendy::mesh::{Normal, Position, Tangent, TexCoord}, shape::Shape, Material, MaterialDefaults, Mesh, }, }; use serde::{Deserialize, Serialize}; pub enum WingFlapS...
random
[]
Rust
crates/nu-parser/src/lite_parse.rs
Amanita-muscaria/nushell
416ba1407b8553f5da4a6f8ad59c64b85fda3fb4
use std::iter::Peekable; use std::str::CharIndices; use nu_source::{Span, Spanned, SpannedItem}; use crate::errors::{ParseError, ParseResult}; type Input<'t> = Peekable<CharIndices<'t>>; #[derive(Debug, Clone)] pub struct LiteCommand { pub name: Spanned<String>, pub args: Vec<Spanned<String>>, } impl LiteC...
use std::iter::Peekable; use std::str::CharIndices; use nu_source::{Span, Spanned, SpannedItem}; use crate::errors::{ParseError, ParseResult}; type Input<'t> = Peekable<CharIndices<'t>>; #[derive(Debug, Clone)] pub struct LiteCommand { pub name: Spanned<String>, pub args: Vec<Spanned<String>>, } impl LiteC...
, span, ), partial: Some(bare.spanned(span)), }); } if let Some(delimiter) = inside_quote { bare.push(delimiter); let span = Span::new( start_offset + span_offset, start_offset + span_offset + ba...
match block { BlockKind::Paren => ")", BlockKind::SquareBracket => "]", BlockKind::CurlyBracket => "}", }
if_condition
[ { "content": "pub fn span_for_spanned_list(mut iter: impl Iterator<Item = Span>) -> Span {\n\n let first = iter.next();\n\n\n\n let first = match first {\n\n None => return Span::unknown(),\n\n Some(first) => first,\n\n };\n\n\n\n let last = iter.last();\n\n\n\n match last {\n\n ...
Rust
crates/revm/src/evm.rs
mattsse/revm
247d4d0e19b15feb0cf400e8d5dd93921b41a9d7
use crate::{ db::{Database, DatabaseCommit, DatabaseRef, RefDBWrapper}, error::ExitReason, evm_impl::{EVMImpl, Transact}, subroutine::State, BerlinSpec, ByzantineSpec, Env, Inspector, IstanbulSpec, LatestSpec, LondonSpec, NoOpInspector, Spec, SpecId, TransactOut, }; use alloc::boxed::Box; use re...
use crate::{ db::{Database, DatabaseCommit, DatabaseRef, RefDBWrapper}, error::ExitReason, evm_impl::{EVMImpl, Transact}, subroutine::State, BerlinSpec, ByzantineSpec, Env, Inspector, IstanbulSpec, LatestSpec, LondonSpec, NoOpInspector, Spec, SpecId, TransactOut, }; use alloc::boxed::Box; use re...
} impl<DB: Database> EVM<DB> { pub fn transact(&mut self) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_mut() { let mut noop = NoOpInspector {}; let out = evm_inner::<DB, false>(&self.env, db, &mut noop).transact(); out } else { ...
ExitReason, TransactOut, u64) { let (exit, out, gas, state) = self.inspect(inspector); self.db.as_mut().unwrap().commit(state); (exit, out, gas) }
function_block-function_prefix_line
[ { "content": "#[inline(always)]\n\nfn gas_call_l64_after<SPEC: Spec>(machine: &mut Machine) -> Result<u64, ExitReason> {\n\n if SPEC::enabled(TANGERINE) {\n\n //EIP-150: Gas cost changes for IO-heavy operations\n\n let gas = machine.gas().remaining();\n\n Ok(gas - gas / 64)\n\n } else...
Rust
src/lib.rs
DerickEddington/cycle_deep_safe_compare
3c3d4f5615c9d434f4037e373a7390ae34656464
#![cfg_attr(unix, doc = include_str!("../README.md"))] #![cfg_attr(windows, doc = include_str!("..\\README.md"))] #![cfg_attr( not(feature = "std"), doc = "\n", doc = "Note: This crate was built without its `std` feature and some premade items are \ unavailable, and so custom types must be provid...
#![cfg_attr(unix, doc = include_str!("../README.md"))] #![cfg_attr(windows, doc = include_str!("..\\README.md"))] #![cfg_attr( not(feature = "std"), doc = "\n", doc = "Note: This crate was built without its `std` feature and some premade items are \ unavailable, and so custom types must be provid...
self } #[inline] fn from_ord(ord: Ordering) -> Self { ord.is_eq() } } impl Cmp for Ordering { #[inline] fn new_equiv() -> Self { Ordering::Equal } #[inline] fn is_equiv(&self) -> bool { self.is_eq() } #[inline] fn from_ord(ord: Orde...
macro_use_extern_crate, meta_variable_misuse, missing_docs, noop_method_call, pointer_structural_match, single_use_lifetimes, trivial_casts, trivial_numeric_casts, unreachable_pub, unused_extern_crates, unused_import_braces, unused_lifetimes, unused_qualif...
random
[ { "content": "struct Args<N>(PhantomData<N>);\n\n\n\nimpl<N: Node> interleave::Params for Args<N>\n\n{\n\n type Node = N;\n\n type RNG = default::RandomNumberGenerator;\n\n type Table = hash_map::Table<Self>;\n\n}\n\n\n\nimpl<N: Node> hash_map::Params for Args<N>\n\n{\n\n type Node = N;\n\n}\n\n\n\n...
Rust
src/proto/par_vec.rs
gereeter/collect-rs
dc4380faac395ef412937dba58249e72873414e9
extern crate alloc; use self::alloc::arc; use std::cmp::min; use std::fmt::{Formatter, Show}; use std::fmt::Error as FmtError; use std::iter::range_inclusive; use std::sync::Arc; use std::mem; use std::ops; pub struct ParVec<T> { data: Arc<Vec<T>>, } impl<T: Send + Sync> ParVec<T> { pub fn new(vec...
extern crate alloc; use self::alloc::arc; use std::cmp::min; use std::fmt::{Formatter, Show}; use std::fmt::Error as FmtError; use std::iter::range_inclusive; use std::sync::Arc; use std::mem; use std::ops; pub struct ParVec<T> { data: Arc<Vec<T>>, } impl<T: Send + Sync> ParVec<T> { pub fn new(vec...
} pub fn into_inner(mut self) -> Vec<T> { loop { match self.into_inner_opt() { Ok(vec) => return vec, Err(new_self) => self = new_self, } } } } fn sub_slices<T>(parent: &[T], slice_count: uint) -> Vec<&[T]> { let mut slices ...
if arc::strong_count(&self.data) == 1 { let vec_ptr: &mut Vec<T> = unsafe { mem::transmute(&*self.data) }; Ok(mem::replace(vec_ptr, Vec::new())) } else { Err(self) }
if_condition
[ { "content": "pub fn insert_seq_n<M, I, R>(n: uint,\n\n map: &mut M,\n\n b: &mut Bencher,\n\n mut insert: I,\n\n mut remove: R) where\n\n I: FnMut(&mut M, uint),\n\n R: FnMut(&mut M, uint),\n\n{...
Rust
postgres/src/transaction.rs
dvic/rust-postgres
5d08af01ec520cba1a8642cb7c66ce070b03f4ca
use crate::{ CancelToken, CopyInWriter, CopyOutReader, GenericClient, Portal, RowIter, Rt, Statement, ToStatement, }; use tokio::runtime::Runtime; use tokio_postgres::types::{ToSql, Type}; use tokio_postgres::{Error, Row, SimpleQueryMessage}; pub struct Transaction<'a> { runtime: &'a mut Runtime, trans...
use crate::{ CancelToken, CopyInWriter, CopyOutReader, GenericClient, Portal, RowIter, Rt, Statement, ToStatement, }; use tokio::runtime::Runtime; use tokio_postgres::types::{ToSql, Type}; use tokio_postgres::{Error, Row, SimpleQueryMessage}; pub struct Transaction<'a> { runtime: &'a mut Runtime, trans...
s) } fn query<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Vec<Row>, Error> where T: ?Sized + ToStatement, { self.query(query, params) } fn prepare(&mut self, query: &str) -> Result<Statement, Error> { self.prepare(query) } fn transaction(...
n.transaction())?; Ok(Transaction { runtime: self.runtime, transaction, }) } } impl<'a> GenericClient for Transaction<'a> { fn execute<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<u64, Error> where T: ?Sized + ToStatement, { ...
random
[ { "content": "pub fn read_be_i32(buf: &mut &[u8]) -> Result<i32, Box<dyn Error + Sync + Send>> {\n\n if buf.len() < 4 {\n\n return Err(\"invalid buffer size\".into());\n\n }\n\n let mut bytes = [0; 4];\n\n bytes.copy_from_slice(&buf[..4]);\n\n *buf = &buf[4..];\n\n Ok(i32::from_be_bytes...
Rust
termwiz/src/widgets/mod.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
#![allow(clippy::new_without_default)] use crate::color::ColorAttribute; use crate::input::InputEvent; use crate::surface::{Change, CursorShape, Position, SequenceNo, Surface}; use anyhow::Error; use fnv::FnvHasher; use std::collections::{HashMap, VecDeque}; use std::hash::BuildHasherDefault; type FnvHashMap<K, V> =...
#![allow(clippy::new_without_default)] use crate::color::ColorAttribute; use crate::input::InputEvent; use crate::surface::{Change, CursorShape, Position, SequenceNo, Surface}; use anyhow::Error; use fnv::FnvHasher; use std::collections::{HashMap, VecDeque}; use std::hash::BuildHasherDefault; type FnvHashMap<K, V> =...
fn hovered_recursive( &self, widget: WidgetId, depth: usize, x: usize, y: usize, best: &mut (usize, WidgetId), ) { let render = &self.render[&widget]; if depth >= best.0 && x >= render.coordinates.x && y >= rende...
let root = match self.graph.root { Some(id) => id, _ => return None, }; let depth = 0; let mut best = (depth, root); self.hovered_recursive(root, depth, coords.x, coords.y, &mut best); Some(best.1) }
function_block-function_prefix_line
[]
Rust
arci-ros/src/ros_localization_client.rs
OpenRR/OpenRR
bfafe3707164cf8ca1143b5daa039f60b1831fdb
use std::borrow::Borrow; use arci::*; use nalgebra as na; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{msg, rosrust_utils::*}; rosrust::rosmsg_include! { std_srvs / Empty } const AMCL_POSE_TOPIC: &str = "/amcl_pose"; const NO_MOTION_UPDATE_SERVICE: &str = "request_nomotion_update";...
use std::borrow::Borrow; use arci::*; use nalgebra as na; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{msg, rosrust_utils::*}; rosrust::rosmsg_include! { std_srvs / Empty } const AMCL_POSE_TOPIC: &str = "/amcl_pose"; const NO_MOTION_UPDATE_SERVICE: &str = "request_nomotion_update";...
} fn default_nomotion_update_service_name() -> String { NO_MOTION_UPDATE_SERVICE.to_string() } fn default_amcl_pose_topic_name() -> String { AMCL_POSE_TOPIC.to_string() }
fn current_pose(&self, _frame_id: &str) -> Result<na::Isometry2<f64>, Error> { self.pose_subscriber.wait_message(100); let pose_with_cov_stamped = self.pose_subscriber .get()? .ok_or_else(|| Error::Connection { message: format!("Failed to g...
function_block-function_prefix_line
[ { "content": "/// Replaces the contents of the specified TOML document based on the specified scripts,\n\n/// returning edited document as string.\n\n///\n\n/// See [`overwrite`] for more.\n\npub fn overwrite_str(doc: &str, scripts: &str) -> Result<String> {\n\n let mut doc: toml::Value = toml::from_str(doc)...
Rust
src/build/windows.rs
kungfoo/boon
788d1265e9e6edd822cf651e5b3be8f2d12483c8
#![allow(clippy::too_many_lines)] use crate::build::{Iterator, collect_zip_directory, get_love_file_name, get_love_version_path, get_output_filename, get_zip_output_filename}; use crate::types::{Bitness, BuildSettings, BuildStatistics, LoveVersion, Platform, Project}; use glob::glob; use remove_dir_all::remove_dir_all;...
#![allow(clippy::too_many_lines)] use crate::build::{Iterator, collect_zip_directory, get_love_file_name, get_love_version_path, get_output_filename, get_zip_output_filename}; use crate::types::{Bitness, BuildSettings, BuildStatistics, LoveVersion, Platform, Project}; use glob::glob; use remove_dir_all::remove_dir_all;...
} let zip_output_file_name = get_zip_output_filename(project, Platform::Windows, bitness); let output_path = project .get_release_path(build_settings) .join(zip_output_file_name); let src_dir = output_path.clone(); let src_dir = src_dir.to_str().context("Could not do string c...
if path.is_file() { let mut file = File::open(path)?; file.read_to_end(&mut buffer)?; output_file.write_all(&buffer)?; buffer.clear(); }
if_condition
[ { "content": "pub fn download_love(version: LoveVersion, platform: Platform, bitness: Bitness) -> Result<()> {\n\n let file_info = get_love_download_location(version, platform, bitness).with_context(|| {\n\n format!(\n\n \"Could not get download location for LÖVE {} on {} {}\",\n\n ...
Rust
compiler/rustc_middle/src/ty/consts/int.rs
cchiw/rust
469ee7cc68aa4d64d6c3bcff4e4108d0c8b97240
use rustc_apfloat::ieee::{Double, Single}; use rustc_apfloat::Float; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_target::abi::Size; use std::convert::{TryFrom, TryInto}; use std::fmt; use crate::ty::TyCtxt; #[derive(Copy, Clone)] pub struct ConstInt { int: ScalarInt, si...
use rustc_apfloat::ieee::{Double, Single}; use rustc_apfloat::Float; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_target::abi::Size; use std::convert::{TryFrom, TryInto}; use std::fmt; use crate::ty::TyCtxt; #[derive(Copy, Clone)] pub struct ConstInt { int: ScalarInt, si...
#[inline] pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> { let i = i.into(); let truncated = size.truncate(i as u128); if size.sign_extend(truncated) as i128 == i { Some(Self { data: truncated, size: size.bytes() as u8 }) } else { ...
pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> { let data = i.into(); if size.truncate(data) == data { Some(Self { data, size: size.bytes() as u8 }) } else { None } }
function_block-full_function
[]
Rust
libsplinter/src/collections/mod.rs
davececchi/splinter
92bc0fdec6e66aa53bc37db13b5521343235b016
use std::collections::hash_map::{Iter, Keys, Values}; use std::collections::HashMap; use std::hash::Hash; #[derive(Clone, Debug, PartialEq, Default)] pub struct BiHashMap<K: Hash + Eq, V: Hash + Eq> { kv_hash_map: HashMap<K, V>, vk_hash_map: HashMap<V, K>, } impl<K: Hash + Eq, V: Hash + Eq> BiHashMap<K, V> ...
use std::collections::hash_map::{Iter, Keys, Values}; use std::collections::HashMap; use std::hash::Hash; #[derive(Clone, Debug, PartialEq, Default)] pub struct BiHashMap<K: Hash + Eq, V: Hash + Eq> { kv_hash_map: HashMap<K, V>, vk_hash_map: HashMap<V, K>, } impl<K: Hash + Eq, V: Hash + Eq> BiHashMap<K, V> ...
#[test] fn test_contains_key_and_value() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); assert!(map.contains_key(&"ONE".to_string())); assert!(map.contains_value(&1)); assert!(!map.contains_key(&"TWO".to_string())); ...
let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); assert_eq!(map.get_by_key(&"ONE".to_string()), Some(&1)); assert_eq!(map.get_by_key(&"TWO".to_string()), Some(&2)); ...
function_block-function_prefix_line
[ { "content": "/// The HandlerWrapper provides a typeless wrapper for typed Handler instances.\n\nstruct HandlerWrapper<MT: Hash + Eq + Debug + Clone> {\n\n inner: InnerHandler<MT>,\n\n}\n\n\n\nimpl<MT: Hash + Eq + Debug + Clone> HandlerWrapper<MT> {\n\n fn handle(\n\n &self,\n\n message_byte...
Rust
src/wasm/terrain_generator/src/rivers.rs
Havegum/Terrain-Generator
8e562f173f0474d1bf7d53ca04ede75768fa96cd
use super::erosion::get_flux; type River = Vec<(usize, f64)>; pub fn get_river( heights: &Vec<f64>, adjacent: &Vec<Vec<usize>>, flux: &Vec<f64>, sea_level: f64, voronoi_cells: &Vec<Vec<usize>>, cell_heights: &Vec<f64>, mut visited: &mut [bool], i: usize, mut river: Vec<(usize, f64)...
use super::erosion::get_flux; type River = Vec<(usize, f64)>; pub fn get_river( heights: &Vec<f64>, adjacent: &Vec<Vec<usize>>, flux: &Vec<f64>, sea_level: f64, voronoi_cells: &Vec<Vec<usize>>, cell_heights: &Vec<f64>, mut visited: &mut [bool], i: usize, mut river: Vec<(usize, f64)...
pub fn get_rivers( heights: &Vec<f64>, adjacent: &Vec<Vec<usize>>, sea_level: f64, voronoi_cells: &Vec<Vec<usize>>, cell_heights: &Vec<f64>, ) -> Vec<River> { let flux = get_flux(heights, adjacent); let mut points_by_height = (0..heights.len()).collect::<Vec<usize>>(); points_by_heigh...
r neighbor in neighbors { if visited[neighbor] { continue; } if adjacent[neighbor].iter().any(|n| heights[*n] < height) { continue; } if !main_branch_found { main_branch_found = true; let (new_river, mut new_tributaries) ...
function_block-function_prefixed
[ { "content": "pub fn smooth(mut heights: Vec<f64>, adjacent: &Vec<Vec<usize>>) -> Vec<f64> {\n\n let alpha = 1.;\n\n let alpha = 0.66;\n\n\n\n for (i, height) in heights\n\n .clone()\n\n .into_iter()\n\n .enumerate()\n\n .collect::<Vec<(usize, f64)>>()\n\n {\n\n le...
Rust
src/conferencing.rs
ktaekwon000/fluminurs
edcbbba13f8f5bf23d713333518b6ee25be5294a
use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::SystemTime; use async_trait::async_trait; use futures_util::future; use reqwest::header::REFERER; use reqwest::{Method, Url}; use scraper::{Html, Selector}; use serde::Deserialize; use crate::resource; use crate::resource::{OverwriteMode, O...
use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::SystemTime; use async_trait::async_trait; use futures_util::future; use reqwest::header::REFERER; use reqwest::{Method, Url}; use scraper::{Html, Selector}; use serde::Deserialize; use crate::resource; use crate::resource::{OverwriteMode, O...
} async fn load_cloud_record( api: &Api, conference: Conference, path: &Path, ) -> Result<Vec<ZoomRecording>> { let request_path = format!("zoom/Meeting/{}/cloudrecord", conference.id); let mut num_404_tries = 0; let cloud_record = loop { let cloud_record = api...
t .into_iter() .collect::<Result<Vec<_>>>() .map(|v| v.into_iter().flatten().collect::<Vec<_>>()), None => Err("Invalid API response from server: type mismatch"), } }
function_block-function_prefixed
[ { "content": "pub fn sanitise_filename(name: &str) -> String {\n\n if cfg!(windows) {\n\n sanitize_filename::sanitize_with_options(\n\n name.trim(),\n\n sanitize_filename::Options {\n\n windows: true,\n\n truncate: true,\n\n replacemen...
Rust
src/io_source.rs
YtFlow/mio-noafd
27bbb8dcb72a253ad86031ddc5f4ab2a1f2cda27
use std::ops::{Deref, DerefMut}; #[cfg(unix)] use std::os::unix::io::AsRawFd; #[cfg(windows)] use std::os::windows::io::AsRawSocket; #[cfg(debug_assertions)] use std::sync::atomic::{AtomicUsize, Ordering}; use std::{fmt, io}; #[cfg(any(unix, debug_assertions))] use crate::poll; use crate::sys::IoSourceState; use crate...
use std::ops::{Deref, DerefMut}; #[cfg(unix)] use std::os::unix::io::AsRawFd; #[cfg(windows)] use std::os::windows::io::AsRawSocket; #[cfg(debug_assertions)] use std::sync::atomic::{AtomicUsize, Ordering}; use std::{fmt, io}; #[cfg(any(unix, debug_assertions))] use crate::poll; use crate::sys::IoSourceState; use crate...
fn deregister(&mut self, _registry: &Registry) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.remove_association(_registry)?; self.state.deregister() } } impl<T> fmt::Debug for IoSource<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::...
fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.check_association(registry)?; self.state.reregister(registry, token, interests) }
function_block-full_function
[ { "content": "fn main() -> io::Result<()> {\n\n env_logger::init();\n\n\n\n // Create a poll instance.\n\n let mut poll = Poll::new()?;\n\n // Create storage for events.\n\n let mut events = Events::with_capacity(128);\n\n\n\n // Setup the TCP server socket.\n\n let addr = \"127.0.0.1:9000\...
Rust
src/gui/element/my_weakauras.rs
kawarimidoll/ajour
753e0ed24c83d183476a14ca918646a38dff23a3
use { super::{DEFAULT_FONT_SIZE, DEFAULT_PADDING}, crate::gui::{ style, AuraColumnKey, AuraColumnState, Interaction, Message, Mode, SortDirection, State, }, ajour_core::config::Flavor, ajour_core::theme::ColorPalette, ajour_weak_auras::Aura, ajour_widgets::TableRow, ajour_widgets...
use { super::{DEFAULT_FONT_SIZE, DEFAULT_PADDING}, crate::gui::{ style, AuraColumnKey, AuraColumnState, Interaction, Message, Mode, SortDirection, State, }, ajour_core::config::Flavor, ajour_core::theme::ColorPalette, ajour_weak_auras::Aura, ajour_widgets::TableRow, ajour_widgets...
}) .next() { let status = Text::new(aura.status().to_string()).size(DEFAULT_FONT_SIZE); let status_row = Row::new() .push(status) .spacing(3) .align_items(Align::Center); let status_container = Container::new(status_row) .hei...
if *key == AuraColumnKey::Status && !hidden { Some((idx, width)) } else { None }
if_condition
[ { "content": "fn sort_auras(auras: &mut [Aura], sort_direction: SortDirection, column_key: AuraColumnKey) {\n\n match (column_key, sort_direction) {\n\n (AuraColumnKey::Title, SortDirection::Asc) => {\n\n auras.sort_by(|a, b| a.name().to_lowercase().cmp(&b.name().to_lowercase()));\n\n ...
Rust
mm0-rs/components/mmcc/src/mir_opt/ghost.rs
RESEARCHINGETERNITYEGPHILIPPOV/mm0
a4fff5c90f5787aacef23f2b5f0c9e064379658d
use std::{collections::HashSet, mem}; #[allow(clippy::wildcard_imports)] use super::*; #[repr(u8)] #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] pub enum Reachability { Dead, Unreachable, Reachable, } impl Default for Reachability { fn default() -> Self { Self::Dead } } impl ...
use std::{collections::HashSet, mem}; #[allow(clippy::wildcard_imports)] use super::*; #[repr(u8)] #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] pub enum Reachability { Dead, Unreachable, Reachable, } impl Default for Reachability { fn default() -> Self { Self::Dead } } impl ...
.rev_iter(tgt_ctx).filter(|p| p.1).map(|p| p.0).collect() }); for (v, r, _) in args { *r = s.contains(v) } } } } pub fn do_ghost_analysis(&mut self, reachable: &BlockVec<Reachability>, returns: &[Arg], ) { let ghost = self.ghost_analysis(reachable, returns); self.appl...
::Typeof(_) => {} } } } struct GhostAnalysis<'a> { reachable: &'a BlockVec<Reachability>, returns: &'a [Arg], } struct GhostDoms { active: BlockVec<OptBlockId>, vars: BlockVec<im::HashSet<VarId>>, } impl Domains for GhostDoms { type Item = GhostDom;...
random
[ { "content": "/// Performs \"curly transformation\", turning `{x op y op z}` into `(op x y z)`.\n\n///\n\n/// A curly list is valid if\n\n/// - it is a proper list, and\n\n/// - it has at most two elements (in which case it is transformed to itself), or\n\n/// - it has an odd number of elements and the elements...
Rust
src/main.rs
magicgoose/oxipng
a857cfcc1e4379434c1848a58578e94ed231845a
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", warn(enum_glob_use))] #![cfg_attr(feature = "clippy", warn(if_not_else))] #![cfg_attr(feature = "clippy", warn(string_add))] #![cfg_attr(feature = "clippy", warn(string_add_assign))] #![war...
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", warn(enum_glob_use))] #![cfg_attr(feature = "clippy", warn(if_not_else))] #![cfg_attr(feature = "clippy", warn(string_add))] #![cfg_attr(feature = "clippy", warn(string_add_assign))] #![war...
; } if hdrs[0] == "safe" { opts.strip = Headers::Safe; } else { opts.strip = Headers::All; } } else { const FORBIDDEN_CHUNKS: [&str; 5] = ["IHDR", "IDAT", "tRNS", "PLTE", "IEND"]; for i in &hdrs { ...
Err( "'safe' or 'all' presets for --strip should be used by themselves".to_owned(), )
call_expression
[ { "content": "/// Perform optimization on the input file using the options provided\n\npub fn optimize(input_path: &Path, opts: &Options) -> Result<(), PngError> {\n\n // Initialize the thread pool with correct number of threads\n\n let thread_count = opts.threads;\n\n let _ = rayon::ThreadPoolBuilder:...
Rust
quicksilver-utils-async/src/std_web/websocket.rs
johnpmayer/quicksilver-utils
0ddd30d02d4dcf152a142ec79b29495069999d4c
use futures_util::future::poll_fn; use std::cell::RefCell; use std::collections::VecDeque; use std::sync::Arc; use std::task::{Poll, Waker}; use url::Url; use std_web::web::{ event::{ IMessageEvent, SocketCloseEvent, SocketErrorEvent, SocketMessageData, SocketMessageEvent, SocketOpenEvent, }, ...
use futures_util::future::poll_fn; use std::cell::RefCell; use std::collections::VecDeque; use std::sync::Arc; use std::task::{Poll, Waker}; use url::Url; use std_web::web::{ event::{ IMessageEvent, SocketCloseEvent, SocketErrorEvent, SocketMessageData, SocketMessageEvent, SocketOpenEvent, }, ...
.await?; Ok(async_ws) } pub async fn send(&self, msg: &str) -> Result<(), WebSocketError> { trace!("Send"); let inner: &AsyncWebSocketInner = &self.inner.borrow(); inner .ws .send_text(msg) .map_err(|_| WebSocketError::NativeError("S...
poll_fn({ let async_ws = async_ws.clone(); move |cx| { trace!("Polling"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); match &inner.state { SocketState::Init => { inner.waker.r...
call_expression
[ { "content": "struct AsyncWebSocketInner {\n\n ws: WebSocket,\n\n state: SocketState,\n\n waker: Option<Waker>,\n\n buffer: VecDeque<MessageEvent>,\n\n}\n\n\n\npub struct AsyncWebSocket {\n\n inner: Arc<RefCell<AsyncWebSocketInner>>,\n\n}\n\n\n\nimpl Clone for AsyncWebSocket {\n\n fn clone(&se...
Rust
widgetry/src/widgets/compare_times.rs
tnederlof/abstreet
4f00c8d2bbbe2ccb4b65c11b2a071d5d1f87290d
use geom::{Angle, Circle, Distance, Duration, Pt2D}; use crate::{ Color, Drawable, EventCtx, GeomBatch, GfxCtx, Line, ScreenDims, ScreenPt, ScreenRectangle, Text, TextExt, Widget, WidgetImpl, WidgetOutput, }; pub struct CompareTimes { draw: Drawable, max: Duration, top_left: ScreenPt, dims: ...
use geom::{Angle, Circle, Distance, Duration, Pt2D}; use crate::{ Color, Drawable, EventCtx, GeomBatch, GfxCtx, Line, ScreenDims, ScreenPt, ScreenRectangle, Text, TextExt, Widget, WidgetImpl, WidgetOutput, }; pub struct CompareTimes { draw: Drawable, max: Duration, top_left: ScreenPt, dims: ...
} impl WidgetImpl for CompareTimes { fn get_dims(&self) -> ScreenDims { self.dims } fn set_pos(&mut self, top_left: ScreenPt) { self.top_left = top_left; } fn event(&mut self, _: &mut EventCtx, _: &mut WidgetOutput) {} fn draw(&self, g: &mut GfxCtx) { g.redraw_at(sel...
pub fn new_widget<I: AsRef<str>>( ctx: &mut EventCtx, x_name: I, y_name: I, points: Vec<(Duration, Duration)>, ) -> Widget { if points.is_empty() { return Widget::nothing(); } let actual_max = *points.iter().map(|(b, a)| a.max(b)).max().unwrap(); ...
function_block-full_function
[ { "content": "pub fn make_bar(ctx: &mut EventCtx, filled_color: Color, value: usize, max: usize) -> Widget {\n\n let pct_full = if max == 0 {\n\n 0.0\n\n } else {\n\n (value as f64) / (max as f64)\n\n };\n\n let txt = Text::from(format!(\n\n \"{} / {}\",\n\n prettyprint_u...
Rust
src/transforms/geoip.rs
XOSplicer/vector
f04d9452471147c082d8262e103cdb33fb846e26
use super::Transform; use crate::{ event::{Event, Value}, topology::config::{DataType, TransformConfig, TransformContext}, }; use serde::{Deserialize, Serialize}; use string_cache::DefaultAtom as Atom; use std::str::FromStr; use tracing::field; #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fi...
use super::Transform; use crate::{ event::{Event, Value}, topology::config::{DataType, TransformConfig, TransformContext}, }; use serde::{Deserialize, Serialize}; use string_cache::DefaultAtom as Atom; use std::str::FromStr; use tracing::field; #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fi...
exp_geoip_attr.insert("timezone", ""); exp_geoip_attr.insert("latitude", ""); exp_geoip_attr.insert("longitude", ""); exp_geoip_attr.insert("postal_code", ""); for field in exp_geoip_attr.keys() { let k = Atom::from(format!("geo.{}", field).to_string()); pri...
mote_addr"), "geo".to_string()); let new_event = augment.transform(event).unwrap(); let mut exp_geoip_attr = HashMap::new(); exp_geoip_attr.insert("city_name", ""); exp_geoip_attr.insert("country_code", "BT"); exp_geoip_attr.insert("continent_code", "AS"); exp_geoip_attr...
random
[ { "content": "/// Returns a mutable reference to field value specified by the given path.\n\npub fn get_mut<'a>(fields: &'a mut BTreeMap<Atom, Value>, path: &str) -> Option<&'a mut Value> {\n\n let mut path_iter = PathIter::new(path);\n\n\n\n match path_iter.next() {\n\n Some(PathComponent::Key(key...
Rust
server/prisma-rs/libs/database-inspector/tests/tests.rs
otrebu/prisma
298be5c919119847bb8d102d6b16672edd06b2c5
#![allow(non_snake_case)] #![allow(unused)] use barrel::{backend::Sqlite as Squirrel, types, Migration}; use database_inspector::*; use rusqlite::{Connection, Result, NO_PARAMS}; use std::{thread, time}; const SCHEMA: &str = "database_inspector_test"; #[test] fn all_columns_types_must_work() { let inspector = se...
#![allow(non_snake_case)] #![allow(unused)] use barrel::{backend::Sqlite as Squirrel, types, Migration}; use database_inspector::*; use rusqlite::{Connection, Result, NO_PARAMS}; use std::{thread, time}; const SCHEMA: &str = "database_inspector_test"; #[test] fn all_columns_types_must_work() { let inspector = se...
at, is_required: true, foreign_key: None, sequence: None, }, Column { name: "boolean".to_string(), tpe: ColumnType::Boolean, is_required: true, foreign_key: None, sequence: None, }, Column { ...
t()); t.add_column("string2", types::varchar(1)); t.add_column("date_time", types::date()); }); }); let result = inspector.introspect(&SCHEMA.to_string()); let table = result.table("User").unwrap(); let expected_columns = vec![ Column { name: "int".t...
function_block-random_span
[]
Rust
askama_escape/src/lib.rs
tizgafa/askama
d2c38b22ac54cc145bb2ede2925f7f149c8fd57e
#[macro_use] extern crate cfg_if; use std::fmt::{self, Display, Formatter}; use std::str; #[derive(Debug, PartialEq)] pub enum MarkupDisplay<T> where T: Display, { Safe(T), Unsafe(T), } impl<T> MarkupDisplay<T> where T: Display, { pub fn mark_safe(self) -> MarkupDisplay<T> { match self { ...
#[macro_use] extern crate cfg_if; use std::fmt::{self, Display, Formatter}; use std::str; #[derive(Debug, PartialEq)] pub enum MarkupDisplay<T> where T: Display, { Safe(T), Unsafe(T), } impl<T> MarkupDisplay<T> where T: Display, { pub fn mark_safe(self) -> MarkupDisplay<T> { match self { ...
#[cfg(all(target_arch = "x86_64", askama_runtime_sse))] unsafe fn _sse_escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { const VECTOR_SIZE: usize = size_of::<__m128i>(); let len = bytes.len(); let mut start = 0; if len < VECTOR_SIZE { for (i, b) in bytes.iter().enumerate() { ...
6_set1_epi8((LEN + 1) as i8); let v_flag_below = _mm256_set1_epi8(FLAG_BELOW as i8); let start_ptr = bytes.as_ptr(); let end_ptr = bytes[len..].as_ptr(); let mut ptr = start_ptr; debug_assert!(start_ptr <= ptr && start_ptr <= end_ptr.sub(VECTOR_SIZE)); if LOOP_SIZE <= len { { ...
function_block-function_prefixed
[ { "content": "/// Limit string length, appends '...' if truncated\n\npub fn truncate(s: &fmt::Display, len: &usize) -> Result<String> {\n\n let mut s = s.to_string();\n\n if s.len() < *len {\n\n Ok(s)\n\n } else {\n\n s.truncate(*len);\n\n s.push_str(\"...\");\n\n Ok(s)\n\n ...
Rust
bee-bundle/src/constants.rs
zesterer/bee-p
375357bdfe8f670e4d26b62a7683d97f339f056f
use common::constants::*; pub struct Offset { pub start: usize, pub length: usize, } pub struct Field { pub trit_offset: Offset, pub tryte_offset: Offset, } impl Field { pub fn byte_start(&self) -> usize { self.trit_offset.start / 5 } pub fn byte_length(&self) -> usize { ...
use common::constants::*; pub struct Offset { pub start: usize, pub length: usize, } pub struct Field { pub trit_offset: Offset, pub tryte_offset: Offset, } impl Field { pub fn byte_start(&self) -> usize { self.trit_offset.start / 5 } pub fn byte_length(&self) -> usize { ...
h + LAST_INDEX.trit_offset.length + BUNDLE_HASH.trit_offset.length + TRUNK_HASH.trit_offset.length + BRANCH_HASH.trit_offset.length + TAG.trit_offset.length + ATTACHMENT_TS.trit_offset.length + ATTACHMENT_LBTS.trit_offset.length ...
r) => { Field { trit_offset: Offset { start: ($prev).trit_offset.start + ($prev).trit_offset.length, length: $length, }, tryte_offset: Offset { start: (($prev).trit_offset.start + ($prev).trit_offset.length) / 3, ...
random
[ { "content": "fn trits_with_length(trits: &[Trit], length: usize) -> Vec<Trit> {\n\n if trits.len() < length {\n\n let mut result = vec![0; length];\n\n result[..trits.len()].copy_from_slice(&trits);\n\n result\n\n } else {\n\n trits[..length].to_vec()\n\n }\n\n}\n", "fi...
Rust
src/client/market.rs
zeta1999/huobi_future_async
e5202c50b15cd1fd22ccb696534bb4c513af1b49
use super::HuobiFuture; use crate::{ models::*, }; use failure::Fallible; use futures::prelude::*; use std::{collections::BTreeMap}; impl HuobiFuture { pub fn get_contract_info<S1, S2, S3>( &self, symbol: S1, contract_type: S2, contract_code: S3 ) -> Fallible<impl Fu...
use super::HuobiFuture; use crate::{ models::*, }; use failure::Fallible; use futures::prelude::*; use std::{collections::BTreeMap}; impl HuobiFuture { pub fn get_contract_info<S1, S2, S3>( &self, symbol: S1, contract_type: S2, contract_code: S3 ) -> Fallible<impl Fu...
}
pub fn get_price_limit<S1, S2, S3>( &self, symbol: S1, contract_type: S2, contract_code: S3 ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<PriceLimit>>>>> where S1: Into<Option<String>>, S2: Into<Option<String>>, S3: Into<Option<String>> {...
function_block-full_function
[ { "content": "pub fn build_query_string(parameters: &[(String,String)]) -> String \n\n{\n\n parameters\n\n .iter()\n\n .map(|(key, value)| format!(\"{}={}\", key, percent_encode(&value.clone())))\n\n .collect::<Vec<String>>()\n\n .join(\"&\")\n\n}\n\n\n", "file_path": "src/tra...
Rust
src/cigar.rs
Daniel-Liu-c0deb0t/block-aligner
b54c09e0210605bd56c85e950aa9cd1cbf1c1f31
use std::fmt; #[derive(Debug, PartialEq, Copy, Clone)] #[repr(u8)] pub enum Operation { Sentinel = 0u8, M = 1u8, I = 2u8, D = 3u8 } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct OpLen { pub op: Operation, pub len: usize } pub struct Cigar { s: Vec<OpLen>, i...
use std::fmt; #[derive(Debug, PartialEq, Copy, Clone)] #[repr(u8)] pub enum Operation { Sentinel = 0u8, M = 1u8, I = 2u8, D = 3u8 } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct OpLen { pub op: Operation, pub len: usize } pub struct Cigar { s: Vec<OpLen>, i...
; write!(f, "{}{}", op_len.len, c)?; } Ok(()) } }
match op_len.op { Operation::M => 'M', Operation::I => 'I', Operation::D => 'D', _ => continue }
if_condition
[ { "content": "/// Given an input byte string, create a randomly mutated copy and\n\n/// add random suffixes to both strings.\n\npub fn rand_mutate_suffix<R: Rng>(a: &mut Vec<u8>, k: usize, alpha: &[u8], suffix_len: usize, rng: &mut R) -> Vec<u8> {\n\n let mut b = rand_mutate(a, k, alpha, rng);\n\n let a_s...
Rust
pallets/account-linker/src/lib.rs
FueledAmp/litentry-node
bb703fbd06f45824c79c32a3e938799f07e9442d
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use sp_std::prelude::*; use sp_io::crypto::secp256k1_ecdsa_recover_compressed; use frame_support::{decl_module, decl_storage, decl_event, decl_error, dispatch, ensure}; use frame_system::{ensure_signed}; use btc::base58::ToBase58; use btc::witness::WitnessP...
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use sp_std::prelude::*; use sp_io::crypto::secp256k1_ecdsa_recover_compressed; use frame_support::{decl_module, decl_storage, decl_event, decl_error, dispatch, ensure}; use frame_system::{ensure_signed}; use btc::base58::ToBase58; use btc::witness::WitnessP...
nt); if (index >= addrs.len()) && (addrs.len() != MAX_ETH_LINKS) { addrs.push(addr.clone()); } else if (index >= addrs.len()) && (addrs.len() == MAX_ETH_LINKS) { addrs[MAX_ETH_LINKS - 1] = addr.clone(); } else { addrs[index] = addr.clone(); } <EthereumLink<T>>::insert(account.clone(), ad...
ber > current_block_number, Error::<T>::LinkRequestExpired); ensure!((expiring_block_number - current_block_number) < T::BlockNumber::from(EXPIRING_BLOCK_NUMBER_MAX), Error::<T>::InvalidExpiringBlockNumber); let mut bytes = b"Link Litentry: ".encode(); let mut account_vec = account.encode(); let mut ex...
random
[ { "content": "pub fn hash160(bytes: &[u8]) -> [u8; 20] {\n\n let mut hasher_sha256 = Sha256::new();\n\n hasher_sha256.update(bytes);\n\n let digest = hasher_sha256.finalize();\n\n\n\n let mut hasher_ripemd = Ripemd160::new();\n\n hasher_ripemd.update(digest);\n\n\n\n let mut ret = [0; 20];\n\n...
Rust
ezgui/src/screen_geom.rs
accelsao/abstreet
eca71d27c95abd74a96863ed20bbd92c7850cd33
use crate::Canvas; use geom::{trim_f64, Polygon, Pt2D}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq)] pub struct ScreenPt { pub x: f64, pub y: f64, } impl ScreenPt { pub fn new(x: f64, y: f64) -> ScreenPt { ScreenPt { x, y } } pub fn to_pt(self) -...
use crate::Canvas; use geom::{trim_f64, Polygon, Pt2D}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq)] pub struct ScreenPt { pub x: f64, pub y: f64, } impl ScreenPt { pub fn new(x: f64, y: f64) -> ScreenPt { ScreenPt { x, y } } pub fn to_pt(self) -...
} pub fn scaled(&self, factor: f64) -> ScreenDims { ScreenDims::new(self.width * factor, self.height * factor) } } impl From<winit::dpi::LogicalSize<f64>> for ScreenDims { fn from(size: winit::dpi::LogicalSize<f64>) -> ScreenDims { ScreenDims { width: size.width, ...
if corner.x + self.width < canvas.window_width { if corner.y + self.height < canvas.window_height { corner } else { ScreenPt::new(corner.x, corner.y - self.height) } } else { ...
if_condition
[ { "content": "fn area_under_curve(raw: Vec<(Time, usize)>, width: f64, height: f64) -> Polygon {\n\n assert!(!raw.is_empty());\n\n let min_x = Time::START_OF_DAY;\n\n let min_y = 0;\n\n let max_x = raw.last().unwrap().0;\n\n let max_y = raw.iter().max_by_key(|(_, cnt)| *cnt).unwrap().1;\n\n\n\n ...
Rust
crates/witx2/src/interface.rs
yowl/witx-bindgen
9c10658073776e0ea4e3e30cef295cb1e306ecb0
use crate::{ abi::Abi, ast::interface::{Ast, Item}, rewrite_error, }; use anyhow::{bail, Context, Result}; use id_arena::{Arena, Id}; use std::collections::{HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; #[derive(Debug, Clone)] pub struct Interface { pub name: String, pub types: Ar...
use crate::{ abi::Abi, ast::interface::{Ast, Item}, rewrite_error, }; use anyhow::{bail, Context, Result}; use id_arena::{Arena, Id}; use std::collections::{HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; #[derive(Debug, Clone)] pub struct Interface { pub name: String, pub types: Ar...
pub fn parse_with( path: impl AsRef<Path>, contents: &str, mut load: impl FnMut(&str) -> Result<(PathBuf, String)>, ) -> Result<Interface> { Interface::_parse_with( path.as_ref(), contents, &mut load, &mut HashSet::new(), ...
let path = path.as_ref(); let parent = path.parent().unwrap(); let contents = std::fs::read_to_string(&path) .with_context(|| format!("failed to read interface `{}`", path.display()))?; Interface::parse_with(path, &contents, |name| load_fs(parent, name)) }
function_block-function_prefix_line
[ { "content": "pub fn case_name(id: &str) -> String {\n\n if id.chars().next().unwrap().is_alphabetic() {\n\n id.to_camel_case()\n\n } else {\n\n format!(\"V{}\", id)\n\n }\n\n}\n\n\n", "file_path": "crates/gen-rust/src/lib.rs", "rank": 0, "score": 443626.0483821046 }, { ...
Rust
kernel/src/drivers/keyboard/codes.rs
andrewimm/imm-dos-nx
2716a4954eae779cdf0596e061d16484d06c3563
#[derive(Copy, Clone)] #[repr(u8)] pub enum KeyCode { None = 0x00, Delete = 0x07, Backspace = 0x08, Tab = 0x09, Enter = 0x0d, Caps = 0x10, Shift = 0x11, Control = 0x12, Menu = 0x13, Alt = 0x14, Escape = 0x1b, Space = 0x20, ArrowLeft = 0x21, ArrowUp = 0x22, ArrowRight = 0x23, ArrowDo...
#[derive(Copy, Clone)] #[repr(u8)] pub enum KeyCode { None = 0x00, Delete = 0x07, Backspace = 0x08, Tab = 0x09, Enter = 0x0d, Caps = 0x10, Shift = 0x11, Control = 0x12, Menu = 0x13, Alt = 0x14, Escape = 0x1b, Space = 0x20, ArrowLeft = 0x21, ArrowUp = 0x22, ArrowRight = 0x23, ArrowDo...
eyCode::Enter, 0x48 => KeyCode::ArrowUp, 0x4b => KeyCode::ArrowLeft, 0x4d => KeyCode::ArrowRight, 0x50 => KeyCode::ArrowDown, _ => KeyCode::None, } }
pub const SCANCODES_TO_KEYCODES: [KeyCode; 60] = [ KeyCode::None, KeyCode::Escape, KeyCode::Num1, KeyCode::Num2, KeyCode::Num3, KeyCode::Num4, KeyCode::Num5, KeyCode::Num6, KeyCode::Num7, KeyCode::Num8, KeyCode::Num9, KeyCode::Num0, KeyCode::Minus, KeyCode::Equals, KeyCode::Backspace, KeyCode::Tab, KeyCode::...
random
[]
Rust
futures-util/src/compat/compat03as01.rs
EkardNT/futures-rs
90c83b8faca107e6c4db63d10b0d4f2ea36d6628
use futures_01::{ task as task01, Async as Async01, Future as Future01, Poll as Poll01, Stream as Stream01, }; #[cfg(feature = "sink")] use futures_01::{ AsyncSink as AsyncSink01, Sink as Sink01, StartSend as StartSend01, }; use futures_core::{ task::{RawWaker, RawWakerVTable}, TryFuture as TryFutur...
use futures_01::{ task as task01, Async as Async01, Future as Future01, Poll as Poll01, Stream as Stream01, }; #[cfg(feature = "sink")] use futures_01::{ AsyncSink as AsyncSink01, Sink as Sink01, StartSend as StartSend01, }; use futures_core::{ task::{RawWaker, RawWakerVTable}, TryFuture as TryFutur...
} }
self) -> std::io::Result<Async01<()>> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_01(Pin::new(&mut self.inner).poll_close(&mut cx)) }
function_block-function_prefixed
[ { "content": "#[doc(hidden)]\n\npub fn poll<F: Future + Unpin>(future: F) -> PollOnce<F> {\n\n PollOnce { future }\n\n}\n\n\n\n#[allow(missing_debug_implementations)]\n\n#[doc(hidden)]\n\npub struct PollOnce<F: Future + Unpin> {\n\n future: F,\n\n}\n\n\n\nimpl<F: Future + Unpin> Future for PollOnce<F> {\n...
Rust
src/usbphy/pll_sic_tog.rs
thorhs/mk66f18
ea5a3c933656be9f2f548b28dee91d0bb7821923
#[doc = "Reader of register PLL_SIC_TOG"] pub type R = crate::R<u32, super::PLL_SIC_TOG>; #[doc = "Writer for register PLL_SIC_TOG"] pub type W = crate::W<u32, super::PLL_SIC_TOG>; #[doc = "Register PLL_SIC_TOG `reset()`'s with value 0x0001_2000"] impl crate::ResetValue for super::PLL_SIC_TOG { type Type = u32; ...
#[doc = "Reader of register PLL_SIC_TOG"] pub type R = crate::R<u32, super::PLL_SIC_TOG>; #[doc = "Writer for register PLL_SIC_TOG"] pub type W = crate::W<u32, super::PLL_SIC_TOG>; #[doc = "Register PLL_SIC_TOG `reset()`'s with value 0x0001_2000"] impl crate::ResetValue for super::PLL_SIC_TOG { type Type = u32; ...
#[doc = "Checks if the value of the field is `_00`"] #[inline(always)] pub fn is_00(&self) -> bool { *self == PLL_DIV_SEL_A::_00 } #[doc = "Checks if the value of the field is `_01`"] #[inline(always)] pub fn is_01(&self) -> bool { *self == PLL_DIV_SEL_A::_01 } } #[doc =...
pub fn variant(&self) -> crate::Variant<u8, PLL_DIV_SEL_A> { use crate::Variant::*; match self.bits { 0 => Val(PLL_DIV_SEL_A::_00), 1 => Val(PLL_DIV_SEL_A::_01), i => Res(i), } }
function_block-full_function
[ { "content": " ///\n\n ///Registers marked with `Readable` can be also `modify`'ed\n\n pub trait Writable { } ///Reset value of the register\n", "file_path": "lib.rs", "rank": 0, "score": 220323.13240861555 }, { "content": " ///\n\n ///This value is initial value for `write` method.\n\n ///I...
Rust
termwiz/src/hyperlink.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
use anyhow::{anyhow, ensure, Error}; use regex::{Captures, Regex}; use serde::{self, Deserialize, Deserializer, Serialize}; use std::collections::HashMap; use std::fmt::{Display, Error as FmtError, Formatter}; use std::ops::Range; use std::sync::Arc; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub...
use anyhow::{anyhow, ensure, Error}; use regex::{Captures, Regex}; use serde::{self, Deserialize, Deserializer, Serialize}; use std::collections::HashMap; use std::fmt::{Display, Error as FmtError, Formatter}; use std::ops::Range; use std::sync::Arc; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub...
} impl Rule { pub fn new(regex: &str, format: &str) -> Result<Self, Error> { Ok(Self { regex: Regex::new(regex)?, format: format.to_owned(), }) } pub fn match_hyperlinks(line: &str, rules: &[Rule]) -> Vec<RuleMatch> { let mut matches = Vec::n...
rmat!("${}", n); result = result.replace(&search, self.captures.get(n).unwrap().as_str()); } result }
function_block-function_prefixed
[ { "content": "pub fn language_from_string(s: &str) -> Result<hb_language_t, Error> {\n\n unsafe {\n\n let lang = hb_language_from_string(s.as_ptr() as *const i8, s.len() as i32);\n\n ensure!(!lang.is_null(), \"failed to convert {} to language\");\n\n Ok(lang)\n\n }\n\n}\n\n\n", "f...
Rust
src/recovery/hystart.rs
ehaydenr/quiche
d0b40f791fd46f1ffdf0357f18e1ba5953723a59
use std::cmp; use std::time::Duration; use std::time::Instant; use crate::packet; use crate::recovery; const LOW_CWND: usize = 16; const MIN_RTT_THRESH: Duration = Duration::from_millis(4); const MAX_RTT_THRESH: Duration = Duration::from_millis(16); pub const LSS_DIVISOR: f64 = 0.25; pub const N_RTT_SAMPLE: usi...
use std::cmp; use std::time::Duration; use std::time::Instant; use crate::packet; use crate::recovery; const LOW_CWND: usize = 16; const MIN_RTT_THRESH: Duration = Duration::from_millis(4); const MAX_RTT_THRESH: Duration = Duration::from_millis(16); pub const LSS_DIVISOR: f64 = 0.25; pub const N_RTT_SAMPLE: usi...
} pub fn try_enter_lss( &mut self, packet: &recovery::Acked, rtt: Duration, cwnd: usize, now: Instant, max_datagram_size: usize, ) -> bool { if self.lss_start_time().is_none() { if let Some(current_round_min_rtt) = self.current_round_min_rtt { self....
if self.window_end.is_none() { *self = Hystart { enabled: self.enabled, window_end: Some(pkt_num), last_round_min_rtt: self.current_round_min_rtt, current_round_min_rtt: None, rtt_sample_count: 0, lss_start_...
if_condition
[ { "content": "/// Returns true if the stream is bidirectional.\n\npub fn is_bidi(stream_id: u64) -> bool {\n\n (stream_id & 0x2) == 0\n\n}\n\n\n\n/// An iterator over QUIC streams.\n\n#[derive(Default)]\n\npub struct StreamIter {\n\n streams: Vec<u64>,\n\n}\n\n\n\nimpl StreamIter {\n\n #[inline]\n\n ...
Rust
src/ketos/string.rs
salewski/ketos
011287590ebeb6e6a199e34c8b9da14e2daeb1ce
use std::str::CharIndices; use crate::lexer::{BytePos, Span}; use crate::parser::{ParseError, ParseErrorKind}; pub fn parse_byte(s: &str, pos: BytePos) -> Result<(u8, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Single); r.parse_byte() } pub fn parse_byte_string(s: &str, pos: Byt...
use std::str::CharIndices; use crate::lexer::{BytePos, Span}; use crate::parser::{ParseError, ParseErrorKind}; pub fn parse_byte(s: &str, pos: BytePos) -> Result<(u8, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Single); r.parse_byte() } pub fn parse_byte_string(s: &str, pos: Byt...
} fn back_span(&self, back: BytePos, len: BytePos) -> Span { let start = self.start + self.last_index as BytePos - back; Span{lo: start, hi: start + len} } fn span_one(&self) -> Span { Span{ lo: self.start + self.last_index as BytePos, hi: self.start + ...
match self.chars.clone().next() { Some((_, ch)) => Ok(ch), None => Err(ParseError::new(self.span_from(self.start, 1), if self.ty == StringType::Single { ParseErrorKind::UnterminatedChar } else { ParseErrorKind::UnterminatedS...
if_condition
[ { "content": "fn consume_block_comment(start: usize, chars: &mut CharIndices) -> Result<usize, ParseErrorKind> {\n\n let mut n_blocks = 1;\n\n\n\n loop {\n\n match chars.next() {\n\n Some((_, '|')) => match chars.clone().next() {\n\n Some((ind, '#')) => {\n\n ...
Rust
src/value.rs
Mingun/serde-gff
2bfacbb0b6b361da749082f99edaec474ccc6c7c
use indexmap::IndexMap; use crate::{Label, LocString, ResRef}; use crate::index::{U64Index, I64Index, F64Index, StringIndex, ResRefIndex, LocStringIndex, BinaryIndex}; #[derive(Debug, Clone, PartialEq)] pub enum SimpleValueRef { Byte(u8), Char(i8), Word(u16), Short(i16), ...
use indexmap::IndexMap; use crate::{Label, LocString, ResRef}; use crate::index::{U64Index, I64Index, F64Index, StringIndex, ResRefIndex, LocStringIndex, BinaryIndex}; #[derive(Debug, Clone, PartialEq)] pub enum SimpleValueRef { Byte(u8), Char(i8), Word(u16), Short(i16), ...
(val) => Value::LocString(val), Void(val) => Value::Void(val), } } }
Short(i16), Dword(u32), Int(i32), Dword64(u64), Int64(i64), Float(f32), Double(f64), String(String), ResRef(ResRef), LocString(LocString), Void(Vec<u8>), } #[derive(Debug, Clone,...
random
[ { "content": "/// Возможные представления ключа отображений в форматах данных\n\nenum Key {\n\n /// Ключ отображения является строкой, символом или массивом байт и соответствует\n\n /// метке поля\n\n Label(Label),\n\n /// Ключ отображения является числом и соответствует элементу многоязыковой строки\n\n S...
Rust
src/lib.rs
wangkang/hiredis
10bf22dc35c26e3846a025866993a2f361441d13
extern crate hiredis_sys as ffi; extern crate libc; use libc::{c_char, c_int, size_t}; use std::convert::{From, Into}; use std::ffi::{CStr, CString}; use std::marker::PhantomData; use std::{error, fmt, mem, slice}; macro_rules! raise( ($message:expr) => (return Err(Error::from($message))); ); macro_rules! succ...
extern crate hiredis_sys as ffi; extern crate libc; use libc::{c_char, c_int, size_t}; use std::convert::{From, Into}; use std::ffi::{CStr, CString}; use std::marker::PhantomData; use std::{error, fmt, mem, slice}; macro_rules! raise( ($message:expr) => (return Err(Error::from($message))); ); macro_rules! succ...
#[inline] pub fn reconnect(&mut self) -> Result<()> { if unsafe { ffi::redisReconnect(self.raw) } != ffi::REDIS_OK { raise!("failed to reconnect"); } Ok(()) } } impl Drop for Context { #[inline] fn drop(&mut self) { unsafe { ffi::redisFree(self.raw...
t mut argvlen = Vec::with_capacity(argc); for argument in arguments.iter() { let data = argument.as_bytes(); argv.push(data.as_ptr() as *const _); argvlen.push(data.len() as size_t); } let raw = unsafe { ffi::redisCommandArgv(self.raw, argc as c_i...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn push_pop_strings() {\n\n let mut context = ok!(hiredis::connect(\"127.0.0.1\", 6379));\n\n match ok!(context.command(&[\"RPUSH\", \"hiredis-baz\", \"Good news, everyone!\"])) {\n\n Reply::Integer(integer) => assert!(integer > 0),\n\n _ => assert!(false),\n\n }\...
Rust
src/docker_run/http_extra.rs
glotcode/docker-run
d2ee4c820a19ef063e12b115f0d4463c51dca430
use http::{Request, Response}; use http::header; use http::status; use http::header::CONTENT_LENGTH; use http::header::TRANSFER_ENCODING; use http::response; use std::io::{Read, Write}; use serde::Deserialize; use serde::de::DeserializeOwned; use std::io; use std::io::BufReader; use std::io::BufRead; use std::str::From...
use http::{Request, Response}; use http::header; use http::status; use http::header::CONTENT_LENGTH; use http::header::TRANSFER_ENCODING; use http::response; use std::io::{Read, Write}; use serde::Deserialize; use serde::de::DeserializeOwned; use std::io; use std::io::BufReader; use std::io::BufRead; use std::str::From...
} pub fn send_request<Stream, ResponseBody>(mut stream: Stream, req: Request<Body>) -> Result<Response<ResponseBody>, Error> where Stream: Read + Write, ResponseBody: DeserializeOwned, { write_request_head(&mut stream, &req) .map_err(Error::WriteRequest)?; write_request_body(&...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::WriteRequest(err) => { write!(f, "Failed to send request: {}", err) } Error::ReadResponse(err) => { write!(f, "Failed read response: {}", err) } ...
function_block-full_function
[ { "content": "pub fn remove_container<Stream: Read + Write>(stream: Stream, container_id: &str) -> Result<http::Response<http_extra::EmptyResponse>, Error> {\n\n let req = remove_container_request(container_id)\n\n .map_err(|x| Error::PrepareRequest(PrepareRequestError::Request(x)))?;\n\n\n\n http_...
Rust
src/compute/nullif.rs
abreis/arrow2
982454620d1db7964a4e272b3f74745563b6ba5a
use crate::array::PrimitiveArray; use crate::compute::comparison::primitive_compare_values_op; use crate::datatypes::DataType; use crate::error::{ArrowError, Result}; use crate::{array::Array, types::NativeType}; use super::utils::combine_validities; pub fn nullif_primitive<T: NativeType>( lhs: &PrimitiveArray<T>...
use crate::array::PrimitiveArray; use crate::compute::comparison::primitive_compare_values_op; use crate::datatypes::DataType; use crate::error::{ArrowError, Result}; use crate::{array::Array, types::NativeType}; use super::utils::combine_validities; pub fn nullif_primitive<T: NativeType>( lhs: &PrimitiveArray<T>...
pub fn nullif(lhs: &dyn Array, rhs: &dyn Array) -> Result<Box<dyn Array>> { if lhs.data_type() != rhs.data_type() { return Err(ArrowError::InvalidArgumentError( "Nullif expects arrays of the the same logical type".to_string(), )); } if lhs.len() != rhs.len() { return Err(...
function_block-full_function
[ { "content": "/// Logically compares two [ArrayData].\n\n/// Two arrays are logically equal if and only if:\n\n/// * their data types are equal\n\n/// * their lengths are equal\n\n/// * their null counts are equal\n\n/// * their null bitmaps are equal\n\n/// * each of their items are equal\n\n/// two items are ...
Rust
meilisearch-core/src/update/settings_update.rs
irevoire/MeiliSearch
66c455413695ae8bda7af9e909077b9402d65b2e
use std::{borrow::Cow, collections::{BTreeMap, BTreeSet}}; use heed::Result as ZResult; use fst::{SetBuilder, set::OpBuilder}; use sdset::SetBuf; use meilisearch_schema::Schema; use meilisearch_tokenizer::analyzer::{Analyzer, AnalyzerConfig}; use crate::database::{MainT, UpdateT}; use crate::settings::{UpdateState, S...
use std::{borrow::Cow, collections::{BTreeMap, BTreeSet}}; use heed::Result as ZResult; use fst::{SetBuilder, set::OpBuilder}; use sdset::SetBuf; use meilisearch_schema::Schema; use meilisearch_tokenizer::analyzer::{Analyzer, AnalyzerConfig}; use crate::database::{MainT, UpdateT}; use crate::settings::{UpdateState, S...
fn apply_attributes_for_faceting_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, schema: &mut Schema, attributes: &[String] ) -> MResult<()> { let mut attribute_ids = Vec::new(); for name in attributes { attribute_ids.push(schema.insert(name)?); } let attribu...
pub fn apply_settings_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, settings: SettingsUpdate, ) -> MResult<()> { let mut must_reindex = false; let mut schema = match index.main.schema(writer)? { Some(schema) => schema, None => { match settings.primary_ke...
function_block-full_function
[]
Rust
2020/day-12/src/main.rs
dstoza/advent-2017
22de531632c1633814ed1d2b9827590af989fb6e
#![deny(clippy::all, clippy::pedantic)] use std::{ env, fs::File, io::{BufRead, BufReader}, }; #[derive(Clone, Copy)] enum Direction { North = 0, East = 1, South = 2, West = 3, } impl Direction { fn from_i32(value: i32) -> Self { match value { 0 => Direction::North...
#![deny(clippy::all, clippy::pedantic)] use std::{ env, fs::File, io::{BufRead, BufReader}, }; #[derive(Clone, Copy)] enum Direction { North = 0, East = 1, South = 2, West = 3, } impl Direction { fn from_i32(value: i32) -> Self { match value { 0 => Direction::North...
fn move_forward(&mut self, amount: i32) { match self.mode { Mode::Ship => self.translate(self.direction, amount), Mode::Waypoint => { self.x += self.waypoint_x * amount; self.y += self.waypoint_y * amount; } } } fn parse_...
fn turn(&mut self, rotation: &Rotation, amount: i32) { let clockwise_amount = match rotation { Rotation::Right => amount, Rotation::Left => 360 - amount, }; let direction = self.direction as i32 + clockwise_amount / 90; for _ in 0..(clockwise_amount / 90) { ...
function_block-full_function
[ { "content": "fn roll_die(die: &mut i32) -> i32 {\n\n let roll = *die;\n\n *die = (*die % 100) + 1;\n\n roll\n\n}\n\n\n", "file_path": "2021/day-21/src/main.rs", "rank": 0, "score": 192315.6612448546 }, { "content": "fn get_triangle_value(value: i32) -> i32 {\n\n (value * (value ...
Rust
src/statemachine/mac.rs
nathanwhit/tarpaulin
42dd578e753e4b380d27545704b49239f9f6ea30
#![allow(unused)] #![allow(non_snake_case)] use crate::config::Config; use crate::errors::RunError; use crate::statemachine::*; use log::{debug, trace}; use nix::errno::Errno; use nix::sys::signal::Signal; use nix::sys::wait::*; use nix::unistd::Pid; use nix::Error as NixErr; use std::collections::{HashMap, HashSet}; ...
#![allow(unused)] #![allow(non_snake_case)] use crate::config::Config; use crate::errors::RunError; use crate::statemachine::*; use log::{debug, trace}; use nix::errno::Errno; use nix::sys::signal::Signal; use nix::sys::wait::*; use nix::unistd::Pid; use nix::Error as NixErr; use std::collections::{HashMap, HashSet}; ...
} impl<'a> MacData<'a> { pub fn new(traces: &'a mut TraceMap, config: &'a Config) -> MacData<'a> { MacData { wait_queue: Vec::new(), current: Pid::from_raw(0), parent: Pid::from_raw(0), breakpoints: HashMap::new(), traces, config, ...
fn stop(&mut self) -> Result<TestState, RunError> { let mut actions = Vec::new(); let mut pcs = HashSet::new(); let mut result = Ok(TestState::wait_state()); let pending = self.wait_queue.clone(); self.wait_queue.clear(); for status in &pending { let state = m...
function_block-full_function
[ { "content": "/// Launches tarpaulin with the given configuration.\n\npub fn launch_tarpaulin(config: &Config) -> Result<(TraceMap, i32), RunError> {\n\n setup_environment(&config);\n\n cargo::core::enable_nightly_features();\n\n let cwd = match config.manifest.parent() {\n\n Some(p) => p.to_pat...
Rust
tests/read_write_pdbs.rs
douweschulte/pdbtbx
4495b3af56d88b72f27e5d9f17848bcbdec34381
use pdbtbx::*; use std::path::Path; use std::time::Instant; use std::{env, fs}; #[test] fn run_pdbs() { let current_dir = env::current_dir().unwrap(); let pdb_dir = current_dir.as_path().join(Path::new("example-pdbs")); let dump_dir = current_dir .as_path() .join(Path::new("dump")) ...
use pdbtbx::*; use std::path::Path; use std::time::Instant; use std::{env, fs}; #[test] fn run_pdbs() { let current_dir = env::current_dir().unwrap(); let pdb_dir = current_dir.as_path().join(Path::new("example-pdbs")); let dump_dir = current_dir .as_path() .join(Path::new("dump")) ...
as_path() .join(Path::new("dump")) .join(Path::new("save_test.cif")) .into_os_string() .into_string() .unwrap(); let atom = Atom::new(false, 0, "H", 0.0, 0.0, 0.0, 0.0, 0.0, "H", 0).unwrap(); let mut model = Model::new(0); model.add_atom(atom, "A", (0, None), ("LYS",...
function_block-function_prefix_line
[ { "content": "/// Parse a loop containing atomic data\n\nfn parse_atoms(input: &Loop, pdb: &mut PDB) -> Option<Vec<PDBError>> {\n\n /// These are the columns needed to fill out the PDB correctly\n\n const COLUMNS: &[&str] = &[\n\n \"atom_site.group_PDB\",\n\n \"atom_site.label_atom_id\",\n\n...
Rust
lib/llvm-backend/src/platform/unix.rs
spacemeshos/wasmer
31365510edd73878916e1aba2dd79f415b8c6891
use super::common::round_up_to_page_size; use crate::structs::{LLVMResult, MemProtect}; use libc::{ c_void, mmap, mprotect, munmap, siginfo_t, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_READ, PROT_WRITE, }; use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, SIGBUS, SIGSEGV}; use st...
use super::common::round_up_to_page_size; use crate::structs::{LLVMResult, MemProtect}; use libc::{ c_void, mmap, mprotect, munmap, siginfo_t, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_READ, PROT_WRITE, }; use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, SIGBUS, SIGSEGV}; use st...
res == 0 { LLVMResult::OK } else { LLVMResult::PROTECT_FAILURE } } pub unsafe fn dealloc_memory(ptr: *mut u8, size: usize) -> LLVMResult { let res = munmap(ptr as _, round_up_to_page_size(size)); if res == 0 { LLVMResult::OK } else { LLVMResult::DEALLOC_FAILURE ...
mut p = addr; let end = p.add(size); loop { if p >= end { break; } p = process_fde(p, visitor); } } #[cfg(not(target_os = "macos"))] pub unsafe fn visit_fde(addr: *mut u8, _size: usize, visitor: extern "C" fn(*mut u8)) { visitor(addr); } extern "C" { #[cfg_at...
random
[ { "content": "type Trampoline = unsafe extern \"C\" fn(*mut Ctx, NonNull<Func>, *const u64, *mut u64);\n", "file_path": "lib/win-exception-handler/src/exception_handling.rs", "rank": 0, "score": 336851.1212825576 }, { "content": "pub fn round_up_to_page_size(size: usize) -> usize {\n\n (s...
Rust
datafusion/src/physical_plan/file_format/json.rs
andts/arrow-datafusion
1c39f5ce865e3e1225b4895196073be560a93e82
use async_trait::async_trait; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::physical_plan::{ DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics, }; use arrow::{datatypes::SchemaRef, json}; use std::any::Any; use std::sync...
use async_trait::async_trait; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::physical_plan::{ DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics, }; use arrow::{datatypes::SchemaRef, json}; use std::any::Any; use std::sync...
} } async fn execute( &self, partition: usize, _runtime: Arc<RuntimeEnv>, ) -> Result<SendableRecordBatchStream> { let proj = self.base_config.projected_file_column_names(); let batch_size = self.base_config.batch_size; let file_schema = Arc::clone(...
Err(DataFusionError::Internal(format!( "Children cannot be replaced in {:?}", self )))
call_expression
[]
Rust
language/vm/vm-runtime/src/loaded_data/loaded_module.rs
end-o/libra
38d2a1ed3fde793784b2dba978ee349099cdecfe
use crate::loaded_data::function::FunctionDef; use bytecode_verifier::VerifiedModule; use libra_types::{ identifier::Identifier, vm_error::{StatusCode, VMStatus}, }; use std::{collections::HashMap, sync::RwLock}; use vm::{ access::ModuleAccess, errors::VMResult, file_format::{ CompiledModu...
use crate::loaded_data::function::FunctionDef; use bytecode_verifier::VerifiedModule; use libra_types::{ identifier::Identifier, vm_error::{StatusCode, VMStatus}, }; use std::{collections::HashMap, sync::RwLock}; use vm::{ access::ModuleAccess, errors::VMResult, file_format::{ CompiledModu...
} for (idx, field_def) in module.field_defs().iter().enumerate() { let name = module.identifier_at(field_def.name).into(); let fd_idx = FieldDefinitionIndex::new(idx as TableIndex); field_defs_table.insert(name, fd_idx); } for (idx, function_def) in ...
if let StructFieldInformation::Declared { field_count, fields, } = &struct_def.field_information { for i in 0..*field_count { let field_index = fields.into_index(); assume!(field_index <=...
if_condition
[ { "content": "/// Get the StructTag for a StructDefinition defined in a published module.\n\npub fn resource_storage_key(module: &impl ModuleAccess, idx: StructDefinitionIndex) -> StructTag {\n\n let resource = module.struct_def_at(idx);\n\n let res_handle = module.struct_handle_at(resource.struct_handle)...
Rust
src/serialization/v2.rs
duncandean/macaroon
601ca1d8d76a93c6e4deae9f8d3f4bf0b2d7a67c
use caveat::{Caveat, CaveatBuilder}; use error::MacaroonError; use serialization::macaroon_builder::MacaroonBuilder; use ByteString; use Macaroon; use Result; const EOS: u8 = 0; const LOCATION: u8 = 1; const IDENTIFIER: u8 = 2; const VID: u8 = 4; const SIGNATURE: u8 = 6; const VARINT_PACK_SIZE: usize = 128; fn varin...
use caveat::{Caveat, CaveatBuilder}; use error::MacaroonError; use serialization::macaroon_builder::MacaroonBuilder; use ByteString; use Macaroon; use Result; const EOS: u8 = 0; const LOCATION: u8 = 1; const IDENTIFIER: u8 = 2; const VID: u8 = 4; const SIGNATURE: u8 = 6; const VARINT_PACK_SIZE: usize = 128; fn varin...
}
fn test_serialize_deserialize() { let mut macaroon = Macaroon::create(Some("http://example.org/".into()), &"key".into(), "keyid".into()).unwrap(); macaroon.add_first_party_caveat("account = 3735928559".into()); macaroon.add_first_party_caveat("user = alice".into()); macaroon....
function_block-full_function
[ { "content": "pub fn deserialize(data: &[u8]) -> Result<Macaroon> {\n\n let v2j: Serialization = serde_json::from_slice(data)?;\n\n Macaroon::from_json(v2j)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::super::Format;\n\n use ByteString;\n\n use Caveat;\n\n use Macaroon;\n\n use Ma...
Rust
src/main.rs
tcr/rager
b664f0a93c2a773d232b30f9827813d57a32d5f7
#[macro_use] extern crate structopt; extern crate termion; extern crate ransid; extern crate failure; extern crate libc; extern crate crossbeam_channel; use std::path::PathBuf; use structopt::StructOpt; use failure::Error; use termion::event::*; use termion::scroll; use termion::input::{TermRead, MouseTerminal}; use t...
#[macro_use] extern crate structopt; extern crate termion; extern crate ransid; extern crate failure; extern crate libc; extern crate crossbeam_channel; use std::path::PathBuf; use structopt::StructOpt; use failure::Error; use termion::event::*; use termion::scroll; use termion::input::{TermRead, MouseTerminal}; use t...
fn get(&self, x: usize, y: usize) -> RagerChar { self.3[y][x] } fn width(&self) -> usize { self.0 } fn height(&self) -> usize { self.1 } } #[derive(Debug, StructOpt)] #[structopt(name = "rager", about = "A pager, like more or less.", author = "")] struct Opt { #[s...
fn set(&mut self, x: usize, y: usize, val: RagerChar) { if y >= self.height() { for _ in 0..(y - self.height() + 1) { self.expand_vertical(); } } self.3[y][x] = val; }
function_block-full_function
[ { "content": "# rager 🎉\n\n\n\n[![](http://meritbadge.herokuapp.com/rager)](https://crates.io/crates/rager)\n\n\n\nA terminal Pager written in Rust. Like more or less.\n\n\n\n* Supports any `xterm`-supporting terminal thanks to Termion.\n\n* Support mouse scrolling (or up/down keys)\n\n* Supports content over ...
Rust
src/function.rs
eisterman/RustaCUDA
4f78c255c9e017c47e21af72a9dd8710f3b571e1
use crate::context::{CacheConfig, SharedMemoryConfig}; use crate::error::{CudaResult, ToResult}; use crate::module::Module; use cuda_sys::cuda::{self, CUfunction}; use std::marker::PhantomData; use std::mem::transmute; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GridSize { pub x: u32, ...
use crate::context::{CacheConfig, SharedMemoryConfig}; use crate::error::{CudaResult, ToResult}; use crate::module::Module; use cuda_sys::cuda::{self, CUfunction}; use std::marker::PhantomData; use std::mem::transmute; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GridSize { pub x: u32, ...
.to_result()?; Ok(val) } } pub fn set_cache_config(&mut self, config: CacheConfig) -> CudaResult<()> { unsafe { cuda::cuFuncSet...
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum FunctionAttribute { MaxThreadsPerBlock = 0, SharedMemorySizeBytes = 1, ConstSizeBytes = 2, LocalSizeBytes = 3, NumRegisters = 4, PtxVersion = 5, BinaryVersion =...
random
[ { "content": "/// Shortcut for initializing the CUDA Driver API and creating a CUDA context with default settings\n\n/// for the first device.\n\n///\n\n/// This is useful for testing or just setting up a basic CUDA context quickly. Users with more\n\n/// complex needs (multiple devices, custom flags, etc.) sho...
Rust
src/client/options/test.rs
judy2k/mongo-rust-driver
f39251fce6ede7ad712cca26e00f0b09fef6e085
use bson::{Bson, Document}; use pretty_assertions::assert_eq; use serde::Deserialize; use crate::{ client::options::{ClientOptions, StreamAddress}, error::ErrorKind, selection_criteria::{ReadPreference, SelectionCriteria}, test::run_spec_test, RUNTIME, }; #[derive(Debug, Deserialize)] struct TestFi...
use bson::{Bson, Document}; use pretty_assertions::assert_eq; use serde::Deserialize; use crate::{ client::options::{ClientOptions, StreamAddress}, error::ErrorKind, selection_criteria::{ReadPreference, SelectionCriteria}, test::run_spec_test, RUNTIME, }; #[derive(Debug, Deserialize)] struct TestFi...
.block_on(ClientOptions::parse(&test_case.uri)) .unwrap(); let hosts: Vec<_> = options .hosts .into_iter() .map(StreamAddress::into_document) .collect(); ...
adpreferencetags", tags); } if let Some(i) = max_staleness { doc.insert("maxstalenessseconds", i.as_secs() as i64); } } if let Some(b) = options.retry_reads.take() { doc.insert("retryreads", b); } if let Some(b) = options.retry_writes.take() { doc.i...
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": 304714.2147247278 }, { "conte...
Rust
tremor-pipeline/src/op/runtime/tremor.rs
0xd34b33f/tremor-runtime
73af8033509e224e4cbf078559f27bec4c12cf3d
use crate::op::prelude::*; use crate::FN_REGISTRY; use simd_json::borrowed::Value; use tremor_script::highlighter::Dumb as DumbHighlighter; use tremor_script::path::load as load_module_path; use tremor_script::prelude::*; use tremor_script::{self, AggrType, EventContext, Return, Script}; op!(TremorFactory(node) { ...
use crate::op::prelude::*; use crate::FN_REGISTRY; use simd_json::borrowed::Value; use tremor_script::highlighter::Dumb as DumbHighlighter; use tremor_script::path::load as load_module_path; use tremor_script::prelude::*; use tremor_script::{self, AggrType, EventContext, Return, Script}; op!(TremorFactory(node) { ...
t_eq!("out", out); assert_eq!( *event.data.suffix().value(), Value::from(json!({"snot": "badger", "a": 1})) ) } #[test] pub fn test_how_it_handles_errors() { let config = Config { script: r#"match this is invalid code so no match case"#.to_string...
.id.clone().to_string()).into()) } }); #[derive(Debug, Clone, Deserialize)] struct Config { script: String, } impl ConfigImpl for Config {} #[derive(Debug)] pub struct Tremor { config: Config, runtime: Script, id: String, } impl Operator for Tremor { fn on_event( &mut self, _i...
random
[]
Rust
node/src/components/rpc_server/rpcs/docs.rs
sacherjj/casper-node
2569ebd51923d0353542c93c5d47480246170cbb
#![allow(clippy::field_reassign_with_default)] use futures::{future::BoxFuture, FutureExt}; use http::Response; use hyper::Body; use once_cell::sync::Lazy; use schemars::{ gen::{SchemaGenerator, SchemaSettings}, schema::Schema, JsonSchema, Map, MapEntry, }; use semver::Version; use serde::{Deserialize, S...
#![allow(clippy::field_reassign_with_default)] use futures::{future::BoxFuture, FutureExt}; use http::Response; use hyper::Body; use once_cell::sync::Lazy; use schemars::{ gen::{SchemaGenerator, SchemaSettings}, schema::Schema, JsonSchema, Map, MapEntry, }; use semver::Version; use serde::{Deserialize, S...
; Example { name: format!("{}_example", method_name), params, result: ExampleResult { name: format!("{}_example_result", method_name), value: result_value, }, } } fn from_rpc_with_params<T: RpcWithParams>() -> Self...
match maybe_params_obj { Some(params_obj) => params_obj .as_object() .unwrap() .iter() .map(|(name, value)| ExampleParam { name: name.clone(), value: value.clone(), }) .col...
if_condition
[ { "content": "fn dependencies(values: &[&str]) -> Result<Vec<DeployHash>> {\n\n let mut hashes = Vec::with_capacity(values.len());\n\n for value in values {\n\n let digest = Digest::from_hex(value).map_err(|error| Error::CryptoError {\n\n context: \"dependencies\",\n\n error,\...
Rust
src/poller.rs
dwrensha/multipoll
91eddb3bf9281c5d300efbef9a7b605a3e1a0122
use std::pin::Pin; use std::task::{Context, Poll}; use futures::{Future, FutureExt, Stream}; use futures::stream::FuturesUnordered; use futures::channel::mpsc; use std::cell::{RefCell}; use std::rc::Rc; enum EnqueuedTask<E> { Task(Pin<Box<dyn Future<Output=Result<(), E>>>>), Terminate(Result<(), E>), } enum ...
use std::pin::Pin; use std::task::{Context, Poll}; use futures::{Future, FutureExt, Stream}; use futures::stream::FuturesUnordered; use futures::channel::mpsc; use std::cell::{RefCell}; use std::rc::Rc; enum EnqueuedTask<E> { Task(Pin<Box<dyn Future<Output=Result<(), E>>>>), Terminate(Result<(), E>), } enum ...
ueued_stream_complete = true; break; } Poll::Ready(Some(EnqueuedTask::Terminate(r))) => { in_progress.push(TaskInProgress::Terminate(Some(r))); } Poll::Ready(Some(EnqueuedTask::Task(f))) => { ...
ler<E> where E: 'static { type Output = Result<(),E>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let mut enqueued_stream_complete = false; if let Poller { enqueued: Some(ref mut enqueued), ref mut in_progress, ref reaper, ..} = self.as_mut().get_mut() { ...
random
[ { "content": "multipoll\n\n=========\n\n\n", "file_path": "README.md", "rank": 4, "score": 7310.110037664616 }, { "content": "extern crate futures;\n\n\n\npub use poller::{Poller, PollerHandle, Finisher};\n\n\n\nmod poller;\n", "file_path": "src/lib.rs", "rank": 11, "score": 6.24...
Rust
src/contract.rs
SivaS2003/cw-template
2d75e09e2a9dfd65813bcfd71fa54fb888df33f7
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Coin, BankMsg, has_coins}; use cosmwasm_std::Addr; use cw2::set_contract_version; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, Que...
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Coin, BankMsg, has_coins}; use cosmwasm_std::Addr; use cw2::set_contract_version; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, Que...
} #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::RenterAdd {} => try_add(deps, env, info), ExecuteMsg::RenterPay {} => try_pay(deps,...
Ok(Response::new() .add_attribute("method", "instantiate") .add_attribute("owner", info.sender) .add_attribute("address", msg.address))
call_expression
[ { "content": "fn main() {\n\n let mut out_dir = current_dir().unwrap();\n\n out_dir.push(\"schema\");\n\n create_dir_all(&out_dir).unwrap();\n\n remove_schemas(&out_dir).unwrap();\n\n\n\n export_schema(&schema_for!(InstantiateMsg), &out_dir);\n\n export_schema(&schema_for!(ExecuteMsg), &out_di...
Rust
src/asm/x86/predict.rs
kevleyski/rav1e
d9492a21b007eea38fa5a1409249e75502dfafa6
use crate::context::MAX_TX_SIZE; use crate::cpu_features::CpuFeatureLevel; use crate::predict::{ rust, IntraEdgeFilterParameters, PredictionMode, PredictionVariant, }; use crate::tiling::PlaneRegionMut; use crate::transform::TxSize; use crate::util::Aligned; use crate::Pixel; use v_frame::pixel::PixelType; macro_r...
use crate::context::MAX_TX_SIZE; use crate::cpu_features::CpuFeatureLevel; use crate::predict::{ rust, IntraEdgeFilterParameters, PredictionMode, PredictionVariant, }; use crate::tiling::PlaneRegionMut; use crate::transform::TxSize; use crate::util::Aligned; use crate::Pixel; use v_frame::pixel::PixelType; macro_r...
3( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::PAETH_PRED => { rav1e_ipred_paeth_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::UV_CFL_PRED => { let ac_ptr = ac.as_ptr() as *const...
function_block-function_prefixed
[ { "content": "pub fn ac_q(qindex: u8, delta_q: i8, bit_depth: usize) -> i16 {\n\n static AC_Q: [&[i16; 256]; 3] =\n\n [&ac_qlookup_Q3, &ac_qlookup_10_Q3, &ac_qlookup_12_Q3];\n\n let bd = ((bit_depth ^ 8) >> 1).min(2);\n\n AC_Q[bd][((qindex as isize + delta_q as isize).max(0) as usize).min(255)]\n\n}\n\n\n...
Rust
src/embeds/osu/pinned.rs
JoshiDhima/Bathbot
7a8dd8a768caede285df4f8ea5aead27bdbbf660
use std::fmt::Write; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{Beatmapset, GameMode, Score, User}; use crate::{ commands::osu::TopOrder, core::Context, embeds::{osu, Author, Footer}, pp::PpCalculator, util::{ constants::OSU_BASE, datetime::how_long_ago_dynamic, numbe...
use std::fmt::Write; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{Beatmapset, GameMode, Score, User}; use crate::{ commands::osu::TopOrder, core::Context, embeds::{osu, Author, Footer}, pp::PpCalculator, util::{ constants::OSU_BASE, datetime::how_long_ago_dynamic, numbe...
} fn mode_str(mode: GameMode) -> &'static str { match mode { GameMode::STD => "osu!", GameMode::TKO => "Taiko", GameMode::CTB => "Catch", GameMode::MNA => "Mania", } } impl_builder!(PinnedEmbed { author, description, footer, thumbnail, });
stars = osu::get_stars(stars); let pp = osu::get_pp(pp, max_pp); let mapset_opt = if let ScoreOrder::RankedDate = sort_by { let mapset_fut = ctx.psql().get_beatmapset::<Beatmapset>(mapset.mapset_id); match mapset_fut.await { Ok(mapset) => Som...
function_block-function_prefixed
[ { "content": "fn new_pp(pp: f32, user: &User, scores: &[Score], actual_offset: f32) -> (usize, f32) {\n\n let actual: f32 = scores\n\n .iter()\n\n .filter_map(|s| s.weight)\n\n .fold(0.0, |sum, weight| sum + weight.pp);\n\n\n\n let total = user.statistics.as_ref().map_or(0.0, |stats| ...
Rust
src/platform_impl/web/event_loop/window_target.rs
michaelkirk/winit
412bd94ea473c7b175f94a190d66f4be3e92aaab
use super::{super::monitor, backend, device, proxy::Proxy, runner, window}; use crate::dpi::{PhysicalSize, Size}; use crate::event::{DeviceId, ElementState, Event, KeyboardInput, TouchPhase, WindowEvent}; use crate::event_loop::ControlFlow; use crate::window::{Theme, WindowId}; use std::clone::Clone; use std::collectio...
use super::{super::monitor, backend, device, proxy::Proxy, runner, window}; use crate::dpi::{PhysicalSize, Size}; use crate::event::{DeviceId, ElementState, Event, KeyboardInput, TouchPhase, WindowEvent}; use crate::event_loop::ControlFlow; use crate::window::{Theme, WindowId}; use std::clone::Clone; use std::collectio...
}
device_id: DeviceId(device::Id(pointer_id)), position, modifiers, }, }); }); let runner = self.runner.clone(); canvas.on_mouse_press(move |pointer_id, button, modifiers| { runner.send_event(Event...
random
[ { "content": "pub fn event_mods(event: id) -> ModifiersState {\n\n let flags = unsafe { NSEvent::modifierFlags(event) };\n\n let mut m = ModifiersState::empty();\n\n m.set(\n\n ModifiersState::SHIFT,\n\n flags.contains(NSEventModifierFlags::NSShiftKeyMask),\n\n );\n\n m.set(\n\n ...
Rust
crates/oci-distribution/src/reference.rs
thomastaylor312/krustlet
a99a507bda67595a07713860e1c13ab40f977bad
use std::convert::{Into, TryFrom}; use std::error::Error; use std::fmt; use std::path::PathBuf; use std::str::FromStr; const NAME_TOTAL_LENGTH_MAX: usize = 255; #[derive(Debug, PartialEq, Eq)] pub enum ParseError { DigestInvalidFormat, NameContainsUppercase, NameEmpty, NameNotCanonical, NameTooLon...
use std::convert::{Into, TryFrom}; use std::error::Error; use std::fmt; use std::path::PathBuf; use std::str::FromStr; const NAME_TOTAL_LENGTH_MAX: usize = 255; #[derive(Debug, PartialEq, Eq)] pub enum ParseError { DigestInvalidFormat, NameContainsUppercase, NameEmpty, NameNotCanonical, NameTooLon...
#[test] fn name_too_long() { assert_eq!( Reference::try_from(format!( "webassembly.azurecr.io/{}", (0..256).map(|_| "a").collect::<String>() )) .err(), Some(ParseError::NameTooLong) ...
fn validate_digest(reference: &Reference) { assert_eq!( reference.digest(), Some("sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9") ); }
function_block-full_function
[ { "content": "fn config_file_path_str(file_name: impl AsRef<std::path::Path>) -> String {\n\n config_dir().join(file_name).to_str().unwrap().to_owned()\n\n}\n\n\n", "file_path": "tests/oneclick/src/main.rs", "rank": 0, "score": 299495.3732690705 }, { "content": "fn warn_if_premature_exit(...
Rust
src_testbed/nphysics_backend.rs
sebcrozet/rapier
b61bec83487224c285a1e95ac58d48885254285b
use ncollide::shape::{Ball, Capsule, Cuboid, ShapeHandle}; use nphysics::force_generator::DefaultForceGeneratorSet; use nphysics::joint::{ DefaultJointConstraintSet, FixedConstraint, PrismaticConstraint, RevoluteConstraint, }; use nphysics::object::{ BodyPartHandle, ColliderDesc, DefaultBodyHandle, DefaultBodyS...
use ncollide::shape::{Ball, Capsule, Cuboid, ShapeHandle}; use nphysics::force_generator::DefaultForceGeneratorSet; use nphysics::joint::{ DefaultJointConstraintSet, FixedConstraint, PrismaticConstraint, RevoluteConstraint, }; use nphysics::object::{ BodyPartHandle, ColliderDesc, DefaultBodyHandle, DefaultBodyS...
}
Some( ColliderDesc::new(shape) .position(pos) .density(density) .sensor(collider.is_sensor()), )
call_expression
[ { "content": "pub fn generate_contacts_trimesh_shape(ctxt: &mut ContactGenerationContext) {\n\n let collider1 = &ctxt.colliders[ctxt.pair.pair.collider1];\n\n let collider2 = &ctxt.colliders[ctxt.pair.pair.collider2];\n\n\n\n if let Some(trimesh1) = collider1.shape().as_trimesh() {\n\n do_genera...
Rust
tests/cli-v1.rs
Boddlnagg/rustup.rs
c4e7616c565630d0ad93767ec8676c8a570995c5
extern crate rustup_dist; extern crate rustup_utils; extern crate rustup_mock; extern crate tempdir; use std::fs; use tempdir::TempDir; use rustup_mock::clitools::{self, Config, Scenario, expect_ok, expect_stdout_ok, expect_err, expect_stderr_ok, set_current_di...
extern crate rustup_dist; extern crate rustup_utils; extern crate rustup_mock; extern crate tempdir; use std::fs; use tempdir::TempDir; use rustup_mock::clitools::{self, Config, Scenario, expect_ok, expect_stdout_ok, expect_err, expect_stderr_ok, set_current_di...
#[test] fn default_existing_toolchain() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_stderr_ok(config, &["rustup", "default", "nightly"], for_host!("using existing install for 'nightly-{0}'")); }); } #[test] fn update_channel() { ...
fn install_toolchain_from_version() { setup(&|config| { expect_ok(config, &["rustup", "default" , "1.1.0"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); }
function_block-full_function
[ { "content": "pub fn rustc_version(toolchain: &Toolchain) -> String {\n\n if toolchain.exists() {\n\n let rustc_path = toolchain.binary_file(\"rustc\");\n\n if utils::is_file(&rustc_path) {\n\n let mut cmd = Command::new(&rustc_path);\n\n cmd.arg(\"--version\");\n\n ...
Rust
src/bin/vessel.rs
ByronBecker/vessel
a2c2d3c2ffe39b3802a82be512f812e75ee32ea2
use anyhow::Result; use fern::colors::ColoredLevelConfig; use fern::Output; use log::LevelFilter; use std::io::Write; use std::path::PathBuf; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(about = "Simple package management for Motoko")] struct Opts { #[structopt(long, parse(from_os_str), d...
use anyhow::Result; use fern::colors::ColoredLevelConfig; use fern::Output; use log::LevelFilter; use std::io::Write; use std::path::PathBuf; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(about = "Simple package management for Motoko")] struct Opts { #[structopt(long, parse(from_os_str), d...
bin_path.join("moc") } (Some(_), Some(_)) => { return Err(anyhow::anyhow!( "The --version and --moc flags are mutually exclusive." )) } }; match package { N...
Vessel::new(&opts.package_set)?; let path = vessel.install_compiler()?; print!("{}", path.display().to_string()); std::io::stdout().flush()?; Ok(()) } Command::Sources => { let vessel = vessel::Vessel::new(&opts.package_set)?; let s...
function_block-random_span
[ { "content": "/// Like `fetch_latest_package_set`, but lets you specify the tag\n\npub fn fetch_package_set(tag: &str) -> Result<(Url, Hash)> {\n\n let client = reqwest::blocking::Client::new();\n\n fetch_package_set_impl(&client, tag)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score"...
Rust
crates/binding_core_node/src/parse.rs
10088/swc
6bc39005bb851b57f4f49b046688f4acc6e850f3
use std::{ path::{Path, PathBuf}, sync::Arc, }; use anyhow::Context as _; use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Env, Task, }; use swc::{ config::{ErrorFormat, ParseOptions}, Compiler, }; use swc_common::{comments::Comments, FileName}; use swc_nodejs_common::{deserialize...
use std::{ path::{Path, PathBuf}, sync::Arc, }; use anyhow::Context as _; use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Env, Task, }; use swc::{ config::{ErrorFormat, ParseOptions}, Compiler, }; use swc_common::{comments::Comments, FileName}; use swc_nodejs_common::{deserialize...
c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) }) .convert_err()?; Ok(serde_json::to_string(&program)?) } #[napi] pub fn parse_file_...
let comments = if options.comments { Some(c.comments() as &dyn Comments) } else { None };
assignment_statement
[]
Rust
rlp/src/impls.rs
Byeongjee/rlp
6a4c2c39f76eba2b3b68863941cd64fddee3e5cc
use super::stream::RlpStream; use super::traits::{Decodable, Encodable}; use super::{DecoderError, Rlp}; use primitives::{H128, H160, H256, H384, H512, H520, H768, U256}; use std::iter::{empty, once}; use std::{cmp, mem, str}; pub fn decode_usize(bytes: &[u8]) -> Result<usize, DecoderError> { let expected = mem:...
use super::stream::RlpStream; use super::traits::{Decodable, Encodable}; use super::{DecoderError, Rlp}; use primitives::{H128, H160, H256, H384, H512, H520, H768, U256}; use std::iter::{empty, once}; use std::{cmp, mem, str}; pub fn decode_usize(bytes: &[u8]) -> Result<usize, DecoderError> { let expected = mem:...
} impl<T> Decodable for Option<T> where T: Decodable, { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { let items = rlp.item_count()?; match items { 1 => rlp.val_at(0).map(Some), 0 => Ok(None), got => Err(DecoderError::RlpIncorrectListLen { ...
s.begin_list(0); } Some(ref value) => { s.begin_list(1); s.append(value); } } }
function_block-function_prefix_line
[ { "content": "/// Shortcut function to encode structure into rlp.\n\n///\n\n/// ```rust\n\n/// fn main () {\n\n/// \tlet animal = \"cat\";\n\n/// \tlet out = rlp::encode(&animal);\n\n/// \tassert_eq!(out, vec![0x83, b'c', b'a', b't']);\n\n/// }\n\n/// ```\n\npub fn encode<E>(object: &E) -> Vec<u8>\n\nwhere\n\n ...
Rust
src/main.rs
MeiK2333/river
1106b73423620bd70af37d9f41f683c0bcf4293c
#![recursion_limit = "512"] #[macro_use] extern crate log; use std::path::Path; use std::pin::Pin; use futures::StreamExt; use futures_core::Stream; use log4rs; use tempfile::tempdir_in; use tokio::fs::read_dir; use tonic::transport::Server; use tonic::{Request, Response, Status}; use river::judge_request::Data; use...
#![recursion_limit = "512"] #[macro_use] extern crate log; use std::path::Path; use std::pin::Pin; use futures::StreamExt; use futures_core::Stream; use log4rs; use tempfile::tempdir_in; use tokio::fs::read_dir; use tonic::transport::Server; use tonic::{Request, Response, Status}; use river::judge_request::Data; use...
async fn main() -> Result<(), Box<dyn std::error::Error>> { log4rs::init_file("log4rs.yaml", Default::default()).unwrap(); let addr = "0.0.0.0:4003".parse()?; let river = RiverService::default(); info!("listen on: {}", addr); Server::builder() .concurrency_limit_per_connection(5) ...
function_block-full_function
[ { "content": "pub fn system_error(err: Error) -> JudgeResponse {\n\n warn!(\"{}\", err);\n\n JudgeResponse {\n\n state: Some(State::Result(JudgeResult {\n\n time_used: 0,\n\n memory_used: 0,\n\n result: JudgeResultEnum::SystemError as i32,\n\n errmsg: for...
Rust
src/sys/windows/mod.rs
jmagnuson/mio
40df934a11b05233a7796c4de19a4ee06bc4e03e
mod afd; mod io_status_block; pub mod event; pub use event::{Event, Events}; mod selector; pub use selector::{Selector, SelectorInner, SockState}; cfg_net! { macro_rules! syscall { ($fn: ident ( $($arg: expr),* $(,)* ), $err_test: path, $err_value: expr) => {{ let res = unsafe ...
mod afd; mod io_status_block; pub mod event; pub use event::{Event, Events}; mod selector; pub use selector::{Selector, SelectorInner, SockState}; cfg_net! { macro_rules! syscall { ($fn: ident ( $($arg: expr),* $(,)* ), $err_test: path, $err_value: expr) => {{ let res = unsafe ...
f e.kind() == io::ErrorKind::WouldBlock { self.inner.as_ref().map_or(Ok(()), |state| { state .selector .reregister(state.sock_state.clone(), state.token, state.interests) })?; } ...
() -> IoSourceState { IoSourceState { inner: None } } pub fn do_io<T, F, R>(&self, f: F, io: &T) -> io::Result<R> where F: FnOnce(&T) -> io::Result<R>, { let result = f(io); if let Err(ref e) = result { i
random
[ { "content": "fn expect_waker_event(poll: &mut Poll, events: &mut Events, token: Token) {\n\n poll.poll(events, Some(Duration::from_millis(100))).unwrap();\n\n assert!(!events.is_empty());\n\n for event in events.iter() {\n\n assert_eq!(event.token(), token);\n\n assert!(event.is_readable...
Rust
sway-core/src/parse_tree/declaration/reassignment.rs
mitchmindtree/sway
38479274e0c50518e20c919682b8173ae4a555d3
use crate::build_config::BuildConfig; use crate::error::{err, ok, CompileError, CompileResult}; use crate::parse_tree::Expression; use crate::parser::Rule; use crate::span::Span; use crate::{parse_array_index, Ident}; use pest::iterators::Pair; #[derive(Debug, Clone)] pub struct Reassignment { pub lhs: Box<Ex...
use crate::build_config::BuildConfig; use crate::error::{err, ok, CompileError, CompileResult}; use crate::parse_tree::Expression; use crate::parser::Rule; use crate::span::Span; use crate::{parse_array_index, Ident}; use pest::iterators::Pair; #[derive(Debug, Clone)] pub struct Reassignment { pub lhs: Box<Ex...
let body = iter.next().unwrap(); let body = check!( Expression::parse_from_pair(body.clone(), config), Expression::Tuple { fields: vec![], span: Span { span: body.as_span(...
let name = check!( Expression::parse_from_pair_inner(iter.next().unwrap(), config), return err(warnings, errors), warnings, errors );
assignment_statement
[ { "content": "fn disallow_opcode(op: &Ident) -> Vec<CompileError> {\n\n let mut errors = vec![];\n\n\n\n match op.as_str().to_lowercase().as_str() {\n\n \"jnei\" => {\n\n errors.push(CompileError::DisallowedJnei {\n\n span: op.span().clone(),\n\n });\n\n ...
Rust
src/interchange/src/avro/encode.rs
jiangyuzhao/materialize
2f8bf7a64197cff27e43132f251d5908f2f9e520
use std::fmt; use byteorder::{NetworkEndian, WriteBytesExt}; use chrono::Timelike; use itertools::Itertools; use lazy_static::lazy_static; use mz_avro::types::AvroMap; use repr::adt::jsonb::JsonbRef; use repr::adt::numeric::{self, NUMERIC_AGG_MAX_PRECISION, NUMERIC_DATUM_MAX_PRECISION}; use repr::{ColumnName, Column...
use std::fmt; use byteorder::{NetworkEndian, WriteBytesExt}; use chrono::Timelike; use itertools::Itertools; use lazy_static::lazy_static; use mz_avro::types::AvroMap; use repr::adt::jsonb::JsonbRef; use repr::adt::numeric::{self, NUMERIC_AGG_MAX_PRECISION, NUMERIC_DATUM_MAX_PRECISION}; use repr::{ColumnName, Column...
impl<'a> mz_avro::types::ToAvro for TypedDatum<'a> { fn avro(self) -> Value { let TypedDatum { datum, typ } = self; if typ.nullable && datum.is_null() { Value::Union { index: 0, inner: Box::new(Value::Null), n_variants: 2, ...
I: IntoIterator<Item = Datum<'a>>, { let value_fields: Vec<(String, Value)> = names_types .iter() .zip_eq(datums) .map(|((name, typ), datum)| { let name = name.as_str().to_owned(); use mz_avro::types::ToAvro; (name, TypedDatum::new(datum, typ.clone()).avro...
function_block-function_prefix_line
[ { "content": "/// Encode a `Value` into avro format.\n\n///\n\n/// **NOTE** This will not perform schema validation. The value is assumed to\n\n/// be valid with regards to the schema. Schema are needed only to guide the\n\n/// encoding for complex type values.\n\npub fn encode_ref(value: &Value, schema: Schema...
Rust
src/comglue/glue.rs
estokes/netidx-excel
959d7b8f02188970a26b8130a4072767b22124bb
use crate::{ comglue::{ dispatch::IRTDUpdateEventWrap, interface::{IDispatch, IRTDServer, IRTDUpdateEvent}, variant::{string_from_wstr, SafeArray, Variant}, }, server::{Server, TopicId}, }; use anyhow::{bail, Result}; use com::sys::{HRESULT, IID, NOERROR}; use log::{debug, error}; us...
use crate::{ comglue::{ dispatch::IRTDUpdateEventWrap, interface::{IDispatch, IRTDServer, IRTDUpdateEvent}, variant::{string_from_wstr, SafeArray, Variant}, }, server::{Server, TopicId}, }; use anyhow::{bail, Result}; use com::sys::{HRESULT, IID, NOERROR}; use log::{debug, error}; us...
}, } NOERROR } } impl IRTDServer for NetidxRTD { fn server_start(&self, _cb: *const IRTDUpdateEvent, _res: *mut i32) -> HRESULT { debug!("ServerStart called directly"); NOERROR } fn connect_data(&self, _topic_id: i32, _topi...
{ *wh.get_mut(&[0, i as i32])? = Variant::from(tid); *wh.get_mut(&[1, i as i32])? = variant_of_event(&e); } } *result = Variant::from(array); Ok(()) } unsafe fn dispatch_disconnect_data(server: &Server, params: Params) -> Result<()> { let topic_id = TopicId(params.get(0...
random
[ { "content": "fn next_index(bounds: &[SAFEARRAYBOUND], idx: &mut [i32]) -> bool {\n\n let mut i = 0;\n\n while i < bounds.len() {\n\n if idx[i] < (bounds[i].lLbound + bounds[i].cElements as i32) {\n\n idx[i] += 1;\n\n for j in 0..i {\n\n idx[j] = bounds[j].lLbou...
Rust
app/gui/src/presenter.rs
hubertp/enso
d3846578cceb4844f1f94d4e7ca51762bba3fada
pub mod code; pub mod graph; pub mod project; pub mod searcher; pub use code::Code; pub use graph::Graph; pub use project::Project; pub use searcher::Searcher; use crate::prelude::*; use crate::controller::ide::StatusNotification; use crate::executor::global::spawn_stream_handler; use crate::presenter; use enso_f...
pub mod code; pub mod graph; pub mod project; pub mod searcher; pub use code::Code; pub use graph::Graph; pub use project::Project; pub use searcher::Searcher; use crate::prelude::*; use crate::controller::ide::StatusNotification; use crate::executor::global::spawn_stream_handler; use crate::presenter; use enso_f...
fn setup_status_bar_notification_handler(&self) { use controller::ide::BackgroundTaskHandle as ControllerHandle; use ide_view::status_bar::process::Id as ViewHandle; let logger = self.model.logger.clone_ref(); let process_map = SharedHashMap::<ControllerHandle, ViewHandle>::new();...
self.setup_controller_notification_handler(); self.set_projects_list_on_welcome_screen(); self.model.clone_ref().setup_and_display_new_project(); self }
function_block-function_prefix_line
[ { "content": "/// Create providers from the current controller's action list.\n\npub fn create_providers_from_controller(logger: &Logger, controller: &controller::Searcher) -> Any {\n\n use controller::searcher::Actions;\n\n match controller.actions() {\n\n Actions::Loading => as_any(Rc::new(list_v...
Rust
examples/log-sensors.rs
quietlychris/f3
7ccc6f26fe16a4c053d09bcc61434c422f24d82f
#![deny(warnings)] #![no_main] #![no_std] extern crate panic_semihosting; use core::ptr; use aligned::Aligned; use byteorder::{ByteOrder, LE}; use cortex_m::{asm, itm}; use cortex_m_rt::entry; use f3::{ hal::{i2c::I2c, prelude::*, spi::Spi, stm32f30x, timer::Timer}, l3gd20::{self, Odr}, lsm303dlhc::{Ac...
#![deny(warnings)] #![no_main] #![no_std] extern crate panic_semihosting; use core::ptr; use aligned::Aligned; use byteorder::{ByteOrder, LE}; use cortex_m::{asm, itm}; use cortex_m_rt::entry; use f3::{ hal::{i2c::I2c, prelude::*, spi::Spi, stm32f30x, timer::Timer}, l3gd20::{self, Odr}, lsm303dlhc::{Ac...
LE::write_i16(&mut buf[start..start + 2], ar.x); start += 2; LE::write_i16(&mut buf[start..start + 2], ar.y); start += 2; LE::write_i16(&mut buf[start..start + 2], ar.z); start += 2; LE::write_i16(&mut buf[start..start + 2], g.x); start += 2; LE:...
timer.wait()).unwrap(); let m = lsm303dlhc.mag().unwrap(); let ar = l3gd20.gyro().unwrap(); let g = lsm303dlhc.accel().unwrap(); let mut buf = [0; 18]; let mut start = 0; LE::write_i16(&mut buf[start..start + 2], m.x); start += 2; LE::...
random
[ { "content": "#[entry]\n\nfn main() -> ! {\n\n let p = cortex_m::Peripherals::take().unwrap();\n\n let mut itm = p.ITM;\n\n\n\n iprintln!(&mut itm.stim[0], \"Hello, world!\");\n\n\n\n asm::bkpt();\n\n\n\n loop {}\n\n}\n", "file_path": "examples/itm.rs", "rank": 0, "score": 89875.80130...
Rust
benchmark/src/main.rs
negamartin/midly
6881b0b1cf55ef5aa8e8573a9176f14334e02555
use std::{ env, fs, path::{Path, PathBuf}, time::Instant, }; const MIDI_DIR: &str = "../test-asset"; const MIDI_EXT: &[&str] = &["mid", "midi", "rmi"]; const PARSERS: &[(&str, fn(&Path) -> Result<usize, String>)] = &[ (&"midly", parse_midly), (&"nom-midi", parse_nom), (&"rimd", parse_rimd), ]...
use std::{ env, fs, path::{Path, PathBuf}, time::Instant, }; const MIDI_DIR: &str = "../test-asset"; const MIDI_EXT: &[&str] = &["mid", "midi", "rmi"]; const PARSERS: &[(&str, fn(&Path) -> Result<usize, String>)] = &[ (&"midly", parse_midly), (&"nom-midi", parse_nom), (&"rimd", parse_rimd), ]...
fn main() { let midi_filter = env::args().nth(1).unwrap_or_default().to_lowercase(); let parser_filter = env::args().nth(2).unwrap_or_default().to_lowercase(); let midi_dir = env::args().nth(3).unwrap_or(MIDI_DIR.to_string()); let parsers = PARSERS .iter() .filter(|(name, _)| name.con...
let avg_time = round(total_time / (iters as f64)); eprintln!( "{} tracks in {} iters / min {} / avg {} / max {}", track_count, iters, min_time, avg_time, max_time ); Ok(()) }
function_block-function_prefix_line
[ { "content": "#[cfg(feature = \"alloc\")]\n\nfn validate_smf(header: &Header, track_count_hint: u16, track_count: usize) -> Result<()> {\n\n if cfg!(feature = \"strict\") {\n\n ensure!(\n\n track_count_hint as usize == track_count,\n\n err_malformed!(\"file has a different amount...
Rust
crates/rust-analyzer/src/config.rs
theHamsta/rust-analyzer
f7f01dd5f0a8254abeefb0156e2c4ebe1447bfb6
use std::{ffi::OsString, path::PathBuf}; use lsp_types::ClientCapabilities; use ra_flycheck::FlycheckConfig; use ra_ide::{AssistConfig, CompletionConfig, InlayHintsConfig}; use ra_project_model::CargoConfig; use serde::Deserialize; #[derive(Debug, Clone)] pub struct Config { pub client_caps: ClientCapsConfig, ...
use std::{ffi::OsString, path::PathBuf}; use lsp_types::ClientCapabilities; use ra_flycheck::FlycheckConfig; use ra_ide::{AssistConfig, CompletionConfig, InlayHintsConfig}; use ra_project_model::CargoConfig; use serde::Deserialize; #[derive(Debug, Clone)] pub struct Config { pub client_caps: ClientCapsConfig, ...
} impl Config { #[rustfmt::skip] pub fn update(&mut self, value: &serde_json::Value) { log::info!("Config::update({:#})", value); let client_caps = self.client_caps.clone(); *self = Default::default(); self.client_caps = client_caps; set(value, "/withSysroot", &mut se...
cargo: CargoConfig::default(), rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() }, check: Some(FlycheckConfig::CargoCommand { command: "check".to_string(), all_targets: true, all_features: true, extra_args: Vec::new(), ...
function_block-function_prefix_line
[ { "content": "pub fn run_dist(nightly: bool, client_version: Option<String>) -> Result<()> {\n\n let dist = project_root().join(\"dist\");\n\n rm_rf(&dist)?;\n\n fs2::create_dir_all(&dist)?;\n\n\n\n if let Some(version) = client_version {\n\n let release_tag = if nightly { \"nightly\".to_stri...
Rust
wasm/src/context.rs
PoiScript/blog
e6b08531d30bcb41a5fde53bfe07eb20f2a152c8
use chrono::serde::{ts_milliseconds, ts_milliseconds_option}; use chrono::{DateTime, Utc}; use maud::Markup; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use wasm_bindgen::prelude::*; #[derive(Debug, Serialize, Deserialize)] pub struct OrgMeta { pub slug: String, pub title: String, ...
use chrono::serde::{ts_milliseconds, ts_milliseconds_option}; use chrono::{DateTime, Utc}; use maud::Markup; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use wasm_bindgen::prelude::*; #[derive(Debug, Serialize, Deserialize)] pub struct OrgMeta { pub slug: String, pub title: String, ...
#[wasm_bindgen] pub fn get_status(&self) -> u32 { match self.content { Content::Amp { status, .. } => status, Content::Html { status, .. } => status, Content::Rss { status, .. } => status, Content::Txt { status, .. } => status, } } #[was...
pub fn get_type(&self) -> String { match self.content { Content::Txt { .. } => "txt", Content::Amp { .. } => "amp", Content::Html { .. } => "html", Content::Rss { .. } => "rss", } .into() }
function_block-function_prefix_line
[ { "content": "pub fn get_id(n: usize, s: &str) -> String {\n\n let mut hasher = DefaultHasher::new();\n\n\n\n for c in s.chars() {\n\n hasher.write_u32(c as u32);\n\n }\n\n\n\n format!(\"{n:02x}{:.6x}\", hasher.finish() as u32)\n\n}\n", "file_path": "wasm/src/utils.rs", "rank": 0, ...
Rust
tests/poll.rs
Licenser/mio
0d8f48d24c577e5379c936e72610a997aa716e8c
use mio::net::{TcpListener, TcpStream}; use mio::*; use std::net; use std::sync::{Arc, Barrier}; use std::thread::{self, sleep}; use std::time::Duration; mod util; use util::{any_local_address, assert_send, assert_sync, init}; #[test] fn is_send_and_sync() { assert_sync::<Poll>(); assert_send::<Poll>(); ...
use mio::net::{TcpListener, TcpStream}; use mio::*; use std::net; use std::sync::{Arc, Barrier}; use std::thread::{self, sleep}; use std::time::Duration; mod util; use util::{any_local_address, assert_send, assert_sync, init}; #[test] fn is_send_and_sync() { assert_sync::<Poll>(); assert_send::<Poll>(); ...
#[test] fn add_then_drop() { init(); let mut events = Events::with_capacity(16); let l = TcpListener::bind(any_local_address()).unwrap(); let mut poll = Poll::new().unwrap(); poll.registry() .register(&l, Token(1), Interests::READABLE | Interests::WRITABLE) .unwrap(); drop(l);...
fn run_once_with_nothing() { init(); let mut events = Events::with_capacity(16); let mut poll = Poll::new().unwrap(); poll.poll(&mut events, Some(Duration::from_millis(100))) .unwrap(); }
function_block-full_function
[ { "content": "pub fn init() {\n\n static INIT: Once = Once::new();\n\n\n\n INIT.call_once(|| {\n\n env_logger::try_init().expect(\"unable to initialise logger\");\n\n })\n\n}\n\n\n", "file_path": "tests/util/mod.rs", "rank": 0, "score": 197869.68898741424 }, { "content": "///...
Rust
src/direct.rs
passcod/streampager
b562cb044029a9f67512d4a5ca8bf6fd3a490f30
use crate::config::{InterfaceMode, WrappingMode}; use crate::event::{Event, EventStream}; use crate::file::File; use crate::line::Line; use crate::progress::Progress; use anyhow::Result; use bit_set::BitSet; use std::time::{Duration, Instant}; use termwiz::input::InputEvent; use termwiz::surface::change::Change; use ...
use crate::config::{InterfaceMode, WrappingMode}; use crate::event::{Event, EventStream}; use crate::file::File; use crate::line::Line; use crate::progress::Progress; use anyhow::Result; use bit_set::BitSet; use std::time::{Duration, Instant}; use termwiz::input::InputEvent; use termwiz::surface::change::Change; use ...
#[derive(Default)] struct StreamingLines { past_output_row_count: usize, new_output_lines: Vec<Vec<u8>>, error_lines: Vec<Vec<u8>>, progress_lines: Vec<Vec<u8>>, erase_row_count: usize, pending_changes: bool, } impl StreamingLines { fn add_lines( &mut self, mut append_outp...
e); } _ => (), } } _ => (), } if let Some(deadline) = delayed_deadline { if deadline <= Instant::now() { return Ok(Outcome::RenderNothing); } } if let Some(outcome) = r...
function_block-function_prefixed
[ { "content": "/// Determine the rendering width for a character.\n\nfn render_width(c: char) -> usize {\n\n if c < ' ' || c == '\\x7F' {\n\n // Render as <XX>\n\n 4\n\n } else if let Some(w) = c.width() {\n\n // Render as the character itself\n\n w\n\n } else {\n\n //...
Rust
automerge-backend/src/backend.rs
gterzian/automerge-rs
a81a37dfb4eef71dbdf5016cd65289b652f19c38
use crate::actor_map::ActorMap; use crate::change::encode_document; use crate::error::AutomergeError; use crate::internal::ObjectId; use crate::op_handle::OpHandle; use crate::op_set::OpSet; use crate::pending_diff::PendingDiff; use crate::Change; use automerge_protocol as amp; use core::cmp::max; use std::collections:...
use crate::actor_map::ActorMap; use crate::change::encode_document; use crate::error::AutomergeError; use crate::internal::ObjectId; use crate::op_handle::OpHandle; use crate::op_set::OpSet; use crate::pending_diff::PendingDiff; use crate::Change; use automerge_protocol as amp; use core::cmp::max; use std::collections:...
pub fn load_changes(&mut self, changes: Vec<Change>) -> Result<(), AutomergeError> { self.apply(changes, None)?; Ok(()) } pub fn apply_changes( &mut self, changes: Vec<Change>, ) -> Result<amp::Patch, AutomergeError> { self.apply(changes, None) } pub f...
dep| dep != &last_hash) .collect() } else { self.op_set.deps.iter().cloned().collect() }; deps.sort_unstable(); Ok(amp::Patch { diffs, deps, max_op: self.op_set.max_op, clock: self .states ...
function_block-function_prefixed
[ { "content": "#[wasm_bindgen(js_name = initSyncState)]\n\npub fn init_sync_state() -> SyncState {\n\n SyncState(am::sync::State::new())\n\n}\n\n\n\n// this is needed to be compatible with the automerge-js api\n", "file_path": "rust/automerge-wasm/src/lib.rs", "rank": 0, "score": 207346.0183412675...
Rust
src/options.rs
Mange/graceful-shutdown
c99fb299c07611c9c57526f9be59080500094b39
extern crate structopt; extern crate termion; extern crate users; use matcher::MatchMode; use signal::Signal; use std::time::Duration; use structopt::clap::Shell; #[derive(Debug, Clone, Copy)] pub enum OutputMode { Normal, Verbose, Quiet, } #[derive(Debug, Clone, Copy)] enum ColorMode { Auto, Alw...
extern crate structopt; extern crate termion; extern crate users; use matcher::MatchMode; use signal::Signal; use std::time::Duration; use structopt::clap::Shell; #[derive(Debug, Clone, Copy)] pub enum OutputMode { Normal, Verbose, Quiet, } #[derive(Debug, Clone, Copy)] enum ColorMode { Auto, Alw...
} impl OutputMode { pub fn show_normal(self) -> bool { match self { OutputMode::Verbose | OutputMode::Normal => true, OutputMode::Quiet => false, } } pub fn show_verbose(self) -> bool { match self { OutputMode::Verbose => true, Outpu...
fn from(cli_options: CliOptions) -> Options { let wait_time = if cli_options.wait_time > 0.0 { Some(duration_from_secs_float(cli_options.wait_time)) } else { None }; let user_mode = match (cli_options.user, cli_options.mine) { (Some(name), false) => U...
function_block-full_function
[ { "content": "#[must_use]\n\nfn send_with_error_handling(signal: Signal, options: &Options, process: &Process) -> bool {\n\n match process.send(signal) {\n\n Ok(_) => true,\n\n // Process quit before we had time to signal it? That should be fine. The next steps will\n\n // verify that it...
Rust
src/structs/types/system_boot_information.rs
alesharik/smbios-lib
27dc2fa78afa2163763207165c31a900f72a02e1
use crate::{SMBiosStruct, UndefinedStruct}; use serde::{ser::SerializeStruct, Serialize, Serializer}; use core::{fmt, any}; pub struct SMBiosSystemBootInformation<'a> { parts: &'a UndefinedStruct, } impl<'a> SMBiosStruct<'a> for SMBiosSystemBootInformation<'a> { const STRUCT_TYPE: u8 = 32u8; fn new(parts...
use crate::{SMBiosStruct, UndefinedStruct}; use serde::{ser::SerializeStruct, Serialize, Serializer}; use core::{fmt, any}; pub struct SMBiosSystemBootInformation<'a> { parts: &'a UndefinedStruct, } impl<'a> SMBiosStruct<'a> for SMBiosSystemBootInformation<'a> { const STRUCT_TYPE: u8 = 32u8; fn new(parts...
} #[derive(Serialize, Debug, PartialEq, Eq)] pub enum SystemBootStatus { NoErrors, NoBootableMedia, NormalOSFailedToLoad, FirmwareDetectedFailure, OSDetectedFailure, UserRequestedBoot, SystemSecurityViolation, P...
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("SystemBootStatusData", 1)?; state.serialize_field("system_boot_status", &self.system_boot_status())?; state.end() }
function_block-full_function
[ { "content": "/// Returns smbios raw data\n\npub fn raw_smbios_from_device() -> Result<Vec<u8>, Error> {\n\n Ok(try_load_macos_table()?)\n\n}\n", "file_path": "src/macos/platform.rs", "rank": 0, "score": 173349.63818810516 }, { "content": "/// Returns smbios raw data\n\npub fn raw_smbios_...
Rust
dbcrossbarlib/src/drivers/postgres_shared/table.rs
faradayio/schemaconv
eeb808354af7d58f1782927eaa9e754d59544011
use itertools::Itertools; use std::{ collections::{HashMap, HashSet}, fmt, }; use super::{PgColumn, PgDataType, PgName, PgScalarDataType}; use crate::common::*; use crate::schema::Column; use crate::separator::Separator; #[derive(Debug)] pub(crate) enum CheckCatalog { Yes, No, } impl From...
use itertools::Itertools; use std::{ collections::{HashMap, HashSet}, fmt, }; use super::{PgColumn, PgDataType, PgName, PgScalarDataType}; use crate::common::*; use crate::schema::Column; use crate::separator::Separator; #[derive(Debug)] pub(crate) enum CheckCatalog { Yes, No, } impl From...
pub(crate) fn named_type_names(&self) -> HashSet<&PgName> { let mut names = HashSet::new(); for col in &self.columns { let scalar_ty = match &col.data_type { PgDataType::Array { ty, .. } => ty, PgDataType::Scalar(ty) => ty, }; ...
pub(crate) fn aligned_with( &self, other_table: &PgCreateTable, ) -> Result<PgCreateTable> { let column_map = self .columns .iter() .map(|c| (&c.name[..], c)) .collect::<HashMap<_, _>>(); Ok(PgCreateTable { name: self.name.c...
function_block-full_function
[ { "content": "/// Specify the the location of data or a schema.\n\npub trait Locator: fmt::Debug + fmt::Display + Send + Sync + 'static {\n\n /// Provide a mechanism for casting a `dyn Locator` back to the underlying,\n\n /// concrete locator type using Rust's `Any` type.\n\n ///\n\n /// See [this S...
Rust
src/apu/dmc.rs
zeta0134/rusticnes-core
de44cda41670c8902e96f9f5f7b624b6cf1d8ac1
use mmc::mapper::Mapper; use super::audio_channel::AudioChannelState; use super::ring_buffer::RingBuffer; pub struct DmcState { pub name: String, pub chip: String, pub debug_disable: bool, pub debug_buffer: Vec<i16>, pub output_buffer: RingBuffer, pub looping: bool, pub period_initial: u16...
use mmc::mapper::Mapper; use super::audio_channel::AudioChannelState; use super::ring_buffer::RingBuffer; pub struct DmcState { pub name: String, pub chip: String, pub debug_disable: bool, pub debug_buffer: Vec<i16>, pub output_buffer: RingBuffer, pub looping: bool, pub period_initial: u16...
pub fn clock(&mut self, mapper: &mut dyn Mapper) { if self.period_current == 0 { self.period_current = self.period_initial - 1; self.update_output_unit(); } else { self.period_current -= 1; } if self.sample_buffer_empty && self.bytes_remaining > ...
pub fn update_output_unit(&mut self) { if !(self.silence_flag) { let mut target_output = self.output_level; if (self.shift_register & 0b1) == 0 { if self.output_level >= 2 { target_output -= 2; } } else { if...
function_block-full_function
[ { "content": "pub fn mapper_from_file(file_data: &[u8]) -> Result<Box<dyn Mapper>, String> {\n\n let mut file_reader = file_data;\n\n return mapper_from_reader(&mut file_reader);\n\n}", "file_path": "src/cartridge.rs", "rank": 0, "score": 278454.8317243863 }, { "content": "pub fn mappe...
Rust
src/lib.rs
ravenexp/python3-dll-a
3735d6543ced976ab9405fdda3f010243c7fe551
#![deny(missing_docs)] #![allow(clippy::needless_doctest_main)] use std::env; use std::fs::{create_dir_all, write}; use std::io::{Error, ErrorKind, Result}; use std::path::{Path, PathBuf}; use std::process::Command; const IMPLIB_EXT_GNU: &str = ".dll.a"; const IMPLIB_EXT_MSVC: &str = ".lib"; const DLLTOOL_GNU: &s...
#![deny(missing_docs)] #![allow(clippy::needless_doctest_main)] use std::env; use std::fs::{create_dir_all, write}; use std::io::{Error, ErrorKind, Result}; use std::path::{Path, PathBuf}; use std::process::Command; const IMPLIB_EXT_GNU: &str = ".dll.a"; const IMPLIB_EXT_MSVC: &str = ".lib"; const DLLTOOL_GNU: &s...
#[test] fn generate_msvc() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("x86_64-pc-windows-msvc"); dir.push("python3-dll"); ImportLibraryGenerator::new("x86_64", "msvc") .generate(&dir) .unwrap(); ...
fn generate_gnu32() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("i686-pc-windows-gnu"); dir.push("python3-dll"); generate_implib_for_target(&dir, "x86", "gnu").unwrap(); }
function_block-full_function
[ { "content": "#!/usr/bin/env python3\n\n# Parses Python Stable ABI symbol definitions from the manifest in the CPython repository located at https://github.com/python/cpython/blob/main/Misc/stable_abi.toml\n\n# and produces a definition file following the format described at https://docs.microsoft.com/en-us/cpp...
Rust
src/lib.rs
Ekleog/libtest-mimic
f902a460e6b951af824ba5f1a5fed5602cbd0314
extern crate crossbeam_channel; extern crate rayon; #[macro_use] extern crate structopt; extern crate termcolor; use std::{ process, }; use rayon::prelude::*; mod args; mod printer; pub use args::{Arguments, ColorSetting, FormatSetting}; #[derive(Clone, Debug)] pub struct Test<D = ()> { pub name...
extern crate crossbeam_channel; extern crate rayon; #[macro_use] extern crate structopt; extern crate termcolor; use std::{ process, }; use rayon::prelude::*; mod args; mod printer; pub use args::{Arguments, ColorSetting, FormatSetting}; #[derive(Clone, Debug)] pub struct Test<
inter.print_title(tests.len() as u64); let mut failed_tests = Vec::new(); let mut num_ignored = 0; let mut num_benches = 0; let mut num_passed = 0; for event in run_tests_threaded(args, tests, run_test) { match event { RunnerEvent::Started { name, kind } => { ...
D = ()> { pub name: String, pub kind: String, pub is_ignored: bool, pub is_bench: bool, pub data: D, } impl<D: Default> Test<D> { pub fn test(name: impl Into<String>) -> Self { Self { name: name.into(), ...
random
[ { "content": "/// Performs a couple of tidy tests.\n\nfn run_test(test: &Test<PathBuf>) -> Outcome {\n\n let path = &test.data;\n\n let content = fs::read(path).expect(\"io error\");\n\n\n\n // Check that the file is valid UTF-8\n\n let content = match String::from_utf8(content) {\n\n Err(_) ...
Rust
src/indicators/woodies_cci.rs
b100pro/yata
18bf83e134e5a89bc57e58b39d0cff9d098c9543
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use super::commodity_channel_index::CommodityChannelIndexInstance; use super::CommodityChannelIndex; use crate::core::{Action, Error, Method, PeriodType, ValueType, Window, OHLC}; use crate::core::{IndicatorConfig, IndicatorInitializer, IndicatorInstance, ...
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use super::commodity_channel_index::CommodityChannelIndexInstance; use super::CommodityChannelIndex; use crate::core::{Action, Error, Method, PeriodType, ValueType, Window, OHLC}; use crate::core::{IndicatorConfig, IndicatorInitializer, IndicatorInstance, ...
}
fn next(&mut self, candle: T) -> IndicatorResult { let cci1 = self.cci1.next(candle).value(0); let cci2 = self.cci2.next(candle).value(0); let cci1_sign = signi(cci1); let d_cci = cci1 - cci2; let sma = self.sma.next(d_cci); let s1 = self.cross1.next((sma, 0.)); let s0 = self.cross2.next((cci1, 0.)); ...
function_block-full_function
[ { "content": "/// Basic trait for implementing [Open-High-Low-Close timeseries data](https://en.wikipedia.org/wiki/Candlestick_chart).\n\n///\n\n/// It has already implemented for tuple of 4 and 5 float values:\n\n/// ```\n\n/// use yata::prelude::OHLC;\n\n/// // open high low close\n\n/// let row = (2...
Rust
src/stan_client/mod.rs
stevelr/ratsio
bcda26c44bf82895fa90603a4e2d706c9a663b3b
use crate::nats_client::{ClosableMessage, NatsClient, NatsClientOptions, NatsSid}; use crate::nuid::NUID; use std::{collections::HashMap, sync::Arc}; use tokio::sync::RwLock; use std::fmt::{Debug, Error, Formatter}; use tokio::sync::mpsc::UnboundedSender; pub mod client; const DEFAULT_DISCOVER_PREFIX: &str = "_STAN...
use crate::nats_client::{ClosableMessage, NatsClient, NatsClientOptions, NatsSid}; use crate::nuid::NUID; use std::{collections::HashMap, sync::Arc}; use tokio::sync::RwLock; use std::fmt::{Debug, Error, Formatter}; use tokio::sync::mpsc::UnboundedSender; pub mod client; const DEFAULT_DISCOVER_PREFIX: &str = "_STAN...
one, payload: Vec::new(), timestamp: tstamp_ms, sequence: 0, redelivered: false, ack_inbox: None, ack_handler: None, } } } impl Clone for StanMessage { fn clone(&self) -> Self { StanMessage { subject: self.subje...
self) { self.0() } } impl Debug for AckHandler { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.write_str("<ack-handler>") } } #[derive(Debug, Builder)] #[builder(default)] pub struct StanMessage { pub subject: String, pub reply_to: Option<String>, pub payload: ...
random
[]
Rust
crates/napi/src/promise.rs
AlCalzone/napi-rs
110f2196a4095963d73cdcfc5d49f72a9c579aaa
use std::ffi::CStr; use std::future::Future; use std::marker::PhantomData; use std::os::raw::c_void; use std::ptr; use crate::{check_status, sys, JsError, Result}; pub struct FuturePromise<Data, Resolver: FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>> { deferred: sys::napi_deferred, env: sys::napi_env, ...
use std::ffi::CStr; use std::future::Future; use std::marker::PhantomData; use std::os::raw::c_void; use std::ptr; use crate::{check_status, sys, JsError, Result}; pub struct FuturePromise<Data, Resolver: FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>> { deferred: sys::napi_deferred, env: sys::napi_env, ...
) }) .expect("Failed to call thread safe function"); check_status!(unsafe { sys::napi_release_threadsafe_function(tsfn_value.0, sys::ThreadsafeFunctionReleaseMode::release) }) .expect("Failed to release thread safe function"); } unsafe extern "C" fn call_js_cb< Data, Resolver: FnOnce(sys::napi_env...
check_status!(unsafe { sys::napi_create_string_utf8(env, s.as_ptr(), 32, &mut async_resource_name) })?; Ok(FuturePromise { deferred, resolver, env, tsfn: ptr::null_mut(), async_resource_name, _data: PhantomData, }) } pub(crate) fn start(self) -> Result<TS...
random
[ { "content": "pub fn register_js(exports: &mut JsObject, env: &Env) -> Result<()> {\n\n let test_class = env.define_class(\n\n \"TestClass\",\n\n test_class_constructor,\n\n &[\n\n Property::new(\"miterNative\")?\n\n .with_getter(get_miter_native)\n\n .with_setter(set_miter_native),...
Rust
src/sys/component_manager/tests/test_utils.rs
mehulagg/fuchsia
3f56175ee594da6b287d5fb19f2f0eccea2897f0
use { breakpoint_system_client::BreakpointSystemClient, failure::{format_err, Error, ResultExt}, fidl_fuchsia_io::DirectoryProxy, fidl_fuchsia_sys::{ ComponentControllerEvent, EnvironmentControllerEvent, EnvironmentControllerProxy, EnvironmentMarker, EnvironmentOptions, FileDescriptor,...
use { breakpoint_system_client::BreakpointSystemClient, failure::{format_err, Error, ResultExt}, fidl_fuchsia_io::DirectoryProxy, fidl_fuchsia_sys::{ ComponentControllerEvent, EnvironmentControllerEvent, EnvironmentControllerProxy, EnvironmentMarker, EnvironmentOptions, FileDescriptor,...
fn find_component_manager_in_hub(component_manager_url: &str, label: &str) -> PathBuf { let path_to_env = format!("/hub/r/{}", label); let dir: Vec<DirEntry> = read_dir(path_to_env) .expect("could not open nested environment in the hub") .map(|x| x.expect("entry unreadable")) ...
t_to_breakpoint_system( component_manager_path: &PathBuf, ) -> Result<BreakpointSystemClient, Error> { let path_to_svc = component_manager_path.join("out/svc"); let path_to_svc = path_to_svc.to_str().expect("found invalid chars"); let proxy = connect_to_service_at::<BreakpointSystemMarker>(path_to_svc) ...
function_block-function_prefixed
[]
Rust
src/lib.rs
laurmaedje/symslice
5e650353099e46b35a2b614b64f4eee7d0307bac
use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::path::Path; use crate::elf::ElfFile; use crate::ir::{Microcode, MicroEncoder}; use crate::x86_64::Instruction; #[macro_use] mod helper { use std::fmt::{self, Formatter}; use crate::math::DataType; pub fn write_signed_hex(...
use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::path::Path; use crate::elf::ElfFile; use crate::ir::{Microcode, MicroEncoder}; use crate::x86_64::Instruction; #[macro_use] mod helper { use std::fmt::{self, Formatter}; use crate::math::DataType; pub fn write_signed_hex(...
" {:x}: {}", addr, instruction)?; if f.alternate() { for op in &microcode.ops { writeln!(f, " | {}", op)?; } } } write!(f, "]") } } #[cfg(test)] mod tests { use super::*; fn test(filename: &str) { ...
Ok(()) } } pub fn signed_name(s: bool) -> &'static str { if s { " signed" } else { "" } } pub fn boxed<T>(value: T) -> Box<T> { Box::new(value) } pub fn check_compatible(a: DataType, b: DataType, operation: &str) { assert_eq!(a, b, "incompatible data types fo...
random
[ { "content": "/// Write the closing of the file.\n\npub fn write_footer<W: Write>(mut f: W) -> Result<()> {\n\n writeln!(f, \"}}\")\n\n}\n\n\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use std::fs::{self, File};\n\n use std::process::Command;\n\n use super::*;\n\n\n\n /// Compile the file with grap...
Rust
native-windows-gui/examples/treeview_d.rs
gyk/native-windows-gui
163d0fcb5c2af8a859f603ce23a7ec218e9b6813
/*! An application that show how to use the TreeView control. Requires the following features: `cargo run --example treeview_d --features "tree-view tree-view-iterator listbox image-list frame"` */ extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use nwd::NwgUi; use nwg::Nat...
/*! An application that show how to use the TreeView control. Requires the following features: `cargo run --example treeview_d --features "tree-view tree-view-iterator listbox image-list frame"` */ extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use nwd::NwgUi; use nwg::Nat...
fn log_events(&self, evt: nwg::Event) { self.events_log.insert(0, format!("{:?}", evt)); } fn exit(&self) { nwg::stop_thread_dispatch(); } } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); nwg::Font::set_global_family("Segoe UI").expect("Failed to set def...
tv.set_item_image(&item, 1, true); } else if btn == &self.remove_btn { if let Some(item) = tv.selected_item() { tv.remove_item(&item); } } }
function_block-function_prefix_line
[ { "content": "fn build_frame(button: &mut nwg::ImageFrame, window: &nwg::Window, ico: &nwg::Icon) {\n\n nwg::ImageFrame::builder()\n\n .parent(window)\n\n .build(button);\n\n}\n\n```\n\n*/\n\n#[derive(Default)]\n\npub struct ImageFrame {\n\n pub handle: ControlHandle,\n\n background_brush...
Rust
io-engine/tests/lock_lba_range.rs
openebs/MayaStor
a6424b565ea4023acc7896e591e9c71f832eba3f
#![allow(clippy::await_holding_refcell_ref)] #[macro_use] extern crate tracing; use std::{ cell::{Ref, RefCell, RefMut}, ops::{Deref, DerefMut}, rc::Rc, }; use crossbeam::channel::unbounded; use io_engine::{ bdev::nexus::{nexus_create, nexus_lookup_mut}, core::{ IoChannel, Mayastor...
#![allow(clippy::await_holding_refcell_ref)] #[macro_use] extern crate tracing; use std::{ cell::{Ref, RefCell, RefMut}, ops::{Deref, DerefMut}, rc::Rc, }; use crossbea
lock_sender.send(()).unwrap(); }); reactor_poll!(100); assert!(lock_receiver.try_recv().is_err()); let (s, r) = unbounded::<()>(); reactor.send_future(async move { unlock_range( ctx1.borrow_mut_ctx().deref_mut(), ctx1.borrow_ch().deref(), ) ...
m::channel::unbounded; use io_engine::{ bdev::nexus::{nexus_create, nexus_lookup_mut}, core::{ IoChannel, MayastorCliArgs, MayastorEnvironment, RangeContext, Reactor, Reactors, UntypedBdev, }, }; use spdk_rs::DmaBuf; pub mod common; const NEXUS_NAME:...
random
[ { "content": "#[async_trait(? Send)]\n\npub trait Share: std::fmt::Debug {\n\n type Error;\n\n type Output: std::fmt::Display + std::fmt::Debug;\n\n async fn share_nvmf(\n\n self: Pin<&mut Self>,\n\n cntlid_range: Option<(u16, u16)>,\n\n ) -> Result<Self::Output, Self::Error>;\n\n\n\n ...
Rust
tests/curve_test.rs
AlexandruIca/verg
adcdac98f57492e8b7576e06a92491934d2e0fa1
use crate::common::default_blending; use verg::{ canvas::{Canvas, CanvasDescription, ViewBox}, color::{Color, FillRule, FillStyle}, geometry::{PathOps, Point}, math::{rotate_around, scale_around, translate, Angle}, }; mod common; const WIDTH: usize = 805; const HEIGHT: usize = 405; fn canvas_descri...
use crate::common::default_blending; use verg::{ canvas::{Canvas, CanvasDescription, ViewBox}, color::{Color, FillRule, FillStyle}, geometry::{PathOps, Point}, math::{rotate_around, scale_around, translate, Angle}, }; mod common; const WIDTH: usize = 805; const HEIGHT: usize = 405; fn canvas_descri...
}, background_color: Color::white(), tolerance: 0.25, } } const PATH: [PathOps; 4] = [ PathOps::MoveTo { x: 20.0, y: 360.0 }, PathOps::CubicTo { x1: 100.0, y1: 260.0, x2: 50.0, y2: 160.0, x3: 150.0, y3: 60.0, }, PathOps::CubicTo { ...
width: WIDTH, height: HEIGHT, viewbox: ViewBox { x: 0.0, y: 0.0, width: WIDTH as f64, height: HEIGHT as f64,
function_block-random_span
[ { "content": "pub fn rotate(point: &Point, angle: Angle) -> Point {\n\n let (sin, cos) = angle.to_radians().sin_cos();\n\n\n\n Point {\n\n x: point.x * sin - point.y * cos,\n\n y: point.x * cos + point.y * sin,\n\n }\n\n}\n\n\n", "file_path": "src/math.rs", "rank": 0, "score":...
Rust
pkg-dashboard/rate-app/src/canvas.rs
transparencies/rillrate
a1a6f76e84211224a85bb9fd92602d33f095229e
use anyhow::Error; use approx::abs_diff_ne; use derive_more::{Deref, DerefMut}; use plotters::prelude::*; use plotters_canvas::CanvasBackend; use rate_ui::packages::or_fail::{Fail, Fasten}; use wasm_bindgen::JsCast; use web_sys::{CanvasRenderingContext2d as Context2d, HtmlCanvasElement}; use yew::NodeRef; const SCALE...
use anyhow::Error; use approx::abs_diff_ne; use derive_more::{Deref, DerefMut}; use plotters::prelude::*; use plotters_canvas::CanvasBackend; use rate_ui::packages::or_fail::{Fail, Fasten}; use wasm_bindgen::JsCast; use web_sys::{CanvasRenderingContext2d as Context2d, HtmlCanvasElement}; use yew::NodeRef; const SCALE...
((last_x, prev_y)); } result } /* pub fn sustain_soft<Y: Copy>( mut iter: impl Iterator<Item = (i64, Y)>, last: Option<i64>, ) -> Vec<(i64, Y)> { let mut result = Vec::new(); if let Some((mut prev_x, mut prev_y)) = iter.next() { result.push((prev_x, prev_y)); for (next_x, next_y...
r<Item = (i64, Y)>, last_x: i64) -> Vec<(i64, Y)> { let mut result = Vec::new(); if let Some((mut prev_x, mut prev_y)) = iter.next() { result.push((prev_x, prev_y)); for (next_x, next_y) in iter { let diff = next_x - prev_x; let shift = (diff as f32 * 0.1) as i64; ...
function_block-random_span
[]
Rust
src/env.rs
sezaru/rust-rocks
06245eedaf91b8358688abefa67eba802b607142
use lazy_static::lazy_static; use std::ffi::CStr; use std::mem; use std::path::Path; use std::ptr; use std::str; use rocks_sys as ll; use crate::thread_status::ThreadStatus; use crate::to_raw::{FromRaw, ToRaw}; use crate::{Error, Result}; pub const DEFAULT_PAGE_SIZE: usize = 4 * 1024; lazy_static! { static re...
use lazy_static::lazy_static; use std::ffi::CStr; use std::mem; use std::path::Path; use std::ptr; use std::str; use rocks_sys as ll; use crate::thread_status::ThreadStatus; use crate::to_raw::{FromRaw, ToRaw}; use crate::{Error, Result}; pub const DEFAULT_PAGE_SIZE: usize = 4 * 1024; lazy_static! { static re...
sage")); assert!(!s.contains("debug log message")); } }
("test.log")); assert!(logger.is_ok()); let mut logger = logger.unwrap(); logger.set_log_level(InfoLogLevel::Info); assert_eq!(logger.get_log_level(), InfoLogLevel::Info); logger.log(InfoLogLevel::Error, "test log message"); logger.log(InfoLogLe...
function_block-random_span
[ { "content": "/// Destroy the contents of the specified database.\n\n///\n\n/// Be very careful using this method.\n\npub fn destroy_db<P: AsRef<Path>>(options: &Options, name: P) -> Result<()> {\n\n let name = name.as_ref().to_str().expect(\"valid utf8\");\n\n let mut status = ptr::null_mut();\n\n uns...
Rust
game-core/src/system/ally.rs
TheBlueSmoke/gameoff
b3619817c9c2af750c0eda2fad3e441692852261
use amethyst::{ core::cgmath::{InnerSpace, Vector2}, core::Transform, ecs::{Entities, Join, Read, ReadStorage, System, WriteStorage}, renderer::{SpriteRender, Transparent}, }; use config::GameoffConfig; use crate::component::{Ally, Animation, Motion, Player}; use rand::distributions::{Distribution, Unif...
use amethyst::{ core::cgmath::{InnerSpace, Vector2}, core::Transform, ecs::{Entities, Join, Read, ReadStorage, System, WriteStorage}, renderer::{SpriteRender, Transparent}, }; use config::GameoffConfig; use crate::component::{Ally, Animation, Motion, Player}; use rand::distributions::{Distribution, Unif...
priteRender { sprite_sheet: textures.textures["FRONT.png"].clone(), sprite_number: 1, flip_horizontal: false, flip_vertical: false, }; let anim = Animation { total_frames: 8, ...
ally_positions.push(pos); } for pos in ally_positions { let sprite = S
function_block-random_span
[ { "content": "pub fn run() -> amethyst::Result<()> {\n\n let root = format!(\"{}/resources\", application_root_dir());\n\n let display_config = DisplayConfig::load(format!(\"{}/display_config.ron\", root));\n\n let gameoff_config = config::GameoffConfig::load(format!(\"{}/config.ron\", root));\n\n l...
Rust
examples/demo.rs
alvinhochun/conrod_floatwin
c29c2668bdc4408fce802bd5cc6e44ef05dd82b2
use conrod_core::{ widget, widget_ids, Borderable, Colorable, Labelable, Positionable, Sizeable, Widget, }; use conrod_floatwin::windowing_area::{ layout::{WinId, WindowingState}, WindowBuilder, WindowingArea, WindowingContext, }; use glium::Surface; mod support; fn main() { const WIDTH: u32 = 800; ...
use conrod_core::{ widget, widget_ids, Borderable, Colorable, Labelable, Positionable, Sizeable, Widget, }; use conrod_floatwin::windowing_area::{ layout::{WinId, WindowingState}, WindowBuilder, WindowingArea, WindowingContext, }; use glium::Surface; mod support; fn main() { const WIDTH: u32 = 800; ...
let context = glium::glutin::ContextBuilder::new() .with_vsync(true) .with_multisampling(4); let display = glium::Display::new(window, context, &events_loop).unwrap(); let display = support::GliumDisplayWinitWrapper(display); let mut current_hidpi_factor = display.0.gl_window().get_hid...
let window = glium::glutin::WindowBuilder::new() .with_title("conrod_floatwin demo") .with_dimensions((WIDTH, HEIGHT).into());
assignment_statement
[ { "content": "#![allow(dead_code)]\n\n\n\nuse glium;\n\nuse std;\n\n\n\npub struct GliumDisplayWinitWrapper(pub glium::Display);\n\n\n\nimpl conrod_winit::WinitWindow for GliumDisplayWinitWrapper {\n\n fn get_inner_size(&self) -> Option<(u32, u32)> {\n\n self.0.gl_window().get_inner_size().map(Into::i...