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
config/management/src/validator_config.rs
kkmc/libra
4f212d33d95d3c9f3a09df8c032bdb0957a70e46
use crate::{config::ConfigPath, constants, error::Error, secure_backend::ValidatorBackend}; use libra_config::config::HANDSHAKE_VERSION; use libra_crypto::ValidCryptoMaterial; use libra_global_constants::{ CONSENSUS_KEY, FULLNODE_NETWORK_KEY, OPERATOR_ACCOUNT, OPERATOR_KEY, OWNER_ACCOUNT, VALIDATOR_NETWORK_KE...
use crate::{config::ConfigPath, constants, error::Error, secure_backend::ValidatorBackend}; use libra_config::config::HANDSHAKE_VERSION; use libra_crypto::ValidCryptoMaterial; use libra_global_constants::{ CONSENSUS_KEY, FULLNODE_NETWORK_KEY, OPERATOR_ACCOUNT, OPERATOR_KEY, OWNER_ACCOUNT, VALIDATOR_NETWORK_KE...
ss.append_prod_protos(validator_network_key, HANDSHAKE_VERSION); let raw_validator_address = encode_address(validator_address)?; let key = TEST_SHARED_VAL_NETADDR_KEY; let version = TEST_SHARED_VAL_NETADDR_KEY_VERSION; let enc_validator_address = raw_validator_address.encrypt( ...
in_id::ChainId, transaction::{RawTransaction, Transaction}, }; use std::convert::TryFrom; use structopt::StructOpt; #[derive(Clone, Debug, StructOpt)] pub struct ValidatorConfig { #[structopt(flatten)] pub config: ConfigPath, #[structopt(long, required_unless("config"))] pub chain_id: Option<ChainI...
random
[ { "content": "fn verify_constant(idx: usize, constant: &Constant) -> PartialVMResult<()> {\n\n verify_constant_type(idx, &constant.type_)?;\n\n verify_constant_data(idx, constant)\n\n}\n\n\n", "file_path": "language/bytecode-verifier/src/constants.rs", "rank": 0, "score": 129076.87021287545 ...
Rust
src/sources/mod.rs
tshepang/cargo-deny
05c26fb3c237db3c9a20061ae55cb83b25afc8d3
mod cfg; mod diags; pub use cfg::{Config, GitSpec, ValidConfig}; use crate::{ diag::{CfgCoord, Check, ErrorSink, Label, Pack}, LintLevel, }; use url::Url; pub fn check(ctx: crate::CheckCtx<'_, ValidConfig>, mut sink: ErrorSink) { use bitvec::prelude::*; if ctx.cfg.unknown_registry == LintLevel::...
mod cfg; mod diags; pub use cfg::{Config, GitSpec, ValidConfig}; use crate::{ diag::{CfgCoord, Check, ErrorSink, Label, Pack}, LintLevel, }; use url::Url; pub fn check(ctx: crate::CheckCtx<'_, ValidConfig>, mut sink: ErrorSink) { use bitvec::prelude::*; if ctx.cfg.unknown_registry == LintLevel::...
if name == "master" { GitSpec::Any } else { GitSpec::Branch } } ...
let (lint_level, type_name) = if source.is_registry() { (ctx.cfg.unknown_registry, "registry") } else if source.is_git() { if let Some((min, cfg_coord)) = &min_git_spec { pub use rustsec::package::source::GitReference; let spe...
function_block-random_span
[ { "content": "pub fn check(\n\n ctx: crate::CheckCtx<'_, ValidConfig>,\n\n output_graph: Option<Box<OutputGraph>>,\n\n cargo_spans: diag::CargoSpans,\n\n mut sink: diag::ErrorSink,\n\n) {\n\n let wildcard = VersionReq::parse(\"*\").expect(\"Parsing wildcard mustnt fail\");\n\n\n\n let ValidCon...
Rust
src/server.rs
RustWorks/kachiclash_actix_web
1915462b440836ff6fe6fae82c92333a3a430cd7
use crate::data::DbConn; use super::{data, handlers}; use super::{AppState, Config}; use std::convert::TryInto; use std::process::Command; use actix_files::Files; use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_rt::Arbiter; use actix_rt::time::interval; use actix_session::CookieSession; use ac...
use crate::data::DbConn; use super::{data, handlers}; use super::{AppState, Config}; use std::convert::TryInto; use std::process::Command; use actix_files::Files; use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_rt::Arbiter; use actix_rt::time::interval; use actix_session::CookieSession; use ac...
}
async fn run(self) { let mut interval = interval(Duration::from_secs(10)); while !self.db.is_poisoned() { interval.tick().await; } error!("watchdog: db mutex is poisoned; graceful shutdown"); self.server.stop(true).await; }
function_block-full_function
[ { "content": "pub fn finalize_basho(db: &mut Connection, basho_id: BashoId) -> Result<()> {\n\n debug!(\"finalizing basho {}\", basho_id);\n\n let txn = db.transaction()?;\n\n upsert_basho_results(&txn, basho_id, true)?;\n\n debug!(\"committing\");\n\n txn.commit()?;\n\n Ok(())\n\n}\n\n\n", ...
Rust
crates/exec-wasmtime/src/main.rs
definitelynobody/enarx
435df398058e7dafc97438222663c25d83b42fd6
#![doc = include_str!("../README.md")] #![deny(missing_docs)] #![deny(clippy::all)] #![warn(rust_2018_idioms)] #![feature(core_ffi_c)] mod config; mod loader; use config::Config; use loader::Loader; use std::fs::File; use std::io::Read; use std::mem::forget; use std::os::unix::io::FromRawFd; use std::os::unix::pre...
#![doc = include_str!("../README.md")] #![deny(missing_docs)] #![deny(clippy::all)] #![warn(rust_2018_idioms)] #![feature(core_ffi_c)] mod config; mod loader; use config::Config; use loader::Loader; use std::fs::File; use std::io::Read; use std::mem::forget; use std::os::unix::io::FromRawFd; use std::os::unix::pre...
#[derive(Parser, Debug)] struct Args { #[clap(short, long, value_name = "MODULE", parse(from_os_str))] pub module: Option<PathBuf>, #[clap(short, long, value_name = "CONFIG", parse(from_os_str))] pub config: Option<PathBuf>, } fn main() -> anyhow::Result<()> { env_logger::Bui...
pub extern "C" fn __set_thread_area(p: *mut std::ffi::c_void) -> std::ffi::c_int { let mut rax: usize = 0; if unsafe { core::arch::x86_64::__cpuid(7).ebx } & 1 == 1 { unsafe { std::arch::asm!("wrfsbase {}", in(reg) p); } } else { const ARCH_SET_FS: std::ffi::c_int = 0x100...
function_block-full_function
[]
Rust
src/docbuilder/metadata.rs
ldm0/docs.rs
09b55bc214b676785aca6e44cf7cdb2832609fa5
use crate::error::Result; use failure::err_msg; use std::collections::HashSet; use std::path::Path; use toml::{map::Map, Value}; pub struct Metadata { pub features: Option<Vec<String>>, pub all_features: bool, pub no_default_features: bool, ...
use crate::error::Result; use failure::err_msg; use std::collections::HashSet; use std::path::Path; use toml::{map::Map, Value}; pub struct Metadata { pub features: Option<Vec<String>>, pub all_features: bool, pub no_default_features: bool, ...
lect()); targets.remove(&default_target); BuildTargets { default_target, other_targets: targets, } } } #[cfg(test)] mod test { use super::Metadata; #[test] fn test_cratesfyi_metadata() { crate::test::init_logger(); let manifest = r#" ...
|v| v.as_str()) .map(|v| v.to_owned()); metadata.targets = table .get("targets") .and_then(|f| f.as_array()) .and_then(collect_into_array); metadata.rustc_args = table .get("rustc-args") .and_then(|...
random
[ { "content": "pub fn crates_from_path<F>(path: &PathBuf, func: &mut F) -> Result<()>\n\nwhere\n\n F: FnMut(&str, &str) -> (),\n\n{\n\n if !path.is_dir() {\n\n return Err(err_msg(\"Not a directory\"));\n\n }\n\n\n\n for file in path.read_dir()? {\n\n let file = file?;\n\n let pat...
Rust
c/rust/src/subprocess.rs
elmarco/virtblocks
77f31fe5903394aef8741d383de7ba26412d2082
#![cfg_attr(feature = "cargo-clippy", allow(clippy::not_unsafe_ptr_arg_deref))] use std::ffi::CStr; use std::os::raw::{c_char, c_int, c_uint}; use std::ptr; use super::errors; use virtblocks::subprocess; #[no_mangle] pub extern "C" fn virtblocks_subprocess_new(prog: *const c_char) -> *mut subprocess::Subprocess {...
#![cfg_attr(feature = "cargo-clippy", allow(clippy::not_unsafe_ptr_arg_deref))] use std::ffi::CStr; use std::os::raw::{c_char, c_int, c_uint}; use std::ptr; use super::errors; use virtblocks::subprocess; #[no_mangle] pub extern "C" fn virtblocks_subprocess_new(prog: *const c_char) -> *mut subprocess::Subprocess {...
afe { *c_error = Box::into_raw(Box::new(tmp)); }; false } _ => true, } } #[no_mangle] pub extern "C" fn virtblocks_subprocess_id(c_subprocess: *mut subprocess::Subprocess) -> c_uint { assert!(!c_subprocess.is_null()); let rust_subprocess = unsafe { &...
#[no_mangle] pub extern "C" fn virtblocks_subprocess_add_arg( c_subprocess: *mut subprocess::Subprocess, c_arg: *const c_char, ) { assert!(!c_subprocess.is_null()); assert!(!c_arg.is_null()); let rust_subprocess = unsafe { &mut *c_subprocess }; let rust_arg = unsafe { CStr::from_ptr(c_arg) }....
random
[ { "content": "type ToyCallback = unsafe extern \"C\" fn(*const playground::Toy, *const c_char, *mut c_void) -> bool;\n", "file_path": "c/rust/src/playground/toy.rs", "rank": 0, "score": 164244.05364210124 }, { "content": "type ToyCallbackDataFree = unsafe extern \"C\" fn(*mut c_void);\n\n\n"...
Rust
contracts/campaign/src/entrypoints.rs
topcoder1208/contracts
d4f20ac6e949b5c497d3b8cbb9e499b5a636b104
use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Reply, Response, StdError, to_binary, from_binary, Addr}; use cosmwasm_std::entry_point; use valkyrie::campaign::execute_msgs::{ExecuteMsg, MigrateMsg, Cw20HookMsg}; use valkyrie::campaign::query_msgs::QueryMsg; use valkyrie::campaign_manager::execute_msgs::C...
use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Reply, Response, StdError, to_binary, from_binary, Addr}; use cosmwasm_std::entry_point; use valkyrie::campaign::execute_msgs::{ExecuteMsg, MigrateMsg, Cw20HookMsg}; use valkyrie::campaign::query_msgs::QueryMsg; use valkyrie::campaign_manager::execute_msgs::C...
pub fn receive_cw20( deps: DepsMut, env: Env, info: MessageInfo, cw20_msg: Cw20ReceiveMsg, ) -> ContractResult<Response> { match from_binary(&cw20_msg.msg)? { Cw20HookMsg::Deposit {} => { let sender = info.sender.clone(); executions::deposit( deps, ...
posit_lock_period, qualifier, qualification_description, admin, } => crate::executions::update_campaign_config( deps, env, info, title, description, url, parameter_key, deposit_amo...
function_block-function_prefixed
[]
Rust
src/libstd/cleanup.rs
fabricedesre/rust
1b12dca7f97a51c6cbb4f47ea6e095d841a97c1a
#[doc(hidden)]; use libc::c_void; use ptr; use unstable::intrinsics::TyDesc; use unstable::raw; type DropGlue<'a> = 'a |**TyDesc, *c_void|; /* * Box annihilation * * This runs at task death to free all boxes. */ struct AnnihilateStats { n_total_boxes: uint, n_unique_boxes: uint, n_bytes_freed: uin...
#[doc(hidden)]; use libc::c_void; use ptr; use unstable::intrinsics::TyDesc; use unstable::raw; type DropGlue<'a> = 'a |**TyDesc, *c_void|; /* * Box annihilation * * This runs at task death to free all boxes. */ struct AnnihilateStats { n_total_boxes: uint, n_unique_boxes: uint, n_bytes_freed: uin...
m::size_of::<raw::Box<()>>(); local_free(box as *i8); } true }); if debug_mem() { debug!("annihilator stats:\n \ total boxes: {}\n \ unique boxes: {}\n \ bytes freed: {}", stats.n...
naged::RC_IMMORTAL; } true }); each_live_alloc(false, |box, uniq| { if !uniq { let tydesc = (*box).type_desc; let data = &(*box).data as *(); ((*tydesc).drop_glue)(data as *i8); } true }); ...
function_block-random_span
[ { "content": "fn strange() -> bool { let _x: bool = return true; }\n\n\n", "file_path": "src/test/run-pass/weird-exprs.rs", "rank": 0, "score": 604777.5840939593 }, { "content": "fn is_odd(_n: int) -> bool { return true; }\n\n\n", "file_path": "src/test/run-pass/box-inside-if.rs", "r...
Rust
relayer/src/config/types.rs
interchainio/ibc-rs
194a1714cf9dc807dd7b4e33726319293848dc58
pub use max_msg_num::MaxMsgNum; pub mod max_msg_num { flex_error::define_error! { Error { TooSmall { value: usize } |e| { format_args!("`max_msg_num` must be greater than or equal to {}, found {}", MaxMsgNum::MIN_BOUN...
pub use max_msg_num::MaxMsgNum; pub mod max_msg_num { flex_error::define_error! { Error { TooSmall { value: usize } |e| { format_args!("`max_msg_num` must be greater than or equal to {}, found {}", MaxMsgNum::MIN_BOUN...
) } } impl Serialize for Memo { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.0.serialize(serializer) } } use core::fmt; impl fmt::Display for Memo { fn fmt(&self, f: &mut fmt::F...
match e.detail() { ErrorDetail::TooLong(sub) => D::Error::invalid_length( sub.length, &format!("a string length of at most {}", Self::MAX_LEN).as_str(), ), }
if_condition
[]
Rust
carbide_core/src/widget/rotation_3d_effect.rs
HolgerGottChriestensen/conrod
48b80a0c8915b2d478a445f1e5a8e0f396598652
use cgmath::{Deg, Matrix4, Point3, Vector3}; use crate::draw::{Dimension, Position, Rect}; use crate::prelude::*; use crate::render::PrimitiveKind; #[derive(Debug, Clone, Widget)] #[carbide_exclude(Render)] pub struct Rotation3DEffect { id: Uuid, child: Box<dyn Widget>, position: Position, dimension: ...
use cgmath::{Deg, Matrix4, Point3, Vector3}; use crate::draw::{Dimension, Position, Rect}; use crate::prelude::*; use crate::render::PrimitiveKind; #[derive(Debug, Clone, Widget)] #[carbide_exclude(Render)] pub struct Rotation3DEffect { id: Uuid, child: Box<dyn Widget>, position: Position, dimension: ...
} fn children_direct(&mut self) -> WidgetIterMut { WidgetIterMut::single(&mut self.child) } fn children_direct_rev(&mut self) -> WidgetIterMut { WidgetIterMut::single(&mut self.child) } fn position(&self) -> Position { self.position } fn set_position(&mut sel...
if self.child.flag() == Flags::PROXY { self.child.children_mut() } else { WidgetIterMut::single(&mut self.child) }
if_condition
[ { "content": "/// Bezier estimation function based on an iterative approach. This function\n\n/// will fail if multiple y values can be had for a single x. This excludes some input,\n\n/// but the input is not validated.\n\npub fn cubic_bezier(x: f64, p1: Position, p2: Position) -> f64 {\n\n let precision = ...
Rust
src/metadata.rs
trha/cargo2nix
bbdcb003b13a0f49104f7bfd5f722e17526dbe8f
use std::collections::BTreeMap; use cargo::{ core::{ registry::PackageRegistry, resolver::Method, source::SourceId, GitReference, PackageId, Workspace, }, ops::{get_resolved_packages, load_pkg_lockfile, resolve_with_previous}, util::config::Config, }; use failure::Error; use log::info; ...
use std::collections::BTreeMap; use cargo::{ core::{ registry::PackageRegistry, resolver::Method, source::SourceId, GitReference, PackageId, Workspace, }, ops::{get_resolved_packages, load_pkg_lockfile, resolve_with_previous}, util::config::Config, }; use failure::Error; use log::info; ...
?; info!("dependencies locked"); let packages = get_resolved_packages(&resolve, registry)?; info!("versions locked"); let packages = { let mut pkgs = BTreeMap::new(); for pkg in packages.get_many(packages.package_ids())? { pkgs.insert(pkg.package_id(), pkg.clone()); }...
resolve_with_previous( &mut registry, ws, Method::Everything, previous.as_ref(), None, &[], true, )
call_expression
[ { "content": "pub fn ident(input: &str) -> IResult<String> {\n\n map(\n\n recognize(many1(alt((alphanumeric1, tag(\"-\"), tag(\"_\"))))),\n\n String::from,\n\n )(input)\n\n}\n\n\n", "file_path": "src/resolve/parser.rs", "rank": 1, "score": 121831.76078161687 }, { "content...
Rust
core/src/csv.rs
vishalbelsare/prest
07df526fc940ec0808b90ef8e694573559cdbd31
use std::io::Read; use std::marker::PhantomData; use std::collections::HashSet; use alt::Alt; use alt_set::AltSet; pub trait FromRow { type ParseError; const COLUMN_NAMES : &'static[&'static str]; fn from_row(alternatives : &mut Vec<String>, row : &[&str]) -> Result<Self, Self::ParseError> where S...
use std::io::Read; use std::marker::PhantomData; use std::collections::HashSet; use alt::Alt; use alt_set::AltSet; pub trait FromRow { type ParseError; const COLUMN_NAMES : &'static[&'static str]; fn from_row(alternatives : &mut Vec<String>, row : &[&str]) -> Result<Self, Self::ParseError> where S...
match Row::from_row(&mut self.alternatives, &row) { Err(e) => return Some(Err(Error::ParseRow(e))), Ok(row) => row, } }; match self.current_subject { None => { self.current_sub...
subj.alternatives = self.alternatives.clone(); Some(Ok(subj)) }, None => None, }, Some(r) => match r { Ok(row) => row, Err(e) => return Some(Err(Error::Csv(e)))...
random
[ { "content": "pub fn decode_iterator<T : Decode, R : Read>(f : &mut R) -> Result<Vec<T>> {\n\n let mut result = Vec::new();\n\n while let Some(item) = Decode::decode(f)? {\n\n result.push(item);\n\n }\n\n Ok(result)\n\n}\n\n\n", "file_path": "core/src/codec.rs", "rank": 2, "score"...
Rust
src/lib.rs
dureuill/sentinel_option
5dfc6529ef288c1b7ca0a7c6da983d49593c9173
use std::marker::PhantomData; pub trait Sentinel<T> where T: PartialEq, { fn sentinel() -> T; fn is_sentinel(t: &T) -> bool { *t == Self::sentinel() } } pub struct SentinelOption<T, S> where T: PartialEq, S: Sentinel<T>, { item: T, _phantom: PhantomData<*const S>, } ...
use std::marker::PhantomData; pub trait Sentinel<T> where T: PartialEq, { fn sentinel() -> T; fn is_sentinel(t: &T) -> bool { *t == Self::sentinel() } } pub struct SentinelOption<T, S> where T: PartialEq, S: Sentinel<T>, { item: T, _phantom: PhantomData<*const S>, } ...
sert_eq!(from_sentinel, with_value); } #[test] fn using_from_none() { let sentinel = U64MaxSentinel::from(None); let from_sentinel: Option<u64> = sentinel.into(); assert_eq!(from_sentinel, None); } #[test] #[should_panic] fn some_illegal_value() { U64MaxSent...
{ self.into_option() } } #[cfg(test)] mod tests { use super::*; struct U64Max; impl Sentinel<u64> for U64Max { fn sentinel() -> u64 { u64::max_value() } } type U64MaxSentinel = SentinelOption<u64, U64Max>; #[test] fn is_optimized() { use s...
random
[]
Rust
poem-openapi/src/openapi.rs
Lawliet-Chan/poem
6ec253007c05d4012575e04704da7c9cbd112192
use std::collections::BTreeMap; use poem::{ endpoint::{make_sync, BoxEndpoint}, middleware::CookieJarManager, web::cookie::CookieKey, Endpoint, EndpointExt, FromRequest, IntoEndpoint, IntoResponse, Request, Response, Route, }; use crate::{ base::UrlQuery, registry::{Document, MetaInfo, MetaSer...
use std::collections::BTreeMap; use poem::{ endpoint::{make_sync, BoxEndpoint}, middleware::CookieJarManager, web::cookie::CookieKey, Endpoint, EndpointExt, FromRequest, IntoEndpoint, IntoResponse, Request, Response, Route, }; use crate::{ base::UrlQuery, registry::{Document, MetaInfo, MetaSer...
req.extensions_mut().insert(UrlQuery(query.0)); next.call(req).await } match self.cookie_key { Some(key) => self .api .add_routes(Route::new()) .with(CookieJarManager::with_key(key)) .around(extract_que...
let query: poem::web::Query<BTreeMap<String, String>> = FromRequest::from_request(&req, &mut Default::default()) .await .unwrap_or_default();
assignment_statement
[ { "content": "fn set_header(ep: impl Endpoint) -> impl Endpoint {\n\n ep.with(SetHeader::new().appending(\"Custom-Header\", \"test\"))\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<(), std::io::Error> {\n\n if std::env::var_os(\"RUST_LOG\").is_none() {\n\n std::env::set_var(\"RUST_LOG\", ...
Rust
server/src/engine_handlers.rs
circlesabound/pccg-rs
e662df17d492ef792976edfbff2d1056295a9a4a
use super::schemas; use crate::engine; use engine::api::AddOrUpdateOperation; use engine::{job_board::JobTier, ErrorCategory, ErrorCode}; use std::sync::Arc; use uuid::Uuid; use warp::http::StatusCode; use warp::{reject, reply, Rejection, Reply}; pub async fn add_user_to_registry(api: Arc<engine::Api>) -> Result<impl...
use super::schemas; use crate::engine; use engine::api::AddOrUpdateOperation; use engine::{job_board::JobTier, ErrorCategory, ErrorCode}; use std::sync::Arc; use uuid::Uuid; use warp::http::StatusCode; use warp::{reject, reply, Rejection, Reply}; pub async fn add_user_to_registry(api: Arc<engine::Api>) -> Result<impl...
} } pub async fn list_jobs_for_user( user_id: Uuid, api: Arc<engine::Api>, ) -> Result<impl Reply, Rejection> { info!("Handling: list_jobs_for_user"); match api.list_jobs(&user_id).await { Ok(jobs) => Ok(reply::with_status(reply::json(&jobs), StatusCode::OK)), Err(e) => Err(reject...
info!("Handling: list_cards_from_compendium"); match api.list_card_ids().await { Ok(card_ids) => Ok(reply::with_status( reply::json(&schemas::ListCardsFromCompendiumResponse::from(card_ids)), StatusCode::OK, )), Err(e) => Err(reject::custom(EngineError { ...
function_block-random_span
[]
Rust
libslide/src/grammar/pattern.rs
mahimachander/slide
a79132fb3d36ef973d4691c39e77cf0a40598a2e
pub use super::*; use std::rc::Rc; #[derive(Clone, Debug)] pub enum ExprPat { Const(f64), VarPat(String), ConstPat(String), AnyPat(String), BinaryExpr(BinaryExpr<Self>), UnaryExpr(UnaryExpr<Self>), Parend(Rc<Self>), Bracketed(Rc<Self>), } impl Grammar for ExprPat { ...
pub use super::*; use std::rc::Rc; #[derive(Clone, Debug)] pub enum ExprPat { Const(f64), VarPat(String), ConstPat(String), AnyPat(String), BinaryExpr(BinaryExpr<Self>), UnaryExpr(UnaryExpr<Self>), Parend(Rc<Self>), Bracketed(Rc<Self>), } impl Grammar for ExprPat { ...
} impl From<BinaryExpr<Self>> for ExprPat { fn from(binary_expr: BinaryExpr<Self>) -> Self { Self::BinaryExpr(binary_expr) } } impl From<UnaryExpr<Self>> for ExprPat { fn from(unary_expr: UnaryExpr<Self>) -> Self { Self::UnaryExpr(unary_expr) } } impl fmt::Display for ExprPat { f...
fn hash<H: core::hash::Hasher>(&self, state: &mut H) { use ExprPat::*; match self { Const(f) => state.write(f.to_string().as_bytes()), VarPat(v) => v.hash(state), ConstPat(c) => c.hash(state), AnyPat(a) => a.hash(state), ...
function_block-full_function
[ { "content": "/// Indents all lines of a string with `n` spaces.\n\npub fn indent<T: Into<String>>(s: T, n: usize) -> String {\n\n let s: String = s.into();\n\n let indent = \" \".repeat(n);\n\n s.lines()\n\n .map(|l| format!(\"{}{}\", indent, l))\n\n .collect::<Vec<_>>()\n\n .join...
Rust
tests/selector-extend.rs
johan-smits/grass
68d3a0f8431d2a7b85b177ef478a8a3b4a6b3cc5
#[macro_use] mod macros; test!( simple_attribute_equal, "a {\n color: selector-extend(\"[c=d]\", \"[c=d]\", \"e\");\n}\n", "a {\n color: [c=d], e;\n}\n" ); test!( simple_attribute_unequal_name, "a {\n color: selector-extend(\"[c=d]\", \"[e=d]\", \"f\");\n}\n", "a {\n color: [c=d];\n}\n" ); ...
#[macro_use] mod macros; test!( simple_attribute_equal, "a {\n color: selector-extend(\"[c=d]\", \"[c=d]\", \"e\");\n}\n", "a {\n color: [c=d], e;\n}\n" ); test!( simple_attribute_unequal_name, "a {\n color: selector-extend(\"[c=d]\", \"[e=d]\", \"f\");\n}\n", "a {\n color: [c=d];\n}\n" ); ...
ot(.c)\", \".c\", \":is(.d, .e)\");\n}\n", "a {\n color: :not(.c):not(.d):not(.e);\n}\n" ); test!( simple_pseudo_idempotent_not_and_is_list_of_complex, "a {\n color: selector-extend(\":not(.c)\", \".c\", \":is(.d .e, .f .g)\");\n}\n", "a {\n color: :not(.c):not(.d .e):not(.f .g);\n}\n" ); test!( ...
n", "a {\n color: *|c;\n}\n" ); test!( simple_type_universal_namespace_and_type_universal_namespace, "a {\n color: selector-extend(\"*|c\", \"*|c\", \"d\");\n}\n", "a {\n color: *|c, d;\n}\n" ); test!( simple_pseudo_class_no_arg_equal, "a {\n color: selector-extend(\":c\", \":c\", \"e\");\n}...
random
[ { "content": "#[macro_export]\n\nmacro_rules! test {\n\n (@base $( #[$attr:meta] ),*$func:ident, $input:expr, $output:expr, $options:expr) => {\n\n $(#[$attr])*\n\n #[test]\n\n #[allow(non_snake_case)]\n\n fn $func() {\n\n let sass = grass::from_string($input.to_string(...
Rust
src/tags/case_block.rs
or17191/liquid-rust
bfaeb98593efe551651ffcb0b52b1d40c3ce7f49
use std::io::Write; use itertools; use liquid_error::{Result, ResultLiquidExt}; use liquid_value::Value; use compiler::BlockElement; use compiler::BlockReflection; use compiler::Language; use compiler::ParseBlock; use compiler::TagBlock; use compiler::TagTokenIter; use compiler::TryMatchToken; use interpreter::Contex...
use std::io::Write; use itertools; use liquid_error::{Result, ResultLiquidExt}; use liquid_value::Value; use compiler::BlockElement; use compiler::BlockReflection; use compiler::Language; use compiler::ParseBlock; use compiler::TagBlock; use compiler::TagTokenIter; use compiler::TryMatchToken; use interpreter::Contex...
fn test_no_matches_returns_empty_string() { let text = concat!( "{% case x %}", "{% when 2 %}", "two", "{% when 3 or 4 %}", "three and a half", "{% endcase %}" ); let options = options(); let template = compiler:...
.unwrap(); let mut context = Context::new(); context.stack_mut().set_global("x", Value::scalar(2f64)); assert_eq!(template.render(&mut context).unwrap(), "two"); context.stack_mut().set_global("x", Value::scalar(3f64)); assert_eq!(template.render(&mut context).unwra...
random
[ { "content": "fn int_argument(arg: &Expression, context: &Context, arg_name: &str) -> Result<isize> {\n\n let value = arg.evaluate(context)?;\n\n\n\n let value = value\n\n .as_scalar()\n\n .and_then(Scalar::to_integer)\n\n .ok_or_else(|| unexpected_value_error(\"whole number\", Some(v...
Rust
src/character_systems.rs
BillSchumacher/kyro
36c256f6062c4b918a78337ed2c2c4475d40d64c
use amethyst::{ core::{ math::{Matrix4, UnitQuaternion, Vector3}, Transform, }, ecs::prelude::*, input::{InputEvent, StringBindings}, renderer::Camera, shrev::EventChannel, }; use amethyst_physics::prelude::*; use crate::components::*; const MOUSE_SENSITIVITY: f32 = 0.2; const ...
use amethyst::{ core::{ math::{Matrix4, UnitQuaternion, Vector3}, Transform, }, ecs::prelude::*, input::{InputEvent, StringBindings}, renderer::Camera, shrev::EventChannel, }; use amethyst_physics::prelude::*; use crate::components::*; const MOUSE_SENSITIVITY: f32 = 0.2; const ...
"Left" => { self.horizontal_input.x -= 1.0; } "Jump" => { self.vertical_input -= 1.0; } "Sprint" => { self.sprint = false; } _...
ings>>>(); self.input_event_reader = Some(ie.register_reader()); } } pub struct CharacterMotionControllerSystem { input_event_reader: Option<ReaderId<InputEvent<StringBindings>>>, horizontal_input: Vector3<f32>, vertical_input: f32, jump_time: f32, sprint: bool } impl CharacterMotionCo...
random
[ { "content": "fn add_light_entity(world: &mut World, color: Srgb, direction: Vector3<f32>, intensity: f32) {\n\n let light: light::Light = light::DirectionalLight {\n\n color,\n\n direction: direction.normalize(),\n\n intensity,\n\n }\n\n .into();\n\n\n\n world.create_entity().w...
Rust
src/image.rs
ApoorvaJ/grapheme
32a9a97146988a3d49af1de998184575ed995f40
use crate::*; pub struct Image { pub width: u32, pub height: u32, pub format: vk::Format, pub usage: vk::ImageUsageFlags, pub aspect_flags: vk::ImageAspectFlags, pub vk_image: vk::Image, pub image_view: vk::ImageView, pub opt_device_memory: Option<vk::DeviceMemory>, pub name: Strin...
use crate::*; pub struct Image { pub width: u32, pub height: u32, pub format: vk::Format, pub usage: vk::ImageUsageFlags, pub aspect_flags: vk::ImageAspectFlags, pub vk_image: vk::Image, pub image_view: vk::ImageView, pub opt_device_memory: Option<vk::DeviceMemory>, pub name: Strin...
pub fn transition_image_layout( &self, old_layout: vk::ImageLayout, new_layout: vk::ImageLayout, command_buffer: vk::CommandBuffer, ) { let src_access_mask; let dst_access_mask; let source_stage; let destination_stage; if old_layout == v...
debug_utils.set_image_name(vk_image, name); Image { width, height, format, usage, aspect_flags, vk_image, image_view, opt_device_memory: Some(device_memory), device, name: String::from(name),...
function_block-function_prefix_line
[ { "content": "pub fn vk_to_string(raw_string_array: &[c_char]) -> String {\n\n let raw_string = unsafe {\n\n let pointer = raw_string_array.as_ptr();\n\n CStr::from_ptr(pointer)\n\n };\n\n\n\n raw_string\n\n .to_str()\n\n .expect(\"Failed to convert vulkan raw string.\")\n\n...
Rust
fractal-server/src/fractal.rs
a10nik/borbu-images
240a6440c76a08d38c22406609414fe9e14261b0
use byte_rect::*; static TRANSFORMS: &'static [Transform] = &[ Transform::HeadToTop, Transform::HeadToRight, Transform::HeadToBottom, Transform::HeadToLeft, Transform::HeadToTopInv, Transform::HeadToRightInv, Transform::HeadToBottomInv, Transform::HeadToLeftInv, ]; pub fn find_closest_square<'a, 'b, R>(square...
use byte_rect::*; static TRANSFORMS: &'static [Transform] = &[ Transform::HeadToTop, Transform::HeadToRight, Transform::HeadToBottom, Transform::HeadToLeft, Transform::HeadToTopInv, Transform::HeadToRightInv, Transform::HeadToBottomInv, Transform::HeadToLeftInv, ]; pub fn find_closest_square<'a, 'b, R>(square...
ear(sq.best_coeffs_to_match(desired)))) .unwrap(); (best_i, best_transform, best_coeffs) } #[derive(Debug, PartialEq, Clone, Copy)] pub struct SquareMapping { pub small: SquareCoords, pub big: SquareCoords, pub trans: Transform, pub coeffs: LinearCoeffs, } fn get_closest_chunk_mapping<R>(p...
.flat_map(|(i, sq)| TRANSFORMS.iter().map(move |&t| (i, t, sq.transform(t)))) .map(|(i, t, sq)| (i, t, sq.best_coeffs_to_match(desired), sq)) .min_by_key(|&(_, _, _, ref sq)| desired.dist(&sq.lin
function_block-random_span
[ { "content": "fn rect_avg(vec: &Vec<Vec<u8>>, x: usize, y: usize, side: usize) -> u8 {\n\n (vec[y..y+side].iter()\n\n .map(|ln| ln[x..x + side].iter().fold(0, |a, &el| a + el as usize))\n\n .fold(0, |x, y| x + y as usize) / (side * side)) as u8\n\n}\n\n\n", "file_path": "fractal-server/src/...
Rust
src/core/sampling.rs
shiinamiyuki/rs_pbrt
49d440bef861013e805dd264b4dbf9342970c858
use std::f32::consts::PI; use std::sync::Arc; use crate::core::geometry::{Point2f, Vector2f, Vector3f, XYEnum}; use crate::core::pbrt::clamp_t; use crate::core::pbrt::Float; use crate::core::pbrt::{INV_2_PI, INV_4_PI, INV_PI, PI_OVER_2, PI_OVER_4}; use crate::core::rng::Rng; use crate::core::rng::FLOAT_ONE_MINUS_EPS...
use std::f32::consts::PI; use std::sync::Arc; use crate::core::geometry::{Point2f, Vector2f, Vector3f, XYEnum}; use crate::core::pbrt::clamp_t; use crate::core::pbrt::Float; use crate::core::pbrt::{INV_2_PI, INV_4_PI, INV_PI, PI_OVER_2, PI_OVER_4}; use crate::core::rng::Rng; use crate::core::rng::FLOAT_ONE_MINUS_EPS...
self.p_conditional_v[iv].func[iu] / self.p_marginal.func_int } } pub fn shuffle<T>(samp: &mut [T], count: i32, n_dimensions: i32, rng: &mut Rng) { for i in 0..count { let other: i32 = i + rng.uniform_uint32_bounded((count - i) as u32) as i32; for j in 0..n_dimensions { samp...
let iv: usize = clamp_t( (p[XYEnum::Y] * self.p_marginal.count() as Float) as usize, 0_usize, self.p_marginal.count() - 1_usize, );
assignment_statement
[ { "content": "pub fn knot_offset(knot: &[Float], order: i32, np: i32, t: Float) -> usize {\n\n let first_knot: usize = (order - 1_i32) as usize;\n\n let mut knot_offset: usize = first_knot;\n\n while t > knot[knot_offset + 1_usize] {\n\n knot_offset += 1;\n\n }\n\n // np == last_knot\n\n ...
Rust
openapi2-to-nickel/src/as_ncl.rs
tweag/nickel-kubernetes
022ea99debf47b65d6c0f745e60c5256a998fae1
use crate::defs_overrides::DEFINITIONS_OVERRIDES; pub trait AsNcl { fn to_ncl(&self, name: &str, force_xyz: bool) -> String; } impl AsNcl for openapi::v2::Schema { fn to_ncl(&self, name: &str, force_xyz: bool) -> String { let ncl_id = _k8s_to_ncl_id(name); let contract: String = if DEFINITIONS_OVERRIDES.c...
use crate::defs_overrides::DEFINITIONS_OVERRIDES; pub trait AsNcl { fn to_ncl(&self, name: &str, force_xyz: bool) -> String; } impl AsNcl for openapi::v2::Schema { fn to_ncl(&self, name: &str, force_xyz: bool) -> String { let ncl_id = _k8s_to_ncl_id(name); let contract: String = if DEFINITIONS_OVERRIDES.c...
#[cfg(test)] mod tests { use super::*; use rstest::rstest; #[rstest] #[case("apiGroup", "apiGroup")] #[case("default", "\"default\"")] #[case("$ref", "\"$ref\"")] #[case("$schema", "\"$schema\"")] #[case("weird$word", "\"weird$word\"")] fn test_quote_if_has_ncl_reserved_chars( #[case] input: St...
t" => { openapi_object_contract(&schema.properties, &k8s_group_version_kind) } _ => "<sensible_warning>".to_string(), }, ) }
function_block-function_prefixed
[ { "content": "pub fn _are_brackets_balanced(text: &String) -> bool {\n\n let opening_bracket = text.find('{');\n\n let closing_bracket = text.rfind('}');\n\n match (opening_bracket, closing_bracket) {\n\n (Some(oi), Some(ci)) => {\n\n let distance_between_brackets = ci - oi;\n\n if distance_betw...
Rust
src/sql/parser/mod.rs
thesalva101/mynode
cda24968cfb975698aa0b386ad6d5d24392e4b60
pub mod ast; pub mod lexer; use super::types::DataType; use crate::Error; use lexer::{Keyword, Lexer, Token}; pub struct Parser<'a> { lexer: std::iter::Peekable<Lexer<'a>>, } impl<'a> Parser<'a> { pub fn new(query: &str) -> Parser { Parser { lexer: Lexer::new(query).peekable(), ...
pub mod ast; pub mod lexer; use super::types::DataType; use crate::Error; use lexer::{Keyword, Lexer, Token}; pub struct Parser<'a> { lexer: std::iter::Peekable<Lexer<'a>>, } impl<'a> Parser<'a> { pub fn new(query: &str) -> Parser { Parser { lexer: Lexer::new(query).peekable(), ...
} impl Operator for InfixOperator { fn from(token: &Token) -> Option<Self> { Some(match token { Token::Asterisk => Self::Multiply, Token::Caret => Self::Exponentiate, Token::GreaterThan => Self::CompareGT, Token::GreaterThanOrEqual => Self::CompareGTE, ...
fn build(&self, lhs: ast::Expression, rhs: ast::Expression) -> ast::Expression { let (lhs, rhs) = (Box::new(lhs), Box::new(rhs)); match self { Self::Add => ast::Operation::Add(lhs, rhs), Self::And => ast::Operation::And(lhs, rhs), Self::CompareEQ => ast::Operation::Co...
function_block-full_function
[ { "content": "/// Serializes a value into a byte buffer\n\npub fn serialize<V: serde::Serialize>(value: V) -> Result<Vec<u8>, Error> {\n\n let mut buffer = Vec::new();\n\n value.serialize(&mut rmps::Serializer::new(&mut buffer))?;\n\n Ok(buffer)\n\n}\n\n\n", "file_path": "src/serializer.rs", "r...
Rust
src/user/mod.rs
tarkov-database/identity-server
67bd21d6329ef811748544a820f5b63f58337b2a
mod handler; mod routes; use crate::{ database::Database, error, model::{ListOptions, Status}, Result, }; use chrono::{DateTime, TimeZone, Utc}; use futures::stream::TryStreamExt; use hyper::StatusCode; use mongodb::{ bson::{ doc, oid::ObjectId, serde_helpers::chrono_datetime_as_bson_datet...
mod handler; mod routes; use crate::{ database::Database, error, model::{ListOptions, Status}, Result, }; use chrono::{DateTime, TimeZone, Utc}; use futures::stream::TryStreamExt; use hyper::StatusCode; use mongodb::{ bson::{ doc, oid::ObjectId, serde_helpers::chrono_datetime_as_bson_datet...
pub async fn update_user(&self, filter: Document, update: Document) -> Result<UserDocument> { let mut doc = update; doc.insert("$currentDate", doc! { "lastModified": true }); let opts = FindOneAndUpdateOptions::builder() .return_document(ReturnDocument::After) .bui...
nsert_user(&self, doc: &UserDocument) -> Result<()> { self.collection::<UserDocument>(COLLECTION) .insert_one(doc, None) .await?; Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn validate_and_hash(password: &str) -> Result<String> {\n\n if let Err(e) = validate_password(password) {\n\n return Err(AuthenticationError::from(e).into());\n\n }\n\n\n\n let hash = match hash_password(password) {\n\n Ok(h) => h,\n\n Err(e) => {\n\n ...
Rust
lib/src/semantics/analyze.rs
ajkachnic/bliss
94030e04bcbc55f8a8a1f5268ce38d6828c5188c
use super::{context::Context, util}; use crate::ast::{Expr, Program, Stmt, Pattern}; use crate::style::{bold, yellow}; use std::default::Default; type AnalysisResult = Result<(), Vec<String>>; pub fn analyze_stmts(program: Program, parent: Option<&mut Context>) -> AnalysisResult { let mut default = Context { ...
use super::{context::Context, util}; use crate::ast::{Expr, Program, Stmt, Pattern}; use crate::style::{bold, yellow}; use std::default::Default; type AnalysisResult = Result<(), Vec<String>>; pub fn analyze_stmts(program: Program, parent: Option<&mut Context>) -> AnalysisResult { let mut default = Context { ...
Expr::Array(items) => { for item in items { let res = analyze_expr(item, context); interpolate_errors(res,...
format!("While analyzing an import statement, we were expecting to find the name as an identifier, but we instead found this: {} Hint: Only use identifiers as names in imports Here is an example of a valid import statement: import ident from 'string';", &name) ) } if...
random
[ { "content": "fn check_program(program: Program, expected: Vec<Stmt>) {\n\n expected.iter().enumerate().for_each(|(index, stmt)| {\n\n assert_eq!(stmt, &program.0[index]);\n\n });\n\n}\n", "file_path": "lib/src/parser/parser_test.rs", "rank": 5, "score": 171534.2946890965 }, { "...
Rust
skia-safe/examples/gl-window/main.rs
pum-purum-pum-pum/rust-skia
cd0b8be8256f3baf55a49d2ab388a25f8a587510
#![allow(dead_code)] #[rustfmt::skip] #[path = "../icon/renderer.rs"] mod renderer; #[cfg(target_os = "android")] fn main() { println!("This example is not supported on Android (https://github.com/rust-windowing/winit/issues/948).") } #[cfg(all(not(target_os = "android"), not(feature = "gl")))] fn main() { p...
#![allow(dead_code)] #[rustfmt::skip] #[path = "../icon/renderer.rs"] mod renderer; #[cfg(target_os = "android")] fn main() { println!("This example is not supported on Android (https://github.com/rust-windowing/winit/issues/948).") } #[cfg(all(not(target_os = "android"), not(feature = "gl")))] fn main() { p...
run(move |event, _, control_flow| { *control_flow = ControlFlow::Wait; #[allow(deprecated)] match event { Event::LoopDestroyed => {} Event::WindowEvent { event, .. } => match event { WindowEvent::Resized(physical_size) => { surface = c...
; unsafe { gl::GetIntegerv(gl::FRAMEBUFFER_BINDING, &mut fboid) }; FramebufferInfo { fboid: fboid.try_into().unwrap(), format: skia_safe::gpu::gl::Format::RGBA8.into(), } }; windowed_context .window() .set_inner_size(glutin::dpi::Size::new(glutin...
random
[ { "content": "pub fn draw(driver: &mut impl DrawingDriver, path: &path::Path) {\n\n let path = path.join(\"SkShaper-Example\");\n\n\n\n icu::init();\n\n\n\n driver.draw_image_256(&path, \"rtl-shaped\", draw_rtl_shaped);\n\n driver.draw_image_256(&path, \"rtl-unshaped\", draw_rtl_unshaped);\n\n}\n\n\...
Rust
src/observation.rs
chridou/metrix
2d8052cd54cbc70a6bd18908074b357727aa0927
use std::time::{Duration, Instant}; use crate::snapshot::ItemKind; #[derive(Debug, Clone, Copy)] pub enum TimeUnit { Nanoseconds, Microseconds, Milliseconds, Seconds, } impl Default for TimeUnit { fn default() -> Self { TimeUnit::Microseconds } } #[derive(Debug)] pub enum Observation...
use std::time::{Duration, Instant}; use crate::snapshot::ItemKind; #[derive(Debug, Clone, Copy)] pub enum TimeUnit { Nanoseconds, Microseconds, Milliseconds, Seconds, } impl Default for TimeUnit { fn default() -> Self { TimeUnit::Microseconds } } #[derive(Debug)] pub enum Observation...
::Float(v) => { if v <= std::i64::MAX as f64 { Some(v.round() as i64) } else { None } } ObservedValue::Bool(_) => None, ObservedValue::Duration(_, _) => None, ObservedValue::ChangedBy...
let millis = (d.0.as_secs() * 1_000) + (d.0.subsec_nanos() as u64 / 1_000_000); (millis, d.1).into() } TimeUnit::Seconds => (d.0.as_secs(), d.1).into(), } } } impl From<super::Increment> for ObservedValue { fn from(_: super::Increment) -> Self { ...
random
[ { "content": "#[inline]\n\nfn duration_to_micros(d: Duration) -> u64 {\n\n let nanos = (d.as_secs() * 1_000_000_000) + (d.subsec_nanos() as u64);\n\n nanos / 1000\n\n}\n\n*/\n", "file_path": "src/driver.rs", "rank": 0, "score": 190065.67455786144 }, { "content": "fn duration_to_display...
Rust
cdc-mysql/src/producer/profile.rs
infinyon/fluvio-demo-apps-rust
00815139d94324ce07cdd6d48f262b550261349c
use serde::{Deserialize, Serialize}; use std::fs::read_to_string; use std::io::{Error, ErrorKind}; use std::path::{Path, PathBuf}; use crate::util::expand_tilde; const DEFAULT_TOPIC: &str = "rust-mysql-cdc"; const DEFAULT_REPLICAS: i16 = 1; pub struct Config { profile: Profile, } impl Config { pub fn ...
use serde::{Deserialize, Serialize}; use std::fs::read_to_string; use std::io::{Error, ErrorKind}; use std::path::{Path, PathBuf}; use crate::util::expand_tilde; const DEFAULT_TOPIC: &str = "rust-mysql-cdc"; const DEFAULT_REPLICAS: i16 = 1; pub struct Config { profile: Profile, } impl Config { pub fn ...
ore_file(), &base_path.join(local_store_file) ); assert_eq!(profile.topic(), "rust-mysql-cdc".to_owned()); assert_eq!(profile.replicas(), 1); } #[test] fn test_normalize_filter() { let mut filter = Filters::Include { include_dbs: vec![ ...
&base_path.join(binlog_index_file) ); assert_eq!( profile.resume_offset_file(), &base_path.join(resume_offset_file) ); assert_eq!( profile.local_st
function_block-random_span
[ { "content": "fn get_index_file_path(base_dir: &Path, file: String) -> Result<PathBuf, Error> {\n\n let path = base_dir.join(file);\n\n\n\n match path.exists() {\n\n true => Ok(path),\n\n false => Err(Error::new(\n\n ErrorKind::InvalidInput,\n\n format!(\"cannot find {:...
Rust
src/graphics/texture.rs
pgermishuys/tetra
dfd9d3946e15948945311aa127971cc69451a614
use std::cell::RefCell; use std::path::Path; use std::rc::Rc; use image; use crate::error::{Result, TetraError}; use crate::fs; use crate::graphics::{self, DrawParams, Drawable, Rectangle}; use crate::platform::{GraphicsDevice, RawTexture}; use crate::Context; #[derive(Debug, Clone, PartialEq)] pub struct Texture ...
use std::cell::RefCell; use std::path::Path; use std::rc::Rc; use image; use crate::error::{Result, TetraError}; use crate::fs; use crate::graphics::{self, DrawParams, Drawable, Rectangle}; use crate::platform::{GraphicsDevice, RawTexture}; use crate::Context; #[derive(Debug, Clone, PartialEq)] pub struct Texture ...
pub fn from_rgba(ctx: &mut Context, width: i32, height: i32, data: &[u8]) -> Result<Texture> { Texture::with_device(&mut ctx.device, width, height, data) } pub(crate) fn with_device( device: &mut GraphicsDevice, width: i32, ...
s(); Texture::from_rgba( ctx, width as i32, height as i32, image.into_raw().as_slice(), ) }
function_block-function_prefixed
[ { "content": "/// Sets the size of the window.\n\n///\n\n/// # Errors\n\n///\n\n/// * `TetraError::FailedToChangeDisplayMode` will be returned if the game was unable to\n\n/// change the window size.\n\npub fn set_size(ctx: &mut Context, width: i32, height: i32) -> Result {\n\n ctx.window.set_window_size(wid...
Rust
discord_game_sdk/src/events.rs
AlexApps99/discord_game_sdk
0ab2f707fefbea2905b27768e7ff6e3c3629003c
use crate::{ discord::{Discord, DiscordInner}, sys, utils, Activity, Entitlement, EventHandler, Relationship, User, UserAchievement, }; use std::{ffi::c_void, mem::ManuallyDrop}; fn with_event_handler<E>(inner: *mut c_void, callback: impl FnOnce(&mut E, &Discord<'_, E>)) { let _guard = utils::prevent_unwin...
use crate::{ discord::{Discord, DiscordInner}, sys, utils, Activity, Entitlement, EventHandler, Relationship, User, UserAchievement, }; use std::{ffi::c_void, mem::ManuallyDrop}; fn with_event_handler<E>(inner: *mut c_void, callback: impl FnOnce(&mut E, &Discord<'_, E>)) { let _guard = utils::prevent_unwin...
Some(on_entitlement_create::<E>) }, on_entitlement_delete: { extern "C" fn on_entitlement_delete<E: EventHandler>( inner: *mut c_void, entitlement: *mut sys::DiscordEntitlement, ) { with_event_handler(inner, |eh: &mut...
d, entitlement: *mut sys::DiscordEntitlement, ) { with_event_handler(inner, |eh: &mut E, discord| { eh.on_entitlement_create(discord, unsafe { &*(entitlement as *const Entitlement) }) }) ...
function_block-function_prefixed
[ { "content": "use crate::sys;\n\n\n\n/// Activity Type\n\n///\n\n/// > [Enum in official docs](https://discordapp.com/developers/docs/game-sdk/activities#data-models-activitytype-enum)\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\n\npub enum ActivityKind {\n\n /// Listening to music (only Spotify as...
Rust
src/node.rs
kaifoon/tsinghua_ds
c434939e51e4f14a8b25d90bf8cc1e52b0ce5cd4
use std::cmp::max; use std::mem::{replace, swap}; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub key: i32, pub val: i32, pub height: usize, pub left: Option<Box<TreeNode>>, pub right: Option<Box<TreeNode>>, } #[derive(Debug, PartialEq, Eq)] pub enum ChildType {...
use std::cmp::max; use std::mem::{replace, swap}; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub key: i32, pub val: i32, pub height: usize, pub left: Option<Box<TreeNode>>, pub right: Option<Box<TreeNode>>, } #[derive(Debug, PartialEq, Eq)] pub enum ChildType {...
ght(); } fn rotate_right(&mut self) { if self.left.is_none() { return; } let left_node = self.left.as_mut().unwrap(); let left_right_tree = left_node.right.take(); let left_left_tree = left_node.left.take(); let mut new_right_tree = replace(&mut...
left_tree; self.left = new_left_tree; if let Some(node) = self.left.as_mut() { node.update_height(); } self.update_hei
function_block-random_span
[]
Rust
src/decoder.rs
mbari-org/espclient
8d7774da30da964121cc151ad8e033de5b182602
use crate::debug_buffer; use crate::error::*; use crate::event::*; use bytes::BytesMut; use std::mem; pub struct EspDecoder { max_buffer_length: usize, buffer: Vec<u8>, current_stream: EspStream, pending_event: Option<EspEvent>, } impl EspDecoder { pub fn new(max_buffer_length: usize) -> EspDecod...
use crate::debug_buffer; use crate::error::*; use crate::event::*; use bytes::BytesMut; use std::mem; pub struct EspDecoder { max_buffer_length: usize, buffer: Vec<u8>, current_stream: EspStream, pending_event: Option<EspEvent>, } impl EspDecoder { pub fn new(max_buffer_length: usize) -> EspDecod...
oder::EspDecoder::new(4096); let mut bytes = BytesMut::from(&*b"unfinished line".to_vec()); let result = consume(&mut dec, &mut bytes); assert_eq!(result, vec![],); } }
stream = s; } return Ok(Some(event)); } if src.is_empty() { return Ok(None); } let mut k = 0; let max_buffer_length = self.max_buffer_length; loop { if k >= src.len() { return Ok(None); ...
random
[ { "content": "pub fn debug_buffer(prefix: &str, buffer: &[u8], add_new_line: bool) {\n\n eprintln!(\n\n \"[{}: {}{}]\",\n\n prefix,\n\n escape(buffer),\n\n if add_new_line { \"\\\\n\" } else { \"\" }\n\n );\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score"...
Rust
src/integrations/failure.rs
Diggsey/sentry-rust
90554cc82177654f56ef4558a0fb487821ddff20
use failure::{Error, Fail}; use regex::Regex; use crate::backtrace_support::{demangle_symbol, error_typename, filename, strip_symbol}; use crate::hub::Hub; use crate::internals::Uuid; use crate::protocol::{Event, Exception, Frame, Level, Stacktrace}; lazy_static::lazy_static! { static ref MODULE_SPLIT_RE: Regex...
use failure::{Error, Fail}; use regex::Regex; use crate::backtrace_support::{demangle_symbol, error_typename, filename, strip_symbol}; use crate::hub::Hub; use crate::internals::Uuid; use crate::protocol::{Event, Exception, Frame, Level, Stacktrace}; lazy_static::lazy_static! { static ref MODULE_SPLIT_RE: Regex...
pub fn event_from_error(err: &failure::Error) -> Event<'static> { let mut exceptions = vec![]; for (idx, cause) in err.iter_chain().enumerate() { let bt = match cause.backtrace() { Some(bt) => Some(bt), None if idx == 0 => Some(err.backtrace()), None => None, ...
ty, module, value: Some(f.to_string()), stacktrace: bt .map(|backtrace| backtrace.to_string()) .and_then(|x| parse_stacktrace(&x)), ..Default::default() } }
function_block-function_prefix_line
[ { "content": "pub fn filename(s: &str) -> String {\n\n s.rsplitn(2, &['/', '\\\\'][..]).next().unwrap().to_string()\n\n}\n\n\n", "file_path": "src/backtrace_support.rs", "rank": 4, "score": 215302.90723789594 }, { "content": "/// Runs some code with the default test hub and returns the ca...
Rust
drepr/old_code/engine_old/src/writers/json_line.rs
scorpio975/d-repr
1d08024192642233d42d29e1d05f8713ee265bca
use super::StreamStateWriter; use crate::readers::Value; use crate::models::{SemanticModel, GraphNode}; use fnv::FnvHashMap; use hashbrown::HashMap; use std::fs::File; use std::io::{BufWriter, Write}; struct BufferedObject { object: FnvHashMap<String, serde_json::Value>, props: Vec<(usize, usize, String)>, } pub ...
use super::StreamStateWriter; use crate::readers::Value; use crate::models::{SemanticModel, GraphNode}; use fnv::FnvHashMap; use hashbrown::HashMap; use std::fs::File; use std::io::{BufWriter, Write}; struct BufferedObject { object: FnvHashMap<String, serde_json::Value>, props: Vec<(usize, usize, String)>, } pub ...
fn end_subject(&mut self) { self .write_buffer .write( serde_json::to_string(&self.current_object) .unwrap() .as_bytes(), ) .unwrap(); self.write_buffer.write("\n".as_bytes()).unwrap(); } fn end_partial_buffering_subject(&mut self) { let r = self....
self.predicates[predicate].to_string(), serde_json::Value::String(self.idmap[target_cls][object_pseudo_id].clone()), ); }
function_block-function_prefix_line
[ { "content": "/// Create a path to an node in the resource tree\n\npub fn path(index_string: &str) -> Vec<Index> {\n\n // create index vector from <idx|string>:<idx|string>:...\n\n index_string.split(\":\")\n\n .map(|s| {\n\n match s.parse::<usize>() {\n\n Ok(v) => Index::Idx(v),\n\n Err...
Rust
components/vod-meta-server/src/vod/meta/state/manager.rs
tyranron/rust-rtmp-mixing-poc
f74442fd94c283afddf26ef80bc913e7bb8497ae
use std::{path::Path, sync::Arc}; use anyhow::anyhow; use chrono::Utc; use tokio::{fs, io::AsyncReadExt as _, sync::RwLock}; use super::{Playlist, PlaylistSlug, State}; #[derive(Clone, Debug)] pub struct Manager { file: Arc<Path>, state: Arc<RwLock<(State, u8)>>, } impl Manager {...
use std::{path::Path, sync::Arc}; use anyhow::anyhow; use chrono::Utc; use tokio::{fs, io::AsyncReadExt as _, sync::RwLock}; use super::{Playlist, PlaylistSlug, State}; #[derive(Clone, Debug)] pub struct Manager { file: Arc<Path>, state: Arc<RwLock<(State, u8)>>, } impl Manager {...
t now = Utc::now(); for playlist in state.0.values_mut() { let _result = playlist.schedule_nginx_vod_module_set(Some(now), 1); } self.persist_state(&state.0).await } async fn persist_state(&self, state: &State) -> Result<(), anyhow::Error> { ...
rue) .open(&file) .await .map_err(|e| { anyhow!("Failed to open '{}' file: {}", file.display(), e) })? .read_to_end(&mut contents) .await .map_err(|e| { anyhow!("Failed to read '{}' file: {}", file.displa...
random
[ { "content": "#[inline]\n\n#[must_use]\n\npub fn schema() -> Schema {\n\n Schema::new(QueriesRoot, MutationsRoot, SubscriptionsRoot)\n\n}\n\n\n\n/// Root of all [GraphQL queries][1] in the [`Schema`].\n\n///\n\n/// [1]: https://spec.graphql.org/June2018/#sec-Root-Operation-Types\n\n#[derive(Clone, Copy, Debu...
Rust
examples/imageview.rs
avandolder/ggez
54ba8b64e606f09f0dd06f7f1463f301a1747e62
use cgmath; use ggez; use rand; use ggez::audio; use ggez::audio::SoundSource; use ggez::event; use ggez::filesystem; use ggez::graphics::{self, Color}; use ggez::timer; use ggez::{Context, GameResult}; use std::env; use std::path; struct MainState { a: i32, direction: i32, image: graphics::Image, tex...
use cgmath; use ggez; use rand; use ggez::audio; use ggez::audio::SoundSource; use ggez::event; use ggez::filesystem; use ggez::graphics::{self, Color}; use ggez::timer; use ggez::{Context, GameResult}; use std::env; use std::path; struct MainState { a: i32, direction: i32, image: graphics::Image, tex...
} Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult { let c = self.a as u8; graphics::clear(ctx, [0.1, 0.2, 0.3, 1.0].into()); let color = Color::from((c, c, c, 255)); let dest_point = cgmath::Point2::new(0.0, 0.0); graphics::draw(ctx, &self....
if self.a > 250 || self.a <= 0 { self.direction *= -1; println!("Delta frame time: {:?} ", timer::delta(ctx)); println!("Average FPS: {}", timer::fps(ctx)); }
if_condition
[ { "content": "fn build_mesh(ctx: &mut Context) -> GameResult<graphics::Mesh> {\n\n let mb = &mut graphics::MeshBuilder::new();\n\n\n\n mb.line(\n\n &[\n\n Point2::new(200.0, 200.0),\n\n Point2::new(400.0, 200.0),\n\n Point2::new(400.0, 400.0),\n\n Point2:...
Rust
zebra-chain/src/serialization.rs
kiminuo/zebra
acbe711e0213d1dc43a487d4507852526742ea23
use std::io; use std::net::{IpAddr, SocketAddr}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; use thiserror::Error; #[derive(Error, Debug)] pub enum SerializationError { #[error("io error")] Io(#[from] io::Error), #[error("parse error: {0}")] Parse(&'static s...
use std::io; use std::net::{IpAddr, SocketAddr}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; use thiserror::Error; #[derive(Error, Debug)] pub enum SerializationError { #[error("io error")] Io(#[from] io::Error), #[error("parse error: {0}")] Parse(&'static s...
} #[test] fn compactsize_read_then_write_round_trip(bytes in prop::array::uniform9(0u8..)) { if let Ok(s) = Cursor::new(&bytes[..]).read_compactsize() { let...
}; self.write_all(&v6_addr.octets()) } #[inline] fn write_socket_addr(&mut self, addr: SocketAddr) -> io::Result<()> { self.write_ip_addr(addr.ip())?; self.write_u16::<BigEndian>(addr.port()) } #[inline] fn write_string(&mut self, string: &str) -> io::...
random
[ { "content": "fn write_coinbase_height<W: io::Write>(height: BlockHeight, mut w: W) -> Result<(), io::Error> {\n\n // We can't write this as a match statement on stable until exclusive range\n\n // guards are stabilized.\n\n if let 0 = height.0 {\n\n // Genesis block does not include height.\n\n...
Rust
libchordr/src/repeat_detector/mod.rs
cundd/chordr
243a7dcfa1e619dad76de788338485c76c07b51c
use crate::models::structure::SectionIdentifier; use crate::repeat_detector::state_machine::{RepeatMatch, StateMachine}; mod state_machine; #[derive(Debug, PartialEq)] pub(crate) struct RepeatInfo { pub count: usize, pub identifier: SectionIdentifier, } impl RepeatInfo { fn new(count: usize, identifier:...
use crate::models::structure::SectionIdentifier; use crate::repeat_detector::state_machine::{RepeatMatch, StateMachine}; mod state_machine; #[derive(Debug, PartialEq)] pub(crate) struct RepeatInfo { pub count: usize, pub identifier: SectionIdentifier, } impl RepeatInfo { fn new(count: usize, identifier:...
r.detect("Chorus 5*").unwrap() ); assert_eq!( RepeatInfo::new(5, "My Chorus".try_into().unwrap()), detector.detect("My Chorus 5x").unwrap() ); assert_eq!( RepeatInfo::new(5, "My Chorus".try_into().unwrap()), detector.detect("My Chorus 5*")....
) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn detect_prefix_test() { let detector = RepeatDetector::new(); assert_eq!( RepeatInfo::new(2, "Chorus".try_into().unwrap()), detector.detect("2x Chorus").unwrap() ); ...
random
[ { "content": "pub fn json_format<T: Into<JsonTemplateValue>>(format: &str, values: Vec<T>) -> String {\n\n let mut output = format.to_owned();\n\n for value in values {\n\n output = output.replacen(\"$\", &value.into().to_string(), 1);\n\n }\n\n\n\n output\n\n}\n", "file_path": "srvchord/...
Rust
jssat_frontend_js/src/ast/parser/exprs.rs
SirJosh3917/jssat
200f2c7a01287aa43fe6a431c89dd3b4e6ce2b13
#![allow(unused_imports)] #![allow(clippy::match_single_binding)] use crate::ast::parse_nodes::{ArgumentList, IdentifierName}; use super::super::parse_nodes as js; use super::ToParseNode; use swc_ecmascript::ast as swc; impl ToParseNode<js::Expression> for swc::Expr { fn to_parse_node(self) -> js::Expression { ...
#![allow(unused_imports)] #![allow(clippy::match_single_binding)] use crate::ast::parse_nodes::{ArgumentList, IdentifierName}; use super::super::parse_nodes as js; use super::ToParseNode; use swc_ecmascript::ast as swc; impl ToParseNode<js::Expression> for swc::Expr { fn to_parse_node(self) -> js::Expression { ...
}) .unwrap(), other => js::Expression::Variant0(parse_assignment(other).into()), } } fn parse_assignment(expr: swc::Expr) -> js::AssignmentExpression { use swc::Expr::*; match expr { other => js::AssignmentExpression::Variant0(parse_conditional(other).into()), ...
Some(match a { None => js::Expression::Variant0(b.into()), Some(e) => js::Expression::Variant1(e.into(), b.into()), })
call_expression
[ { "content": "fn parse_function_declaration(ident: swc::Ident, f: swc::Function) -> js::FunctionDeclaration {\n\n let name = swc::BindingIdent {\n\n id: ident,\n\n type_ann: None,\n\n }\n\n .to_parse_node();\n\n\n\n let formal_params = f.params.to_parse_node();\n\n\n\n let body = f....
Rust
src/kernel/trampoline.rs
o8vm/octox
ebf5e76766d0b3b85fcf3dcb5871d465b80a7013
use core::arch::asm; use core::hint::unreachable_unchecked; #[link_section = "trampsec"] #[no_mangle] pub unsafe extern "C" fn trampoline() -> ! { asm!(".align 4"); #[link_section = "trampsec"] #[no_mangle] pub unsafe extern "C" fn uservec() -> ! { ...
use core::arch::asm; use core::hint::unreachable_unchecked; #[link_section = "trampsec"] #[no_mangle] pub unsafe extern "C" fn trampoline() -> ! { asm!(".align 4"); #[link_section = "trampsec"] #[no_mangle] pub unsafe extern "C" fn uservec() -> ! { ...
0})", "ld a2, 128({0})", "ld a3, 136({0})", "ld a4, 144({0})", "ld a5, 152({0})", "ld a6, 160({0})", "ld a7, 168({0})", "ld s2, 176({0})", "ld s3, 184({0})", "ld s4, 192({0})", "ld s5, 200({0})", ...
"sfence.vma zero, zero", in(reg) pagetable, ); asm!( "ld t0, 112({0})", "csrw sscratch, t0", in(reg) trapframe, ); asm!( "ld ra, 40({0})", "ld sp, 48({0})", "ld gp, 56({0})"...
random
[ { "content": "// Create a new process, copying the parent.\n\n// Sets up child kernel stack to return as if from fork() system call.\n\npub fn fork() -> Result<usize> {\n\n let p = Cpus::myproc().unwrap();\n\n let p_data = p.data_mut();\n\n let (c, c_guard) = PROCS.alloc()?;\n\n let c_data = c.data_...
Rust
src/game/game.rs
mattswoon/yeats
7f235d340c03eb291fa1a3a84d837f8b29296cae
use rand::{ thread_rng, seq::SliceRandom, }; use serenity::{ prelude::TypeMapKey, model::{ channel::GuildChannel, }, utils::MessageBuilder, }; use crate::{ error::Error, game::{ game_error::GameError, player::Player, turn::{TurnState, Turn, TurnSummary}, ...
use rand::{ thread_rng, seq::SliceRandom, }; use serenity::{ prelude::TypeMapKey, model::{ channel::GuildChannel, }, utils::MessageBuilder, }; use crate::{ error::Error, game::{ game_error::GameError, player::Player, turn::{TurnState, Turn, TurnSummary}, ...
.push("Get ready ") .mention(&t.performer.user) .push(", you'll be performing for ") .mention(&t.guesser.user) .push("!!") .build() ), TurnState::Guessi...
inished) }?; self.state = new_state; Ok(()) } pub fn start_game(&mut self, channel: GuildChannel) -> Result<(), Error> { match &self.state { GameState::PreGame => { self.state = GameState::Round(Round::new(1, &self.players)); self.main...
random
[ { "content": "struct CluePool<C> {\n\n pool: Vec<C>,\n\n rejected: Vec<C>\n\n}\n\n\n\nimpl<C: Clone> CluePool<C> {\n\n fn new(pool: Vec<C>) -> CluePool<C> {\n\n CluePool { pool, rejected: vec![] }\n\n }\n\n\n\n fn to_vec(self) -> Vec<C> {\n\n let CluePool { pool, rejected } = self;\...
Rust
ethereum/lighthouse/account_manager/src/main.rs
AntonPecherkin/ChainMetric
483e3bc1e3f5b1629b9820825dd9784348e40a95
use bls::Keypair; use clap::{App, Arg, SubCommand}; use slog::{crit, debug, info, o, Drain}; use std::fs; use std::path::PathBuf; use types::test_utils::generate_deterministic_keypair; use validator_client::Config as ValidatorClientConfig; pub const DEFAULT_DATA_DIR: &str = ".lighthouse-validator"; pub const CLIENT_CO...
use bls::Keypair; use clap::{App, Arg, SubCommand}; use slog::{crit, debug, info, o, Drain}; use std::fs; use std::path::PathBuf; use types::test_utils::generate_deterministic_keypair; use validator_client::Config as ValidatorClientConfig; pub const DEFAULT_DATA_DIR: &str = ".lighthouse-validator"; pub const CLIENT_CO...
terministic( validator_index: usize, config: &ValidatorClientConfig, log: &slog::Logger, ) { save_key( &generate_deterministic_keypair(validator_index), config, log, ) } fn save_key(keypair: &Keypair, config: &ValidatorClientConfig, log: &slog::Logger) { let key_path: Pa...
rit!(log, "Failed to parse ClientConfig CLI arguments"; "error" => format!("{:?}", e)); return; }; info!(log, ""; "data_dir" => &client_config.data_dir.to_str()); match matches.subcommand() { ("generate", Some(_)) => generate_random(&client_config, &log), ("generate_...
random
[ { "content": "pub fn assert_tests_pass(handler_name: &str, path: &Path, results: &[CaseResult]) {\n\n let (failed, skipped_bls, skipped_known_failures) = categorize_results(results);\n\n\n\n if failed.len() + skipped_known_failures.len() > 0 {\n\n print_results(\n\n handler_name,\n\n ...
Rust
policy-test/tests/admit_authorization_policy.rs
evan-hines-firebolt/linkerd2
57a683a32ebc5c0df805d2d7d9ab0f029f00e400
use linkerd_policy_controller_k8s_api::{ self as api, policy::{AuthorizationPolicy, AuthorizationPolicySpec, LocalTargetRef, NamespacedTargetRef}, }; use linkerd_policy_test::admission; #[tokio::test(flavor = "current_thread")] async fn accepts_valid() { admission::accepts(|ns| AuthorizationPolicy { ...
use linkerd_policy_controller_k8s_api::{ self as api, policy::{AuthorizationPolicy, AuthorizationPolicySpec, LocalTargetRef, NamespacedTargetRef}, }; use linkerd_policy_test::admission; #[tokio::test(flavor = "current_thread")] async fn accepts_valid() { admission::accepts(|ns| AuthorizationPolicy { ...
#[tokio::test(flavor = "current_thread")] async fn rejects_target_ref_deployment() { admission::rejects(|ns| AuthorizationPolicy { metadata: api::ObjectMeta { namespace: Some(ns), name: Some("test".to_string()), ..Default::default() }, spec: Authorizatio...
o", version = "v1alpha1", kind = "AuthorizationPolicy", namespaced )] #[serde(rename_all = "camelCase")] pub struct FakeAuthorizationPolicySpec { pub target_ref: LocalTargetRef, pub required_authentication_refs: Option<Vec<NamespacedTargetRef>>, } admission::...
function_block-function_prefixed
[ { "content": "fn group_kind_name<T>(resource: &T) -> (Option<String>, String, String)\n\nwhere\n\n T: kube::Resource,\n\n T::DynamicType: Default,\n\n{\n\n let dt = Default::default();\n\n\n\n let group = match T::group(&dt) {\n\n g if (*g).is_empty() => None,\n\n g => Some(g.to_string...
Rust
hphp/hack/src/typing/typing_env.rs
tahmidbintaslim/hhvm
64adfea366cfcd3488bddd4b482d5d9963817db8
use crate::typing_env_return_info; pub use crate::typing_env_types::*; use crate::typing_local_types::Local; use crate::typing_per_cont_env::{PerContEntry, TypingContKey}; use decl_provider_rust as decl_provider; use oxidized::ident::Ident; use oxidized::pos::Pos; use oxidized::relative_path::RelativePath; use oxidi...
use crate::typing_env_return_info; pub use crate::typing_env_types::*; use crate::typing_local_types::Local; use crate::typing_per_cont_env::{PerContEntry, TypingContKey}; use decl_provider_rust as decl_provider; use oxidized::ident::Ident; use oxidized::pos::Pos; use oxidized::relative_path::RelativePath; use oxidi...
pub fn get_local_expr_id(&self, x: LocalId<'a>) -> Option<Ident> { match self.next_cont_opt() { None => { /* dead code */ None } Some(next_cont) => { let lcl = next_cont.local_types.find_ref(&x); lcl.map(|L...
let local = Local(*ty, new_eid); let per_cont_env = self.lenv .per_cont_env .add_to_cont(bld, TypingContKey::Next, x, local); self.lenv.per_cont_env = per_cont_env; } _...
function_block-function_prefix_line
[]
Rust
src/solutions/year2021/day19.rs
aquarhead/advent-of-rust
1027f23cb6ed3b1da971a474518493ddec0a986a
use itertools::Itertools; use rayon::prelude::*; use std::{collections::HashSet, fs}; type Pos = (i32, i32, i32); type PosSet = HashSet<Pos>; #[derive(Debug, Clone)] struct Scanner { beacons: PosSet, aligned: Option<(PosSet, Pos)>, } pub fn solution() { let content = fs::read_to_string("inputs/2021/19.txt").un...
use itertools::Itertools; use rayon::prelude::*; use std::{collections::HashSet, fs}; type Pos = (i32, i32, i32); type PosSet = HashSet<Pos>; #[derive(Debug, Clone)] struct Scanner { beacons: PosSet, aligned: Option<(PosSet, Pos)>, } pub fn solution() { let content = fs::read_to_string("inputs/2021/19.txt").un...
}) .collect::<Vec<_>>(); resolvers.extend(nr); if scanners.iter().all(|s| s.aligned.is_some()) { break; } } println!( "beacons: {}", scanners .iter() .fold(HashSet::new(), |mut acc, s| { let x = s.aligned.as_ref().unwrap(); x.0.iter().for_each(|&...
if let Some(align) = try_overlap(&resolver, &s) { s.aligned = Some(align); Some(idx) } else { None }
if_condition
[ { "content": "fn terminate(prog: &Vec<Inst>, mut acc: i32, mut pc: usize, mut visited: HashSet<usize>) -> Option<i32> {\n\n loop {\n\n visited.insert(pc);\n\n match prog.get(pc).unwrap() {\n\n Acc(arg) => {\n\n acc += arg;\n\n pc += 1;\n\n }\n\n Jmp(arg) => {\n\n pc = ...
Rust
src/main.rs
pbartyik/window-renamer
4e31223d7423eb7088cce7a819e0ce79f186c28e
use regex::Regex; use rexpect::process; use rexpect::spawn; use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::path::Path; use std::process::Command; use std::time; use tokio::prelude::*; use tokio::sync::mpsc; use tokio::task; use tokio::time::delay_for; #[derive(Debug, Clone)] struct Prompt {...
use regex::Regex; use rexpect::process; use rexpect::spawn; use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::path::Path; use std::process::Command; use std::time; use tokio::prelude::*; use tokio::sync::mpsc; use tokio::task; use tokio::time::delay_for; #[derive(Debug, Clone)] struct Prompt {...
} enum TreeInstruction { ProcessLine(String), RemovePane(u32), Refresh, } enum Instruction { Refresh, AttachTo(u32), RemovePane(u32), DoNothing, } #[tokio::main] async fn main() { let prompts = vec![Prompt { name: "titan".to_string(), rege...
fn remove_pane(&mut self, pane_id: u32) { self.panes.remove(&pane_id); let window_id = self.clone().get_window_of_pane(pane_id).unwrap(); let index = self.windows[&window_id] .iter() .position(|pid| *pid == pane_id) .unwrap(); let mut windows = self.wi...
function_block-full_function
[ { "content": "Tool to automatically rename tmux windows to connected devices for quick navigation with fzf.\n", "file_path": "readme.md", "rank": 5, "score": 8229.368522776384 } ]
Rust
src/request/notification/plain.rs
Atlas-Apps/a2
3c7f3254c9629783600344c17423d2868dd95f94
use crate::request::notification::{NotificationBuilder, NotificationOptions}; use crate::request::payload::{APSAlert, Payload, APS}; use std::collections::BTreeMap; pub struct PlainNotificationBuilder<'a> { body: &'a str, badge: Option<u32>, sound: Option<&'a str>, category: Option<&'a str>, } impl<'a...
use crate::request::notification::{NotificationBuilder, NotificationOptions}; use crate::request::payload::{APSAlert, Payload, APS}; use std::collections::BTreeMap; pub struct PlainNotificationBuilder<'a> { body: &'a str, badge: Option<u32>, sound: Option<&'a str>, category: Option<&'a str>, } impl<'a...
ap(); let expected_payload = json!({ "aps": { "alert": "kulli", } }) .to_string(); assert_eq!(expected_payload, payload); } #[test] fn test_plain_notification_with_full_data() { let mut builder = PlainNotificationBuilder::new...
[cfg(test)] mod tests { use super::*; #[test] fn test_plain_notification_with_text_only() { let payload = PlainNotificationBuilder::new("kulli") .build("device-token", Default::default()) .to_json_string() .unwr
random
[ { "content": "#[derive(Serialize, Deserialize)]\n\nstruct JwtPayload<'a> {\n\n iss: &'a str,\n\n iat: i64,\n\n}\n\n\n\nimpl Signer {\n\n /// Creates a signer with a pkcs8 private key, APNs key id and team id.\n\n /// Can fail if the key is not valid or there is a problem with system OpenSSL.\n\n ...
Rust
src/quaternion.rs
sebcrozet/cgmath-rs
0bbefed4bcbc36569a34764e5399bcac07323325
use std::fmt; use std::mem; use std::num::{zero, one, cast}; use angle::{Angle, Rad, acos, sin, sin_cos, rad}; use approx::ApproxEq; use array::Array1; use matrix::{Matrix3, ToMatrix3, ToMatrix4, Matrix4}; use num::BaseFloat; use point::Point3; use rotation::{Rotation, Rotation3, Basis3, ToBasis3}; use vector::{Vect...
use std::fmt; use std::mem; use std::num::{zero, one, cast}; use angle::{Angle, Rad, acos, sin, sin_cos, rad}; use approx::ApproxEq; use array::Array1; use matrix::{Matrix3, ToMatrix3, ToMatrix4, Matrix4}; use num::BaseFloat; use point::Point3; use rotation::{Rotation, Rotation3, Basis3, ToBasis3}; use vector::{Vect...
; let theta: Rad<S> = acos(robust_dot.clone()); let scale1 = sin(theta.mul_s(one::<S>() - amount)); let scale2 = sin(theta.mul_s(amount)); self.mul_s(scale1) .add_q(&other.mul_s(scale2)) .mul_s(sin(theta).recip()) } } ...
if dot > one::<S>() { one::<S>() } else if dot < -one::<S>() { -one::<S>() } else { dot }
if_condition
[ { "content": "/// An array containing elements of type `Element`\n\npub trait Array1<Element: Copy>: Index<uint, Element> + IndexMut<uint, Element> {\n\n /// Get the pointer to the first element of the array.\n\n fn ptr<'a>(&'a self) -> &'a Element {\n\n &(*self)[0]\n\n }\n\n\n\n /// Get a mu...
Rust
src/util/util_test.rs
edmellum/sdp
9c8a55f63ac010263a260934576ed9d883adb231
use super::*; use crate::common_description::*; use crate::media_description::*; use crate::session_description::*; use util::Error; fn get_test_session_description() -> SessionDescription { return SessionDescription{ media_descriptions: vec![ MediaDescription { media_name: Med...
use super::*; use crate::common_description::*; use crate::media_description::*; use crate::session_description::*; use util::Error; fn get_test_session_description() -> SessionDescription { return SessionDescription{ media_descriptions: vec![ MediaDescription { media_name: Med...
not generated") } Ok(()) }
payload_type: 121, name: "VP9".to_string(), clock_rate: 90000, fmtp: "max-fs=12288;max-fr=60".to_string(), ..Default::default() }, ), ( 126, Codec { payload_type: 126, ...
random
[ { "content": "#[test]\n\nfn test_extmap() -> Result<(), Error> {\n\n let example_attr_extmap1_line = EXAMPLE_ATTR_EXTMAP1;\n\n let example_attr_extmap2_line = EXAMPLE_ATTR_EXTMAP2;\n\n let failing_attr_extmap1_line =\n\n format!(\"{}{}{}\", ATTRIBUTE_KEY, FAILING_ATTR_EXTMAP1, END_LINE);\n\n ...
Rust
rmi_lib/src/models/cubic_spline.rs
Cobra8/RMI-P4
297ef9ae92b883fb997e961d0164450d55919e46
use crate::models::*; macro_rules! scale { ($val: expr, $min: expr, $max: expr) => { ($val - $min) / ($max - $min) }; } #[allow(clippy::float_cmp)] fn cubic<T: TrainingKey>(data: &RMITrainingData<T>) -> (f64, f64, f64, f64) { if data.len() == 0 { return (0.0, 0.0, 1.0, 0.0); } i...
use crate::models::*; macro_rules! scale { ($val: expr, $min: expr, $max: expr) => { ($val - $min) / ($max - $min) }; } #[allow(clippy::float_cmp)] fn cubic<T: TrainingKey>(data: &RMITrainingData<T>) -> (f64, f64, f64, f64) { if data.len() == 0 { return (0.0, 0.0, 1.0, 0.0); } i...
* m2 - 6.0)) / (xmax - xmin).powf(3.0); let mut d = -xmin * (m1 * xmax.powf(2.0) + xmax * xmin * (m2 - 3.0) + xmin.powf(2.0)) / (xmax - xmin).powf(3.0); a *= ymax - ymin; b *= ymax - ymin; c *= ymax - ymin; d *= ymax - ymin; d += ymin; return (a, b, c, d); } ...
ast_pt = data.get(data.len() - 1); let (xmin, ymin) = (first_pt.0.as_float(), first_pt.1 as f64); let (xmax, ymax) = (last_pt.0.as_float(), last_pt.1 as f64); let (x1, y1) = (0.0, 0.0); let (x2, y2) = (1.0, 1.0); let mut m1 = { let (xn, yn) = data .iter() .find(|&(t...
random
[ { "content": "fn phi(x: f64) -> f64 {\n\n return 1.0 / (1.0 + exp1(-1.65451 * x));\n\n}\n\n\n", "file_path": "rmi_lib/src/models/normal.rs", "rank": 0, "score": 134839.29313369017 }, { "content": "fn exp1(inp: f64) -> f64 {\n\n let mut x = inp;\n\n x = 1.0 + x / 64.0;\n\n x *= x;...
Rust
components/engine_rocks/src/flow_listener.rs
xiongjiwei/tikv
6be3893f7f787b04bf34d99d1369092404ab5cfc
use collections::hash_set_with_capacity; use rocksdb::{CompactionJobInfo, EventListener, FlushJobInfo, IngestionInfo}; use std::sync::mpsc::Sender; use std::sync::Mutex; pub enum FlowInfo { L0(String, u64), L0Intra(String, u64), Flush(String, u64), Compaction(String), } pub struct FlowListener { ...
use collections::hash_set_with_capacity; use rocksdb::{CompactionJobInfo, EventListener, FlushJobInfo, IngestionInfo}; use std::sync::mpsc::Sender; use std::sync::Mutex; pub enum FlowInfo { L0(String, u64), L0Intra(String, u64), Flush(String, u64), Compaction(String), } pub struct FlowListener { ...
fn on_external_file_ingested(&self, info: &IngestionInfo) { if info.picked_level() == 0 { let mut total = 0; let p = info.table_properties(); total += p.data_size() + p.index_size() + p.filter_size(); let _ = self .flow_info_sender ...
fn on_flush_completed(&self, info: &FlushJobInfo) { let mut total = 0; let p = info.table_properties(); total += p.data_size() + p.index_size() + p.filter_size(); let _ = self .flow_info_sender .lock() .unwrap() .send(FlowInfo::Flush(info.c...
function_block-full_function
[ { "content": "pub fn notify_stale_req(term: u64, cb: Callback<impl Snapshot>) {\n\n let resp = cmd_resp::err_resp(Error::StaleCommand, term);\n\n cb.invoke_with_response(resp);\n\n}\n\n\n", "file_path": "components/raftstore/src/store/fsm/apply.rs", "rank": 0, "score": 292202.61229060614 }, ...
Rust
src/graph/grid.rs
kena0ki/rustrithm
fba8480de2240c71af8182a5404e1217dfb73b76
use super::Graph; use super::Edge; use super::WeightedEdge; use super::dinic::Dinic; #[derive(Debug,Default,Clone,PartialEq,Eq)] pub struct Grid<T> { x_size: usize, y_size: usize, graph: T, } impl <T> Grid<T> { pub fn graph(&self) -> &T { return &self.graph; } pub fn x_size(&self) -> u...
use super::Graph; use super::Edge; use super::WeightedEdge; use super::dinic::Dinic; #[derive(Debug,Default,Clone,PartialEq,Eq)] pub struct Grid<T> { x_size: usize, y_size: usize, graph: T, } impl <T> Grid<T> { pub fn graph(&self) -> &T { return &self.graph; } pub fn x_size(&self) -> u...
.y_size); } let x= node % self.x_size; let y= node / self.x_size; return (x,y); } fn edges_from_node<F>(&mut self, x: usize, y:usize, delta_x: &[i64], delta_y: &[i64], should_skip: F) -> Vec<(usize,usize)> where F: Fn(usize,usize) -> bool { let mut edges = Vec::wi...
usize, usize) { if node >= self.x_size * self.y_size { panic!("node >= self.x_size * self.y_size: {:?} >= {:?} * {:?}", node, self.x_size, self
function_block-random_span
[ { "content": "/// Z algorithm: computes the array Z[..], where Z[i] is the length of the\n\n/// longest text prefix of text[i..] that is **also a prefix** of text.\n\n///\n\n/// It runs in O(n) time, maintaining the invariant that l <= i and\n\n/// text[0..r-l] == text[l..r]. It can be embedded in a larger algo...
Rust
src/algorithm/raders_algorithm.rs
adamnemecek/RustFFT
9e8e14877361e1f7223046e69136e62711b697c2
use std::sync::Arc; use num_complex::Complex; use num_traits::Zero; use strength_reduce::StrengthReducedUsize; use crate::common::{verify_length, verify_length_divisible, FFTnum}; use crate::math_utils; use crate::twiddles; use crate::{IsInverse, Length, FFT}; pub struct RadersAlgorithm<T> { inner_fft: Arc<FFT<...
use std::sync::Arc; use num_complex::Complex; use num_traits::Zero; use strength_reduce::StrengthReducedUsize; use crate::common::{verify_length, verify_length_divisible, FFTnum}; use crate::math_utils; use crate::twiddles; use crate::{IsInverse, Length, FFT}; pub struct RadersAlgorithm<T> { inner_fft: Arc<FFT<...
} impl<T> Length for RadersAlgorithm<T> { #[inline(always)] fn len(&self) -> usize { self.len.get() } } impl<T> IsInverse for RadersAlgorithm<T> { #[inline(always)] fn is_inverse(&self) -> bool { self.inner_fft.is_inverse() } } #[cfg(test)] mod unit_tests { use super::*; ...
fn process_multi(&self, input: &mut [Complex<T>], output: &mut [Complex<T>]) { verify_length_divisible(input, output, self.len()); for (in_chunk, out_chunk) in input .chunks_mut(self.len()) .zip(output.chunks_mut(self.len())) { self.perform_fft(in_chunk, out_...
function_block-full_function
[ { "content": "#[inline(always)]\n\npub fn verify_length<T>(input: &[T], output: &[T], expected: usize) {\n\n assert_eq!(\n\n input.len(),\n\n expected,\n\n \"Input is the wrong length. Expected {}, got {}\",\n\n expected,\n\n input.len()\n\n );\n\n assert_eq!(\n\n ...
Rust
src/day08/main.rs
eadanfahey/aoc2020
2b295dfd2092bdbd203a6606f75ac7e196c9a14c
use clap::{App, Arg}; use std::{fs}; use std::collections::{HashSet}; use std::convert::{TryFrom}; #[derive(Debug, Clone)] enum Instruction { Acc(i64), Jmp(i64), Nop(i64), } #[derive(Debug)] struct VM { instructions: Vec<Instruction>, acc: i64, pos: usize, } impl VM { fn...
use clap::{App, Arg}; use std::{fs}; use std::collections::{HashSet}; use std::convert::{TryFrom}; #[derive(Debug, Clone)] enum Instruction { Acc(i64), Jmp(i64), Nop(i64), } #[derive(Debug)] struct VM { instructions: Vec<Instruction>, acc: i64, pos: usize, } impl VM { fn...
fn part2(instructions: Vec<Instruction>) -> i64 { let swaps = instructions.iter() .enumerate() .filter_map(|(i, instruction)| { match instruction { Instruction::Acc(_) => None, Instruction::Jmp(n) => Some((i, Instruction::Nop(*n))), Instr...
fn part1(instructions: Vec<Instruction>) -> i64 { let mut vm = VM::new(instructions); let mut visited: HashSet<usize> = HashSet::new(); loop { if !visited.insert(vm.pos) { return vm.acc; } vm.execute().unwrap(); } }
function_block-full_function
[ { "content": "fn parse_input(s: &str) -> Option<Vec<Instruction>> {\n\n let mut instructions = Vec::new();\n\n let mut cur_mask = Mask {on: 0, off: 0};\n\n for line in s.split('\\n').filter(|l| !l.is_empty()) {\n\n let mut sp = line.split(\" = \");\n\n let ident = sp.next()?;\n\n i...
Rust
arangodb-tests/src/tests/db_mutex/acquire.rs
juliotpaez/arangodb-types
6170a751a07273a4c74d989245815212795240ac
use arangodb_types::traits::DBCollection; use arangodb_types::traits::DBDocument; use arangodb_types::types::dates::DBDateTime; use arangodb_types::types::DBMutex; use arangodb_types::types::{DBUuid, NullableOption}; use arangodb_types::utilities::{DBMutexError, DBMutexGuard}; use crate::tests::constants::NODE_ID; use...
use arangodb_types::traits::DBCollection; use arangodb_types::traits::DBDocument; use arangodb_types::types::dates::DBDateTime; use arangodb_types::types::DBMutex; use arangodb_types::types::{DBUuid, NullableOption}; use arangodb_types::utilities::{DBMutexError, DBMutexGuard}; use crate::tests::constants::NODE_ID; use...
let document = collection .get_one_by_key(&document_key, None) .await .expect("There is an error trying to get the document") .expect("The document does not exist in DB"); assert_eq!(document.db_key, Some(document_key), "Incorrect db_key"); assert!(document.db_mutex.i...
match error { Ok(_) => panic!("Locking must fail"), Err(DBMutexError::Timeout) => {} _ => unreachable!(), }
if_condition
[ { "content": "#[test]\n\nfn x() {\n\n let x = serde_json::to_string(&ApiTestSimpleEnum::Data).unwrap();\n\n println!(\"{}\", x);\n\n\n\n let x = serde_json::to_string(&ApiTestComplexEnum::Data(54)).unwrap();\n\n println!(\"{}\", x)\n\n}\n", "file_path": "arangodb-tests/src/tests/db_mutex/types.r...
Rust
src/bin/cp2cp.rs
silicon-heaven/chainpack-rs
c051c6c7c49eac48eb947ac900a81438f8d55e50
use clap::{Arg, App}; use std::{process, io, fs}; use std::io::{BufReader, BufRead, BufWriter, stdout}; use chainpack::{CponReader, ChainPackReader, ChainPackWriter, CponWriter}; use chainpack::Reader; use chainpack::Writer; use fern::colors::ColoredLevelConfig; use colored::Color; use colored::Colorize; fn setup_log...
use clap::{Arg, App}; use std::{process, io, fs}; use std::io::{BufReader, BufRead, BufWriter, stdout}; use chainpack::{CponReader, ChainPackReader, ChainPackWriter, CponWriter}; use chainpack::Reader; use chainpack::Writer; use fern::colors::ColoredLevelConfig; use colored::Color; use colored::Colorize; fn setup_log...
failed to initialize logging."); log::info!("====================================================="); log::info!("{} starting up!", std::module_path!()); log::info!("====================================================="); log::info!("Verbosity levels: {}", levels.iter() .map(|(target, level)| f...
, log::LevelFilter::Info)); base_config .level(log::LevelFilter::Info) } Some(levels) => { for level_str in levels.split(',') { let parts: Vec<&str> = level_str.split(':').collect(); let (target, level_abbr) = if parts.len() == 1 { ...
random
[ { "content": "fn from_cpon(data: &str) -> RpcValue {\n\n return RpcValue::from_cpon(data).unwrap()\n\n}\n\n\n", "file_path": "tests/tst_rpcvalue.rs", "rank": 0, "score": 61017.03349914194 }, { "content": "fn main() {\n\n env_logger::init();\n\n let cpon1 = r#\"<1:\"foo\">[1,2,3]\"#;...
Rust
service-common/src/state/mod.rs
ctron/drogue-cloud
5337643fe98ae8f50b45509988da61e2944d54a4
mod config; mod mux; pub use self::config::*; pub use mux::*; use crate::client::DeviceStateClient; use chrono::{DateTime, Utc}; use drogue_client::{ error::{ClientError, ErrorInformation}, registry, }; use drogue_cloud_service_api::services::device_state::{ self, DeleteOptions, DeviceState, Id, InitRespo...
mod config; mod mux; pub use self::config::*; pub use mux::*; use crate::client::DeviceStateClient; use chrono::{DateTime, Utc}; use drogue_client::{ error::{ClientError, ErrorInformation}, registry, }; use drogue_cloud_service_api::services::device_state::{ self, DeleteOptions, DeviceState, Id, InitRespo...
pub async fn ping(&self, expires: DateTime<Utc>) -> anyhow::Result<(DateTime<Utc>, Instant)> { loop { if Utc::now() > expires { anyhow::bail!("Lost session. Must terminate."); } match self.client.ping(&self.session).await { Ok(response) ...
Time<Utc>) -> (DateTime<Utc>, Instant) { let deadline = expires - self.delay_buffer; let delay = (deadline - Utc::now()).num_milliseconds(); let delay = if delay < self.min_delay_ms { self.min_delay_ms as u64 } else { delay as u64 ...
function_block-function_prefixed
[ { "content": "pub fn hash_token(token: &str) -> String {\n\n format!(\"{:x}\", sha3::Sha3_512::digest(token.as_bytes()))\n\n}\n\n\n", "file_path": "access-token-service/src/rng.rs", "rank": 0, "score": 392058.15726042807 }, { "content": "/// The unix epoch, as [`chrono::DateTime`].\n\npub...
Rust
aorist_core/src/python/task/compressed.rs
Vibrant-Planet/aorist
067e119ef4d0d40802ce74a8e47d882e557ce195
use crate::flow::{CompressionKey, ETLFlow, ForLoopCompressedTask, TaskBase, UncompressiblePart}; use crate::python::task::key::PythonBasedTaskCompressionKey; use crate::python::task::uncompressible::PythonBasedTaskUncompressiblePart; use crate::python::{ Add, Assignment, Attribute, BigIntLiteral, BinOp, Call, Dict,...
use crate::flow::{CompressionKey, ETLFlow, ForLoopCompressedTask, TaskBase, UncompressiblePart}; use crate::python::task::key::PythonBasedTaskCompressionKey; use crate::python::task::uncompressible::PythonBasedTaskUncompressiblePart; use crate::python::{ Add, Assignment, Attribute, BigIntLiteral, BinOp, Call, Dict,...
; } else { dependencies = AOption(ROption::RSome(left)); } } let singleton = T::new( self.task_id.clone(), new_collector.clone(), self.key.get_call(), args, kwargs, dependencies, ...
AOption(ROption::RSome(AST::BinOp(BinOp::new_wrapped( left, op, right.clone(), ))))
call_expression
[ { "content": "pub trait CompressionKey: Clone + Hash + PartialEq + Eq {\n\n fn new(\n\n dict_name: AST,\n\n function_call: AOption<AString>,\n\n dedup_key: AOption<ParameterTupleDedupKey>,\n\n preamble: AOption<AString>,\n\n dialect: AOption<Dialect>,\n\n ) -> Self;\n\n ...
Rust
src/connection.rs
fluencelabs/sqlite-1
3431763954dc0727e1d65d6f37861ecfbc2d1e39
use crate::sqlite3_connector as ffi; use crate::{Result, Statement}; use std::marker::PhantomData; use std::path::Path; pub struct Connection { raw: ffi::Sqlite3DbHandle, phantom: PhantomData<ffi::Sqlite3DbHandle>, } #[derive(Clone, Copy, Debug)] pub struct OpenFlags(i32); unsafe impl Send for Connection {}...
use crate::sqlite3_connector as ffi; use crate::{Result, Statement}; use std::marker::PhantomData; use std::path::Path; pub struct Connection { raw: ffi::Sqlite3DbHandle, phantom: PhantomData<ffi::Sqlite3DbHandle>, } #[derive(Clone, Copy, Debug)] pub struct OpenFlags(i32); unsafe impl Send for Connection {}...
#[inline] pub fn execute<T: AsRef<str>>(&self, statement: T) -> Result<()> { unsafe { ok_descr!( self.raw, ffi::sqlite3_exec(self.raw, statement.as_ref().into(), 0, 0,) ); } Ok(()) } #[inline...
pub fn open_with_flags<T: AsRef<Path>>(path: T, flags: OpenFlags) -> Result<Connection> { unsafe { let path = path.as_ref(); let path = path.to_string_lossy().into_owned(); let result = ffi::sqlite3_open_v2(&path, flags.0, &String::new()); match result.ret_code {...
function_block-full_function
[ { "content": "#[inline]\n\npub fn new<T: AsRef<str>>(raw1: ffi::Sqlite3DbHandle, statement: T) -> Result<Statement> {\n\n let result = unsafe { ffi::sqlite3_prepare_v2(raw1, statement.as_ref().into()) };\n\n if result.ret_code != ffi::SQLITE_OK {\n\n error!(raw1, result.ret_code)\n\n }\n\n\n\n ...
Rust
mayastor/src/core/bio.rs
payes/mayastor
917c4f7cd8a3d8642307a7ea9165e2403bc4b028
use core::fmt; use std::{ fmt::{Debug, Formatter}, ptr::NonNull, }; use libc::c_void; use spdk_sys::{spdk_bdev_io, spdk_bdev_io_complete}; use crate::{ bdev::nexus::nexus_bdev::{Nexus, NEXUS_PRODUCT_ID}, core::{Bdev, NvmeStatus}, }; #[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Eq)] pub enum I...
use core::fmt; use std::{ fmt::{Debug, Formatter}, ptr::NonNull, }; use libc::c_void; use spdk_sys::{spdk_bdev_io, spdk_bdev_io_complete}; use crate::{ bdev::nexus::nexus_bdev::{Nexus, NEXUS_PRODUCT_ID}, core::{Bdev, NvmeStatus}, }; #[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Eq)] pub enum I...
} impl From<i8> for IoStatus { fn from(status: i8) -> Self { (status as i32).into() } } #[derive(Clone)] #[repr(transparent)] pub struct Bio(NonNull<spdk_bdev_io>); impl From<*mut c_void> for Bio { fn from(io: *mut c_void) -> Self { Bio(NonNull::new(io as *mut spdk_bdev_io).expect("null ...
2, IoStatus::Failed => -1, IoStatus::Pending => 0, IoStatus::Success => 1, } }
function_block-function_prefixed
[ { "content": "/// main shutdown routine for mayastor\n\npub fn mayastor_env_stop(rc: i32) {\n\n let r = Reactors::master();\n\n\n\n match r.get_state() {\n\n ReactorState::Running | ReactorState::Delayed | ReactorState::Init => {\n\n r.send_future(async move {\n\n do_shutd...
Rust
src/lib.rs
Trangar/bitrange
24097aaf3a259428eba652fbfc73a132838bfe05
#![deny(warnings)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "panic")] mod error { #[cfg(feature = "std")] use std::marker::PhantomData; #[cfg(feature = "std")] use std::fmt::Binary; #[cfg(not(feature = "std"))] use core::marker::PhantomData; #[cfg(not(feature = "std"))] ...
#![deny(warnings)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "panic")] mod error { #[cfg(feature = "std")] use std::marker::PhantomData; #[cfg(feature = "std")] use std::fmt::Binary; #[cfg(not(feature = "std"))] use core::marker::PhantomData; #[cfg(not(feature = "std"))] ...
} } pub use error::Error; #[macro_export] macro_rules! bitrange { ( $struct_name:ident: $struct_size:ty, $struct_size_string:tt, $format:tt, $( $field_format:ident: $( $field_name:ident )+ ),+ ) => { ...
pub fn invalid_bits(expected: T, provided: T) -> Error<T> { Error { expected, provided, } }
function_block-full_function
[ { "content": "#[proc_macro_derive(Bitrange, attributes(BitrangeMask, BitrangeSize))]\n\npub fn bitrange(input: TokenStream) -> TokenStream {\n\n let pattern = Pattern::from_stream(input).expect(\"Could not parse mask\");\n\n\n\n let str = format!(r#\"\n\nimpl {struct_name} {{\n\n {get_mask}\n\n {get...
Rust
src/events.rs
ishikado/slack-rs
1e8e385546ac96d76500f12606706c693475fb2a
use api::{Bot, Message, File, FileComment, Channel, User, MessageUnpinnedItem, MessagePinnedItem, stars, reactions}; use std::boxed::Box; #[derive(Clone, Debug, Deserialize)] #[serde(tag = "type")] #[serde(rename_all = "snake_case")] pub enum Event { Hello, Message(Box<Message>), ...
use api::{Bot, Message, File, FileComment, Channel, User, MessageUnpinnedItem, MessagePinnedItem, stars, reactions}; use std::boxed::Box; #[derive(Clone, Debug, Deserialize)] #[serde(tag = "type")] #[serde(rename_all = "snake_case")] pub enum Event { Hello, Message(Box<Message>), ...
#[test] fn decode_presence_change_event() { let event: Event = Event::from_json(r##"{ "type": "presence_change", "users": ["U024BE7LH", "U012EA2U1"], "presence": "away" }"##) .unwrap(); match event { Event::PresenceChange{...
Event::MessageError(MessageError { reply_to, error: MessageErrorDetail { code, msg, .. }, .. }) => { assert_eq!(reply_to, 1); assert_eq!(code, 2); ...
function_block-function_prefix_line
[ { "content": "#[derive(Debug)]\n\nenum WsMessage {\n\n Close,\n\n Text(String),\n\n}\n\n\n\n/// The actual messaging client.\n\npub struct RtmClient {\n\n start_response: api::rtm::StartResponse,\n\n sender: Sender,\n\n rx: mpsc::Receiver<WsMessage>,\n\n}\n\n\n\n/// Thread-safe API for sending me...
Rust
src/citysim/texcache.rs
glampert/rust-citysim
cf988f5cd5f2686e9b03f5a5169c99817b6ad721
extern crate xml; extern crate image; extern crate glium; use std; use std::path::Path; use std::fs::File; use std::io::BufReader; use xml::reader::{EventReader, XmlEvent}; use citysim::common::*; use citysim::tile::{Tile, TileGeometry}; pub struct TexAtlasSubTexture { pub filename: String, pub x: ...
extern crate xml; extern crate image; extern crate glium; use std; use std::path::Path; use std::fs::File; use std::io::BufReader; use xml::reader::{EventReader, XmlEvent}; use citysim::common::*; use citysim::tile::{Tile, TileGeometry}; pub struct TexAtlasSubTexture { pub filename: String, pub x: ...
et tex_file_path = format!("{}{}{}{}", base_path, path_sep, atlas_file, tex_ext); let as_sys_path = Path::new(&tex_file_path); let meta_file_path = format!("{}{}{}{}", base_path, path_sep, atlas_file, meta_ext); let atlas = TextureAtlas::parse_from_xml(meta_file_path.as_ref()); ...
= TEXTURE_ATLAS_TEX_FILE_EXT; let tex_atlas_list = config.get_texture_atlases(); for atlas_file in tex_atlas_list { l
function_block-random_span
[ { "content": "fn main() {\n\n let config = Config::new();\n\n\n\n let display = glium::glutin::WindowBuilder::new()\n\n .with_dimensions(config.get_initial_screen_dimensions().0, config.get_initial_screen_dimensions().1)\n\n .with_title(format!(\"Hello world\"))\n\n .build_glium()\n\n...
Rust
src/map.rs
letheed/rgol
841513e265556e7328c15e4df8a727db1c65ce48
use std::{ error::Error, fmt::{self, Display}, ops::{Index, IndexMut}, str::FromStr, }; use cell::Cell; mod cell; #[derive(Debug)] pub enum ParseMapError { Empty, NotRectangular, } impl Error for ParseMapError {} impl Display for ParseMapError { fn fmt(&self, f: &mut fmt::Formatter<'_>)...
use std::{ error::Error, fmt::{self, Display}, ops::{Index, IndexMut}, str::FromStr, }; use cell::Cell; mod cell; #[derive(Debug)] pub enum ParseMapError { Empty, NotRectangular, }
1; cells.push(match c { '·' => Cell::new_dead(), _ => Cell::new_alive(), }); } if nchar != ncol { return Err(NotRectangular); } } Ok(Self::from_parts(cells, (nrow, ncol))) } }...
impl Error for ParseMapError {} impl Display for ParseMapError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ParseMapError::Empty => write!(f, "map is empty"), ParseMapError::NotRectangular => write!(f, "map is not rectangular"), } } } pub ...
random
[ { "content": "/// A cell that can be dead or alive.\n\n///\n\n/// When creating a new cell, both flags should be set to the same value.\n\n#[allow(clippy::manual_non_exhaustive)]\n\npub struct Cell {\n\n /// Is the cell alive?\n\n pub alive: bool,\n\n /// Does the cell live or die at the end of this tu...
Rust
zebra-chain/src/transparent/address.rs
preston-evans98/zebra-btc
7b67007d9e24d05bfd33d967115972d29d8faa3f
use std::{fmt, io}; use ripemd160::{Digest, Ripemd160}; use secp256k1::PublicKey; use sha2::{Digest as sha2Digest, Sha256}; #[cfg(test)] use proptest::{arbitrary::Arbitrary, collection::vec, prelude::*}; use crate::{ parameters::Network, serialization::{BitcoinDeserialize, BitcoinSerialize, SerializationEr...
use std::{fmt, io}; use ripemd160::{Digest, Ripemd160}; use secp256k1::PublicKey; use sha2::{Digest as sha2Digest, Sha256}; #[cfg(test)] use proptest::{arbitrary::Arbitrary, collection::vec, prelude::*}; use crate::{ parameters::Network, serialization::{BitcoinDeserialize, BitcoinSerialize, SerializationEr...
#[test] fn empty_script_testnet() { zebra_test::init(); let script = Script(vec![0; 20]); let t_addr = script.to_address(Network::Testnet); assert_eq!(format!("{}", t_addr), "t2L51LcmpA43UMvKTw2Lwtt9LMjwyqU2V1P"); } #[test] fn from_string() { zebra_test:...
zebra_test::init(); let script = Script(vec![0; 20]); let t_addr = script.to_address(Network::Mainnet); assert_eq!(format!("{}", t_addr), "t3Y5pHwfgHbS6pDjj1HLuMFxhFFip1fcJ6g"); }
function_block-function_prefix_line
[ { "content": "/// Check that the hard-coded lists cover the Sapling network upgrade\n\nfn checkpoint_list_hard_coded_segwit(network: Network) -> Result<(), BoxError> {\n\n zebra_test::init();\n\n\n\n let sapling_activation = SegWit\n\n .activation_height(network)\n\n .expect(\"Unexpected net...
Rust
linkerd/io/src/boxed.rs
ihciah/linkerd2-proxy
dcd95569da4f9356ec4a0ef48c312336228025ac
use super::{AsyncRead, AsyncWrite, IoSlice, PeerAddr, Poll, ReadBuf, Result}; use std::{pin::Pin, task::Context}; pub struct BoxedIo(Pin<Box<dyn Io + Unpin>>); trait Io: AsyncRead + AsyncWrite + PeerAddr + Send {} impl<I> Io for I where I: AsyncRead + AsyncWrite + PeerAddr + Send {} impl BoxedIo { pub fn new<T>...
use super::{AsyncRead, AsyncWrite, IoSlice, PeerAddr, Poll, ReadBuf, Result}; use std::{pin::Pin, task::Context}; pub struct BoxedIo(Pin<Box<dyn Io + Unpin>>); trait Io: AsyncRead + AsyncWrite + PeerAddr + Send {} impl<I> Io for I where I: AsyncRead + AsyncWrite + PeerAddr + Send {} impl BoxedIo { pub fn new<T>...
}
async fn boxed_io_uses_vectored_io() { use bytes::Bytes; let mut io = BoxedIo::new(WriteBufDetector); futures::future::poll_fn(|cx| { match crate::poll_write_buf(Pin::new(&mut io), cx, &mut Bytes::from("hello")) { Poll::Ready(Ok...
function_block-full_function
[ { "content": "/// Attempt to split_to the given index. If there are not enough bytes then\n\n/// Err is returned and the given Bytes is not modified.\n\nfn try_split_to(buf: &mut Bytes, n: usize) -> Result<Bytes, InsufficientBytes> {\n\n if buf.len() >= n {\n\n Ok(buf.split_to(n))\n\n } else {\n\n...
Rust
src/cpu_scs/nvic_iabr1.rs
helium/cc13x2-cc26x2-pac
8b98fc8840b8674be57c9de1ae83e12dc817a5f8
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::NVIC_IABR1 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::NVIC_IABR1 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'...
#[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct RESERVED6R { bits: u32, } impl RESERVED6R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u32 { ...
pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); }
function_block-full_function
[]
Rust
src/expr.rs
m-dahl/boolean_expression
47ae4a3bdf9d39611c3b8475f792249d4143740b
use std::collections::HashMap; use std::fmt::Debug; use std::cmp::Ord; use std::hash::Hash; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Expr<T> where T: Clone + Debug + Eq + Ord + Hash, { Terminal(T), Const(bool), Not(Box<Expr<T>>), And(Box<Ex...
use std::collections::HashMap; use std::fmt::Debug; use std::cmp::Ord; use std::hash::Hash; #[derive(Clone, Debug, PartialE
Expr<T>) -> Expr<T> { Expr::Or(Box::new(e1), Box::new(e2)) } pub fn evaluate(&self, vals: &HashMap<T, bool>) -> bool { match self { &Expr::Terminal(ref t) => *vals.get(t).unwrap_or(&false), &Expr::Const(val) => val, &Expr::And(ref a, ref b) => a.ev...
q, Eq, PartialOrd, Ord, Hash)] pub enum Expr<T> where T: Clone + Debug + Eq + Ord + Hash, { Terminal(T), Const(bool), Not(Box<Expr<T>>), And(Box<Expr<T>>, Box<Expr<T>>), Or(Box<Expr<T>>, Box<Expr<T>>), } impl<T> Expr<T> where T: Clone + Debug + Eq + Ord + Ha...
random
[ { "content": "// boolean_expression: a Rust crate for Boolean expressions and BDDs.\n\n//\n\n// Copyright (c) 2016 Chris Fallin <cfallin@c1f.net>. Released under the MIT\n\n// License.\n\n//\n\n\n\nuse std::iter;\n\nuse std::slice;\n\nuse std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};\n\nuse std::collect...
Rust
src/range/mod.rs
JuMastro/rust-net-adds
2bf11fd2db19ae54e9b7e971bbd76706715b3912
use std::fmt; use std::net::IpAddr; use std::str::FromStr; use std::vec::IntoIter; use crate::errors::NetAddsError; use crate::iter::{IntoSmartIterator, IpAddrSmartIterator, Ipv4AddrSmartIterator, Ipv6AddrSmartIterator}; mod v4; pub use v4::*; mod v6; pub use v6::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash,...
use std::fmt; use std::net::IpAddr; use std::str::FromStr; use std::vec::IntoIter; use crate::errors::NetAddsError; use crate::iter::{IntoSmartIterator, IpAddrSmartIterator, Ipv4AddrSmartIterator, Ipv6AddrSmartIterator}; mod v4; pub use v4::*; mod v6; pub use v6::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash,...
}
ddr::from(0); let range = Ipv6AddrRange::new(a, b); assert_eq!(Ok(range), "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff-0:0:0:0:0:0:0:0".parse()); assert_eq!(Ok(range), "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff-::".parse()); let err = Err(NetAddsError::RangeAddrParse(RangeAddrParseError())); ...
function_block-function_prefixed
[ { "content": "///\n\n/// [`FromStr`]: std::str::FromStr\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use std::net::Ipv4Addr;\n\n///\n\n/// use net_adds::Ipv4AddrRange;\n\n///\n\n/// let a = Ipv4Addr::new(192, 168, 0, 0);\n\n/// let b = Ipv4Addr::new(192, 168, 0, 255);\n\n/// let range = Ipv4AddrRange::new(...
Rust
wallet-cli/src/command/wallet/util.rs
gguoss/rust-cardano
bfe4ae2fde8d3013d1bf3e0b92a0c643581bede8
use cardano::{bip39, paperwallet, wallet}; use rand; use termion::{style, color, clear, cursor}; use termion::input::TermRead; use std::io::{Write, stdout, stdin}; use super::config; pub fn get_password() -> String { let stdout = stdout(); let mut stdout = stdout.lock(); let stdin = stdin(); let mut ...
use cardano::{bip39, paperwallet, wallet}; use rand; use termion::{style, color, clear, cursor}; use termion::input::TermRead; use std::io::{Write, stdout, stdin}; use super::config; pub fn get_password() -> String { let stdout = stdout(); let mut stdout = stdout.lock(); let stdin = stdin(); let mut ...
want to create a new account named {:?}?{} (No|yes): ", color::Fg(color::Green), alias, color::Fg(color::Reset)).unwrap(); stdout.flush().unwrap(); let mchoice = stdin.read_line().unwrap(); match mchoice { None => { error!("invalid input"); ::std::process::exit(1); }, So...
require your private keys when", crate_name!()); println!("performing public operations (like creating addresses)."); println!("{}", style::NoItalic); println!(""); println!("Here is the list of existing accounts: {:?}", known_accounts); { let stdout = stdout(); let mut stdout = st...
random
[ { "content": "/// Given a 4 bytes IV, and a password, scramble the input\n\n/// using a simple XOR, and returning the IV prepended to the shielded input\n\npub fn scramble(iv: &[u8], password: &[u8], input: &[u8]) -> Vec<u8> {\n\n assert!(iv.len() == IV_SIZE);\n\n let sz = IV_SIZE + input.len();\n\n le...
Rust
day-18/src/main.rs
Shriram-Balaji/rust-advent-of-code-2020
a1002a2f50d12eff744f7cb0db1f7271b9020c3a
use std::{env, fs}; fn evaluate(expression: &str, add_has_precedence: bool) -> (u64, usize) { let mut result = 0; let mut apply_operation = |operand, operator: Option<u8>| match operator { Some(b'+') => result += operand, Some(b'*') => result *= operand, None => result = operand, ...
use std::{env, fs}; fn evaluate(expression: &str, add_has_precedence: bool) -> (u64, usize) { let mut result = 0; let mut apply_operation = |operand, operator: Option<u8>| match operator { Some(b'+') => result += operand, Some(b'*') => result *= operand, None => result = operand, ...
#[cfg(test)] mod tests { use super::*; fn eval_expression(expression: &str, expected: u64) -> bool { let (actual, _) = evaluate(expression, false); actual == expected } fn eval_expression_with_add_precedence(expression: &str, expected: u64) -> bool { let (actual, _) = evaluate...
put .lines() .map(|expr| evaluate(expr, true)) .fold(0, |acc, (result, _)| acc + result); println!("Part 02 Sum: {}", sum); }
function_block-function_prefixed
[ { "content": "fn process(input: &str) -> (u64, Vec<&str>) {\n\n let notes: Vec<&str> = input.split('\\n').collect();\n\n let timestamp = notes[0].parse::<u64>().expect(\"Invalid timestamp\");\n\n let bus_ids: Vec<&str> = notes[1].split(',').collect();\n\n (timestamp, bus_ids)\n\n}\n\n\n", "file_...
Rust
src/api/errors.rs
nlopes/avro-schema-registry
f18168bacfd1f141be857b7f41cda8c7a874ce93
use actix_web::{http::StatusCode, HttpResponse}; macro_rules! enum_number { ($name:ident { $($variant:ident = $value:expr, )* }) => { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum $name { $($variant = $value,)* } impl ::serde::Serialize for $name { f...
use actix_web::{http::StatusCode, HttpResponse}; macro_rules! enum_number { ($name:ident { $($variant:ident = $value:expr, )* }) => { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum $name { $($variant = $value,)* } impl ::serde::Serialize for $name { f...
Self { status_code, response: ApiErrorResponse { error_code, message: error_code.message().to_string(), }, } } } impl std::fmt::Display for ApiAvroErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { ...
let status_code = match error_code { ApiAvroErrorCode::SubjectNotFound => StatusCode::NOT_FOUND, ApiAvroErrorCode::VersionNotFound => StatusCode::NOT_FOUND, ApiAvroErrorCode::SchemaNotFound => StatusCode::NOT_FOUND, ApiAvroErrorCode::InvalidAvroSchema => StatusCode::UNPR...
assignment_statement
[ { "content": "/// `get_subject_version_from_db` fetches a specific subject version pair from the\n\n/// database, given a subject name and an optional version. If the version is not given,\n\n/// then we get the latest schema id.\n\npub fn get_subject_version_from_db(\n\n conn: &diesel::r2d2::PooledConnectio...
Rust
src/main.rs
pasberth/tcp2socks
d5c1ccece812039c41e93149358a9d8a8196c105
#[macro_use] extern crate eyre; use ::clap::App; use color_eyre::Section; use eyre::{Result, WrapErr}; use log::*; use std::io; use std::net::SocketAddr; use tcp2socks::model::model::Address; use url::Url; fn parse_url(s: &str) -> Result<Url> { Url::parse(s).wrap_err_with(|| eyre!("invalid URL: {}", s)) } fn v...
#[macro_use] extern crate eyre; use ::clap::App; use color_eyre::Section; use eyre::{Result, WrapErr}; use log::*; use std::io; use std::net::SocketAddr; use tcp2socks::model::model::Address; use url::Url; fn parse_url(s: &str) -> Result<Url> { Url::parse(s).wrap_err_with(|| eyre!("invalid URL: {}", s)) } fn v...
-> Address { self.0.clone() } } fn set_handler(signals: &[i32], handler: impl Fn(i32) + Send + 'static) -> io::Result<()> { use signal_hook::*; let signals = iterator::Signals::new(signals)?; std::thread::spawn(move || signals.forever().for_each(handler)); Ok(()) } fn main() -> eyre::Resul...
Url, } impl Pipeline { pub fn parse(args: Vec<&str>) -> Result<Self> { if args.len() != 3 { return Err(eyre!("pipeline must be length 3. (src, proxy, dst)")); } match args.as_slice() { [src, proxy, dst] => { let src = ServerUrl::new(parse_url(src)?)?...
random
[ { "content": "/// spawn `name`d thread performs `f`\n\npub fn spawn_thread<F, R>(name: &str, f: F) -> io::Result<JoinHandle<R>>\n\nwhere\n\n F: FnOnce() -> R + Send + 'static,\n\n R: Send + 'static,\n\n{\n\n thread::Builder::new().name(name.into()).spawn(move || f())\n\n}\n", "file_path": "src/thre...
Rust
src/flash/fcfg_bank.rs
helium/cc13x2-cc26x2-pac
8b98fc8840b8674be57c9de1ae83e12dc817a5f8
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::FCFG_BANK { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::FCFG_BANK { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w...
#[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut ...
t(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); }
function_block-function_prefixed
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
rsdbc-sqlite/src/options/mod.rs
eventfully-engineered/r2dbc
ae2585f629ba3cc7bd52b7f9a29a21924e995ec0
mod auto_vacuum; mod journal_mode; mod locking_mode; mod synchronous; mod parse; mod mode; pub use auto_vacuum::SqliteAutoVacuum; pub use journal_mode::SqliteJournalMode; pub use locking_mode::SqliteLockingMode; pub use synchronous::SqliteSynchronous; use std::{borrow::Cow, time::Duration}; use std::future::Future;...
mod auto_vacuum; mod journal_mode; mod locking_mode; mod synchronous; mod parse; mod mode; pub use auto_vacuum::SqliteAutoVacuum; pub use journal_mode::SqliteJournalMode; pub use locking_mode::SqliteLockingMode; pub use synchronous::SqliteSynchronous; use std::{borrow::Cow, time::Duration}; use std::future::Future;...
...
s = on; self } pub fn journal_mode(mut self, mode: SqliteJournalMode) -> Self { self.journal_mode = mode; self } pub fn locking_mode(mut self, mode: SqliteLockingMode) -> Self { self.locking_mode = mode; self } ...
random
[ { "content": "/// Metadata about the product a [ConnectionFactory] is applicable to.\n\npub trait ConnectionFactoryMetadata {\n\n\n\n /// Returns the name of the product a [ConnectionFactory] can connect to\n\n fn name(&self) -> String;\n\n\n\n}\n\n\n", "file_path": "rsdbc-core/src/connection.rs", ...
Rust
src/ais/vdm_t16.rs
johann2/nmea-parser
0dd55af67546526399bbc026067e51da8ea3fdc1
/* Copyright 2020 Timo Saarinen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
/* Copyright 2020 Timo Saarinen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
#[cfg(test)] mod test { use super::*; #[test] fn test_parse_vdm_type16() { let mut p = NmeaParser::new(); match p.parse_sentence("!AIVDM,1,1,,A,@01uEO@mMk7P<P00,0*18") { Ok(ps) => { match ps { ParsedMessage::AssignmentMo...
pub(crate) fn handle( bv: &BitVec, station: Station, own_vessel: bool, ) -> Result<ParsedMessage, ParseError> { let single = bv.len() < 144; Ok(ParsedMessage::AssignmentModeCommand( AssignmentModeCommand { own_vessel: { own_vessel }, station: { station }, ...
function_block-full_function
[ { "content": "/// Parse hour, minute, second and nano seconds from HHMMSS.SS string.\n\nfn parse_time_with_fractions(hhmmss: &str) -> Result<(u32, u32, u32, u32), ParseError> {\n\n let hour = pick_s2(hhmmss, 0).parse::<u32>()?;\n\n let minute = pick_s2(hhmmss, 2).parse::<u32>()?;\n\n let second = pick_...
Rust
src/regret_matcher.rs
elliottneilclark/little-sorry
049090f24a062e017abdae235b07092a7f59074d
#![allow(clippy::cast_precision_loss)] use ndarray::prelude::*; use rand::distributions::Distribution; use rand::thread_rng; use rand_distr::weighted::WeightedIndex; use std::vec::Vec; #[derive(Debug, Clone)] pub struct RegretMatcher { num_experts: usize, p: Array1<f64>, sum_p: Array1...
#![allow(clippy::cast_precision_loss)] use ndarray::prelude::*; use rand::distributions::Distribution; use rand::thread_rng; use rand_distr::weighted::WeightedIndex; use std::vec::Vec; #[derive(Debug, Clone)] pub struct RegretMatcher { num_experts: usize, p: Array1<f64>, sum_p: Array1...
#[must_use] pub fn new_from_p(p: Vec<f64>) -> Self { let num_experts = p.len(); let dist = WeightedIndex::new(&p).unwrap(); Self { num_experts, p: Array1::from(p), sum_p: Array1::zeros(num_experts), cumulative_r...
pub fn new(num_experts: usize) -> Self { let p = Self::rand_weights(num_experts); Self::new_from_p(p) }
function_block-full_function
[ { "content": "pub fn bench(c: &mut Criterion) {\n\n c.bench_function(\"iter\", move |b| {\n\n b.iter_custom(|iters| {\n\n let mut runner = RPSRunner::new();\n\n let start = Instant::now();\n\n for _i in 0..iters {\n\n runner.run_one();\n\n }\n...
Rust
syncpool/src/utils.rs
Chopinsky/byte_buffer
5fd931ec272fb25cf6c72735536b820fe7b3fd1d
#![allow(unused)] use crate::boxed::make_box; use crate::bucket::SLOT_CAP; use crate::pool::ElemBuilder; use std::sync::atomic; const GET_MASK: u16 = 0b1010_1010_1010_1010; const PUT_MASK: u16 = 0b1111_1111_1111_1111; const FULL_FLAG: u16 = 0b0101_0101_0101_0101; pub(crate) fn make_elem<T>(builder: &ElemBuilder<T>) ...
#![allow(unused)] use crate::boxed::make_box; use crate::bucket::SLOT_CAP; use crate::pool::ElemBuilder; use std::sync::atomic; const GET_MASK: u16 = 0b1010_1010_1010_1010; const PUT_MASK: u16 = 0b1111_1111_1111_1111; const FULL_FLAG: u16 = 0b0101_0101_0101_0101; pub(crate) fn make_elem<T>(builder: &ElemBuilder<T>) ...
010111; assert_eq!(enter(test3, false), Ok(4)); assert_eq!(enter(test3, true), Ok(1)); let test4 = 0b0101010001011011; assert_eq!(enter(test4, false), Ok(4)); assert_eq!(enter(test4, true), Ok(2)); } #[test] fn access_deny() { let test1 = 0b0010000000000000;...
_eq!(enter(test1, false), Ok(0)); assert_eq!(enter(test1, true), Ok(1)); let test2 = 0b0101010001010101; assert_eq!(enter(test2, false), Ok(4)); assert_eq!(enter(test2, true), Ok(0)); let test3 = 0b0101010001
function_block-random_span
[ { "content": "/// This API is a wrapper on the unsafer version of the direct-to-the-heap-box APIs. The API is safe\n\n/// because it is the caller's responsiblity to supply the struct initialier as a closure, such that\n\n/// after calling the struct initializer, the returned object shall be valid and meaningfu...
Rust
src/main.rs
foldu/blocklistdownloadthing
c80106f55366545106dd329a41fff7b35cfa407e
use atomicwrites::{AtomicFile, OverwriteBehavior}; use clap::Clap; use eyre::Context; use log::{info, warn}; use once_cell::sync::Lazy; use regex::Regex; use serde::Deserialize; use std::{ collections::BTreeSet, convert::TryFrom, io::{BufWriter, Write}, net::IpAddr, path::PathBuf, time::{Duratio...
use atomicwrites::{AtomicFile, OverwriteBehavior}; use clap::Clap; use eyre::Context; use log::{info, warn}; use once_cell::sync::Lazy; use regex::Regex; use serde::Deserialize; use std::{ collections::BTreeSet, convert::TryFrom, io::{BufWriter, Write}, net::IpAddr, path::PathBuf, time::{Duratio...
t_url, &hosts) { warn!("Failed writing to cache: {:#}", e); } Ok(Some(hosts)) } Err(e) => { warn!("{:#}", e); if let Ok(Some(hosts)) = cache.get(&blocklist_url) { info!("Using cached version"); Ok(Some(hosts)...
ome blocklists failed")) } else { Ok(()) } } const HALF_DAY: Duration = Duration::from_secs(60 * 60 * 12); fn get_hosts( agent: &Agent, blocklist_url: &Url, cache: &mut Cache, current_time: SystemTime, ) -> Result<Option<String>, eyre::Error> { if let Some(last_cached) = cache.last...
random
[ { "content": "# blocklistdownloadthing\n\nThis is a thing that downloads blocklists and merges them into a single file\n\nfor use by unbound, dnsmasq or /etc/hosts.\n", "file_path": "README.md", "rank": 9, "score": 8650.859116625654 } ]
Rust
src/net/udp.rs
0gajun/mio
9d77d0160f22fd91444b1051f50642da2ee5c27e
use {io, sys, Evented, Ready, Poll, PollOpt, Token}; use super::SelectorId; use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; #[derive(Debug)] pub struct UdpSocket { sys: sys::UdpSocket, selector_id: SelectorId, } impl UdpSocket { pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> { ...
use {io, sys, Evented, Ready, Poll, PollOpt, Token}; use super::SelectorId; use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; #[derive(Debug)] pub struct UdpSocket { sys: sys::UdpSocket, selector_id: SelectorId, } impl UdpSocket { pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> { ...
pub fn local_addr(&self) -> io::Result<SocketAddr> { self.sys.local_addr() } pub fn try_clone(&self) -> io::Result<UdpSocket> { self.sys.try_clone() .map(|s| { UdpSocket { sys: s, selector_id...
pub fn from_socket(socket: net::UdpSocket) -> io::Result<UdpSocket> { Ok(UdpSocket { sys: try!(sys::UdpSocket::new(socket)), selector_id: SelectorId::new(), }) }
function_block-function_prefix_line
[ { "content": "fn validate_args(token: Token, interest: Ready) -> io::Result<()> {\n\n if token == AWAKEN {\n\n return Err(io::Error::new(io::ErrorKind::Other, \"invalid token\"));\n\n }\n\n\n\n if !interest.is_readable() && !interest.is_writable() {\n\n return Err(io::Error::new(io::Error...
Rust
python_ext/pyo3/python_algebra/src/module/free_module.rs
JoeyBF/sseq
d553df5e2466aaad47f4a36bf5e051a3922b0dd0
use pyo3::{ prelude::*, PyObjectProtocol, }; use python_utils::{ self, py_repr, rc_wrapper_type, wrapper_type, }; use algebra::Algebra as AlgebraT; use algebra::module::{ Module, FreeModule as FreeModuleRust, OperationGeneratorPair as OperationGeneratorPairRu...
use pyo3::{ prelude::*, PyObjectProtocol, }; use python_utils::{ self, py_repr, rc_wrapper_type, wrapper_type, }; use algebra::Algebra as AlgebraT; use algebra::module::{ Module, FreeModule as FreeModuleRust, OperationGeneratorPair as OperationGeneratorPairRu...
}
nerators_immediate( &self, degree: i32, num_gens: usize, gen_names: Option<Vec<String>>, ) -> PyResult<()> { self.inner()?.add_generators_immediate(degree, num_gens, gen_names); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn rename_submodule(module : &PyModule, name : &str, new_name : &str) -> PyResult<()> {\n\n let submodule = module.get(name)?;\n\n submodule.setattr(\"__name__\", new_name)?;\n\n module.add(new_name, submodule)?;\n\n module.delattr(name)?;\n\n Ok(())\n\n}\n\n\n", "file_path"...
Rust
src/lib.rs
andreevlex/zbx-sender-rs
8b599a8821fbb0535da58e7864137c5e5c3b51ca
#![warn(missing_docs)] #![cfg_attr( all(feature = "_tls_common", feature = "clap"), doc = r##" See details in the documentation for [tls::ClapArgs]. "## )] use serde::{Deserialize, Serialize}; #[macro_use] extern crate lazy_static; #[cfg(feature = "tracing")] use tracing::{debug, trace}; mod error; #[c...
#![warn(missing_docs)] #![cfg_attr( all(feature = "_tls_common", feature = "clap"), doc = r##" See details in the documentation for [tls::ClapArgs]. "## )] use serde::{Deserialize, Serialize}; #[macro_use] extern crate lazy_static; #[cfg(feature = "tracing")] use tracing::{debug, trace}; mod error; #[c...
stream.write_all(&send_data)?; #[cfg(feature = "tracing")] debug!( message = serde_json::to_string(&msg)?.as_str(), "sent trap to Zabbix" ); let mut zbx_hdr = [0; ZBX_HDR_SIZE]; stream.read_exact(&mut zbx_hdr)?; if ZBX_HDR != &zbx_hdr[.....
let mut stream = if let Some(t) = &self.tls { Box::new(t.connect(&self.server, stream)?) } else { Box::new(stream) as Box<dyn Stream> };
assignment_statement
[ { "content": "fn load_psk_key(path: impl AsRef<Path>) -> Result<Vec<u8>, TlsError> {\n\n let path = path.as_ref();\n\n\n\n let mut buffer = Vec::new();\n\n let mut rdr = File::open(&path)?;\n\n rdr.read_to_end(&mut buffer)?;\n\n buffer = buffer.into_iter().filter(u8::is_ascii_hexdigit).collect();...
Rust
src/bit.rs
Kazik24/diminish
566bc8b3449165e026a4cc9c2313e2e1a9d3d726
use std::io::*; use std::mem::{replace, size_of}; use std::slice::from_mut; use std::convert::TryInto; use bitstream_io::{BitRead, Numeric, SignedNumeric}; pub struct BitWriter<'a,W: Write>{ pub(crate) inner: &'a mut W, pub(crate) current: u8, pub(crate) length: u8, } pub struct BitReader<'a,R: Read>{ ...
use std::io::*; use std::mem::{replace, size_of}; use std::slice::from_mut; use std::convert::TryInto; use bitstream_io::{BitRead, Numeric, SignedNumeric}; pub struct BitWriter<'a,W: Write>{ pub(crate) inner: &'a mut W, pub(crate) current: u8, pub(crate) length: u8, } pub struct BitReader<'a,R: Read>{ ...
){ assert_read(data,off,expect,|mut r|r.read_u8().unwrap()); } fn assert_read_arr(data: impl AsRef<[u8]>, off: u8, expect: u8){ assert_read(data,off,expect,|mut r|{ let mut val = 0; r.read_exact(from_mut(&mut val)).map(|_|val).unwrap() ...
mut R, pub(crate) current: u8, pub(crate) length: u8, } impl<'a,W: Write> BitWriter<'a,W>{ pub fn write_u32(&mut self,value: u32)->Result<()>{ self.write_u16(value.wrapping_shr(16) as _)?; self.write_u16((value & 0xffff) as _) } pub fn write_u16(&mut self,mut value: u16)->Result<(...
random
[ { "content": "pub trait Serializable: PartialEq + Hash + Debug{ //todo remove debug\n\n fn convert_to_bits<W: Write>(&self,write: &mut BitWriter<'_,W>)->Result<()>;\n\n fn convert_from_bits<R: Read>(read: &mut BitReader<'_,R>)->Result<Self> where Self: Sized;\n\n}\n\n\n\nimpl Serializable for bool{\n\n ...
Rust
capnp-rpc/examples/calculator/server.rs
nicholastmosher/capnproto-rust
8b1998fc2559f767b1191f057012bb22920b350d
use capnp::Error; use capnp::primitive_list; use capnp_rpc::{RpcSystem, twoparty, rpc_twoparty_capnp}; use calculator_capnp::calculator; use capnp::capability::Promise; use futures::{Future, Stream}; use tokio::io::{AsyncRead}; use tokio::runtime::current_thread; struct ValueImpl { value: f64 } impl ValueImp...
use capnp::Error; use capnp::primitive_list; use capnp_rpc::{RpcSystem, twoparty, rpc_twoparty_capnp}; use calculator_capnp::calculator; use capnp::capability::Promise; use futures::{Future, Stream}; use tokio::io::{AsyncRead}; use tokio::runtime::current_thread; struct ValueImpl { value: f64 } impl ValueImp...
ent_thread::spawn(rpc_system.map_err(|e| println!("error: {:?}", e))); Ok(()) }); current_thread::block_on_all(done).unwrap(); }
) - params.get(1), calculator::Operator::Multiply => params.get(0) * params.get(1), calculator::Operator::Divide => params.get(0) / params.get(1), }; results.get().set_value(v); Promise::ok(()) } } } struct CalculatorImpl; impl calcul...
random
[ { "content": "pub fn new_builder<'a>(p : *mut u8, len : u32) -> Builder<'a> {\n\n unsafe { ::std::slice::from_raw_parts_mut(p, len as usize) }\n\n}\n\n\n\nimpl <'a> crate::traits::FromPointerBuilder<'a> for Builder<'a> {\n\n fn init_pointer(builder : PointerBuilder<'a>, size : u32) -> Builder<'a> {\n\n ...
Rust
sources/api/corndog/src/main.rs
spolve/bottlerocket
7e0a918524697098c6f2ff5e99ae19f96633f401
/*! corndog is a delicious way to get at the meat inside the kernels. It sets kernel-related settings, for example: * sysctl values, based on key/value pairs in `settings.kernel.sysctl` * lockdown mode, based on the value of `settings.kernel.lockdown` */ #![deny(rust_2018_idioms)] use constants; use log::{debug, erro...
/*! corndog is a delicious way to get at the meat inside the kernels. It sets kernel-related settings, for example: * sysctl values, based on key/value pairs in `settings.kernel.sysctl` * lockdown mode, based on the value of `settings.kernel.lockdown` */ #![deny(rust_2018_idioms)] use constants; use log::{debug, erro...
}
e")); assert_eq!( "none integrity confidentiality", parse_kernel_setting("none integrity confidentiality\n") ); }
function_block-function_prefixed
[ { "content": "/// Retrieves settings from the API.\n\n///\n\n/// NOTE: this function creates its own tokio runtime to make the async apiclient call. It should\n\n/// not be called if you're running another tokio runtime. The program structure requires forking\n\n/// to handle long-running update actions, and ...
Rust
src/gc/swiper/mod.rs
hoangpq/dora
8b361d7ad44ee675c327712d0fa430c098418b9c
use parking_lot::Mutex; use scoped_threadpool::Pool; use std::fmt; use std::sync::Arc; use ctxt::VM; use driver::cmd::Args; use gc::root::{get_rootset, Slot}; use gc::swiper::card::CardTable; use gc::swiper::controller::{HeapConfig, SharedHeapConfig}; use gc::swiper::crossing::CrossingMap; use gc::swiper::full::FullCo...
use parking_lot::Mutex; use scoped_threadpool::Pool; use std::fmt; use std::sync::Arc; use ctxt::VM; use driver::cmd::Args; use gc::root::{get_rootset, Slot}; use gc::swiper::card::CardTable; use gc::swiper::controller::{HeapConfig, SharedHeapConfig}; use gc::swiper::crossing::CrossingMap; use gc::swiper::full::FullCo...
fn alloc_normal(&self, vm: &VM, size: usize, array_ref: bool) -> Address { let ptr = self.young.bump_alloc(size); if !ptr.is_null() { return ptr; } self.perform_collection_and_choose(vm, GcReason::AllocationFailure); let ptr = self.young.bump_alloc(size); ...
fn alloc_tlab_area(&self, vm: &VM, size: usize) -> Option<Region> { let ptr = self.young.bump_alloc(size); if !ptr.is_null() { return Some(ptr.region_start(size)); } self.perform_collection_and_choose(vm, GcReason::AllocationFailure); let ptr = self.young.bump_allo...
function_block-full_function
[ { "content": "pub fn start(rootset: &[Slot], heap: Region, perm: Region, threadpool: &mut Pool) {\n\n let number_workers = threadpool.thread_count() as usize;\n\n let mut workers = Vec::with_capacity(number_workers);\n\n let mut stealers = Vec::with_capacity(number_workers);\n\n\n\n for _ in 0..numb...
Rust
src/ray_tracing/intersection.rs
y2k4life/rustic_ray
7393976b69d4ccd57f0d43e384889a7eb7aa2f6c
use crate::shapes::Shape; use crate::{float_cmp, Point, Ray, ShapeContainer, Vector, EPSILON}; use std::cmp::Ordering; #[derive(Debug, Copy, Clone)] pub struct Intersection<'a> { pub t: f64, pub object: &'a dyn Shape, } pub struct Computations<'a> { pub t: f64, pub object: &'a dyn Shape, pub point...
use crate::shapes::Shape; use crate::{float_cmp, Point, Ray, ShapeContainer, Vector, EPSILON}; use std::cmp::Ordering; #[derive(Debug, Copy, Clone)] pub struct Intersection<'a> { pub t: f64, pub object: &'a dyn Shape, } pub struct Computations<'a> { pub t: f64, pub object: &'a dyn Shape, pub point...
#[test] fn the_hit_all_intersections_some_negative_t() { let s = Sphere::new(); let xs = vec![Intersection::new(-1.0, &s), Intersection::new(1.0, &s)]; let hit = Intersection::hit(&xs); if let Some(i) = hit { assert_eq!(1.0, i.t); } } ...
let s = Sphere::new(); let xs = vec![Intersection::new(2.0, &s), Intersection::new(1.0, &s)]; let hit = Intersection::hit(&xs); if let Some(i) = hit { assert_eq!(1.0, i.t); } }
function_block-function_prefix_line
[ { "content": "pub fn float_eq(a: f64, b: f64) -> bool {\n\n (a - b).abs() < EPSILON\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 202448.56319117217 }, { "content": "pub fn get_ball(x: f64, y: f64, z: f64) -> Box<dyn Shape> {\n\n let mut left = Sphere::new();\n\n left....
Rust
codegen/tests/test_nested.rs
cibingeorge/rhai
60622f4c97c259ad4f74f4fe7779e2ecd3a3f849
use rhai::module_resolvers::*; use rhai::{Array, Engine, EvalAltResult, RegisterFn, FLOAT, INT}; pub mod one_fn_module_nested_attr { use rhai::plugin::*; #[export_module] pub mod advanced_math { use rhai::plugin::*; use rhai::FLOAT; #[rhai_fn(return_raw)] pub fn get_mystic...
use rhai::module_resolvers::*; use rhai::{Array, Engine, EvalAltResult, RegisterFn, FLOAT, INT}; pub mod one_fn_module_nested_attr { use rhai::plugin::*; #[export_module] pub mod advanced_math { use rhai::plugin::*; use rhai::FLOAT; #[rhai_fn(return_raw)] pub fn get_mystic...
= 41; let hi = Math::Advanced::foo_second_adders::add_int(gi, 1); [fx, hx, fi, hi] "#, )?; assert_eq!(&output_array[0].as_float().unwrap(), &42.0); assert_eq!(&output_array[1].as_float().unwrap(), &42.0); assert_eq!(&output_array[2].as_int().unwrap(), &42); assert_eq!(&outp...
ne.eval::<Array>( r#" let ex = 41.0; let fx = Math::Advanced::foo_first_adders::add_float(ex, 1.0); let ei = 41; let fi = Math::Advanced::foo_first_adders::add_int(ei, 1); let gx = 41.0; let hx = Math::Advanced::foo_second_adders::add_float(gx, 1.0); le...
random
[ { "content": "#[cfg(not(feature = \"no_object\"))]\n\n#[test]\n\nfn test_constant_mut() -> Result<(), Box<EvalAltResult>> {\n\n #[derive(Debug, Clone)]\n\n struct TestStruct(INT); // custom type\n\n\n\n let mut engine = Engine::new();\n\n\n\n engine\n\n .register_type_with_name::<TestStruct>(...
Rust
src/server.rs
mimblewimble/mwixnet
0ac1886dc34ac05e230533f7b685765e93c7ae9c
use crate::onion; use crate::secp::{self, Commitment, ComSignature, SecretKey}; use crate::ser; use crate::types::Onion; use jsonrpc_derive::rpc; use jsonrpc_http_server::*; use jsonrpc_http_server::jsonrpc_core::*; use jsonrpc_core::{Result, Value}; use serde::{Deserialize, Serialize}; use std::net::SocketA...
use crate::onion; use crate::secp::{self, Commitment, ComSignature, SecretKey}; use crate::ser; use crate::types::Onion; use jsonrpc_derive::rpc; use jsonrpc_http_server::*; use jsonrpc_http_server::jsonrpc_core::*; use jsonrpc_core::{Result, Value}; use serde::{Deserialize, Serialize}; use std::net::SocketA...
} pub fn listen<F>(server_config: &ServerConfig, shutdown_signal: F) -> std::result::Result<(), Box<dyn std::error::Error>> where F: futures::future::Future<Output = ()> + Send + 'static, { let mut io = IoHandler::new(); io.extend_with(ServerImpl::to_delegate(ServerImpl::new(server_config.k...
fn swap(&self, swap: SwapReq) -> Result<Value> { let _ = swap.comsig.verify(&swap.onion.commit, &swap.msg) .map_err(|_| jsonrpc_core::Error::invalid_params("ComSignature invalid"))?; let peeled = onion::peel_layer(&swap.onion, &self.server_key) ....
function_block-full_function
[ { "content": "/// Add a blinding factor to an existing Commitment\n\npub fn add_excess(commitment: &Commitment, excess: &SecretKey) -> Result<Commitment> {\n\n let secp = Secp256k1::with_caps(ContextFlag::Commit);\n\n let excess_commit : Commitment = secp.commit(0, excess.clone())?;\n\n\n\n let commits...
Rust
saiko/src/client.rs
YangKeao/saiko
a0a17fc2439f42414d38b57df5658dbb8cb71d29
use super::socket::WaylandSocket; use super::wayland; use super::wayland::{WlDisplay, WlObject, WlRawObject}; use crate::wayland::WlCallback; use std::collections::HashMap; use std::sync::Mutex; use std::sync::{Arc, Condvar, RwLock}; use std::thread; #[derive(Clone)] pub struct Client { socket: Arc<WaylandSocket>,...
use super::socket::WaylandSocket; use super::wayland; use super::wayland::{WlDisplay, WlObject, WlRawObject}; use crate::wayland::WlCallback; use std::collections::HashMap; use std::sync::Mutex; use std::sync::{Arc, Condvar, RwLock}; use std::thread; #[derive(Clone)] pub struct Client { socket: Arc<WaylandSocket>,...
} _ => {} }, _ => {} })); self.get_display().sync(callback_id); let &(ref done, ref cond_var) = &*done_pair; let mut done = done.lock().unwrap(); while !*done { done = cond_var.wait(done).unwrap(); } ...
if done.sender_id == callback_id { info!("Callback id {} Done", callback_id); let &(ref done, ref cond_var) = &*c_done_pair; *(done.lock().unwrap()) = true; cond_var.notify_all(); }
if_condition
[ { "content": "fn main() {\n\n env_logger::init();\n\n\n\n let mut client = saiko::client::Client::connect(None);\n\n println!(\"Connected to display\");\n\n\n\n let mut wl_compositor_id = Arc::new(Mutex::new(0));\n\n let mut c_wl_compositor_id = wl_compositor_id.clone();\n\n\n\n let mut wl_she...
Rust
src/camera/realistic_camera.rs
gillett-hernandez/rust-pathtracer
5ee181616fbca2cf0544e698baf13be74fc133f2
use std::f32::consts::SQRT_2; use crate::geometry::*; use crate::materials::MaterialId; use crate::math::{ random, spectral::EXTENDED_VISIBLE_RANGE, Point3, Ray, Sampler, TangentFrame, Transform3, Vec3, }; use optics::{ bladed_aperture, lens_sampler::RadialSampler, Input, LensAssembly, LensInterface, Output, }...
use std::f32::consts::SQRT_2; use crate::geometry::*; use crate::materials::MaterialId; use crate::math::{ random, spectral::EXTENDED_VISIBLE_RANGE, Point3, Ray, Sampler, TangentFrame, Transform3, Vec3, }; use optics::{ bladed_aperture, lens_sampler::RadialSampler, Input, LensAssembly, LensInterface, Output, }...
pub fn get_pixel_for_ray(&self, _ray: Ray, _lambda: f32) -> Option<(f32, f32)> { todo!(); } pub fn with_aspect_ratio(mut self, aspect_ratio: f32) -> Self { self.aspect_ratio = aspect_ratio; self } } unsafe impl Send for RealisticCamera {} unsafe impl Sync for Real...
trace_result { pupil_ray = self.transform.to_world(pupil_ray); pupil_ray.direction = pupil_ray.direction.normalized(); result = Some((pupil_ray, tau)); break; } } if let Some(r) = re...
function_block-function_prefix_line
[ { "content": "fn ggx_lambda(alpha: f32, w: Vec3) -> f32 {\n\n if w.z() == 0.0 {\n\n return 0.0;\n\n }\n\n let a2 = alpha * alpha;\n\n let w2 = Vec3::from_raw(w.0 * w.0);\n\n let c = 1.0 + (a2 * w2.x() + a2 * w2.y()) / w2.z(); // replace a2 with Vec2 for anistropy\n\n c.sqrt() * 0.5 - 0....
Rust
src/backend/metal/src/native.rs
scoopr/gfx
c71fe15c1f93a3c0171414aa58ddb1f14b2eb376
use {Backend}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::os::raw::{c_void, c_long, c_int}; use std::ptr; use hal::{self, image, pass, pso}; use cocoa::foundation::{NSRange, NSUInteger}; use metal::{self, MTLPrimitiveType}; use objc; use spirv_cross::msl; #[derive(Debug)] pub enum ShaderMo...
use {Backend}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::os::raw::{c_void, c_long, c_int}; use std::ptr; use hal::{self, image, pass, pso}; use cocoa::foundation::{NSRange, NSUInteger}; use metal::{self, MTLPrimitiveType}; use objc; use spirv_cross::msl; #[derive(Debug)] pub enum ShaderMo...
; (layout.binding, binding) }).collect(); let inner = DescriptorSetInner { layout: layout_bindings.to_vec(), bindings, }; DescriptorSet::Emulated(Arc::new(Mutex::new(i...
match layout.ty { pso::DescriptorType::Sampler => { let resources = (0 .. layout.count).map(|_| None); DescriptorSetBinding::Sampler(resources.collect()) } pso::DescriptorT...
if_condition
[ { "content": "pub fn map_descriptor_range(bind: &DescriptorSetLayoutBinding, register_space: u32) -> D3D12_DESCRIPTOR_RANGE {\n\n D3D12_DESCRIPTOR_RANGE {\n\n RangeType: match bind.ty {\n\n pso::DescriptorType::Sampler => D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,\n\n pso::DescriptorTy...
Rust
proptest/src/strategy/shuffle.rs
mimoo/proptest
6521f0f7751015300c6845a6036766460abdb451
use crate::std_facade::{Cell, Vec, VecDeque}; use rand::Rng; use crate::num; use crate::strategy::traits::*; use crate::test_runner::*; #[derive(Clone, Debug)] #[must_use = "strategies do nothing unless used"] pub struct Shuffle<S>(pub(super) S); pub trait Shuffleable { fn shuffle_len(&self) -> usize; ...
use crate::std_facade::{Cell, Vec, VecDeque}; use rand::Rng; use crate::num; use crate::strategy::traits::*; use crate::test_runner::*; #[derive(Clone, Debug)] #[must_use = "strategies do nothing unless used"] pub struct Shuffle<S>(pub(super) S); pub trait Shuffleable { fn shuffle_len(&self) -> usize; ...
huffle(); for _ in 0..1024 { let mut value = input.new_tree(&mut runner).unwrap(); let mut prev_dist = i32::MAX; loop { let v = value.current(); let mut dist = 0; for (ix, &nominal) in v.iter()...
fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> { let rng = runner.new_rng(); self.0.new_tree(runner).map(|inner| ShuffleValueTree { inner, rng, dist: Cell::new(None), simplifying_inner: false, }) } } #[derive(Clone, Debug)...
random
[ { "content": "/// A generated value and its associated shrinker.\n\n///\n\n/// Conceptually, a `ValueTree` represents a spectrum between a \"minimally\n\n/// complex\" value and a starting, randomly-chosen value. For values such as\n\n/// numbers, this can be thought of as a simple binary search, and this is ho...
Rust
src/saveload/tests.rs
MaulingMonkey/specs
9ffc149b850614a390c3229b82220c19491e411b
extern crate ron; use std::hash::Hash; use super::*; use crate::{ error::{Error, NoError}, prelude::*, }; mod marker_test { use super::*; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct A(i32); impl Component for A { type Storage = VecStorage<Self>; } #[de...
extern crate ron; use std::hash::Hash; use super::*; use crate::{ error::{Error, NoError}, prelude::*, }; mod marker_test { use super::*; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct A(i32); impl Component for A { type Storage = VecStorage<Self>; } #[de...
let marker_id_set: HashSet<_> = marker_ids.iter().cloned().collect(); assert_eq!(marker_ids.len(), marker_id_set.len()); }); } }
let marker_ids: Vec<_> = (&ents, &markers) .join() .map(|(_entity, marker)| marker.id()) .collect();
assignment_statement
[ { "content": "/// This trait should be implemented by a component which is going to be used as\n\n/// marker. This marker should be set to entity that should be serialized.\n\n/// If serialization strategy needs to set marker to some entity\n\n/// then it should use newly allocated marker from `Marker::Allocato...
Rust
compiler/src/pass/dedup_surfaces.rs
SkyprayerAudioStudio/axiom
ae019ab6f1679f3041dfa94727ef0d2b56360ed9
use crate::mir; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; pub fn deduplicate_surfaces(surfaces: &mut HashMap<mir::SurfaceRef, mir::Surface>) { let (surface_ordering, mut surface_dependents) = determine_surface_order_and_dependents(surfaces); for (orderi...
use crate::mir; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; pub fn deduplicate_surfaces(surfaces: &mut HashMap<mir::SurfaceRef, mir::Surface>) { let (surface_ordering, mut surface_dependents) = determine_surface_order_and_dependents(surfaces); for (orderi...
let duplicate_surface_id = match find_duplicate_surface(current_surface, below_surfaces, all_surfaces) { Some(duplicate) => duplicate, None => return false, }; let dependent_surfaces = &surface_dependents[&surface_id]; for dependent_surface_id in dependent_surfaces ...
function_block-function_prefix_line
[ { "content": "pub fn order_nodes(surface: &mut mir::Surface, target: &TargetProperties) {\n\n let outputs = get_output_nodes(&surface);\n\n let associated_sockets = get_associated_sockets(&surface);\n\n let ordered_nodes = get_ordered_nodes(\n\n &surface.nodes,\n\n &outputs,\n\n &a...
Rust
src/lib.rs
dholroyd/mpeg4-audio-const
b25f532a792e4d8ac68eef41d49b314ae5dab123
use std::convert::TryFrom; use std::fmt; #[derive(PartialEq, Debug)] pub enum AudioObjectTypeError { EscapeValue, TooLarge(u8), } #[derive(Eq, PartialEq, Copy, Clone)] pub struct AudioObjectType(u8); pub const AOT_ESCAPE_VALUE: u8 = 0b_11111; impl From<AudioObjectType> for u8 { fn from(...
use std::convert::TryFrom; use std::fmt; #[derive(PartialEq, Debug)] pub enum AudioObjectTypeError { EscapeValue, TooLarge(u8), } #[derive(Eq, PartialEq, Copy, Clone)] pub struct AudioObjectType(u8); pub const AOT_ESCAPE_VALUE: u8 = 0b_11111; impl From<AudioObjectType> for u8 { fn from(...
} macro_rules! implement_aot { ( $( $tag:literal $id:ident $desc:literal ),* , ) => { impl AudioObjectType { $( #[doc=$desc] pub const $id: AudioObjectType = AudioObjectType($tag); )* } impl fmt::Debug for AudioObjectTyp...
ObjectTypeError::EscapeValue), 96..=255 => Err(AudioObjectTypeError::TooLarge(value)), _ => Ok(AudioObjectType(value)), } }
function_block-function_prefixed
[]
Rust
src/lib.rs
zgcarvalho/tfbs-scan
213ec8a902eb8009f10599046d7ab213e2d9d9f9
use core::str; use std::fmt; pub struct Sequence { idxs: Vec<usize>, bases: Vec<char>, } impl From<&str> for Sequence { fn from(seq: &str) -> Self { seq.char_indices() .filter(|&(_,x)| !x.eq(&'-')) .fold(Sequence { bases: Vec::<char>::new(), idxs: Vec::<usize>::ne...
use core::str; use std::fmt; pub struct Sequence { idxs: Vec<usize>, bases: Vec<char>, } impl From<&str> for Sequence { fn from(seq: &str) -> Self { seq.char_indices() .filter(|&(_,x)| !x.eq(&'-')) .fold(Sequence { bases: Vec::<char>::new(), idxs: Vec::<usize>::ne...
pub fn scan(&self, seq: &Sequence) -> Vec<Score> { let (s,e) = match self.strand { Strand::Forward => (1, self.length), Strand::Reverse => (self.length, 1), }; let scores: Vec<Score> = seq.bases .windows(self.length) .map( |w|...
n calculate_max_score(&mut self) { self.max_score = self .probs .iter() .map(|p| { p.iter() .take(4) .fold(f64::NEG_INFINITY, |state, x| state.max(*x)) }) .enumerate() .fold(0.0, |acc,...
function_block-function_prefixed
[]
Rust
src/bin/05_window_surface.rs
matthew-russo/vulkan-tutorial-rs
a37389453cd88e4a3f82d1bdaa0dd2e3cde9162d
extern crate vulkano; extern crate vulkano_win; extern crate winit; use std::sync::Arc; use std::collections::HashSet; use winit::{EventsLoop, WindowBuilder, Window, dpi::LogicalSize, Event, WindowEvent}; use vulkano_win::VkSurfaceBuild; use vulkano::instance::{ Instance, InstanceExtensions, ApplicationI...
extern crate vulkano; extern crate vulkano_win; extern crate winit; use std::sync::Arc; use std::collections::HashSet; use winit::{EventsLoop, WindowBuilder, Window, dpi::LogicalSize, Event, WindowEvent}; use vulkano_win::VkSurfaceBuild; use vulkano::instance::{ Instance, InstanceExtensions, ApplicationI...
urface, device); indices.is_complete() } fn find_queue_families(surface: &Arc<Surface<Window>>, device: &PhysicalDevice) -> QueueFamilyIndices { let mut indices = QueueFamilyIndices::new(); for (i, queue_family) in device.queue_families().enumerate() { if queue_fami...
se { Instance::new(Some(&app_info), &required_extensions, None) .expect("failed to create Vulkan instance") } } fn check_validation_layer_support() -> bool { let layers: Vec<_> = layers_list().unwrap().map(|l| l.name().to_owned()).collect(); VALIDATION_LAYERS...
random
[ { "content": "/// Required device extensions\n\nfn device_extensions() -> DeviceExtensions {\n\n DeviceExtensions {\n\n khr_swapchain: true,\n\n .. vulkano::device::DeviceExtensions::none()\n\n }\n\n}\n\n\n\n#[cfg(all(debug_assertions))]\n\nconst ENABLE_VALIDATION_LAYERS: bool = true;\n\n#[c...
Rust
examples/private_xo/src/routes/error.rs
davececchi/splinter
92bc0fdec6e66aa53bc37db13b5521343235b016
use std::error::Error; use std::fmt; use iron::prelude::*; use iron::status; use protobuf::error::ProtobufError; #[derive(Clone, Debug)] pub enum BatchSubmitError { InvalidBatchListFormat(String), Internal(String), } impl Error for BatchSubmitError { fn cause(&self) -> Option<&dyn Error> { None...
use std::error::Error; use std::fmt; use iron::prelude::*; use iron::status; use protobuf::error::ProtobufError; #[derive(Clone, Debug)] pub enum BatchSubmitError { InvalidBatchListFormat(String), Internal(String), } impl Error for BatchSubmitError { fn cause(&self) -> Option<&dyn Error> { None...
} #[derive(Clone, Debug)] pub enum StateError { BadRequest(String), NotFound(String), Internal(String), ServiceUnavailable(String), } impl Error for StateError { fn cause(&self) -> Option<&dyn Error> { None } fn description(&self) -> &str { match self { StateE...
StatusesError::InvalidParameter(_) => status::BadRequest, BatchStatusesError::Internal(_) => status::InternalServerError, }; let msg = err.to_string(); IronError { error: Box::new(err), response: Response::with((status, msg)), } }
function_block-function_prefixed
[ { "content": "/// Returns a BatchList containing the provided Batch\n\n///\n\n/// # Arguments\n\n///\n\n/// * `batch` - a Batch\n\npub fn create_batch_list_from_one(batch: Batch) -> BatchList {\n\n let mut batch_list = BatchList::new();\n\n batch_list.set_batches(protobuf::RepeatedField::from_vec(vec![bat...