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
common/kernel/elf/mod.rs
pczarn/rustboot
d367cd61964235a63b40f1fcbf5ec615bd8ba2fc
use core::ptr::RawPtr; use core::ptr::{copy_nonoverlapping_memory, set_memory}; use core::mem::transmute; use core::prelude::*; use core; use kernel::process::Process; use kernel::mm; use platform::io; #[cfg(target_word_size = "32")] pub use self::elf32::{Ehdr, Phdr, Auxv, AuxvValue, AuxvType}; #[cfg(target_word_size...
use core::ptr::RawPtr; use core::ptr::{copy_nonoverlapping_memory, set_memory}; use core::mem::transmute; use core::prelude::*; use core; use kernel::process::Process; use kernel::mm; use platform::io; #[cfg(target_word_size = "32")] pub use self::elf32::{Ehdr, Phdr, Auxv, AuxvValue, AuxvType}; #[cfg(target_word_size...
}, _ => {} } } static stack_bottom: u32 = 0xC0000000; let stack_vaddr = (stack_bottom - 0x1000) as *mut u8; task.mmap(stack_vaddr, 0x1000, stack_flags); let stack_ptr = (stack_bottom as *mut u8).offset(-(((4 + 5 + 15) & !0xF) + 8 + 4 ...
if (*pheader).p_flags.contains(PT_X) { stack_flags = mm::Flags::empty(); }
if_condition
[ { "content": "#[allow(dead_assignment)]\n\n#[no_mangle]\n\npub fn memcpy(dest: *mut u8, src: *const u8, mut n: uint) {\n\n if unlikely!(n == 0) {\n\n return;\n\n }\n\n unsafe {\n\n if n < 12 {\n\n asm!(\"rep movsb\" :: \"{edi}\"(dest), \"{esi}\"(src), \"{ecx}\"(n))\n\n ...
Rust
src/service.rs
radicle-dev/madness
cb12159a06f3698d0ba4ea078e95f8a915a9a9d3
use std::collections::HashSet; use std::io; use std::net::SocketAddr; use std::net::{Ipv4Addr, Ipv6Addr}; use std::str::FromStr; use std::time::Duration; use crate::dns; use crate::error::Error; use crate::META_QUERY_SERVICE; use once_cell::sync::Lazy; use tokio::sync::{mpsc, oneshot}; use tokio::time; use super::dns...
use std::collections::HashSet; use std::io; use std::net::SocketAddr; use std::net::{Ipv4Addr, Ipv6Addr}; use std::str::FromStr; use std::time::Duration; use crate::dns; use crate::error::Error; use crate::META_QUERY_SERVICE; use once_cell::sync::Lazy; use tokio::sync::{mpsc, oneshot}; use tokio::time; use super::dns...
match orx.try_recv() { Err(oneshot::error::TryRecvError::Closed) => break, _ => { let _ = sender.send(service.clone()).await; } } } }); ServiceDiscovery(otx, service_name.as_r...
f, service_name: impl AsRef<str>, interval: Duration, ) -> ServiceDiscovery { let (otx, mut orx) = oneshot::channel(); let mut interval = time::interval(interval); let mut sender = self.discovery_scheduler_snd.clone(); let service = service_name.as_ref().to_string(); ...
function_block-random_span
[ { "content": "fn append_qname(out: &mut Vec<u8>, name: &[u8]) {\n\n debug_assert!(name.is_ascii());\n\n\n\n for element in name.split(|&c| c == b'.') {\n\n assert!(element.len() < 64, \"Service name has a label too long\");\n\n assert_ne!(element.len(), 0, \"Service name contains zero length...
Rust
day-2/src/main.rs
mmehrten/advent-of-code-2021
f04ac08718f4bda3d24ecf255083dac7b6b2cf8a
use std::fs::File; use std::io::{BufRead, BufReader}; fn get_buf_reader(input_path: &str) -> BufReader<File> { let contents = File::open(input_path).expect(format!("Error reading file: {}", input_path).as_str()); let reader = BufReader::new(contents); reader } fn record_movements(input_path: ...
use std::fs::File; use std::io::{BufRead, BufReader}; fn get_buf_reader(input_path: &str) -> BufReader<File> { let contents = File::open(input_path).expect(format!("Error reading file: {}", input_path).as_str()); let reader = BufReader::new(contents); reader } fn record_movements(input_path: ...
fn parse_file_path(args: &[String]) -> &str { if args.len() != 2 { panic!( "Expected one file path and an optional window size to run against, got: {} arguments", args.len() - 1 ); } let input_path = &args[1]; input_path.as_str() } fn main() { let args: Vec...
fn record_movements_with_aim(input_path: &str) -> (i32, i32) { let reader = get_buf_reader(input_path); let (mut horizontal, mut depth, mut aim) = (0, 0, 0); for line in reader.lines() { let line = line.expect("Failed to parse line from file."); let mut parts: Vec<&str> = line.split(" ").col...
function_block-full_function
[ { "content": "/// Parse the gamma and epsilon power factors from a binary power report.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `input_path - The input file path containing the power report.\n\n///\n\n/// # Returns\n\n///\n\n/// The (gamma rate, epsilon rate) of the power report\n\n///\n\n/// # Examples\n\n//...
Rust
cex/src/test/named.rs
angelrain1/enumx
65843e0d367329014a9b4137408c0971b26db7f4
use super::*; use enumx_derive::Exchange; #[ derive( Exchange, Debug )] enum ReadU32Error { IO( std::io::Error ), Parse( std::num::ParseIntError ), } fn read_u32( filename: &'static str ) -> Result<u32, Cex<ReadU32Error>> { use std::io::Read; let mut f = std::fs::File::open( filename ).may_throw...
use super::*; use enumx_derive::Exchange; #[ derive( Exchange, Debug )] enum ReadU32Error { IO( std::io::Error ), Parse( std::num::ParseIntError ), } fn read_u32( filename: &'static str ) -> Result<u32, Cex<ReadU32Error>> { use std::io::Read; let mut f = std::fs::File::open( filename ).may_throw...
#[test] fn test_mix_named_with_adhoc() { fn read_u32_throws_adhoc( filename: &'static str ) -> Result<u32, Cex<Enum!( std::io::Error, std::num::ParseIntError )>> { read_u32( filename ).may_rethrow() } assert!( read_u32_throws_adhoc("src/test/no_file").is_err() ); fn read_u32_throw...
x ); } }, }; let c = match read_u32( file_c ) { Ok( value ) => value, Err( cex ) => match cex.error { ReadU32Error::IO( _ ) => 0, ReadU32Error::Parse( err ) => throw!( err ), }, }; a.checked_mul( b ) .ok_or( MulOverflow...
function_block-function_prefixed
[ { "content": "#[cex]\n\nfn a_mul_b_eq_c( file_a: &'static str, file_b: &'static str, file_c : &'static str )\n\n -> Result<bool, Cex<Enum!( std::io::Error, std::num::ParseIntError, MulOverflow )>>\n\n{\n\n let a = read_u32( file_a )???;\n\n\n\n let b = match read_u32( file_b ) {\n\n Ok( value )...
Rust
hphp/hack/src/rupro/lib/alloc/alloc_decl_defs.rs
Wilfred/hhvm
87cea12a34ec7edb94111be6bfb9458aac7b1997
use super::Allocator; use crate::decl_defs::{self, shallow, ty, DeclTy, DeclTy_, FunParam, FunType, UserAttribute}; use crate::reason::Reason; use oxidized_by_ref as obr; use pos::{ConstName, FunName, TypeName}; impl<R: Reason> Allocator<R> { #[inline] fn slice<T: Copy, U>(&self, items: &[T], f: impl Fn(&Sel...
use super::Allocator; use crate::decl_defs::{self, shallow, ty, DeclTy, DeclTy_, FunParam, FunType, UserAttribute}; use crate::reason::Reason; use oxidized_by_ref as obr; use pos::{ConstName, FunName, TypeName}; impl<R: Reason> Allocator<R> { #[inline] fn slice<T: Copy, U>(&self, items: &[T], f: impl Fn(&Sel...
, Tunion(tys) => DTunion(self.slice(tys, Self::ty_from_decl)), Tintersection(tys) => DTintersection(self.slice(tys, Self::ty_from_decl)), TvecOrDict((ty1, ty2)) => { DTvecOrDict(Box::new((self.ty_from_decl(ty1), self.ty_from_decl(ty2)))) } Tacc...
DTgeneric(Box::new(( TypeName(self.symbol(pos_id)), self.slice(tys, Self::ty_from_decl), )))
call_expression
[]
Rust
src/expr/transform/column_knowledge.rs
cuongdo/materialize
5e32da2ef02ce32a5b2cfec7f861c40b698402d0
use std::collections::HashMap; use repr::Datum; use repr::{ColumnType, ScalarType}; use crate::{EvalEnv, GlobalId, RelationExpr, ScalarExpr, UnaryFunc}; #[derive(Debug)] pub struct ColumnKnowledge; impl super::Transform for ColumnKnowledge { fn transform( &self, expr: &mut RelationExpr, ...
use std::collections::HashMap; use repr::Datum; use repr::{ColumnType, ScalarType}; use crate::{EvalEnv, GlobalId, RelationExpr, ScalarExpr, UnaryFunc}; #[derive(Debug)] pub struct ColumnKnowledge; impl super::Transform for ColumnKnowledge { fn transform( &self, expr: &mut RelationExpr, ...
rType::Bool).nullable(false), ); optimize(expr, env, column_knowledge) } else { DatumKnowledge { value: None, nullable: true, } } } ScalarExpr::CallBinary { func: _...
&[DatumKnowledge], ) -> DatumKnowledge { match expr { ScalarExpr::Column(index) => { let index = *index; if let Some((datum, typ)) = &column_knowledge[index].value { *expr = ScalarExpr::Literal(datum.clone(), typ.clone()); } column_knowledge[i...
random
[ { "content": "/// Delete each constraint in `constraints` from any filter immediately preceding a get for `bound_name`.\n\nfn delete_constraints(expr: &mut RelationExpr, bound_id: LocalId, constraints: &[ScalarExpr]) {\n\n match expr {\n\n RelationExpr::Filter { input, predicates } => {\n\n ...
Rust
new_project/src/main.rs
intrepion/Rust-Web-Programming-A-hands-on-guide-to-developing-fast-and-secure-web-apps-with-the-Rust-programmi
0ecf256e66f08ece6d09c9fc1c61796438a8c35e
#[cfg(test)] mod should { use super::*; #[test] fn error_check_new_project_when_missing_page_number() { let expected = format!("Missing page number.\n{}", USAGE); let arguments = vec!["new_project".to_string()]; let actual = check_new_project(arguments).unwrap_err(); asse...
#[cfg(test)] mod should { use super::*; #[test] fn error_check_new_project_when_missing_page_number() { let expected = format!("Missing page number.\n{}", USAGE); let arguments = vec!["new_project".to_string()]; let actual = check_new_project(arguments).unwrap_err(); asse...
.arg("build") .output() .expect("failed to build project"); let rust_yml_beginning = "name: Rust on: push: branches: [ main ] pull_request: branches: [ main ] env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 ...
h arguments[2].parse::<u32>() { Ok(last_page) => Ok(Project { last_page: last_page, name: arguments[3].to_string(), page_number: page_number, }), Err(_) => Err(format!("Invalid last page.\n{}", USAGE)), }, Err(_) => Err(...
random
[ { "content": "pub fn process_token(request: &ServiceRequest) -> Result<String, &'static str> {\n\n match processes::extract_header_token(request) {\n\n Ok(token) => processes::check_password(token),\n\n Err(message) => Err(message),\n\n }\n\n}\n", "file_path": "projects/page_242_building...
Rust
src/lib/commands.rs
smehlhoff/twitch-log-bot
989f46a95afc28ddcbe390ce070e8c336bea4b7e
use chrono::prelude::*; use irc::client::prelude::*; use std::{thread, time}; use crate::lib::{config, db, error, file, message}; fn check_prefix(mut channels: Vec<String>) -> Vec<String> { for channel in &mut channels { if !channel.contains('#') { channel.insert(0, '#'); } } ...
use chrono::prelude::*; use irc::client::prelude::*; use std::{thread, time}; use crate::lib::{config, db, error, file, message}; fn check_prefix(mut channels: Vec<String>) -> Vec<String> { for channel in &mut channels { if !channel.contains('#') { channel.insert(0, '#'); } } ...
fn part( client: &irc::client::IrcClient, mut bot_state: std::sync::MutexGuard<config::State>, mut config: config::Config, admin: &str, channels: Vec<String>, ) -> Result<(), error::Error> { let channels = check_prefix(channels); let mut v = Vec::new(); for channel in &channels { ...
state: std::sync::MutexGuard<config::State>, mut config: config::Config, admin: &str, channels: Vec<String>, ) -> Result<(), error::Error> { let channels = check_prefix(channels); let mut v = Vec::new(); file::create_dirs(&channels)?; for channel in &channels { if !config.channels....
function_block-function_prefixed
[ { "content": "pub fn create_dirs(channels: &[String]) -> Result<(), error::Error> {\n\n fs::create_dir_all(path::Path::new(\"logs/admin/\"))?;\n\n\n\n for channel in channels.iter() {\n\n fs::create_dir_all(path::Path::new(\"logs/\").join(channel.replace(\"#\", \"\")))?;\n\n }\n\n\n\n Ok(())\...
Rust
src/lib.rs
Freaky/compresstimator
030d112453bc24619e47f234bc566c1494b1590e
#![warn(missing_docs)] #![warn(missing_doc_code_examples)] use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::path::Path; use lz4::EncoderBuilder; #[derive(Debug, Default)] struct WriteCount { written: u64, } impl Write for WriteCount { fn write(&mut self, buf: &[u8]) -> io::Resul...
#![warn(missing_docs)] #![warn(missing_doc_code_examples)] use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::path::Path; use lz4::EncoderBuilder; #[derive(Debug, Default)] struct WriteCount { written: u64, } impl Write for WriteCount { fn write(&mut self, buf: &[u8]) -> io::Resul...
margin: 0.1, confidence: Confidence::C95, } } } impl Compresstimator { pub fn new() -> Self { Self::default() } pub fn with_block_size(block_size: u64) -> Self { Self { block_size: block_size as u64, ..Self::default() }...
99, } impl From<Confidence> for f32 { fn from(c: Confidence) -> f32 { match c { Confidence::C80 => 1.28, Confidence::C85 => 1.44, Confidence::C90 => 1.65, Confidence::C95 => 1.96, Confidence::C99 => 2.58, } } } fn sample_size(pop: u64...
random
[ { "content": "fn main() -> std::io::Result<()> {\n\n let estimator = Compresstimator::default();\n\n\n\n for path in std::env::args_os()\n\n .skip(1)\n\n .map(std::path::PathBuf::from)\n\n .filter(|p| p.is_file())\n\n {\n\n println!(\"Path: {}\", path.display());\n\n\n\n ...
Rust
src/app/run.rs
KSXGitHub/sane-fmt
c0855105e29ce532d91ff76c74ef6d5f04cc98cc
use super::super::{ act, cli_opt::{LogFormat, When}, cross_platform_path, file_list, term::color::{ColorScheme, ColorfulScheme, ColorlessScheme}, }; use super::App; use pipe_trait::*; use relative_path::RelativePath; use std::{ fs, io::{stdin, Read}, path::{Path, PathBuf, MAIN_SEPARATOR}, };...
use super::super::{ act, cli_opt::{LogFormat, When}, cross_platform_path, file_list, term::color::{ColorScheme, ColorfulScheme, ColorlessScheme}, }; use super::App; use pipe_trait::*; use relative_path::RelativePath; use std::{ fs, io::{stdin, Read}, path::{Path, PathBuf, MAIN_SEPARATOR}, };...
}
else { let path = if cfg!(unix) { path } else { cross_platform_path::convert_path(&path, '/') }; let path = path .pipe_ref(RelativePath::fro...
function_block-function_prefix_line
[ { "content": "/// Add all applicable files in a directory into an existing list\n\npub fn read_into(list: &mut List, dirname: &Path) -> Result<(), Error> {\n\n let mut entries = read_dir(dirname)\n\n .map_err(|error| Error::new(dirname.to_path_buf(), error))?\n\n .map(|entry| -> Result<_, _> {\...
Rust
src/constraints/arithmetic/equalities.rs
VincentVigneron/solver_cp
60c00b020b91fcf0b4301fb65eb991b83a5d0bbc
use constraints::{Constraint, PropagationState}; use variables::domains::{OrderedDomain, PrunableDomain}; use variables::handlers::{ VariableContainerHandler, VariableContainerView, VariablesHandler, }; use variables::{Variable, VariableError, VariableId, VariableState}; #[derive(Clone)] pub struct Equal<VarType, ...
use constraints::{Constraint, PropagationState}; use variables::domains::{OrderedDomain, PrunableDomain}; use variables::handlers::{ VariableContainerHandler, VariableContainerView, VariablesHandler, }; use variables::{Variable, VariableError, VariableId, VariableState}; #[derive(Clone)] pub struct Equal<VarType, ...
arType, View> = <Equal<VarType, View> as Clone>::clone(ref_self); Box::new(cloned) as Box<Constraint<Handler>> } fn propagate( &mut self, variables_handler: &mut Handler, ) -> Result<PropagationState, VariableError> { let mut output = vec![]; self.output ...
w> where Handler: VariablesHandler + VariableContainerHandler<View> + Clone, View: VariableContainerView + 'static, Var: PrunableDomain<Type = VarType>, Var::Type: Eq + Ord + Clone + 'static, { fn box_clone(&self) -> Box<Constraint<Handler>> { let ref_self: &Equal<VarType, View> = &self; ...
random
[ { "content": "/// Represents type holdings variables. A Variable is a VariableContainer because\n\n/// its holds itsefl. An Array of Variables is a VariableContainer because it holds\n\n/// a list of Variables.\n\npub trait VariableContainerView: Clone {\n\n ///// The `Type` managed by the Handler (Variable ...
Rust
bee-ledger/src/worker.rs
LouayKamel/bee-p
8b8eda7d348867a076284f0bb07dda176a1e6050
use crate::{ error::Error, event::MilestoneConfirmed, merkle_hasher::MerkleHasher, metadata::WhiteFlagMetadata, storage::Backend, white_flag::visit_dfs, }; use bee_common::shutdown_stream::ShutdownStream; use bee_common_ext::{ event::Bus, node::{Node, ResHandle}, worker::Worker, }; use bee_messag...
use crate::{ error::Error, event::MilestoneConfirmed, merkle_hasher::MerkleHasher, metadata::WhiteFlagMetadata, storage::Backend, white_flag::visit_dfs, }; use bee_common::shutdown_stream::ShutdownStream; use bee_common_ext::{ event::Bus, node::{Node, ResHandle}, worker::Worker, }; use bee_messag...
#[async_trait] impl<N: Node> Worker<N> for LedgerWorker where N::Backend: Backend, { type Config = (MilestoneIndex, ProtocolCoordinatorConfig, Arc<Bus<'static>>); type Error = Infallible; fn dependencies() -> &'static [TypeId] { vec![TypeId::of::<TangleWorker>(), TypeId::of::<StorageWorker>()...
async fn confirm<N: Node>( tangle: &MsTangle<N::Backend>, storage: &ResHandle<N::Backend>, message_id: MessageId, index: &mut MilestoneIndex, _coo_config: &ProtocolCoordinatorConfig, bus: &Arc<Bus<'static>>, ) -> Result<(), Error> where N::Backend: Backend, { let message = tangle.get(&me...
function_block-full_function
[ { "content": "pub fn info(message: &str, context: &str) {\n\n if log_enabled!(log::Level::Info) {\n\n info!(\"{} {}\", context, message);\n\n }\n\n}\n\n\n", "file_path": "bee-network/examples/common/logger.rs", "rank": 0, "score": 116292.57667807199 }, { "content": "pub fn rando...
Rust
src/core/data_types.rs
kN1e1ght/penrose
5efd2bcfa3831d02b87056583e66eac8bb92cb9d
use crate::{ core::xconnection::{Atom, Xid}, Result, }; pub type ResizeAction = (Xid, Option<Region>); pub type WinId = u32; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WinType { CheckWin, InputOnly, ...
use crate::{ core::xconnection::{Atom, Xid}, Result, }; pub type ResizeAction = (Xid, Option<Region>); pub type WinId = u32; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WinType { CheckWin, InputOnly, ...
, new_width, self.w )) } else { Ok(( Self { w: new_width, ..*self }, Self { x: self.x + new_width, w: self.w - new_width, ...
, n_columns: u32) -> Vec<Region> { if n_columns <= 1 { return vec![*self]; } let w = self.w / n_columns as u32; (0..n_columns) .map(|n| Region::new((self.x + n as u32 * w) as u32, self.y, w, self.h)) .collect() } ...
random
[ { "content": "/// A no-op floating layout that simply satisfies the type required for Layout\n\npub fn floating(_: &[&Client], _: Option<Xid>, _: &Region, _: u32, _: f32) -> Vec<ResizeAction> {\n\n vec![]\n\n}\n\n\n\nimpl Layout {\n\n /// Create a new Layout for a specific monitor\n\n pub fn new(\n\n ...
Rust
packages/api/src/externals/function.rs
chmp/wasmer-python
953a17ad7666ea623a7b08419e347a76ec9107e7
use crate::{ errors::to_py_err, store::Store, types::FunctionType, values::{to_py_object, to_wasm_value}, wasmer_inner::wasmer, }; use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, prelude::*, types::{PyDict, PyTuple}, }; use std::{io, sync::Arc}; #[pyclass(unsendable)] #[text_sig...
use crate::{ errors::to_py_err, store::Store, types::FunctionType, values::{to_py_object, to_wasm_value}, wasmer_inner::wasmer, }; use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, prelude::*, types::{PyDict, PyTuple}, }; use std::{io, sync::Arc}; #[pyclass(unsendable)] #[text_sig...
_string()) })?] } else { Vec::new() }) }, ); Ok(Self::raw_new(host_function)) } #[call] #[args(arguments = "*")] fn __call__<'p>(&self, py: Python<'p>, arguments: &PyTuple) -> PyResult<PyObject> { ...
ent .py_function .call(py, PyTuple::new(py, arguments), None) .map_err(|error| { wasmer::RuntimeError::new(io::Error::from(error).to_string()) })?; let result_types = environment.result_types.clone()...
function_block-random_span
[]
Rust
src/bin/daemon/main.rs
b0r3dd3v/mangadex-fs
90b8718f5da13d0334a1339496033b27abcdbddf
#[macro_use] extern crate log; mod ipc; mod cli; use tokio::stream::StreamExt; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); let cli = cli::daemon() .version(env!("CARGO_PKG_VERSION")) ...
#[macro_use] extern crate log; mod ipc; mod cli; use tokio::stream::StreamExt; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); let cli = cli::daemon() .version(env!("CARGO_PKG_VERSION")) ...
ml * it's not possible to receive None here. */ } } } context.log_out().await.ok(); polyfuse_sig_tx.send(()).ok(); polyfuse.await?.ok(); tokio::fs::remove_file(config.socke...
_ = sigint.recv() => { info!("received an interrupt signal, shutting down..."); break; }, _ = sigterm.recv() => { info!("received a termination signal, shutting down..."); ...
random
[ { "content": "pub fn config_file_path() -> std::path::PathBuf {\n\n let project_dirs = project_dirs();\n\n let config_dir = project_dirs.config_dir();\n\n config_dir.join(std::path::Path::new(DEFAULT_CONFIG_NAME))\n\n}\n\n\n", "file_path": "src/lib/cfg/mod.rs", "rank": 0, "score": 117959.89...
Rust
src/game_map.rs
awheeler294/jmc
9fba41ae779e2480e4b362120d370551026871f4
use oorandom; use std::collections::HashMap; use crate::color_scheme::{ColorName, get_stone_color, get_floor_color}; use noise::{Billow, MultiFractal, Seedable, NoiseFn, ScalePoint}; use quicksilver::prelude::*; pub struct GameMap { map: HashMap<u32, HashMap<u32, HashMap<u32, HashMap<u32, Vec<Tile>>>>>, pub c...
use oorandom; use std::collections::HashMap; use crate::color_scheme::{ColorName, get_stone_color, get_floor_color}; use noise::{Billo
lf.level_thickness, &self.random_seed) ); } let chunk = &y_map.get(&center_z).unwrap(); let chunk_x = x % chunk_size; let chunk_y = y % chunk_size; let chunk_z = z % chunk_size; let chunk_plane = &chunk.get(&chunk_z)....
w, MultiFractal, Seedable, NoiseFn, ScalePoint}; use quicksilver::prelude::*; pub struct GameMap { map: HashMap<u32, HashMap<u32, HashMap<u32, HashMap<u32, Vec<Tile>>>>>, pub chunk_size: u32, pub max_chuncks_x: u32, pub max_chuncks_y: u32, pub max_chuncks_z: u32, pub surface_level: u32, pub...
random
[ { "content": "pub fn get_stone_color(val: &f64, min: &f64, max: &f64) -> ColorName {\n\n let min = *min;\n\n let max = *max;\n\n\n\n let step = (max - min) / 7.0;\n\n if (min..(min+step)).contains(&val) {\n\n ColorName::Void\n\n }\n\n else if (min+step..min+(2.0*step)).contains(&val) {\...
Rust
quinn-h3/src/qpack/stream.rs
nbaksalyar/quinn
eade6f4d9a71ed795af463f0e0e0ad5b55efe863
use bytes::{Buf, BufMut}; use super::parse_error::ParseError; use super::prefix_int::{self, Error as IntError}; use super::prefix_string::{self, Error as StringError}; pub enum EncoderInstruction { InsertWithNameRef, InsertWithoutNameRef, Duplicate, DynamicTableSizeUpdate, Unknown, } impl Encoder...
use bytes::{Buf, BufMut}; use super::parse_error::ParseError; use super::prefix_int::{self, Error as IntError}; use super::prefix_string::{self, Error as StringError}; pub enum EncoderInstruction { InsertWithNameRef, InsertWithoutNameRef, Duplicate, DynamicTableSizeUpdate, Unknown, } impl Encoder...
}
ction = StreamCancel(42); let mut buf = vec![]; instruction.encode(&mut buf); let mut read = Cursor::new(&buf); assert_eq!(StreamCancel::decode(&mut read), Ok(Some(instruction))); }
function_block-function_prefixed
[ { "content": "pub fn decode<B: Buf>(size: u8, buf: &mut B) -> Result<Vec<u8>, Error> {\n\n let (flags, len) = prefix_int::decode(size - 1, buf)?;\n\n if buf.remaining() < len {\n\n return Err(Error::UnexpectedEnd);\n\n }\n\n\n\n let payload = buf.take(len);\n\n let value = if flags & 1 == ...
Rust
graph-http/src/download/client.rs
northfuse/graph-rs
950802541cc35f19d6b582648f740e6abee9df5c
use crate::async_client::AsyncClient; use crate::blocking_client::BlockingClient; use crate::iotools::IoTools; use crate::url::GraphUrl; use crate::{HttpClient, RequestAttribute, RequestClient, RequestType}; use graph_error::{AsRes, ErrorMessage, GraphError, GraphFailure, GraphResult, GraphRsError}; use reqwest::header...
use crate::async_client::AsyncClient; use crate::blocking_client::BlockingClient; use crate::iotools::IoTools; use crate::url::GraphUrl; use crate::{HttpClient, RequestAttribute, RequestClient, RequestType}; use graph_error::{AsRes, ErrorMessage, GraphError, GraphFailure, GraphResult, GraphRsError}; use reqwest::header...
} impl AsyncDownload { pub fn new_async(client: AsyncClient) -> AsyncDownload { let path = client.download_dir.clone().unwrap(); DownloadClient { request: std::sync::Arc::new(tokio::sync::Mutex::new(DownloadRequest::new(path))), client: HttpClient::from(client), } ...
fn download(self) -> GraphResult<PathBuf> { let request = self.request.borrow(); if request.create_dir_all.eq(&true) { IoTools::create_dir(request.path.as_path())?; } else if !request.path.exists() { let dir = request.path.to_string_lossy().to_string(); ...
function_block-full_function
[ { "content": "// You can convert a file to a different format using the download_format() method.\n\n// There are 4 formats: glb, html, jpg, and pdf that an item can be converted to.\n\n// This uses the PDF conversion which can be converted from: doc, docx, epub,\n\n// eml, htm, html, md, msg, odp, ods, odt, pp...
Rust
src/connectivity/bluetooth/tests/integration/src/harness/emulator.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use { anyhow::{format_err, Error}, fidl_fuchsia_bluetooth::{DeviceClass, MAJOR_DEVICE_CLASS_TOY}, fidl_fuchsia_bluetooth_test::{ AdvertisingData, BredrPeerParameters, ConnectionState, HciEmulatorProxy, LowEnergyPeerParameters, PeerProxy, }, fuchsia_bluetooth::{ expectation:...
use { anyhow::{format_err, Error}, fidl_fuchsia_bluetooth::{DeviceClass, MAJOR_DEVICE_CLASS_TOY}, fidl_fuchsia_bluetooth_test::{ AdvertisingData, BredrPeerParameters, ConnectionState, HciEmulatorProxy, LowEnergyPeerParameters, PeerProxy, }, fuchsia_bluetooth::{ expectation:...
pub fn advertising_type_is<S>(type_: LegacyAdvertisingType) -> Predicate<S> where S: 'static + EmulatorHarnessState, { let descr = format!("advertising type is: {:#?}", type_); Predicate::new( move |state: &S| -> bool { state .as_ref(...
c + EmulatorHarnessState, { let descr = format!("advertising was (enabled: {})", enabled); Predicate::new( move |state: &S| -> bool { state.as_ref().advertising_state_changes.iter().any(|s| s.enabled == enabled) }, Some(&descr), ) }
function_block-function_prefixed
[]
Rust
src/mapping.rs
agluszak/quad-gamepad
7f88d4eadf5e4ce0d9d8cd3edce6c32d472b5053
#![allow(dead_code)] use std::collections::HashMap; use crate::GamepadButton; const MAPPINGS: &str = include_str!("mappings.txt"); #[allow(dead_code)] #[derive(Debug, Clone, Copy, PartialEq)] pub enum Platform { Linux, Windows, Mac, Android, IOS, } const MAX_BTNS: usize = 140; #[derive(Debug, ...
#![allow(dead_code)] use std::collections::HashMap; use crate::GamepadButton; const MAPPINGS: &str = include_str!("mappings.txt"); #[allow(dead_code)] #[derive(Debug, Clone, Copy, PartialEq)] pub enum Platform { Linux, Windows, Mac, Android, IOS, } const MAX_BTNS: usize = 140; #[derive(Debug, ...
apping.platform { mappings_map.insert(guid.to_owned(), mapping); } } mappings_map }
ashMap::new(); for line in MAPPINGS.lines() { if line.starts_with("#") || line.is_empty() { continue; } let mut tokens = line.split(','); let guid = tokens.next().unwrap(); let name = tokens.next().unwrap(); let mut mapping = Mapping::new(guid); ...
random
[ { "content": "pub fn kIOHIDProductKey() -> &'static str {\n\n \"Product\"\n\n}\n\n\n", "file_path": "src/platform/macos/io_kit.rs", "rank": 1, "score": 122374.74345710987 }, { "content": "pub fn kIOHIDProductIDKey() -> &'static str {\n\n \"ProductID\"\n\n}\n\n\n", "file_path": "src...
Rust
src/widgets/lazy_paragraph.rs
TehPers/smapi_log_parser
dcce85b992c53b919a7aa48ba9d89e683432f9c4
use crate::{ events::AppEvent, widgets::{BindingDisplay, IconPack, Scrollbar, State}, }; use crossterm::event::{Event, KeyCode}; use indexmap::IndexMap; use tui::{ buffer::Buffer, layout::Rect, style::Style, text::Spans, widgets::{Block, Clear, StatefulWidget, Widget}, }; use unicode_width::...
use crate::{ events::AppEvent, widgets::{BindingDisplay, IconPack, Scrollbar, State}, }; use crossterm::event::{Event, KeyCode}; use indexmap::IndexMap; use tui::{ buffer::Buffer, layout::Rect, style::Style, text::Spans, widgets::{Block, Clear, StatefulWidget, Widget}, }; use unicode_width::...
} } pub fn is_scrolling(self) -> bool { if let AutoScroll::Enabled { scrolling } = self { scrolling } else { false } } } impl Default for AutoScroll { fn default() -> Self { AutoScroll::Disabled } }
state.lines.saturating_sub(height); state.auto_scroll.scroll(); } else { state.auto_scroll.reset(); }; let first_line = line_after_last_line.saturating_sub(height); state.offset.y = first_line; let render_scrollbar = state.lines > heigh...
random
[ { "content": "pub trait State {\n\n /// Updates this state. Returns `true` if the event was handled.\n\n fn update(&mut self, event: &AppEvent) -> bool;\n\n\n\n /// Adds controls this state uses to the given map.\n\n fn add_controls<I: IconPack>(&self, _controls: &mut IndexMap<BindingDisplay<I>, &'s...
Rust
src/function_codes.rs
dbrgn/gerber-types-rs
5e9bd3e4f3d701a38eec4428c17738249f5f7a4e
use std::io::Write; use crate::coordinates::{CoordinateOffset, Coordinates}; use crate::errors::GerberResult; use crate::traits::{GerberCode, PartialGerberCode}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum DCode { Operation(Operation), SelectAperture(i32), } impl<W: Write> GerberCode<W> for DCode { ...
use std::io::Write; use crate::coordinates::{CoordinateOffset, Coordinates}; use crate::errors::GerberResult; use crate::traits::{GerberCode, PartialGerberCode}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum DCode { Operation(Operation), SelectAperture(i32), } impl<W: Write> GerberCode<W> for DCode { ...
} #[derive(Debug, Clone, PartialEq, Eq)] pub enum GCode { InterpolationMode(InterpolationMode), RegionMode(bool), QuadrantMode(QuadrantMode), Comment(String), } impl<W: Write> GerberCode<W> for GCode { fn serialize(&self, writer: &mut W) -> GerberResult<()> { match *self { GCo...
fn serialize(&self, writer: &mut W) -> GerberResult<()> { match *self { DCode::Operation(ref operation) => operation.serialize(writer)?, DCode::SelectAperture(code) => writeln!(writer, "D{}*", code)?, }; Ok(()) }
function_block-full_function
[ { "content": "/// All types that implement this trait can be converted to a complete Gerber\n\n/// Code line. Generated code should end with a newline.\n\npub trait GerberCode<W: Write> {\n\n fn serialize(&self, writer: &mut W) -> GerberResult<()>;\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 0...
Rust
src/lib/ui/carnelian/examples/font_metrics.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
use anyhow::Error; use carnelian::{ color::Color, drawing::{load_font, FontFace}, input::{self}, render::Context as RenderContext, scene::{ facets::{ FacetId, SetColorMessage, SetTextMessage, TextFacetOptions, TextHorizontalAlignment, TextVerticalAlignment, ...
use anyhow::Error; use carnelian::{ color::Color, drawing::{load_font, FontFace}, input::{self}, render::Context as RenderContext, scene::{ facets::{ FacetId, SetColorMessage, SetTextMessage, TextFacetOptions, TextHorizontalAlignment, TextVerticalAlignment, ...
Box::new(SetTextMessage { text: self.sample_paragraph.clone() }), ); } self.app_context.request_render(self.view_key); } fn new_sample_text(&mut self) { let (title, para) = Self::new_sample_pair(); self.update_text(title, para); } fn new_blank_text(&mut ...
Box::new(SetTextMessage { text: self.sample_title.clone() }), ); scene_details.scene.send_message( &scene_details.sample_paragraph.clone(),
function_block-random_span
[]
Rust
rustmo-devices/src/sony/receivers/str_za5000_es.rs
eeeebbbbrrrr/rustmo
33e20d5576e0a34ebab5c2a926380abe131a1b20
use std::net::IpAddr; use rustmo_server::virtual_device::{VirtualDevice, VirtualDeviceError, VirtualDeviceState}; const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(4); #[derive(Clone, Copy)] pub struct Device { ip_address: IpAddr, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pu...
use std::net::IpAddr; use rustmo_server::virtual_device::{VirtualDevice, VirtualDeviceError, VirtualDeviceState}; const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(4); #[derive(Clone, Copy)] pub struct Device { ip_address: IpAddr, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pu...
est::ClientBuilder::new().timeout(TIMEOUT).build()?; let body = format!("{{\"type\":\"http_set\",\"packet\":[{{\"id\":274,\"feature\":\"{str}\",\"value\":\"main\"}}]}}", str = str).clone(); client .post(format!("http://{}/request.cgi", self.ip_address.to_string()).as_str()) .body...
tr()) .body("{\"type\":\"http_get\",\"packet\":[{\"id\":1,\"feature\":\"main.input\"}]}") .send()?; let response = response.text()?; let response: VideoInputResponse = serde_json::from_str(response.as_str())?; Ok(match response.packet.get(0).unwrap_or(&VideoInputRespons...
random
[ { "content": "///\n\n/// The `VirtualDevice` trait allows implementors to create devices that\n\n/// can be exposed to Alexa via `RustmoServer`\n\n///\n\n/// Rustmo pretends that devices are a \"plug\", so they only have two states:\n\n/// On and Off.\n\n///\n\n/// Some implementation notes:\n\n///\n\n/// 1) ...
Rust
core/src/decode.rs
psiberx/redscript
85ebd54f3d13fbd4fb10fbec8b09b538a556e10d
use std::io; use byteorder::{LittleEndian, ReadBytesExt}; pub trait Decode: Sized { fn decode<I: io::Read>(input: &mut I) -> io::Result<Self>; } impl Decode for i64 { #[inline(always)] fn decode<I: io::Read>(input: &mut I) -> io::Result<Self> { input.read_i64::<LittleEndian>() } } impl Decod...
use std::io; use byteorder::{LittleEndian, ReadBytesExt}; pub trait Decode: Sized { fn decode<I: io::Read>(input: &mut I) -> io::Result<Self>; } impl Decode for i64 { #[inline(always)] fn decode<I: io::Read>(input: &mut I) -> io::Result<Self> { input.read_i64::<LittleEndian>() } } impl Decod...
} impl<const N: usize> Decode for [u8; N] { #[inline(always)] fn decode<I: io::Read>(input: &mut I) -> io::Result<Self> { let mut buf: [u8; N] = [0; N]; input.read_exact(&mut buf)?; Ok(buf) } } pub trait DecodeExt: io::Read + Sized { #[inline(always)] fn decode<A: Decode>(...
c = input.read_u8()?; if c == 0 { break; } buf.push(c); } String::from_utf8(buf).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) }
function_block-function_prefixed
[ { "content": "fn crc(bytes: &[u8]) -> u32 {\n\n let mut hasher = crc32fast::Hasher::new();\n\n hasher.update(bytes);\n\n hasher.finalize()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::io::Cursor;\n\n\n\n use super::ScriptBundle;\n\n use crate::error::Error;\n\n\n\n const PREDEF: &[u...
Rust
northstar/src/runtime/cgroups.rs
adoerr/northstar
0df358d2421d953a9dcf28c263b3642a54a84851
use super::{ stats::{to_value, ContainerStats}, Container, EventTx, Pid, }; use crate::{ npk::manifest, runtime::{CGroupEvent, ContainerEvent, Event, MemoryEvent}, }; use cgroups_rs::{ memory::MemController, BlkIoDeviceResource, BlkIoDeviceThrottleResource, BlkIoResources, Controller, CpuResourc...
use super::{ stats::{to_value, ContainerStats}, Container, EventTx, Pid, }; use crate::{ npk::manifest, runtime::{CGroupEvent, ContainerEvent, Event, MemoryEvent}, }; use cgroups_rs::{ memory::MemController, BlkIoDeviceResource, BlkIoDeviceThrottleResource, BlkIoResources, Controller, CpuResourc...
) .collect() } fn root(&self) -> std::path::PathBuf { self.inner.root() } fn root_control_group(&self) -> cgroups_rs::Cgroup { self.inner.root_control_group() } fn v2(&self) -> bool { self.inner.v2() } } #[derive(Debug)] pub struct CGroups { contai...
match s { cgroups_rs::Subsystem::Pid(_) => false, cgroups_rs::Subsystem::Mem(_) => true, cgroups_rs::Subsystem::CpuSet(_) => false, cgroups_rs::Subsystem::CpuAcct(_) => false, cgroups_rs::Subsystem::Cpu(_) => true, cgroups_r...
if_condition
[]
Rust
neqo-http3/src/transaction_server.rs
surender786/neqo
ef263a356addf64e1b1ac6f7d8cd8232eff34b3b
use crate::connection::Http3Transaction; use crate::hframe::{HFrame, HFrameReader}; use crate::server_connection_events::Http3ServerConnEvents; use crate::Header; use crate::{Error, Res}; use neqo_common::{matches, qdebug, qinfo, qtrace, Encoder}; use neqo_qpack::decoder::QPackDecoder; use neqo_qpack::encoder::QPackE...
use crate::connection::Http3Transaction; use crate::hframe::{HFrame, HFrameReader}; use crate::server_connection_events::Http3ServerConnEvents; use crate::Header; use crate::{Error, Res}; use neqo_common::{matches, qdebug, qinfo, qtrace, Encoder}; use neqo_qpack::decoder::QPackDecoder; use neqo_qpack::encoder::QPackE...
} } } TransactionRecvState::Closed => { panic!("Stream readable after being closed!"); } }; } } fn has_data_to_send(&self) -> bool { matches!(self.send_state, TransactionSendState::SendingRe...
match self.recv_frame(conn)? { (None, true) => { self.conn_events.data(self.stream_id, Vec::new(), true); self.recv_state = TransactionRecvState::Closed; return Ok(()); ...
random
[ { "content": "#[must_use]\n\npub fn maybe_authenticate(conn: &mut Connection) -> bool {\n\n let authentication_needed = |e| matches!(e, ConnectionEvent::AuthenticationNeeded);\n\n if conn.events().any(authentication_needed) {\n\n conn.authenticated(AuthenticationStatus::Ok, now());\n\n retur...
Rust
limitador/src/prometheus_metrics.rs
Kuadrant/limitador
823fe0bb11973af6c4efdccea32a9a814dcf77b1
use crate::limit::Namespace; use prometheus::{Encoder, IntCounterVec, IntGauge, Opts, Registry, TextEncoder}; const NAMESPACE_LABEL: &str = "limitador_namespace"; const LIMIT_NAME_LABEL: &str = "limit_name"; struct Metric { name: String, description: String, } lazy_static! { static ref AUTHORIZED_CALLS: ...
use crate::limit::Namespace; use prometheus::{Encoder, IntCounterVec, IntGauge, Opts, Registry, TextEncoder}; const NAMESPACE_LABEL: &str = "limitador_namespace"; const LIMIT_NAME_LABEL: &str = "limit_name"; struct Metric { name: String, description: String, } lazy_static! { static ref AUTHORIZED_CALLS: ...
fn authorized_calls_counter() -> IntCounterVec { IntCounterVec::new( Opts::new(&AUTHORIZED_CALLS.name, &AUTHORIZED_CALLS.description), &[NAMESPACE_LABEL], ) .unwrap() } fn limited_calls_counter(use_limit_name_label: bool) -> IntCounterVec { let mut ...
fn new_with_options(use_limit_name_label: bool) -> Self { let authorized_calls_counter = Self::authorized_calls_counter(); let limited_calls_counter = Self::limited_calls_counter(use_limit_name_label); let limitador_up_gauge = Self::limitador_up_gauge(); let registry = Registry::new(); ...
function_block-full_function
[ { "content": "fn lock_name(entry_name: impl AsRef<str>) -> String {\n\n format!(\"lock:{}\", entry_name.as_ref())\n\n}\n", "file_path": "limitador/src/storage/infinispan/dist_lock.rs", "rank": 0, "score": 225560.0706491694 }, { "content": "pub fn key_for_limits_of_namespace(namespace: &Na...
Rust
src/api/auth.rs
gtsiam/mangadex-rs
f3b02ac1653d2f027dff78e09c9d8932cfc9aba4
use crate::schema::auth::*; use crate::schema::NoData; use crate::Result; use serde::Serialize; #[derive(Debug, Serialize, Clone)] pub struct Login<'a> { pub username: &'a str, pub password: &'a str, } impl_endpoint! { POST "/auth/login", #[body] Login<'_>, #[flatten_result] Result<Lo...
use crate::schema::auth::*; use crate::schema::NoData; use crate::Result; use serde::Serialize; #[derive(Debug, Serialize, Clone)] pub struct Login<'a> { pub username: &'a str, pub password: &'a str, } impl_endpoint! { POST "/auth/login", #[body] Login<'_>, #[flatten_result] Result<Lo...
#[tokio::test] async fn login_err_400() -> anyhow::Result<()> { let server = MockServer::start_async().await; let mock = server .mock_async(|when, then| { when.method(POST) .path("/auth/login") .header("Content-Type", "applic...
async fn login_ok() -> anyhow::Result<()> { let server = MockServer::start_async().await; let mock = server .mock_async(|when, then| { when.method(POST) .path("/auth/login") .header("Content-Type", "application/json") ...
function_block-full_function
[ { "content": "//! Data structures for API abstraction\n\n\n\npub mod at_home;\n\npub mod auth;\n\npub mod author;\n\npub mod chapter;\n\npub mod cover;\n\npub mod errors;\n\npub mod feed;\n\npub mod group;\n\npub mod legacy;\n\npub mod list;\n\npub mod manga;\n\npub mod report;\n\npub mod user;\n\n\n\nmod commo...
Rust
src/renamer.rs
jedisct1/dnssector
380f2fbaf076cf90072ab27f10027fc83d55805e
use crate::compress::*; use crate::constants::*; use crate::errors::*; use crate::parsed_packet::*; use crate::response_iterator::*; use crate::rr_iterator::*; use byteorder::{BigEndian, ByteOrder}; pub struct Renamer; impl Renamer { pub fn replace_raw( name: &[u8], target_name: &[u...
use crate::compress::*; use crate::constants::*; use crate::errors::*; use crate::parsed_packet::*; use crate::response_iterator::*; use crate::rr_iterator::*; use byteorder::{BigEndian, ByteOrder}; pub struct Renamer; impl Renamer { pub fn replace_raw( name: &[u8], target_name: &[u...
rget_name, source_name, match_suffix, ) } fn rename_additional_section( renamed_packet: &mut Vec<u8>, parsed_packet: &mut ParsedPacket, suffix_dict: &mut SuffixDict, target_name: &[u8], source_name: &[u8], match_suffix: bool, )...
cket.len() < raw.name_end + DNS_RR_HEADER_SIZE { bail!(DSError::PacketTooSmall) } let renamed_packet_offset_data = renamed_packet.len(); renamed_packet.extend(&raw.packet[raw.name_end..raw.name_end + DNS_RR_HEADER_SIZE]); let rr_type = ...
random
[ { "content": "/// Get the raw (binary, encoded) name for a name given as a string, and\n\n/// an optional default zone.\n\npub fn raw_name_from_str(name: &[u8], raw_zone: Option<&[u8]>) -> Result<Vec<u8>, Error> {\n\n let mut raw_name = Vec::with_capacity(name.len() + raw_zone.map_or(1, |x| x.len()));\n\n ...
Rust
http/src/kouryaku.rs
DoumanAsh/roseline.rs
642755e39903de6ac8e087c748ce012bb8c2541c
use ::actix::prelude::{Actor, Supervised, Handler, Context, SystemService, Message, ActorFuture, WrapFuture, ResponseActFuture}; use ::regex::Regex; use ::futures::{future, Future}; use ::encoding::codec::japanese::Windows31JEncoding as ShiftJS; use ::encoding::types::{Encoding, DecoderTrap}; use ::{HttpDate, Response...
use ::actix::prelude::{Actor, Supervised, Handler, Context, SystemService, Message, ActorFuture, WrapFuture, ResponseActFuture}; use ::regex::Regex; use ::futures::{future, Future}; use ::encoding::codec::japanese::Windows31JEncoding as ShiftJS; use ::encoding::types::{Encoding, DecoderTrap}; use ::{HttpDate, Response...
spawn(mirai); }); } }
let mirai = kouryaku.send(Find(MIRAI_RADIO.to_string())).map(move |mirai_radio| { let mirai_radio = mirai_radio.expect("Expect to successfully find Mirai Radio"); let mirai_radio = mirai_radio.expect("Expect to find some Mirai Radio"); assert_eq!(mirai_radio.0, "未来ラジオと人工...
assignment_statement
[ { "content": "fn kouryaku(context: &mut Context, message: &Message, args: Args) -> Result<(), CommandError> {\n\n if args.is_empty() {\n\n message.reply(\"For which VN?\")?;\n\n } else {\n\n let kouryaku = {\n\n let data = context.data.lock();\n\n data.get::<KouryakuHan...
Rust
src/objects/pose.rs
l1048576/fbx-load
2cf0a6c6a237f12ac1501d832a974aced494e266
use std::io::Read; use fbx_binary_reader::EventReader; use definitions::Definitions; use error::Result; use node_loader::{NodeLoader, NodeLoaderCommon, RawNodeInfo, ignore_current_node}; use objects::properties::ObjectProperties; #[derive(Debug, Clone)] pub struct Pose { pub id: i64, pub name: String, pu...
use std::io::Read; use fbx_binary_reader::EventReader; use definitions::Definitions; use error::Result; use node_loader::{NodeLoader, NodeLoaderCommon, RawNodeInfo, ignore_current_node}; use objects::properties::ObjectProperties; #[derive(Debug, Clone)] pub struct Pose { pub id: i64, pub name: String, pu...
awNodeInfo) -> Result<()> { let RawNodeInfo { name, properties } = node_info; match name.as_ref() { "Node" => { self.node = properties.iter().next().and_then(|p| p.get_i64()); }, "Matrix" => { self.matrix = properties.iter().next().and_...
("`Pose/NbPoseNodes` node is required but it was invalid or not found"); Ok(None) } } } impl<'a, R: Read> NodeLoader<R> for PoseLoader<'a> { fn on_child_node(&mut self, reader: &mut EventReader<R>, node_info: RawNodeInfo) -> Result<()> { let RawNodeInfo { name, properties } = node_i...
random
[ { "content": "#[derive(Debug, Default)]\n\nstruct PropertyTemplateLoader {\n\n properties: Option<GenericProperties>,\n\n}\n\n\n\nimpl PropertyTemplateLoader {\n\n pub fn new() -> Self {\n\n Default::default()\n\n }\n\n}\n\n\n\nimpl NodeLoaderCommon for PropertyTemplateLoader {\n\n type Targe...
Rust
src/bigram_model.rs
jxcl/rust-autocomplete
067f367baed3a8635d032484d829c9c6e12e48c1
use predictionentry::PredictionEntry; use simplemodel::SimpleWordTrainer; use simplemodel::SimpleWordPredictor; use std::old_io::File; use std::old_io::BufferedReader; use std::collections::HashMap; use std::collections::hash_map::Entry; pub struct BigramTrainer { outer_map: HashMap<String, SimpleWordTraine...
use predictionentry::PredictionEntry; use simplemodel::SimpleWordTrainer; use simplemodel::SimpleWordPredictor; use std::old_io::File; use std::old_io::BufferedReader; use std::collections::HashMap; use std::collections::hash_map::Entry; pub struct BigramTrainer { outer_map: HashMap<String, SimpleWordTraine...
one() } #[test] fn test_from_str() { let mut model = BigramTrainer::new(); model.train_str("there once was a man from dundee"); let prev_word = model.prev_word.clone(); assert_eq!("dundee", prev_word.unwrap()); model.train_str("joe was a happy man"); let pr...
t simplemodel = self.get_simplemodel(word1); match simplemodel { Some(ref predictor) => predictor.predict(letters), None => Vec::new(), } } fn get_simplemodel(&self, word1: &str) -> Option<&SimpleWordPredictor>{ let &BigramPredictor(ref hm) = self; hm.g...
random
[ { "content": "fn count_words(model: &mut SimpleWordTrainer, input: &Vec<&str>) {\n\n let &mut SimpleWordTrainer(ref mut model_hm) = model;\n\n for word in input {\n\n train_single_word(model_hm, word);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use simplemodel::SimpleWordTrainer;\n\n ...
Rust
src/lib.rs
mpetri/streamvbyte-sys
b773f5c3741ebf02566fa37cacb3f930af063610
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] pub type __uint8_t = ::std::os::raw::c_uchar; pub type __uint32_t = ::std::os::raw::c_uint; pub type size_t = ::std::os::raw::c_ulong; extern "C" { pub fn streamvbyte_encode(in_: *const u32, length: u32, out: *mut u8) -> si...
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] pub type __uint8_t = ::std::os::raw::c_uchar; pub type __uint32_t = ::std::os::raw::c_uint; pub type size_t = ::std::os::raw::c_ulong; extern "C" { pub fn streamvbyte_encode(in_: *const u32, length: u32, out: *mut u8) -> si...
code( in_: *const u8, out: *mut u32, length: u32, prev: u32, ) -> size_t; } #[cfg(test)] mod tests { fn create_input(bits: u32, len: usize) -> Vec<u32> { use rand::distributions::{Distribution, Uniform}; let min = 0; let max: u64 = (1 << bits) - 1; ...
b fn streamvbyte_decode(in_: *const u8, out: *mut u32, length: u32) -> size_t; } extern "C" { pub fn streamvbyte_delta_encode( in_: *const u32, length: u32, out: *mut u8, prev: u32, ) -> size_t; } extern "C" { pub fn streamvbyte_delta_de
random
[ { "content": "fn main() {\n\n // compile library\n\n let dst = cmake::build(\"external/streamvbyte\");\n\n println!(\"cargo:rustc-link-search=native={}/lib/\", dst.display());\n\n println!(\"cargo:rustc-link-lib=static=streamvbyte_static\");\n\n}\n", "file_path": "build.rs", "rank": 0, "...
Rust
src/import.rs
Marwes/gluon
0d16ec713ffb472d2d25665c0caea6f2c98194ef
use std::any::Any; use std::sync::{Arc, RwLock, Mutex}; use std::fs::File; use std::io; use std::io::Read; use std::path::{Path, PathBuf}; use base::ast::{Expr, Literal, SpannedExpr, TypedIdent}; use base::metadata::Metadata; use base::pos; use base::symbol::Symbol; use vm::macros::{Macro, MacroExpander, Error as Ma...
use std::any::Any; use std::sync::{Arc, RwLock, Mutex}; use std::fs::File; use std::io; use std::io::Read; use std::path::{Path, PathBuf}; use base::ast::{Expr, Literal, SpannedExpr, TypedIdent}; use base::metadata::Metadata; use base::pos; use base::symbol::Symbol; use vm::macros::{Macro, MacroExpander, Error as Ma...
} #[derive(Clone)] pub struct CheckImporter(pub Arc<Mutex<FnvMap<String, SpannedExpr<Symbol>>>>); impl CheckImporter { pub fn new() -> CheckImporter { CheckImporter(Arc::new(Mutex::new(FnvMap::default()))) } } impl Importer for CheckImporter { fn import(&self, compiler: &mut Compiler...
fn import(&self, compiler: &mut Compiler, vm: &Thread, modulename: &str, input: &str, expr: SpannedExpr<Symbol>) -> Result<(), MacroError> { use compiler_pipeline::*; try!(MacroValue { expr: expr }.load_script(compiler,...
function_block-full_function
[ { "content": "fn compile_repl(vm: &Thread) -> Result<(), Box<StdError + Send + Sync>> {\n\n\n\n try!(vm.register_type::<Editor>(\"Editor\", &[]));\n\n\n\n try!(vm.define_global(\"rustyline\",\n\n record!(\n\n new_editor => primitive!(1 new_editor),\n\n readline => pr...
Rust
build.rs
pollend/rust-lua53
83af5861a876edf58dd9773231444db35e83c725
extern crate cc; use std::fs; use std::io; use std::env; use std::path::{Path, PathBuf}; use std::process::Command; use std::ffi::OsString; use std::ffi::OsStr; trait CommandExt { fn execute(&mut self) -> io::Result<()>; } impl CommandExt for Command { fn execute(&mut self) -> io::Result<()> { l...
extern crate cc; use std::fs; use std::io; use std::env; use std::path::{Path, PathBuf}; use std::process::Command; use std::ffi::OsString; use std::ffi::OsStr; trait CommandExt { fn execute(&mut self) -> io::Result<()>; } impl CommandExt for Command { fn execute(&mut self) -> io::Result<()> { l...
} } } fn build_lua(tooling: &cc::Tool, source: &Path, build: &Path) -> io::Result<()> { let platform = match env::var("TARGET").unwrap().split('-').nth(2).unwrap() { "windows" => "mingw", "darwin" => "macosx", "linux" => "linux", "freebsd" => "freebsd", "dr...
Err(io::Error::new(io::ErrorKind::Other, format!("The command\n\ \t{:?}\n\ did not run successfully.", self)))
call_expression
[ { "content": "#[doc(hidden)]\n\n#[inline(always)]\n\npub fn _check_type(f: fn(&mut State) -> c_int) -> fn(&mut State) -> c_int {\n\n f\n\n}\n\n\n", "file_path": "src/macros.rs", "rank": 3, "score": 79020.98241592865 }, { "content": "fn main() {\n\n let mut state = lua::State::new();\n\n\n\...
Rust
src/utils/fs.rs
pthariensflame/tokei
f3f21ae6f1b81bc43ac6750a28df89cbfb0b6199
use std::collections::BTreeMap; use std::path::Path; use std::sync::mpsc; use std::error::Error; use ignore::WalkBuilder; use ignore::overrides::OverrideBuilder; use ignore::WalkState::*; use language::{Language, LanguageType}; use language::LanguageType::*; pub use language::get_filetype_from_shebang; macro_rules...
use std::collections::BTreeMap; use std::path::Path; use std::sync::mpsc; use std::error::Error; use ignore::WalkBuilder; use ignore::overrides::OverrideBuilder; use ignore::WalkState::*; use language::{Language, LanguageType}; use language::LanguageType::*; pub use language::get_filetype_from_shebang; macro_rules...
pub fn get_extension<P: AsRef<Path>>(path: P) -> Option<String> { let path = path.as_ref(); match path.extension() { Some(extension_os) => { Some(extension_os.to_string_lossy().to_lowercase()) } None => { match get_filetype_from_shebang(path) { ...
pub fn get_all_files(paths: Vec<&str>, ignored_directories: Vec<&str>, languages: &mut BTreeMap<LanguageType, Language>) { let (tx, rx) = mpsc::channel(); let mut paths = paths.iter(); let mut walker = WalkBuilder::new(paths.next().unwrap()); for path in path...
function_block-full_function
[ { "content": "/// This is for getting the file type from the first line of a file\n\npub fn get_filetype_from_shebang<P: AsRef<Path>>(file: P) -> Option<&'static str> {\n\n let file = match File::open(file) {\n\n Ok(file) => file,\n\n _ => return None,\n\n };\n\n let mut buf = BufReader::...
Rust
src/artos/server/client/leader.rs
apmedvedev/artos-rust
c307644812211bb9ab9a2798e1030f68a6b89e53
use crate::artos::common::{Error, ErrorKind}; use crate::artos::common::{FlowController, FlowType}; use crate::artos::message::server::{LogEntry, LogValueType, NULL_UUID}; use crate::artos::server::channel::{Context, ServerRole, ServerState}; use crate::artos::server::replication::{NullReplicationProtocol, ReplicationP...
use crate::artos::common::{Error, ErrorKind}; use crate::artos::common::{FlowController, FlowType}; use crate::artos::message::server::{LogEntry, LogValueType, NULL_UUID}; use crate::artos::server::channel::{Context, ServerRole, ServerState}; use crate::artos::server::replication::{NullReplicationProtocol, ReplicationP...
: LogEntry, user_data: usize, } impl LeaderClientProtocolImpl { pub fn new( context: Rc<Context>, handler: Rc<dyn CompletionHandler<usize, Error>>, flow_controller: Rc<dyn FlowController>, ) -> LeaderClientProtocolImpl { let commit_period = context.server_channel_factory_con...
ted!() } fn on_follower(&self) { unimplemented!() } } pub struct NullLeaderClientProtocol {} impl NullLeaderClientProtocol { pub fn new() -> Rc<dyn LeaderClientProtocol> { Rc::new(NullLeaderClientProtocol {}) } } impl LeaderClientProtocol for NullLeaderClientProtocol {} pub stru...
random
[ { "content": "#[cfg_attr(test, mockall::automock)]\n\npub trait ReplicationProtocol {\n\n fn start(&self, _server_state: &mut ServerState) {\n\n unimplemented!()\n\n }\n\n\n\n fn stop(&self) {\n\n unimplemented!()\n\n }\n\n\n\n fn on_timer(&self, _current_time: Instant, _server_stat...
Rust
puzzles/single_player/medium/marslander2/src/game.rs
ronlobo/rust_codingame
b914f2cdde229238c936dcc447689b61a2b72892
use std::{io, mem}; use std::sync::{Arc, Mutex, Once}; use marslander::cartesian::{Line, LineValue, Point2, Vector2}; use marslander::lander::LanderState; use marslander::physics::{Particle, Speed}; use crate::env::is_prod; macro_rules! parse_input { ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) } typ...
use std::{io, mem}; use std::sync::{Arc, Mutex, Once}; use marslander::cartesian::{Line, LineValue, Point2, Vector2}; use marslander::lander::LanderState; use marslander::physics::{Particle, Speed}; use crate::env::is_prod; macro_rules! parse_input { ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) } typ...
#[derive(Clone, Debug)] pub struct GameState { pub ground: Line, pub init_lander_state: LanderState, } impl GameState { const fn new( ground: Line, init_lander_state: LanderState, ) -> Self { Self { ground, init_lander_state } } pub fn build() -> Self { let mu...
ton() -> &'static GameStateSingleton { static mut SINGLETON: *const GameStateSingleton = 0 as *const GameStateSingleton; static ONCE: Once = Once::new(); unsafe { ONCE.call_once(|| { let singleton = GameStateSingleton { inner: Arc::new(Mutex::new(GameSt...
function_block-function_prefixed
[ { "content": "pub fn is_prod() -> bool {\n\n match ENV {\n\n EnvOption::PROD => true,\n\n EnvOption::DEV => false\n\n }\n\n}", "file_path": "puzzles/single_player/medium/marslander2/src/env.rs", "rank": 2, "score": 66526.07186263465 }, { "content": "fn calculate_lander_fi...
Rust
slimchain-tx-engine-tee/src/ocall.rs
hkbudb/slimchain
acd527b1cc00d5b87170de5cecfcbf6db0dfa12f
use slimchain_common::{ basic::{Address, Code, Nonce, StateKey, StateValue, H160, H256}, error::Result, }; use slimchain_tx_engine::TxTaskId; use std::{cmp::min, ptr::copy_nonoverlapping, slice}; #[inline] unsafe fn get_address_from_raw(acc_address: *const u8) -> Address { let buf = slice::from_raw_parts(a...
use slimchain_common::{ basic::{Address, Code, Nonce, StateKey, StateValue, H160, H256}, error::Result, }; use slimchain_tx_engine::TxTaskId; use std::{cmp::min, ptr::copy_nonoverlapping, slice}; #[inline] unsafe fn get_address_from_raw(acc_address: *const u8) -> Address { let buf = slice::from_raw_parts(a...
; copy_nonoverlapping(v.as_bytes().as_ptr(), value, 32); 0 } #[inline] fn get_value(id: TxTaskId, acc_address: Address, key: StateKey) -> Result<StateValue> { let mut task_state = crate::engine::TaskState::get_task_state(id)?; task_state.get_read_ctx_mut().get_value(acc_address, key) } #[no_mangle] pu...
) } #[no_mangle] pub unsafe extern "C" fn ocall_get_code_len( id: u32, acc_address: *const u8, code_len: *mut usize, ) -> i32 { let acc_address = get_address_from_raw(acc_address); *code_len = try_run!(get_code_len(id.into(), acc_address)); 0 } #[inline] fn get_code_len(id: TxTaskId, acc_addre...
random
[ { "content": "pub fn account_data_to_digest(nonce_hash: H256, code_hash: H256, acc_state_root: H256) -> H256 {\n\n if nonce_hash.is_zero() && code_hash.is_zero() && acc_state_root.is_zero() {\n\n H256::zero()\n\n } else {\n\n let mut hash_state = default_blake2().to_state();\n\n hash_...
Rust
src/tests.rs
1crcbl/tlsh-rs
585c2c1867ce6b2cefdd638a0a6c9afed971c8d0
#![allow(unused_imports, dead_code)] use crate::{ tlsh::{BucketKind, ChecksumKind, TlshBuilder}, Tlsh, Version, }; fn exe_test_str( s: &str, len: u32, expected: &str, bucket: BucketKind, checksum: ChecksumKind, test_name: &str, ) -> Tlsh { let mut full_str = String::with_capacity(le...
#![allow(unused_imports, dead_code)] use crate::{ tlsh::{BucketKind, ChecksumKind, TlshBuilder}, Tlsh, Version, }; fn exe_test_str( s: &str, len: u32, expected: &str, bucket: BucketKind, checksum: ChecksumKind, test_name: &str, ) -> Tlsh { let mut full_str = String::with_capacity(le...
; let tlsh2 = exe_test_str( "This is a test for Jon Oliver. This is a string. Hello Hello Hello ", 1024, "T130AEF1112A600114F35ACA028219F14673306B1EC481BFDF8D070C865AC638A0D910D029EE1A8C869A5A4F0F9380A9AEA2F2BA2B8F8208AEA34272885F0FB2D34E6912484C", BucketKind::Bucket256, Che...
exe_test_str( "This is a test for Lili Diao. This is a string. Hello Hello Hello ", 512, "T1096463F055A00114F31B8A069219E18273306B0EC081BBDF9D070C865DC638A0D910D029AE198CC69A5A4F0F9380A9EE93F2BA2BCF4208AEA74276DC5F0BB2D34E68114848", BucketKind::Bucket256, ChecksumKind::ThreeByte,...
call_expression
[ { "content": "fn hash_len(bucket: BucketKind, checksum: ChecksumKind, ver: Version) -> usize {\n\n (bucket.bucket_count() >> 1) + (checksum.checksum_len() << 1) + ver.ver().len() + 4\n\n}\n", "file_path": "src/tlsh.rs", "rank": 1, "score": 113824.28287527755 }, { "content": "/// In this e...
Rust
crates/kubelet/src/mio_uds_windows/listener.rs
brooksmtownsend/krustlet
02cf569e796ad8137814ffb6bdc4a92ba591cdfb
use std::fmt; use std::io; use std::path::Path; use mio::{Evented, Poll, PollOpt, Ready, Token}; use super::net::{self, SocketAddr}; use super::poll::SelectorId; use super::stream::UnixStream; use super::sys; pub struct UnixListener { sys: sys::UnixListener, selector_id: SelectorId, } impl UnixListener { ...
use std::fmt; use std::io; use std::path::Path; use mio::{Evented, Poll, PollOpt, Ready, Token}; use super::net::{self, SocketAddr}; use super::poll::SelectorId; use super::stream::UnixStream; use super::sys; pub struct UnixListener { sys: sys::UnixListener, selector_id: SelectorId, } impl UnixListener { ...
} pub fn accept_std(&self) -> io::Result<Option<(net::UnixStream, SocketAddr)>> { match self.sys.accept() { Ok((socket, addr)) => Ok(Some((socket, addr))), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Ok(None), Err(e) => ...
match self.accept_std()? { Some((stream, addr)) => Ok(Some((UnixStream::from_stream(stream)?, addr))), None => Ok(None), }
if_condition
[ { "content": "fn wait_for(poll: &mut Poll, events: &mut Events, token: Token) {\n\n loop {\n\n poll.poll(events, Some(Duration::from_millis(MS))).unwrap();\n\n\n\n let cnt = (0..events.len())\n\n .map(|i| events.get(i).unwrap())\n\n .filter(|e| e.token() == token)\n\n ...
Rust
implementations/rust/ockam/ockam_macros/src/node_test_attribute/hygiene.rs
iakev/ockam
24f4b29c5af609e7d173838ee115456325666188
use quote::quote; use syn::{ punctuated::Punctuated, Error, FnArg, ItemFn, Pat, PatIdent, Path, ReturnType, Token, Type, TypePath, }; pub(crate) fn node_test(input: ItemFn) -> Result<(ItemFn, NodeReturn, NodeCtx), Error> { let ret = NodeReturn::new(&input)?; ret.node_test_checks(&input)?; let ctx ...
use quote::quote; use syn::{ punctuated::Punctuated, Error, FnArg, ItemFn, Pat, PatIdent, Path, ReturnType, Token, Type, TypePath, }; pub(crate) fn node_test(input: ItemFn) -> Result<(ItemFn, NodeReturn, NodeCtx), Error> { let ret = NodeReturn::new(&input)?; ret.node_test_checks(&input)?; let ctx ...
} fn node_test_checks(&self, input: &ItemFn) -> Result<(), Error> { self.arg_is_ctx()?; self.ctx_is_mut_ref(input)?; Ok(()) } fn arg_is_ctx(&self) -> Result<(), Error> { let parse_path = |path: &Path| match path.segments.last() { None => {...
Ok(Self { pat: ident.clone(), ty: ty.clone(), mutability, and_token, })
call_expression
[ { "content": "fn has_generic(ty: &Type, generics_list: &[&Ident]) -> bool {\n\n if let Some(inner) = get_inner(ty) {\n\n return has_generic(inner, generics_list);\n\n }\n\n if let Type::Path(tp) = ty {\n\n if generics_list.contains(&&tp.path.segments[0].ident) {\n\n return true...
Rust
samplecode/unit-test/enclave/src/test_signal.rs
haerdib/incubator-teaclave-sgx-sdk
08264d6bff679d6047e5e9bc36058b4475c58ed4
use sgx_libc::ocall::getpid; use sgx_libc::{c_int, pid_t, siginfo_t, SIGILL, SIGINT, SIGTERM, SIGUSR1, SIGUSR2}; use sgx_signal::signal::{ raise_signal, register, register_sigaction, unregister, unregister_signal, }; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::thread; use std::time:...
use sgx_libc::ocall::getpid; use sgx_libc::{c_int, pid_t, siginfo_t, SIGILL, SIGINT, SIGTERM, SIGUSR1, SIGUSR2}; use sgx_signal::signal::{ raise_signal, register, register_sigaction, unregister, unregister_signal, }; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::thread; use std::time:...
} panic!("Timed out waiting for the signal"); } pub fn test_signal_with_pid() { let status = Arc::new(AtomicUsize::new(0)); let action = { let status = Arc::clone(&status); move |siginfo: &siginfo_t| { #[repr(C)] ...
match current { 0 => continue, _ if current == 1 => return, _ => panic!("Wrong result value {}", current), }
if_condition
[ { "content": "#[must_use]\n\npub fn current() -> SgxThread {\n\n thread_info::current_thread().expect(\n\n \"Use of thread::current() need TCS policy is bound\",\n\n )\n\n}\n\n\n\n/// Cooperatively gives up a timeslice to the OS scheduler.\n\n///\n\n/// This calls the underlying OS scheduler's yiel...
Rust
components/sup/tests/util/docker.rs
discord-tech/habitat
0f58a74cd6f0000efe60fae997ea8050b510ea47
use util::command; use time; use regex::Regex; use std::thread; use std::env; use std::time::Duration; #[derive(Debug)] pub struct Docker { pub container_id: String, } fn docker_cmd(args: &[&str]) -> Docker { println!( "{}: Starting docker with {:?}", thread::current().name().unwrap_or("main...
use util::command; use time; use regex::Regex; use std::thread; use std::env; use std::time::Duration; #[derive(Debug)] pub struct Docker { pub container_id: String, } fn docker_cmd(args: &[&str]) -> Docker { println!( "{}: Starting docker with {:?}", thread::current().name().unwrap_or("main...
ch={}", watch), ], ) } pub fn run_with_etcd_topology(image: &str, topology: &str) -> Docker { docker_cmd( &[ "run", "-d", "--link=bldr_etcd_1:etcd", "-e=BLDR_CONFIG_ETCD=http://etcd:4001", image, "start", "test/...
peer_topology(image: &str, peer: &str, topology: &str) -> Docker { docker_cmd( &[ "run", "-d", "--cap-add=NET_ADMIN", image, "start", image, &format!("--topology={}", topology), &format!("--peer={}", peer), ...
random
[ { "content": "pub fn run(cmd: &str, args: &[&str]) -> CmdResult<Cmd> {\n\n let command = command(cmd, args);\n\n spawn(command)\n\n}\n\n\n", "file_path": "components/builder-depot/tests/support/command.rs", "rank": 5, "score": 458322.9008231298 }, { "content": "pub fn run_with_env(cmd:...
Rust
piet-pathfinder/examples/standalone.rs
yamadapc/piet
440f56e20c9b95119cf77924e626315067a16f19
use glutin::dpi::PhysicalSize; use glutin::event::{Event, KeyboardInput, VirtualKeyCode, WindowEvent}; use glutin::event_loop::{ControlFlow, EventLoop}; use glutin::window::WindowBuilder; use glutin::{ContextBuilder, GlProfile, GlRequest}; use image::GenericImageView; use pathfinder_canvas::{Canvas, CanvasFontContext...
use glutin::dpi::PhysicalSize; use glutin::event::{Event, KeyboardInput, VirtualKeyCode, WindowEvent}; use glutin::event_loop::{ControlFlow, EventLoop}; use glutin::window::WindowBuilder; use glutin::{ContextBuilder, GlProfile, GlRequest}; use image::GenericImageView; use pathfinder_canvas::{Canvas, CanvasFontContext...
fn draw_a_picture(canvas: &mut impl piet::RenderContext) { use image::io::Reader as ImageReader; let img = ImageReader::open("./piet-pathfinder/test.png") .unwrap() .decode() .unwrap(); let img = canvas .make_image( img.width() as usize, img.height()...
canvas.fill( piet::kurbo::Rect::from_origin_size((130., 190.), (40., 60.)), &brush, ); let mut path = piet::kurbo::BezPath::new(); path.move_to((50., 140.)); path.line_to((150., 60.)); path.line_to((250., 140.)); path.close_path(); canvas.stroke(path, &brush, 10.0)...
function_block-function_prefix_line
[ { "content": "fn path2d_from_shape(shape: impl Shape) -> pathfinder_canvas::Path2D {\n\n let mut path = pathfinder_canvas::Path2D::new();\n\n if let Some(Line { p0, p1 }) = shape.as_line() {\n\n path.move_to(vec2f_from_point(p0));\n\n path.line_to(vec2f_from_point(p1));\n\n } else if let ...
Rust
crates/c-api/src/instance.rs
cheme/wasmtime
8b5f28eff496b1085e1d86cb17bed7a8a9003c46
use crate::{wasm_extern_t, wasm_extern_vec_t, wasm_module_t, wasm_trap_t}; use crate::{wasm_store_t, wasmtime_error_t, ExternHost}; use anyhow::Result; use std::cell::RefCell; use std::ptr; use wasmtime::{Extern, HostRef, Instance, Store, Trap}; #[repr(C)] #[derive(Clone)] pub struct wasm_instance_t { pub(crate) i...
use crate::{wasm_extern_t, wasm_extern_vec_t, wasm_module_t, wasm_trap_t}; use crate::{wasm_store_t, wasmtime_error_t, ExternHost}; use anyhow::Result; use std::cell::RefCell; use std::ptr; use wasmtime::{Extern, HostRef, Instance, Store, Trap}; #[repr(C)] #[derive(Clone)] pub struct wasm_instance_t { pub(crate) i...
#[no_mangle] pub extern "C" fn wasm_instance_exports(instance: &wasm_instance_t, out: &mut wasm_extern_vec_t) { let mut cache = instance.exports_cache.borrow_mut(); let exports = cache.get_or_insert_with(|| { let instance = &instance.instance.borrow(); instance .exports() ...
pub fn handle_instantiate( instance: Result<Instance>, instance_ptr: &mut *mut wasm_instance_t, trap_ptr: &mut *mut wasm_trap_t, ) -> Option<Box<wasmtime_error_t>> { fn write<T>(ptr: &mut *mut T, val: T) { *ptr = Box::into_raw(Box::new(val)) } match instance { Ok(instance) => { ...
function_block-full_function
[ { "content": "/// Construct a dummy global for the given global type.\n\npub fn dummy_global(store: &Store, ty: GlobalType) -> Result<Global, Trap> {\n\n let val = dummy_value(ty.content())?;\n\n Ok(Global::new(store, ty, val).unwrap())\n\n}\n\n\n", "file_path": "crates/fuzzing/src/oracles/dummy.rs", ...
Rust
fuzzer/src/lib.rs
rezer0dai/bananafzz
739713366ebd418d884e04f6b0ef1897c239dc49
#![feature(backtrace)] #[macro_use] extern crate lazy_static; use std::backtrace::Backtrace; extern crate core; use core::banana::bananaq::{self,FuzzyQ}; use core::banana::queue; use std::{ sync::{Arc, Weak, RwLock}, }; use std::{ thread, time }; extern crate plugs; use plugs::Observer; use core::con...
#![feature(backtrace)] #[macro_use] extern crate lazy_static; use std::backtrace::Backtrace; extern crate core; use core::banana::bananaq::{self,FuzzyQ}; use core::banana::queue; use std::{ sync::{Arc, Weak, RwLock}, }; use std::{ thread, time }; extern crate plugs; use plugs::Observer; use core::con...
} } /* if !do_gen && reproed && 1 == KNOWLEDGE_MAP[0] { let poc_vec = std::slice::from_raw_parts(data, size).to_vec(); println!("GOT NEW STUFF! {size}"); static mut CORPUS_N: usize = 0; CORPUS_N += 1; generic::write_file_raw( format!("corpus/bfl_{:?}", CORPUS_N).as_s...
objects on bananaq#? {msg}"); } } } fn push_fuzz( banana: &Arc<FuzzyQ> ) -> Result< std::thread::JoinHandle< Result<(), String> >, &'static str > { FuzzyState::fuzz( Box::new( MarioState::spawn( Arc::downgrade(&Arc::clone(banana))))) } fn load_plugins(bana...
random
[ { "content": "#[no_mangle]\n\npub fn push_state(bananaq: &Weak<FuzzyQ>, id: StateTableId, fd: &Fd) {\n\n type TFuzzyObj = Box<dyn IFuzzyObj>;\n\n if let Some(mut fuzzy_obj) = match StateIds::from(id.clone()) {\n\n StateIds::FdCoins => Some::<TFuzzyObj>(Box::new(\n\n CoinsState::alert(ban...
Rust
src/manifest.rs
mike7b4/glrepo
1342cdf030d141bfaf5141177d29437092d51f8e
use crate::error::Error; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::{fmt, fs}; #[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct GlProject { #[serde(skip)] pub name: String, pub fetch_url: String, #[serde(default = "Path...
use crate::error::Error; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::{fmt, fs}; #[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct GlProject { #[serde(skip)] pub name: String, pub fetch_url: String, #[serde(default = "Path...
} } Ok(self) } pub fn insert(&mut self, name: &str, project: GlProject) { self.projects.insert(name.into(), project); } pub fn save_to_yaml<P: AsRef<Path>>(&self, manifest: &P) -> Result<(), Error> { fs::write(manifest, se...
if project.reference.is_empty() { return Err(Error::General(format!("Project: {} are missing reference and the manifest file does not have the field: default_reference!", name))); }
if_condition
[ { "content": "///\n\n/// Read YAML Manifest from and return GlProjects structure on success.\n\n/// # Arguments\n\n///\n\n/// - `manifest_file` Path to manifest file.\n\n///\n\n/// # Error\n\n///\n\n/// Error::Manifest.\n\nfn load_manifest<P: AsRef<Path>>(p: P) -> Result<GlProjects> {\n\n log::info!(\"Read m...
Rust
src/lib.rs
harryrose/rust-vst-brake
55ce73737e6b557255bd85a5abafb0b9c6b46288
#[macro_use] extern crate vst; use std::sync::Arc; use vst::buffer::AudioBuffer; use vst::plugin::{Category, Info, Plugin, PluginParameters}; use vst::util::AtomicFloat; const NO_CHANNELS: i32 = 2; const BUF_LEN_SECS: usize = 10; type SampleType = f32; struct Braker { buf: Box<[(SampleType, SampleType)]>, p...
#[macro_use] extern crate vst; use std::sync::Arc; use vst::buffer::AudioBuffer; use vst::plugin::{Category, Info, Plugin, PluginParameters}; use vst::util::AtomicFloat; const NO_CHANNELS: i32 = 2; const BUF_LEN_SECS: usize = 10; type SampleType = f32; struct Braker { buf: Box<[(SampleType, SampleType)]>, p...
fn set_sample_rate(&mut self, rate: f32) { let buf = vec![(0 as SampleType, 0 as SampleType); rate as usize * BUF_LEN_SECS]; self.buf = buf.into_boxed_slice(); self.rec_head = 0; self.play_head = 0.0; } fn get_parameter_object(&mut self) -> Arc<dyn PluginParameters> { ...
s: NO_CHANNELS, outputs: NO_CHANNELS, parameters: 2, ..Default::default() } }
function_block-function_prefixed
[ { "content": "# Braker\n\n\n\nA simple VST audio effect plugin written in rust, which acts as a brake on a track.\n\n\n\nIt stores a 10 second buffer of audio from when the brake is applied, and slows the track\n\nto a stop.\n\n\n\nIt provides two parameters:\n\n\n\n - `brake` : `0 - 1.0` -- if > 0.5, the brake...
Rust
core/tests/loadtest/src/scenarios/fee_ticker.rs
euevew/zksync
0d8c7959fc2fbba3334dfda44bc9561237731e99
use std::fmt; use async_trait::async_trait; use num::BigUint; use serde::{Deserialize, Serialize}; use zksync::provider::Provider; use zksync::utils::closest_packable_token_amount; use zksync_types::{TokenLike, TxFeeTypes}; use zksync_utils::format_ether; use super::{batch_transfers::batch_sizes_iter, Fees, Scenari...
use std::fmt; use async_trait::async_trait; use num::BigUint; use serde::{Deserialize, Serialize}; use zksync::provider::Provider; use zksync::utils::closest_packable_token_amount; use zksync_types::{TokenLike, TxFeeTypes}; use zksync_utils::format_ether; use super::{batch_transfers::batch_sizes_iter, Fees, Scenari...
}
CHUNK_SIZES, sign_transfers_task, ) .await?; monitor.send_txs_batch(txs_signed).await?; Ok(()) as anyhow::Result<()> } }) .collect::<Vec<_>>(); wait_all_failsafe("run/f...
function_block-function_prefix_line
[ { "content": "/// Returns infinite iterator over the following batch sizes:\n\n/// `[2, max_batch_size / 2, max_batch_size]`\n\npub fn batch_sizes_iter(max_batch_size: usize) -> impl Iterator<Item = usize> {\n\n std::iter::repeat_with(move || match thread_rng().gen_range(0, 3) {\n\n 0 => 2,\n\n ...
Rust
src/sys/ioctl/linux.rs
Gelbpunkt/nix
1495b5cda9d26233928551fbf12956ce33ca9e09
#[cfg(any(target_os = "android", target_env = "musl"))] #[doc(hidden)] pub type ioctl_num_type = ::libc::c_int; #[cfg(not(any(target_os = "android", target_env = "musl")))] #[doc(hidden)] pub type ioctl_num_type = ::libc::c_ulong; #[doc(hidden)] pub type ioctl_param_type = ::libc::c_ulong; #[doc(hidden)] pub const N...
#[cfg(any(target_os = "android", target_env = "musl"))] #[doc(hidden)] pub type io
den)] pub const NONE: u8 = 1; #[doc(hidden)] pub const READ: u8 = 2; #[doc(hidden)] pub const WRITE: u8 = 4; #[doc(hidden)] pub const SIZEBITS: u8 = 13; #[doc(hidden)] pub const DIRBITS: u8 = 3; } #[cfg(any( target_arch = "x86", target_arch = "arm", target_arch = "s390x"...
ctl_num_type = ::libc::c_int; #[cfg(not(any(target_os = "android", target_env = "musl")))] #[doc(hidden)] pub type ioctl_num_type = ::libc::c_ulong; #[doc(hidden)] pub type ioctl_param_type = ::libc::c_ulong; #[doc(hidden)] pub const NRBITS: ioctl_num_type = 8; #[doc(hidden)] pub const TYPEBITS: ioctl_num_type = 8; ...
random
[ { "content": "#[cfg(any(target_os = \"netbsd\", target_os = \"openbsd\"))]\n\ntype type_of_data = i64;\n\n\n", "file_path": "src/sys/event.rs", "rank": 0, "score": 90336.46424927533 }, { "content": "#[cfg(any(target_os = \"netbsd\"))]\n\ntype type_of_udata = intptr_t;\n", "file_path": "s...
Rust
src/lib/types/mod.rs
waldyrious/crush
e767d718a79e5021427f275b05956135107bd1c7
use crate::lang::scope::Scope; use crate::lang::errors::{CrushResult, argument_error}; use crate::lang::{value::Value, r#struct::Struct}; use crate::lang::command::CrushCommand; use crate::lang::execution_context::{ExecutionContext, This}; use crate::lang::argument::{column_names, Argument}; use crate::lang::execution_...
use crate::lang::scope::Scope; use crate::lang::errors::{CrushResult, argument_error}; use crate::lang::{value::Value, r#struct::Struct}; use crate::lang::command::CrushCommand; use crate::lang::execution_context::{ExecutionContext, This}; use crate::lang::argument::{column_names, Argument}; use crate::lang::execution_...
)))?; env.declare("materialize", Value::Command(CrushCommand::command( materialize, true, "materialize", "Recursively convert all streams in input to materialized version", example!("ls | materialize"))))?; env.declare("file", Value::Type(ValueType::File))?; env.declare("typ...
Some(r#" Example: Point := (class) Point:__init__ = { |x:float y:float| this:x = x this:y = y } Point:len = { || math.sqrt this:x*this:x + this:y*this:y } Point:__add__ = { |other| Point:new x=(this:x + other:x) y=(this:y + other:y) ...
call_expression
[ { "content": "fn new(mut context: ExecutionContext) -> CrushResult<()> {\n\n let v: Vec<Value> = context.arguments.drain(..)\n\n .map(|a| a.value)\n\n .collect::<Vec<Value>>();\n\n if v.len() % 2 == 0 {\n\n let vec = v.chunks(2)\n\n .map(|chunks| match (&chunks[0], &chunks[...
Rust
src/lib.rs
curtisalexander/stay-awake-rs
dfbcdc2b733768798500f42acdd6219a3719e628
use colored::Colorize; use std::error::Error; use std::ffi::c_void; use std::fmt; use std::io::{self, Write}; use std::mem::transmute; use structopt::clap::arg_enum; use structopt::StructOpt; #[macro_use] extern crate bitflags; #[derive(StructOpt, Debug)] #[structopt(about = "keep a Windows machine awake")] pub struc...
use colored::Colorize; use std::error::Error; use std::ffi::c_void; use std::fmt; use std::io::{self, Write}; use std::mem::transmute; use structopt::clap::arg_enum; use structopt::StructOpt; #[macro_use] extern crate bitflags; #[derive(StructOpt, Debug)] #[structopt(about = "keep a Windows machine awake")] pub struc...
n {} ==> {}", String::from("From").purple(), prev_thread_exec_state, String::from("To").cyan(), next_thread_exec_state ); print!("\nPress ``{}`` key to reset ", String::from("Enter").yellow()); io::stdout().flush().unwrap(); let mut buffer = String::new(); let ...
function_block-function_prefixed
[ { "content": "fn main() {\n\n let args: Args = Args::from_args();\n\n if let Err(e) = stay_awake::run(args) {\n\n println!(\"Stopping with error: {}\", e);\n\n process::exit(1);\n\n }\n\n process::exit(0);\n\n}", "file_path": "src/main.rs", "rank": 5, "score": 21766.2871163...
Rust
src/exports.rs
Tri-stone/cosmwasm
4c3f22abdc4ec6e957abe15ac58e2eefc2751fe8
#![cfg(target_arch = "wasm32")] use std::fmt::Display; use std::os::raw::c_void; use std::vec::Vec; use schemars::JsonSchema; use serde::de::DeserializeOwned; use snafu::ResultExt; use crate::errors::{Error, ParseErr, SerializeErr}; use crate::imports::{dependencies, ExternalApi, ExternalStorage}; use crate::memory:...
#![cfg(target_arch = "wasm32")] use std::fmt::Display; use std::os::raw::c_void; use std::vec::Vec; use schemars::JsonSchema; use serde::de::DeserializeOwned; use snafu::ResultExt; use crate::errors::{Error, ParseErr, SerializeErr}; use crate::imports::{dependencies, ExternalApi, ExternalStorage}; use crate::memory:...
} pub fn do_query<T: DeserializeOwned + JsonSchema>( query_fn: &dyn Fn(&Extern<ExternalStorage, ExternalApi>, T) -> Result<Vec<u8>, Error>, msg_ptr: *mut c_void, ) -> *mut c_void { match _do_query(query_fn, msg_ptr) { Ok(res) => res, Err(err) => make_query_error_c_string(err), } } fn ...
match _do_handle(handle_fn, params_ptr, msg_ptr) { Ok(res) => res, Err(err) => make_error_c_string(err), }
if_condition
[ { "content": "/// alloc is the same as external allocate, but designed to be called internally\n\npub fn alloc(size: usize) -> *mut c_void {\n\n // allocate the space in memory\n\n let buffer = vec![0u8; size];\n\n release_buffer(buffer)\n\n}\n\n\n", "file_path": "src/memory.rs", "rank": 0, ...
Rust
src/bin/dtnrecv.rs
lehmanju/dtn7-rs
dea23482c55fbd6658e886f0c38599ff6b41a40a
use bp7::*; use clap::{crate_authors, crate_version, App, Arg}; use std::convert::TryFrom; use std::fs; use std::io::prelude::*; use std::process; fn write_bytes(data: &[u8], possible_file: Option<&str>, verbose: bool) { if let Some(outfile) = possible_file { if verbose { println!("Writing to {...
use bp7::*; use clap::{crate_authors, crate_version, App, Arg}; use std::convert::TryFrom; use std::fs; use std::io::prelude::*; use std::process; fn write_bytes(data: &[u8], possible_file: Option<&str>, verbose: bool) { if let Some(outfile) = possible_file { if verbose { println!("Writing to {...
wnload any bundle by ID") .required(false) .takes_value(true), ) .arg( Arg::with_name("outfile") .short("o") .long("output") .value_name("FILE") .help("Write bundle payload to file instead of stdo...
.long("endpoint") .value_name("ENDPOINT") .help("Specify local endpoint, e.g. '/incoming', or a group endpoint 'dtn://helpers/~incoming'") .required_unless("bundleid") .takes_value(true), ) .arg( Arg::with_name("bundle...
random
[ { "content": "fn is_administrative_record_valid(bundle: &Bundle) -> bool {\n\n if !bundle.is_administrative_record() {\n\n warn!(\n\n \"Bundle does not contain an administrative record: {}\",\n\n bundle.id()\n\n );\n\n return false;\n\n }\n\n\n\n let payload =...
Rust
example-databases/rust/log-segments/src/main.rs
Klaven/null-db-1
029fa4685ce721efab090fea3dac3add81514f06
use actix_web::{ get, post, delete, web::{self, Data}, App, Responder, HttpResponse, HttpServer }; #[macro_use] extern crate lazy_static; mod file_reader; use file_reader::EasyReader; use std::fs::OpenOptions; use std::io::prelude::*; use std::collections::HashSet; use std::sync::...
use actix_web::{ get, post, delete, web::{self, Data}, App, Responder, HttpResponse, HttpServer }; #[macro_use] extern crate lazy_static; mod file_reader; use file_reader::EasyReader; use std::fs::OpenOptions; use std::io::prelude::*; use std::collections::HashSet; use std::sync::...
#[post("/{key}")] pub async fn put_value_for_key( file_mutex: Data<RwLock<bool>>, web::Path(key): web::Path<String>, req_body: String ) -> impl Responder { let _write_lock = file_mutex.write(); let mut line_count = 0; { let file = File::open("null.database").unwrap(); ...
File::open("null.database").unwrap(); let mut reader = EasyReader::new(file).unwrap(); reader.build_index(); reader.eof(); while let Some(line) = reader.prev_line().unwrap() { let split = line.split(":").collect::<Vec<&str>>(); if split.len() == 2 { if split[0] == key { ...
function_block-function_prefixed
[ { "content": "pub fn start_compaction(rx: Receiver<i32>) {\n\n\n\n thread::spawn(move || loop {\n\n match rx.try_recv() {\n\n Err(TryRecvError::Empty) => println!(\"compact!\"),\n\n _ => {\n\n println!(\"call to quite compaction\");\n\n break;\n\n ...
Rust
src/lib.rs
deciduously/wasm-dot
5e086a279a56b499fecfbff64d902c9490514018
use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{Document, Element, HtmlElement}; type Result<T> = std::result::Result<T, JsValue>; const STARTING_SIZE: u32 = 50; macro_rules! append_attrs { ($document:ident, $el:ident, $( $attr:expr ),* ) => { $( let attr = $document.cre...
use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{Document, Element, HtmlElement}; type Result<T> = std::result::Result<T, JsValue>; const STARTING_SIZE: u32 = 50; macro_rules! append_attrs { ($document:ident, $el:ident, $( $attr:expr ),* ) => { $( let attr = $document.cre...
pub fn run() -> Result<()> { let document = get_document()?; let body = document.body().unwrap(); mount_app(&document, &body)?; attach_listener(&document)?; Ok(()) }
function_block-full_function
[ { "content": "I've also added our new return type, and as a result we now return a simple `Ok(())` at the end to signify success. This macro expansion contains `?` operators, which will now work as expected!\n\n\n\nNote the trailing comma after `\"DOT\"` is mandatory - that's the \"zero or more\" attributes th...
Rust
src/pgsql/tshark_pgsql.rs
emmanueltouzery/hotwire
3377c82ae7391233dce8dc344fd25550cc2890c6
use crate::tshark_communication; use quick_xml::events::Event; use std::io::BufRead; use std::str; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum PostgresColType { Bool, ByteArray, Name, Char, Text, Oid, Varchar, Int2, Int4, Int8, Timestamp, Other, ...
use crate::tshark_communication; use quick_xml::events::Event; use std::io::BufRead; use std::str; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum PostgresColType { Bool, ByteArray, Name, Char, Text, Oid, Varchar, Int2, Int4, Int8, Timestamp, Other, ...
fn parse_parse_message<B: BufRead>( xml_reader: &mut quick_xml::Reader<B>, ) -> Result<PostgresWireMessage, String> { let mut statement = None; let mut query = None; let mut param_types = vec![]; let buf = &mut vec![]; xml_event_loop!(xml_reader, buf, Ok(Event::Empty(ref e)) => { ...
Ok(Event::End(ref e)) => { if e.name() == b"proto" { return Ok(PostgresWireMessage::Startup { username, database, application, }); } } ) }
function_block-function_prefix_line
[ { "content": "pub fn parse_headers(other_lines: &str) -> Vec<(String, String)> {\n\n other_lines\n\n .lines()\n\n .filter_map(|l| l.split_once(\": \"))\n\n .map(|(k, v)| (k.to_string(), v.trim_end().to_string()))\n\n .collect()\n\n}\n\n\n", "file_path": "src/http/http_message_...
Rust
src/tagged.rs
nickray/flexiber
825eba57df47a8d084e185eca58912caf231df31
use crate::{Decodable, Decoder, Encodable, Encoder, ErrorKind, header::Header, Length, Result, Slice, Tag, TagLike}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct TaggedValue<V, T=Tag> { tag: T, value: V, } pub type TaggedSlice<'a, T=Tag> = TaggedValue<Slice<'a>, T>; impl<V, T> TaggedValue<V, T> ...
use crate::{Decodable, Decoder, Encodable, Encoder, ErrorKind, header::Header, Length, Result, Slice, Tag, TagLike}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct TaggedValue<V, T=Tag> { tag: T, value: V, } pub type TaggedSlice<'a, T=Tag> = TaggedValue<Slice<'a>, T>; impl<V, T> TaggedValue<V, T> ...
(len).map_err(|_| ErrorKind::Length { tag: tag.embedding() })?; Self::from(tag, value) } } impl<'a, T> Encodable for TaggedSlice<'a, T> where T: Copy + Encodable { fn encoded_length(&self) -> Result<Length> { self.header()?.encoded_length()? + self.length() } fn encode(&self, encod...
t<Length> { self.header()?.encoded_length()? + self.value.encoded_length()? } fn encode(&self, encoder: &mut Encoder<'_>) -> Result<()> { self.header()?.encode(encoder)?; encoder.encode(self.value) } } impl<'a, T> TaggedSlice<'a, T> where T: Copy { pub fn from(tag: T, ...
random
[ { "content": "/// Obtain the length of an ASN.1 `SEQUENCE` of [`Encodable`] values when\n\n/// serialized as ASN.1 DER, including the `SEQUENCE` tag and length prefix.\n\npub fn encoded_length(/*tag: Tag,*/ encodables: &[&dyn Encodable]) -> Result<Length> {\n\n let inner_len = encoded_length_inner(encodables...
Rust
tests/array.rs
MatthieuBizien/rust-numpy
d161036faf4f1d4dd1c5499917722891a77d9f54
extern crate ndarray; extern crate numpy; extern crate pyo3; use ndarray::*; use numpy::*; use pyo3::prelude::*; #[test] fn new_c_order() { let gil = pyo3::Python::acquire_gil(); let dim = [3, 5]; let arr = PyArray::<f64, _>::new(gil.python(), dim, false); assert!(arr.ndim() == 2); assert!(arr.dim...
extern crate ndarray; extern crate numpy; extern crate pyo3; use ndarray::*; use numpy::*; use pyo3::prelude::*; #[test] fn new_c_order() { let gil = pyo3::Python::acquire_gil(); let dim = [3, 5]; let arr = PyArray::<f64, _>::new(gil.python(), dim, false); assert!(arr.ndim() == 2); assert!(arr.dim...
(), &[1, 2, 3]); } #[test] fn from_eval_fail() { let gil = pyo3::Python::acquire_gil(); let np = get_array_module(gil.python()).unwrap(); let dict = PyDict::new(gil.python()); dict.set_item("np", np).unwrap(); let converted: Result<&PyArray1<i32>, _> = gil .python() .eval("np.array(...
e='int32')", Some(&dict), None) .unwrap() .extract() .unwrap(); assert_eq!(pyarray.as_slice().unwrap
function_block-random_span
[ { "content": "fn get_unchecked_impl(indices: &[usize], strides: &[isize], size: isize) -> isize {\n\n indices\n\n .iter()\n\n .zip(strides)\n\n .map(|(&i, stride)| stride * i as isize / size)\n\n .sum()\n\n}\n\n\n\n#[doc(hidden)]\n\npub struct PrivateMarker;\n", "file_path": "...
Rust
src/staticfile/static_service.rs
if1live/serv
1bca7aed5d1cf0bbb9b7cb62916c8e8efb2172f9
use std::fs::{self, File}; use std::io::{ErrorKind as IoErrorKind, Read}; use std::path::PathBuf; use std::{mem, time}; use futures::future::*; use futures::sync::mpsc::SendError; use futures::{Async, Future, Poll, Sink, Stream}; use hyper::header::Headers; use hyper::server::{Request, Response, Service}; use hyper::...
use std::fs::{self, File}; use std::io::{ErrorKind as IoErrorKind, Read}; use std::path::PathBuf; use std::{mem, time}; use futures::future::*; use futures::sync::mpsc::SendError; use futures::{Async, Future, Poll, Sink, Stream}; use hyper::header::Headers; use hyper::server::{Request, Response, Service}; use hyper::...
if requested_path.should_redirect(&metadata, &req) { let mut target = req.path().to_owned(); target.push('/'); if let Some(query) = req.query() { target.push('?'); target.push_str(query); } ...
let metadata = match fs::metadata(&requested_path.path) { Ok(meta) => meta, Err(e) => { return match e.kind() { IoErrorKind::NotFound => self.upstream.call(req), IoErrorKind::PermissionDenied => { Box::new(ok(resp.wi...
assignment_statement
[ { "content": "/// `service` builds `HyperService` with given function `F`.\n\npub fn serv<F, Req, Resp, E>(f: F) -> HyperService\n\nwhere\n\n F: Fn(Req) -> Box<Future<Item = Resp, Error = E>> + 'static,\n\n Req: for<'de> serde::Deserialize<'de> + 'static,\n\n Resp: serde::Serialize + 'static,\n\n E:...
Rust
lnx-server/src/main.rs
onerandomusername/lnx
a113965562b05ea0afb51374b820c421c30890e1
mod auth; mod error; mod helpers; mod responders; mod routes; mod snapshot; mod state; #[macro_use] extern crate tracing; use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::{anyhow, Context, Result}; use bincode::Options; use clap::Parser; use engine::structures::{IndexDec...
mod auth; mod error; mod helpers; mod responders; mod routes; mod snapshot; mod state; #[macro_use] extern crate tracing; use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::{anyhow, Context, Result}; use bincode::Options; use clap::Parser; use engine::structures::{IndexDec...
; if let Some(snapshot) = settings.load_snapshot { if let Err(e) = load_snapshot(Path::new(&snapshot)) { error!("error during snapshot extraction: {}", e); } else { info!( "snapshot successfully extracted, restart the server without \ the `--l...
setup_logger( settings.log_level, &settings.log_directory, !settings.disable_asni_logs, settings.pretty_logs, settings.json_logs, settings.verbose_logs, )
call_expression
[ { "content": "pub fn get_router(state: State) -> Router<Body, LnxError> {\n\n Router::builder()\n\n .data(state)\n\n .middleware(Middleware::pre(auth::check_permissions))\n\n .middleware(Middleware::pre(index::ensure_index_perms))\n\n .post(\"/auth\", auth::create_token)\n\n ...
Rust
src/proxy/http/glue.rs
khappucino/linkerd2-proxy
a7960f936dcf47bcf4aa1e32e65691cf805a8c50
use bytes::IntoBuf; use futures::{future, Async, Future, Poll}; use futures::future::Either; use http; use h2; use hyper::{self, body::Payload}; use hyper::client::connect as hyper_connect; use std::{error::Error as StdError, fmt}; use tower_grpc as grpc; use drain; use proxy::http::{HasH2Reason, h1, upgrade::Http11Up...
use bytes::IntoBuf; use futures::{future, Async, Future, Poll}; use futures::future::Either; use http; use h2; use hyper::{self, body::Payload}; use hyper::client::connect as hyper_connect; use std::{error::Error as StdError, fmt}; use tower_grpc as grpc; use drain; use proxy::http::{HasH2Reason, h1, upgrade::Http11Up...
} impl<C> HyperConnect<C> where C: Connect, C::Future: 'static, { pub(in proxy) fn new(connect: C, absolute_form: bool) -> Self { HyperConnect { connect, absolute_form, } } } impl<C> hyper_connect::Connect for HyperConnect<C> where C: Connect + Send + Sync,...
let halves = Http11Upgrade::new( self.upgrade_drain_signal.clone(), ErasedExecutor::erase(self.upgrade_executor.clone()), ); req.extensions_mut().insert(halves.client); Some(halves.server) } else { h1::strip_connection_headers(req....
function_block-function_prefix_line
[ { "content": "/// Checks requests to determine if they want to perform an HTTP upgrade.\n\npub fn wants_upgrade<B>(req: &http::Request<B>) -> bool {\n\n // HTTP upgrades were added in 1.1, not 1.0.\n\n if req.version() != http::Version::HTTP_11 {\n\n return false;\n\n }\n\n\n\n if let Some(up...
Rust
crates/swc_plugin_runner/src/cache.rs
padorang684/swc
53ff81ccd65509dd6fff0bef5aa21003d3c81409
use std::{ env::current_dir, path::{Path, PathBuf}, }; use anyhow::{Context, Error}; use parking_lot::Mutex; use swc_common::{ collections::AHashMap, sync::{Lazy, OnceCell}, }; use wasmer::{Module, Store}; #[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))] use wasmer_cache::{Cache a...
use std::{ env::current_dir, path::{Path, PathBuf}, }; use anyhow::{Context, Error}; use parking_lot::Mutex; use swc_common::{ collections::AHashMap, sync::{Lazy, OnceCell}, }; use wasmer::{Module, Store}; #[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))] use wasmer_cache::{Cache a...
b fn init_plugin_module_cache_once(filesystem_cache_root: &Option<String>) { PLUGIN_MODULE_CACHE.inner.get_or_init(|| { Mutex::new(CacheInner { fs_cache: create_filesystem_cache(filesystem_cache_root), loaded_module_bytes: Default::default(), }) }); } #[cfg(feature = "me...
Some(PathBuf::from(root)) } else if let Ok(cwd) = current_dir() { Some(cwd.join(".swc")) } else { None }; if let Some(root_path) = &mut root_path { root_path.push("plugins"); root_path.push(MODULE_SERIALIZATION_VERSION); return FileSystemCache::new(&root...
random
[]
Rust
src/encode/primitive.rs
Fabian-Gruenbichler/bcder
56fd7a17057423125cea93d696b5c01b161d1c22
use std::io; use bytes::{BufMut, Bytes, BytesMut}; use crate::length::Length; use crate::mode::Mode; use crate::tag::Tag; use super::values::Values; pub trait PrimitiveContent: Sized { const TAG: Tag; fn encoded_len(&self, mode: Mode) -> usize; fn write_encoded<W: io::Write>( &se...
use std::io; use bytes::{BufMut, Bytes, BytesMut}; use crate::length::Length; use crate::mode::Mode; use crate::tag::Tag; use super::values::Values; pub trait PrimitiveContent: Sized { const TAG: Tag; fn encoded_len(&self, mode: Mode) -> usize; fn write_encoded<W: io::Write>( &se...
::INTEGER; fn encoded_len(&self, _: Mode) -> usize { if *self > 0x7F { 2 } else { 1 } } fn write_encoded<W: io::Write>( &self, _: Mode, target: &mut W ) -> Result<(), io::Error> { if *self > 0x7F { target.write_all(&[0])?; } t...
fn encode_ref_as(&self, tag: Tag) -> Primitive<&Self> { Primitive { tag, prim: self } } } impl<'a, T: PrimitiveContent> PrimitiveContent for &'a T { const TAG: Tag = T::TAG; fn encoded_len(&self, mode: Mode) -> usize { (*self).encoded_len(mode) } fn write_encoded<W: io::Write...
random
[ { "content": "/// Returns the length for a structure based on the tag and content length.\n\n///\n\n/// This is necessary because the length octets have a different length\n\n/// depending on the content length.\n\npub fn total_encoded_len(tag: Tag, content_l: usize) -> usize {\n\n tag.encoded_len() + Length...
Rust
src/nfa_builder.rs
legalforce-research/daachorse
e9e68425b5e584fd4f4192735783142240c4517f
use core::cell::RefCell; use core::num::NonZeroU32; use alloc::vec::Vec; use crate::errors::{DaachorseError, Result}; use crate::{MatchKind, Output}; pub const ROOT_STATE_ID: u32 = 0; pub const DEAD_STATE_ID: u32 = 1; pub trait EdgeLabel: Copy + Ord + core::fmt::Debug { fn num_bytes(&self) -> usize; } impl Ed...
use core::cell::RefCell; use core::num::NonZeroU32; use alloc::vec::Vec; use crate::errors::{DaachorseError, Result}; use crate::{MatchKind, Output}; pub const ROOT_STATE_ID: u32 = 0; pub const DEAD_STATE_ID: u32 = 1; pub trait EdgeLabel: Copy + Ord + core::fmt::Debug { fn num_bytes(&self) -> usize; } impl Ed...
.borrow_mut(); if let Some(output) = s.output { s.output_pos = NonZeroU32::new(self.outputs.len().try_into().unwrap()); let parent = self.states[s.fail as usize].borrow().output_pos; self.outputs .push(Output::new(output.0, output.1.get(), ...
e) fn build_outputs(&mut self, q: &[u32]) { debug_assert_ne!(q[0], ROOT_STATE_ID); self.outputs.push(Output::new(0, 0, None)); for &state_id in q { let s = &mut self.states[state_id as usize]
function_block-random_span
[ { "content": "#[derive(Copy, Clone, PartialEq, Eq, Debug)]\n\nstruct Output {\n\n value: u32,\n\n length: u32,\n\n parent: Option<NonZeroU32>,\n\n}\n\n\n\nimpl Output {\n\n #[inline(always)]\n\n pub const fn new(value: u32, length: u32, parent: Option<NonZeroU32>) -> Self {\n\n Self {\n\n ...
Rust
src/spsc.rs
wasm-rs/shared-channel
1b453358f752e1a2a4ab3991c257815a9b1f72ba
use super::*; use js_sys::{Array, Atomics, Int32Array, SharedArrayBuffer, Uint8Array}; use std::marker::PhantomData; use std::time::Duration; #[cfg(test)] #[allow(unused_imports)] use wasm_rs_dbg::dbg; pub struct SharedChannel<T> where T: Shareable, { _header: SharedArrayBuffer, _data: SharedArrayBuffer,...
use super::*; use js_sys::{Array, Atomics, Int32Array, SharedArrayBuffer, Uint8Array}; use std::marker::PhantomData; use std::time::Duration; #[cfg(test)] #[allow(unused_imports)] use wasm_rs_dbg::dbg; pub struct SharedChannel<T> where T: Shareable, { _header: SharedArrayBuffer, _data: SharedArrayBuffer,...
assert_eq!(receiver.recv(None).unwrap().unwrap(), 2); } }
value.into(); let (sender, receiver) = ch.split(); sender.send(&1).unwrap(); sender.send(&2).unwrap(); assert_eq!(receiver.recv(None).unwrap().unwrap(), 1);
function_block-random_span
[ { "content": "/// Any type that can be sent through a shared channel must implement this\n\npub trait Shareable: Sized {\n\n /// A generic error\n\n type Error: std::error::Error;\n\n /// Converts value into a [`js_sys::Uint8Array`]\n\n fn to_bytes(&self) -> Result<Uint8Array, Self::Error>;\n\n /...
Rust
components/tidb_query/src/rpn_expr/impl_cast.rs
lzmhhh123/tikv
ff82aa9eba331585aec1c6cdf9e1584512bccb34
use std::borrow::Cow; use std::convert::TryFrom; use tidb_query_codegen::rpn_fn; use tidb_query_datatype::*; use tipb::{Expr, FieldType}; use crate::codec::convert::*; use crate::codec::data_type::*; use crate::codec::error::{ERR_DATA_OUT_OF_RANGE, WARN_DATA_TRUNCATED}; use crate::expr::EvalContext; use crate::rpn_...
use std::borrow::Cow; use std::convert::TryFrom; use tidb_query_codegen::rpn_fn; use tidb_query_datatype::*; use tipb::{Expr, FieldType}; use crate::codec::convert::*; use crate::codec::data_type::*; use crate::codec::error::{ERR_DATA_OUT_OF_RANGE, WARN_DATA_TRUNCATED}; use crate::expr::EvalContext; use crate::rpn_...
#[rpn_fn(capture = [extra])] #[inline] pub fn cast_string_as_json( extra: &RpnFnCallExtra<'_>, val: &Option<Bytes>, ) -> Result<Option<Json>> { match val { None => Ok(None), Some(val) => { if extra .ret_field_type .flag() .contain...
pub fn cast_int_as_json_boolean(val: &Option<Int>) -> Result<Option<Json>> { match val { None => Ok(None), Some(val) => Ok(Some(Json::Boolean(*val != 0))), } }
function_block-full_function
[ { "content": "#[rpn_fn]\n\n#[inline]\n\npub fn real_is_true(arg: &Option<Real>) -> Result<Option<i64>> {\n\n Ok(Some(arg.map_or(0, |v| (v.into_inner() != 0f64) as i64)))\n\n}\n\n\n", "file_path": "components/tidb_query/src/rpn_expr/impl_op.rs", "rank": 3, "score": 475901.2103745929 }, { "...
Rust
src/raster/geotiff/ifd.rs
phobson/whitebox-tools
b2875095df985a8fa884dc72298264d9cea365ec
use super::geokeys; use crate::utils::{ByteOrderReader, Endianness}; use std::fmt; use std::io::Cursor; #[derive(Default, Clone, Debug)] pub struct Ifd { pub tag: u16, pub ifd_type: u16, pub num_values: u64, pub offset: u64, pub data: Vec<u8>, byte_order: Endianness, } impl Ifd { pub fn ne...
use super::geokeys; use crate::utils::{ByteOrderReader, Endianness}; use std::fmt; use std::io::Cursor; #[derive(Default, Clone, Debug)] pub struct Ifd { pub tag: u16, pub ifd_type: u16, pub num_values: u64, pub offset: u64, pub data: Vec<u8>, byte_order: Endianness, } impl Ifd { pub fn ne...
} } impl fmt::Display for Ifd { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let tag_map = geokeys::get_keys_map(); let ft_map = geokeys::get_field_type_map(); if tag_map.get(&self.tag).is_some() { let off = if self.num_values > 1 || self.ifd_type > 3 { ...
if self.ifd_type == 17 { let mut vals: Vec<i64> = vec![]; let mut val: i64; for _ in 0..how_many_vals { val = bor.read_i64().unwrap(); vals.push(val); } return format!("{:?}", vals); } else { ret...
if_condition
[ { "content": "/// Returns a string represenation of a classiciation numeric value.\n\npub fn convert_class_val_to_class_string(value: u8) -> String {\n\n match value {\n\n 0 => return String::from(\"Created, never classified\"),\n\n 1 => return String::from(\"Unclassified\"),\n\n 2 => re...
Rust
examples/microbit-rak811/src/main.rs
drogue-iot/drogue-rak811
8869db71102965b0437ff64abd11a31c941ab91f
#![no_main] #![no_std] use panic_halt as _; use core::sync::atomic::{compiler_fence, Ordering}; use embedded_hal::digital::v2::OutputPin; use log::LevelFilter; use rtic::app; use rtt_logger::RTTLogger; use rtt_target::rtt_init_print; use nrf52833_hal as hal; use drogue_rak811 as rak811; use hal::gpio::{Level, Outp...
#![no_main] #![no_std] use panic_halt as _; use core::sync::atomic::{compiler_fence, Ordering}; use embedded_hal::digital::v2::OutputPin; use log::LevelFilter; use rtic::app; use rtt_logger::RTTLogger; use rtt_target::rtt_init_print; use nrf52833_hal as hal; use drogue_rak811 as rak811; use hal::gpio::{Level, Outp...
#[idle(resources=[driver])] fn idle(ctx: idle::Context) -> ! { let idle::Resources { driver } = ctx.resources; log::info!("Configuring driver"); driver .set_band(rak811::LoraRegion::EU868) .map_err(|e| log::error!("ERROR: {:?}", e)) .unwrap(); ...
fn init(ctx: init::Context) -> init::LateResources { rtt_init_print!(); log::set_logger(&LOGGER).unwrap(); log::set_max_level(log::LevelFilter::Info); let port0 = hal::gpio::p0::Parts::new(ctx.device.P0); let port1 = hal::gpio::p1::Parts::new(ctx.device.P1); let clocks ...
function_block-full_function
[ { "content": "struct HexSlice<'a>(&'a [u8]);\n\n\n\nimpl<'a> core::fmt::Display for HexSlice<'a> {\n\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {\n\n for b in self.0.iter() {\n\n write!(f, \"{:x}\", b)?;\n\n }\n\n Ok(())\n\n...
Rust
src/fill/fill_depressions.rs
dlalic/flood
da8ad38ea8c68ed91d1dc37a5fb7b2b79de333d7
use std::collections::BinaryHeap; use std::ops::AddAssign; use num_rational::Rational64; use crate::fill::minima::minima; use crate::fill::point::Point; pub fn fill_depressions(input: &[Point]) -> Vec<Rational64> { let mut binary_heap = BinaryHeap::new(); let mut water_levels = vec![]; for point in input...
use std::collections::BinaryHeap; use std::ops::AddAssign; use num_rational::Rational64; use crate::fill::minima::minima; use crate::fill::point::Point; pub fn fill_depressions(input: &[Point]) -> Vec<Rational64> { let mut binary_heap = BinaryHeap::new(); let mut water_levels = vec![]; for point in input...
#[test] fn simple_steps() { let results = fill_depressions(&from_vec(vec![3, 2, 1])); assert_eq!( results, vec![ Rational64::from_integer(3), Rational64::from_integer(3), Rational64::from_integer(3) ] )...
fn simple_valley() { let results = fill_depressions(&from_vec(vec![3, 0, 3])); assert_eq!( results, vec![ Rational64::from_integer(3), Rational64::from_integer(3), Rational64::from_integer(3) ] ); }
function_block-full_function
[ { "content": "pub fn minima(input: &[Rational64], index: usize) -> Vec<usize> {\n\n let mut left = find_minima(input, index, Direction::Left);\n\n let mut right = find_minima(input, index, Direction::Right);\n\n if let Some(left_last) = left.first().cloned() {\n\n if let Some(right_last) = right...
Rust
src/operations.rs
KronosTheLate/juliaup
a3e5fa99e2587e0ac30edc476366fe8701a431f7
use crate::config_file::JuliaupConfig; use crate::config_file::JuliaupConfigChannel; use crate::config_file::JuliaupConfigVersion; use crate::get_bundled_julia_full_version; use crate::jsonstructs_versionsdb::JuliaupVersionDB; use crate::utils::get_arch; use crate::utils::get_juliaserver_base_url; use crate::utils::get...
use crate::config_file::JuliaupConfig; use crate::config_file::JuliaupConfigChannel; use crate::config_file::JuliaupConfigVersion; use crate::get_bundled_julia_full_version; use crate::jsonstructs_versionsdb::JuliaupVersionDB; use crate::utils::get_arch; use crate::utils::get_juliaserver_base_url; use crate::utils::get...
pub fn garbage_collect_versions(config_data: &mut JuliaupConfig) -> Result<()> { let home_path = get_juliaup_home_path().with_context(|| { "Failed to retrieve juliaup folder while trying to garbage collect versions." })?; let mut versions_to_uninstall: Vec<String> = Vec::new(); for (installed...
h))?; let (platform, version) = parse_versionstring(fullversion).with_context(|| format!(""))?; eprintln!("{} Julia {} ({}).", style("Installing").green().bold(), version, platform); download_extract_sans_parent(&download_url.to_string(), &target_path, 1)?; } let mut rel_path...
function_block-function_prefixed
[ { "content": "fn update_channel(config_db: &mut JuliaupConfig, channel: &String, version_db: &JuliaupVersionDB, ignore_linked_channel: bool) -> Result<()> { \n\n let current_version = \n\n config_db.installed_channels.get(channel).ok_or(anyhow!(\"asdf\"))?;\n\n\n\n match current_version {\n\n ...
Rust
src/serde_setup.rs
JeanBarriere/shipyard
fbabbb168439910b5633cabf6bfad844d8a0751e
use alloc::borrow::Cow; pub(crate) static ANCHOR: () = (); #[derive(Clone, Copy)] pub struct GlobalSerConfig { pub same_binary: bool, pub with_entities: bool, pub with_shared: WithShared, } impl Default for GlobalSerConfig { fn default() -> Self { GlobalSerConfig { same_binary: tr...
use alloc::borrow::Cow; pub(crate) static ANCHOR: () = (); #[derive(Clone, Copy)] pub struct GlobalSerConfig { pub same_binary: bool, pub with_entities: bool, pub with_shared: WithShared, } impl Default for GlobalSerConfig { fn default() -> Self { GlobalSerConfig { same_binary: tr...
} impl<'de> serde::Deserialize<'de> for Field { #[inline] fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_identifier(FieldVisitor) } ...
e { b"same_binary" => Ok(Field::SameBinary), b"with_entities" => Ok(Field::WithEntities), _ => Err(serde::de::Error::invalid_value( serde::de::Unexpected::Bytes(value), &"field are `same_binary` and `with_entitie...
function_block-function_prefixed
[ { "content": "pub fn get_media_href(path: &str) -> String {\n\n format!(\"media/{}\", path)\n\n}\n", "file_path": "bunny_demo/src/config.rs", "rank": 0, "score": 164883.64505756972 }, { "content": "pub fn start(mut fps_counter: UniqueViewMut<FpsCounter>) {\n\n fps_counter.begin();\n\n}...
Rust
src/walk.rs
psinghal20/fd
56b6389dac945df313ce54072fcc01b91211a76c
extern crate ctrlc; use exec; use fshelper; use internal::{print_error, print_error_and_exit, FdOptions, EXITCODE_SIGINT, MAX_BUFFER_LENGTH}; use output; use std::error::Error; use std::path::PathBuf; use std::process; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::channel; use std::sync::{Arc,...
extern crate ctrlc; use exec; use fshelper; use internal::{print_error, print_error_and_exit, FdOptions, EXITCODE_SIGINT, MAX_BUFFER_LENGTH}; use output; use std::error::Error; use std::path::PathBuf; use std::process; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::channel; use std::sync::{Arc,...
} else { return ignore::WalkState::Continue; } } let entry_path = entry.path(); if let Some(ref exts_regex) = config.extensions { if let Some(path_str) = entry_path.file_name().map_or(None, |s| s.to_s...
if !(entry_type.is_file() || entry_type.is_dir() || entry_type.is_symlink()) { return ignore::WalkState::Continue; }
if_condition
[ { "content": "/// Executes a command.\n\npub fn execute_command(mut cmd: Command, out_perm: Arc<Mutex<()>>) {\n\n // Spawn the supplied command.\n\n let output = cmd.output();\n\n\n\n // Then wait for the command to exit, if it was spawned.\n\n match output {\n\n Ok(output) => {\n\n ...
Rust
src/lib.rs
ChijinZ/process-communication
478a81c2b8c5da4998b6316d3b1a91e2a04faa3e
#![deny(warnings, missing_debug_implementations)] extern crate tokio; extern crate futures; extern crate tokio_codec; extern crate serde; extern crate bincode; extern crate bytes; use tokio::net; use tokio::prelude::*; use bincode::{deserialize, serialize}; use tokio::io; use tokio_codec::*; use bytes::{BufMut, Byte...
#![deny(warnings, missing_debug_implementations)] extern crate tokio; extern crate futures; extern crate tokio_codec; extern crate serde; extern crate bincode; extern crate bytes; use tokio::net; use tokio::prelude::*; use bincode::{deserialize, serialize}; use tokio::io; use tokio_codec::*; use bytes::{BufMut, Byte...
ld to connect. err:{:?}", e); }) ) } #[allow(dead_code)] pub mod tcp; #[allow(dead_code)] pub mod uds; pub fn create_tcp_fuzz_server<T>(addr: &str, server_name: &str) -> tcp::TcpFuzzServer<T> where T: serde::de::DeserializeOwned + serde::Serialize + Send + 'static + Clone { tcp::TcpFuzzServer::new(addr, ...
Sync, <U as futures::Future>::Error: std::fmt::Debug + 'static + Send + Sync { let (tx, rx): (mpsc::Sender<(String, T)>, mpsc::Receiver<(String, T)>) = mpsc::channel(0); let rx: Box<Stream<Item=(String, T), Error=io::Error> + Send> = Box::new(rx.map_err(|_| panic!())); *user_tx.write().unwrap() =...
random
[ { "content": "#[test]\n\nfn test_vecu8_u64() {\n\n for i in ((1 << 31)-(1<<20))..(1 << 31) {\n\n assert_eq!(i, four_vecu8_to_number(number_to_four_vecu8(i)));\n\n }\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 5, "score": 57940.544616797495 }, { "content": "fn server() {\n...
Rust
src/virtualization/bin/wayland/bridge/src/display.rs
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
use { crate::client::Client, crate::object::{NewObjectExt, ObjectRef, RequestReceiver}, crate::registry::Registry, anyhow::{format_err, Error}, fidl::endpoints::ClientEnd, fidl_fuchsia_element::{GraphicalPresenterMarker, GraphicalPresenterProxy}, fidl_fuchsia_ui_app::ViewProviderMarker, ...
use { crate::client::Client, crate::object::{NewObjectExt, ObjectRef, RequestReceiver}, crate::registry::Registry, anyhow::{format_err, Error}, fidl::endpoints::ClientEnd, fidl_fuchsia_element::{GraphicalPresenterMarker, GraphicalPresenterProxy}, fidl_fuchsia_ui_app::ViewProviderMarker, ...
#[cfg(test)] pub fn new_no_scenic(registry: Registry) -> Result<Self, Error> { let (c1, _c2) = zx::Channel::create()?; let scenic = ScenicProxy::new(fasync::Channel::from_channel(c1)?); let (c1, _c2) = zx::Channel::create()?; let graphical_presenter = GraphicalPresent...
expect("failed to connect to Scenic service"); let graphical_presenter = connect_to_protocol::<GraphicalPresenterMarker>() .expect("failed to connect to GraphicalPresenter service"); Ok(Display { registry: Arc::new(Mutex::new(registry)), scenic: Arc::new(scenic), ...
function_block-function_prefixed
[]
Rust
cita-executor/core/src/contracts/native/crosschain_verify.rs
nanmuxiusi/cita
0158f963ac1f19497502eecc5e1b185b988c735a
use crate::cita_executive::VmExecParams; use crate::contracts::{ native::factory::Contract, solc::ChainManagement, tools::method as method_tools, }; use cita_types::{Address, H256, U256}; use core::header::Header; use core::libchain::chain::TxProof; use ethabi; use crate::storage::Map; use crate::types::context...
use crate::cita_executive::VmExecParams; use crate::contracts::{ native::factory::Contract, solc::ChainManagement, tools::method as method_tools, }; use cita_types::{Address, H256, U256}; use core::header::Header; use core::libchain::chain::TxProof; use ethabi; use crate::storage::Map; use crate::types::context...
fn create(&self) -> Box<Contract> { Box::new(CrossChainVerify::default()) } } impl Default for CrossChainVerify { fn default() -> Self { CrossChainVerify { block_headers: Map::new(H256::from(0)), state_roots: Map::new(H256::from(1)), output: Vec::new(), ...
ock_header(params, data_provider) } sig if sig == *GET_EXPECTED_BLOCK_NUMBER_FUNC => { self.get_expected_block_number(params, data_provider) } _ => Err(NativeError::Internal("out of gas".to_string())), }) }
function_block-function_prefixed
[ { "content": "/// Parse solidity return data `uint256` to rust `u32`\n\npub fn to_u32(output: &[u8]) -> Option<u32> {\n\n to_u256(output).map(|x| x.low_u32())\n\n}\n\n\n", "file_path": "cita-executor/core/src/contracts/tools/decode.rs", "rank": 0, "score": 296840.37878266524 }, { "content...
Rust
crates/lsp/src/asm/signature.rs
JamieCunliffe/lsp-asm
c0dc8266bb8716f24df28894cfe1d5058038661f
use documentation::{Instruction, InstructionTemplate, OperandInfo}; use itertools::Itertools; use lsp_types::{ Documentation, ParameterInformation, ParameterLabel, SignatureHelp, SignatureInformation, }; use rowan::TextSize; use syntax::ast::{find_kind_index, find_parent, SyntaxKind, SyntaxNode, SyntaxToken}; use ...
use documentation::{Instruction, InstructionTemplate, OperandInfo}; use itertools::Itertools; use lsp_types::{ Documentation, ParameterInformation, ParameterLabel, SignatureHelp, SignatureInformation, }; use rowan::TextSize; use syntax::ast::{find_kind_index, find_parent, SyntaxKind, SyntaxNode, SyntaxToken}; use ...
fn make_parameters(operand_info: &[OperandInfo], display_asm: &str) -> Vec<ParameterInformation> { let operand_start = display_asm .chars() .take_while(|c| !c.is_whitespace()) .count(); let operands = display_asm[operand_start..].trim_start(); let operands = operands .spl...
fn get_comma_position(node: &SyntaxNode, current: &SyntaxToken) -> usize { node.descendants_with_tokens() .take_while(|d| d.as_token().map(|t| t != current).unwrap_or(true)) .filter(|d| matches!(d.kind(), SyntaxKind::COMMA)) .count() }
function_block-full_function
[ { "content": "fn start_kind(token: &str) -> SyntaxKind {\n\n if token.ends_with(':') {\n\n if token.starts_with('.') {\n\n SyntaxKind::LOCAL_LABEL\n\n } else {\n\n SyntaxKind::LABEL\n\n }\n\n } else if token.starts_with('.') {\n\n SyntaxKind::DIRECTIVE\n\n...
Rust
sys_util/src/descriptor.rs
danielverkamp/crosvm
ecd3a42fb4651c48240453bc6a23fb647eed5391
use std::convert::TryFrom; use std::fs::File; use std::io::{Stderr, Stdin, Stdout}; use std::mem; use std::net::UdpSocket; use std::ops::Drop; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::os::unix::net::{UnixDatagram, UnixStream}; use serde::{Deserialize, Serialize}; use crate::net::Unlin...
use std::convert::TryFrom; use std::fs::File; use std::io::{Stderr, Stdin, Stdout}; use std::mem; use std::net::UdpSocket; use std::ops::Drop; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::os::unix::net::{UnixDatagram, UnixStream}; use serde::{Deserialize, Serialize}; use crate::net::Unlin...
sRawDescriptor!(UnlinkUnixSeqpacketListener); FromRawDescriptor!(File); IntoRawDescriptor!(File); AsRawDescriptor!(Stdin); AsRawDescriptor!(Stdout); AsRawDescriptor!(Stderr); impl AsRawDescriptor for UdpSocket { fn as_raw_descriptor(&self) -> RawDescriptor { self.as_raw_fd() } } impl AsRawDescriptor f...
} } impl TryFrom<&dyn AsRawFd> for SafeDescriptor { type Error = std::io::Error; fn try_from(fd: &dyn AsRawFd) -> std::result::Result<Self, Self::Error> { Ok(SafeDescriptor { descriptor: clone_fd(fd)?, }) } } impl SafeDescriptor { pub fn try_clone(&self) -> Re...
random
[ { "content": "/// Wraps an AsRawDescriptor in the simple Descriptor struct, which\n\n/// has AsRawFd methods for interfacing with sys_util\n\npub fn wrap_descriptor(descriptor: &dyn AsRawDescriptor) -> Descriptor {\n\n Descriptor(descriptor.as_raw_descriptor())\n\n}\n\n\n", "file_path": "base/src/lib.rs"...
Rust
tests/integ.rs
chethanah/oci-ftrace-syscall-analyzer
362b22415b3632fd51b1c3f1c9f2dcc92f2491e9
extern crate assert_cmd; use std::io::{BufRead, BufReader}; use assert_cmd::Command; use assert_cmd::output::OutputResult; use std::{fs, process, thread, time}; #[cfg(test)] mod integration { use super::*; fn exec_analyzer_command(cid: &str, args: &[&str], with_annotations: Option<bool>) -> OutputResult { ...
extern crate assert_cmd; use std::io::{BufRead, BufReader}; use assert_cmd::Command; use assert_cmd::output::OutputResult; use std::{fs, process, thread, time}; #[cfg(test)] mod integration { use super::*; fn exec_analyzer_command(cid: &str, args: &[&str], with_annotations: Option<bool>) -> OutputResult { ...
macro_rules! get_cid { ($test_id:expr) => {{ &format!("analyzer_test_{}_{}", $test_id, process::id()) }}; } macro_rules! get_tracefs_path { ($cid:expr) => {{ &format!("/sys/kernel/debug/tracing/instances/{}", $cid) }}; } #[test] fn trac...
fn remove_trace_dir(trace_path: &str) { let mut retry = 10; while let Err(_) = fs::remove_dir(&trace_path) { retry -= 1; if retry == 0 { break; } thread::sleep(time::Duration::from_millis(10)); } }
function_block-full_function
[ { "content": "fn change_bufsize(trace_setting_path: &str, bufsize: &str) {\n\n let syscall_bufsize = format!(\"{}/buffer_size_kb\", &trace_setting_path);\n\n fs::write(&syscall_bufsize, bufsize)\n\n .unwrap_or_else(|_| panic!(\"Failed to write to {}\", &syscall_bufsize));\n\n}\n\n\n", "file_pat...
Rust
src/ranges.rs
MrGreenTea/poetry-pubgrub-rs
69282f6a9dbeca201cd278f7572f18f5dd61a369
use crate::version::PEP440Version; use lazy_static::lazy_static; use pubgrub::range::Range; use regex::Regex; use std::str::FromStr; lazy_static! { pub static ref SPECIFIER_PATTERN: Regex = Regex::new(r"^(?P<compare>~=|==|!=|<=|>=|<|>|===)\s*(?P<version>\S+)\s*$").unwrap(); pub static ref DEPENDENCY_PATTE...
use crate::version::PEP440Version; use lazy_static::lazy_static; use pubgrub::range::Range; use regex::Regex; use std::str::FromStr; lazy_static! { pub static ref SPECIFIER_PATTERN: Regex = Regex::new(r"^(?P<compare>~=|==|!=|<=|>=|<|>|===)\s*(?P<version>\S+)\s*$").unwrap(); pub static ref DEPENDENCY_PATTE...
ange::strictly_lower_than(version), Compare::Matching => Range::exact(version), Compare::ArbitraryEqual => Range::exact(version), Compare::Compatible => Range::exact(version), Compare::Exclusion => Range::exact(version).negate(), Compare::StrictGreater => Range:...
o_range(cmp: Compare, version: PEP440Version) -> Range<PEP440Version> { match cmp { Compare::GreaterOrEqual => Range::higher_than(version), Compare::LessOrEqual => { Range::strictly_lower_than(version.clone()).union(&Range::exact(version)) } Compare::StrictLess => R
function_block-random_span
[ { "content": "pub fn resolve(root: &str, version: &str, requires: Vec<(&str, &str)>, dev_requires: Vec<(&str, &str)>) -> Vec<(String, String)> {\n\n let version = version.parse().unwrap();\n\n let dependencies = requires\n\n .iter()\n\n .chain(dev_requires.iter())\n\n .map(|(name, ran...
Rust
compiler-core/src/codegen.rs
inoas/gleam
08f1abe0c5220ebda49301f6058f21dc813b5b28
use crate::{ build::Module, config::{JavascriptConfig, PackageConfig}, erlang, io::{FileSystemWriter, Utf8Writer}, javascript, line_numbers::LineNumbers, Result, }; use itertools::Itertools; use std::{fmt::Debug, path::Path}; #[derive(Debug)] pub struct Erlang<'a> { build_directory: &'a...
use crate::{ build::Module, config::{JavascriptConfig, PackageConfig}, erlang, io::{FileSystemWriter, Utf8Writer}, javascript, line_numbers::LineNumbers, Result, }; use itertools::Itertools; use std::{fmt::Debug, path::Path}; #[derive(Debug)] pub struct Erlang<'a> { build_directory: &'a...
fn erlang_record_headers<Writer: FileSystemWriter>( &self, writer: &Writer, module: &Module, erl_name: &str, ) -> Result<()> { for (name, text) in erlang::records(&module.ast) { let name = format!("{}_{}.hrl", erl_name, name); tracing::debug!(nam...
let path = self.build_directory.join(&name); let mut file = writer.writer(&path)?; let line_numbers = LineNumbers::new(&module.code); let res = erlang::module(&module.ast, &line_numbers, &mut file); tracing::debug!(name = ?name, "Generated Erlang module"); res }
function_block-function_prefix_line
[ { "content": "pub fn pretty(writer: &mut impl Utf8Writer, src: &str, path: &Path) -> Result<()> {\n\n let (module, extra) = crate::parse::parse_module(src).map_err(|error| Error::Parse {\n\n path: path.to_path_buf(),\n\n src: src.to_string(),\n\n error,\n\n })?;\n\n let intermediat...
Rust
src/mirrored/linux.rs
Atul9/slice_deque
4699a9920bbb0b830217a59b68bf491ca6a218ae
use libc::{ c_char, c_int, c_long, c_uint, c_void, close, ftruncate, mkstemp, mmap, munmap, off_t, size_t, syscall, sysconf, SYS_memfd_create, ENOSYS, MAP_FAILED, MAP_FIXED, MAP_SHARED, PROT_READ, PROT_WRITE, _SC_PAGESIZE, }; #[cfg(target_os = "android")] use libc::__errno; #[cfg(not(target_os = "android"...
use libc::{ c_char, c_int, c_long, c_uint, c_void, close, ftruncate, mkstemp, mmap, munmap, off_t, size_t, syscall, sysconf, SYS_memfd_create, ENOSYS, MAP_FAILED, MAP_FIXED, MAP_SHARED, PROT_READ, PROT_WRITE, _SC_PAGESIZE, }; #[cfg(target_os = "android")] use libc::__errno; #[cfg(not(target_os = "android"...
pub unsafe fn deallocate_mirrored(ptr: *mut u8, size: usize) { assert!(!ptr.is_null()); assert!(size != 0); assert!(size % allocation_granularity() == 0); if munmap(ptr as *mut c_void, size as size_t) == -1 { print_error("deallocate munmap failed"); } } #[cfg(all(debug_assertions, feature...
e_deque_fileXXXXXX\0"; let mut fd: c_long = memfd_create(fname.as_mut_ptr() as *mut c_char, 0); if fd == -1 && errno() == ENOSYS { fd = c_long::from(mkstemp(fname.as_mut_ptr() as *mut c_char)); } if fd == -1 { print_error("memfd_create fai...
function_block-function_prefixed
[ { "content": "/// Allocates `size` bytes of uninitialized memory, where the bytes in range\n\n/// `[0, size / 2)` are mirrored into the bytes in range `[size / 2, size)`.\n\n///\n\n/// The algorithm using System V interprocess shared-memory is:\n\n///\n\n/// * 1. Allocate `size / 2` of interprocess shared memor...
Rust
rust-package/brainflow/build.rs
ECGKit/brainflow
ef4e4d249e6672c8fb93f1533cb4842f5ca1fb0e
#[cfg(feature = "generate_binding")] use std::path::PathBuf; #[cfg(feature = "generate_binding")] fn generate_board_controller_binding() { const ALLOW_UNCONVENTIONALS: &'static str = "#![allow(non_camel_case_types)]\n"; let header_path = PathBuf::from("inc"); let header_path = header_path.display(); ...
#[cfg(feature = "generate_binding")] use std::path::PathBuf; #[cfg(feature = "generate_binding")] fn generate_board_controller_binding() { const ALLOW_UNCONVENTIONALS: &'static str = "#![allow(non_camel_case_types)]\n"; let header_path = PathBuf::from("inc"); let header_path = header_path.display(); ...
fn main() { #[cfg(feature = "generate_binding")] generate_binding(); }
e_board_controller_binding(); generate_data_handler_binding(); generate_ml_model_binding(); generate_constants_binding(); }
function_block-function_prefixed
[ { "content": "/// Perform wavelet denoising.\n\npub fn perform_wavelet_denoising<S: AsRef<str>>(\n\n data: &mut [f64],\n\n wavelet: S,\n\n decomposition_level: usize,\n\n) -> Result<()> {\n\n let wavelet = CString::new(wavelet.as_ref())?;\n\n let res = unsafe {\n\n DATA_FILTER.lock().unwra...
Rust
src/handler/mod.rs
andrewhickman/mock-server
e2847e983fb6938264790a4f4b9dd4f6b4320770
mod fs; mod json; mod mock; mod proxy; use std::fmt; use anyhow::Result; use hyper::Body; use self::fs::{DirHandler, FileHandler}; use self::json::JsonHandler; use self::mock::MockHandler; use self::proxy::ProxyHandler; use crate::method::MethodFilter; use crate::path::PathRewriter; use crate::{config, response}; p...
mod fs; mod json; mod mock; mod proxy; use std::fmt; use anyhow::Result; use hyper::Body; use self::fs::{DirHandler, FileHandler}; use self::json::JsonHandler; use self::mock::MockHandler; use self::proxy::ProxyHandler; use crate::method::MethodFilter; use crate::path::PathRewriter; use crate::{config, response}; p...
} impl HandlerKind { fn default_method_filter(&self) -> Box<dyn MethodFilter> { match self { HandlerKind::File(_) | HandlerKind::Dir(_) => fs::default_method_filter(), HandlerKind::Proxy(_) => proxy::default_method_filter(), HandlerKind::Json(_) => json::default_method_...
ait, }; if let Ok(response) = &mut result { response.headers_mut().extend(self.response_headers.clone()); } result }
function_block-function_prefixed
[ { "content": "fn parse_http_method(mut string: String) -> Result<http::Method, http::method::InvalidMethod> {\n\n string.make_ascii_uppercase();\n\n http::Method::from_str(&string)\n\n}\n", "file_path": "src/method.rs", "rank": 0, "score": 121201.60912484102 }, { "content": "pub fn def...
Rust
src/remapper/lattice.rs
kb10uy/uv-remapper
bb0e705ba51bd8282068462a9c025ed56108a656
use std::{ error::Error, fmt::{Display, Formatter, Result as FmtResult}, sync::Arc, }; use rlua::prelude::*; use ultraviolet::{Mat2, Vec2}; #[derive(Debug, Clone, Eq, PartialEq)] pub enum LatticeError { NonRectangular, } impl Display for LatticeError { fn fmt(&self, f: &mut Formatter<'_>) ->...
use std::{ error::Error, fmt::{Display, Formatter, Result as FmtResult}, sync::Arc, }; use rlua::prelude::*; use ultraviolet::{Mat2, Vec2}; #[derive(Debug, Clone, Eq, PartialEq)] pub enum LatticeError { NonRectangular, } impl Display for LatticeError { fn fmt(&self, f: &mut Formatter<'_>) ->...
return Err(LuaError::ExternalError(Arc::new( LatticeError::NonRectangular, ))); } let width = lattice_table.get::<_, LuaTable>(1)?.len()?; if width <= 1 { return Err(LuaError::ExternalError(Arc::new( LatticeError::NonRectangular, ...
ttice に変換できません".into()), }) } }; let height = lattice_table.len()?; if height <= 1 {
random
[ { "content": "/// Lua スクリプトを読み込んで exec() まで実行する。\n\npub fn prepare(lua: &Lua, name: &str, mut reader: impl Read) -> Result<(), Box<dyn Error>> {\n\n let mut script = String::with_capacity(8192);\n\n reader.read_to_string(&mut script)?;\n\n\n\n // 登録\n\n let environment = Environment::new();\n\n l...
Rust
src/safe/program/mod.rs
dmarcuse/dynamic_ocl
6a9b488105d804a5551073082671ada9fa8aafff
mod types; use crate::context::Context; use crate::device::Device; use crate::raw::{ clGetProgramBuildInfo, clGetProgramInfo, clReleaseProgram, clRetainProgram, cl_context, cl_device_id, cl_program, cl_program_build_info, cl_program_info, cl_uint, }; use crate::util::sealed::OclInfoInternal; use crate::Resul...
mod types; use crate::context::Context; use crate::device::Device; use crate::raw::{ clGetProgramBuildInfo, clGetProgramInfo, clReleaseProgram, clRetainProgram, cl_context, cl_device_id, cl_program, cl_program_build_info, cl_program_info, cl_uint, }; use crate::util::sealed::OclInfoInternal; use crate::Resul...
} impl OclInfoInternal for Program { type Param = cl_program_info; const DEBUG_CONTEXT: &'static str = "clGetProgramInfo"; unsafe fn raw_info_internal( &self, param_name: Self::Param, param_value_size: usize, param_value: *mut c_void, param_value_size_ret: *mut usi...
if let Err(e) = wrap_result!("clReleaseProgram" => clReleaseProgram(self.0)) { log::warn!("Error releasing OpenCL program: {:?}: {:?}", self, e); } } }
function_block-function_prefix_line
[ { "content": "/// A program builder type, specifying how a program should be built (e.g.\n\n/// compiled from source code, loaded from a binary, etc)\n\npub trait ProgramBuilderType: sealed::ProgramBuilderTypeInternal {}\n\n\n\n/// A `ProgramBuilderType` implementation for programs to be compiled from\n\n/// so...
Rust
crates/server/src/authority/authority_object.rs
LucioFranco/trust-dns
cb56f66d80f4a278178a35d499b2a8b330b16b82
use std::pin::Pin; use std::task::{Context, Poll}; use futures::{future, Future, TryFutureExt}; use trust_dns_client::op::LowerQuery; use trust_dns_client::proto::rr::dnssec::rdata::key::KEY; use trust_dns_client::rr::dnssec::{DnsSecError, DnsSecResult, Signer, SupportedAlgorithms}; use trust_dns_client::rr::{Lower...
use std::pin::Pin; use std::task::{Context, Poll}; use futures::{future, Future, TryFutureExt}; use trust_dns_client::op::LowerQuery; use trust_dns_client::proto::rr::dnssec::rdata::key::KEY; use trust_dns_client::rr::dnssec::{DnsSecError, DnsSecResult, Signer, SupportedAlgorithms}; use trust_dns_client::rr::{Lower...
pub fn empty() -> Self { BoxedLookupFuture(Box::pin(future::ok( Box::new(EmptyLookup) as Box<dyn LookupObject> ))) } } impl Future for BoxedLookupFuture { type Output = Result<Box<dyn LookupObject>, LookupError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) ->...
e T: Future<Output = Result<Box<dyn LookupObject>, LookupError>> + Send + Sized + 'static, { BoxedLookupFuture(Box::pin(future)) }
function_block-function_prefixed
[ { "content": "pub fn test_create<A: Authority<Lookup = AuthLookup>>(mut authority: A, keys: &[Signer]) {\n\n let name = Name::from_str(\"create.example.com.\").unwrap();\n\n for key in keys {\n\n let name = Name::from_str(key.algorithm().as_str())\n\n .unwrap()\n\n .append_nam...
Rust
ioreg/src/builder/union.rs
ntwyman/zinc
63826151df91f87c2195c9f2c5f6422f275d3191
use std::rc::Rc; use std::iter::FromIterator; use syntax::ast; use syntax::ptr::P; use syntax::codemap::{DUMMY_SP, respan, Spanned}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use node; use super::Builder; use super::utils; enum RegOrPadding<'a> { Reg(&'a node::Reg), Pad(u64) } s...
use std::rc::Rc; use std::iter::FromIterator; use syntax::ast; use syntax::ptr::P; use syntax::codemap::{DUMMY_SP, respan, Spanned}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use node; use super::Builder; use super::utils; enum RegOrPadding<'a> { Reg(&'a node::Reg), Pad(u64) } s...
ast::StructField { span: DUMMY_SP, ident: Some(self.cx.ident_of(format!("_pad{}", index).as_str())), vis: ast::Visibility::Inherited, id: ast::DUMMY_NODE_ID, ty: ty, attrs: Vec::new(), } }, } } fn build_union_type(&self, path...
let ty: P<ast::Ty> = self.cx.ty( DUMMY_SP, ast::TyKind::FixedLengthVec(u8_ty, expr_usize(self.cx, respan(DUMMY_SP, length))));
assignment_statement
[ { "content": "/// The `Path` to the type corresponding to the primitive type of\n\n/// the given register\n\npub fn reg_primitive_type_path(cx: &ExtCtxt, reg: &node::Reg)\n\n -> Option<ast::Path> {\n\n match reg.ty {\n\n node::RegType::RegPrim(ref width, _) => Some(primitive_ty...
Rust
cli/core/src/init.rs
mehdiraized/tauri
f2c4afe3c528122fa0184f9e698c49026f203900
use std::{ collections::BTreeMap, fs::{create_dir_all, remove_dir_all, File}, io::Write, path::{Path, PathBuf}, }; use crate::helpers::Logger; use handlebars::{to_json, Handlebars}; use include_dir::{include_dir, Dir}; use serde::Deserialize; const TEMPLATE_DIR: Dir = include_dir!("./templates"); #[derive(De...
use std::{ collections::BTreeMap, fs::{create_dir_all, remove_dir_all, File}, io::Write, path::{Path, PathBuf}, }; use crate::helpers::Logger; use handlebars::{to_json, Handlebars}; use include_dir::{include_dir, Dir}; use serde::Deserialize; const TEMPLATE_DIR: Dir = include_dir!("./templates"); #[derive(De...
path.join(crate_name) } else { PathBuf::from("..").join(path).join(crate_name) } }
et_path.exists() && !self.force { logger.warn(format!( "Tauri dir ({:?}) not empty. Run `init --force template` to overwrite.", template_target_path )); } else { let (tauri_dep, tauri_build_dep) = if let Some(tauri_path) = self.tauri_path { ( format!( ...
random
[ { "content": "/// Reads a string file.\n\npub fn read_string<P: AsRef<Path>>(file: P) -> crate::Result<String> {\n\n fs::read_to_string(file).map_err(Into::into)\n\n}\n\n\n", "file_path": "tauri-api/src/file.rs", "rank": 0, "score": 317278.5048387131 }, { "content": "/// Checks if the given...
Rust
tests/abc2midi_parity.rs
akaihola/abc-to-midi
7d7f1614352619c9b5b008ba98a435bef0c31491
#[cfg(test)] use abc_parser::{ abc, datatypes::{MusicLine, MusicSymbol::Bar, TuneBody}, }; use abc_to_midi::{ accidentals::{AccidentalTracker, KeySignatureMap}, conversion::Moment, midly_wrappers::{Smf, Track}, time_signatures::TimeSignatureTracker, }; use midly::{ self, num::u7, Hea...
#[cfg(test)] use abc_parser::{ abc, datatypes::{MusicLine, MusicSymbol::Bar, TuneBody}, }; use abc_to_midi::{ accidentals::{AccidentalTracker, KeySignatureMap}, conversion::Moment, midly_wrappers::{Smf, Track}, time_signatures::TimeSignatureTracker, }; use midly::{ self, num::u7, Hea...
w(); let mut accidental_tracker = AccidentalTracker::new(&key_signature_map); let time_signature_tracker = TimeSignatureTracker::new(&TimeSignature(4, 4, 48, 8)).unwrap(); let first_bar_symbols = symbols .iter() .take_while(|&symbol| !m...
function_block-function_prefixed
[ { "content": "// Key signature parsing (for major keys only for now):\n\n// \"F#m\" (in ABC source)\n\n// KeySignatureSymbol { |\n\n// note: Note::F, v\n\n// accidental: Some(Accidental::Sharp),\n\n// minor: true, |\n\n// } ...
Rust
src/rgba/rgba_file.rs
vfx-rs/openexr-rs
5770eba648d0fcb9f45b0efc76cc28e94c56d44e
use crate::{ core::{ cppstd::CppString, error::Error, header::{Header, HeaderRef}, preview_image::PreviewRgba, Compression, LineOrder, }, rgba::rgba::{Rgba, RgbaChannels}, }; use imath_traits::Vec2; use openexr_sys as sys; use std::ffi::CString; use std::path::Path; ...
use crate::{ core::{ cppstd::CppString, error::Error, header::{Header, HeaderRef}, preview_image::PreviewRgba, Compression, LineOrder, }, rgba::rgba::{Rgba, RgbaChannels}, }; use imath_traits::Vec2; use openexr_sys as sys; use std::ffi::CString; use std::path::Path; ...
.as_ref() .to_str() .expect("Invalid bytes in filename"), ) .expect("Internal null bytes in filename"); unsafe { sys::Imf_RgbaInputFile_ctor( &mut inner, c_filename.as_ptr(), num_threads, ...
urrent_scan_line(&self) -> i32 { let mut v = 0; unsafe { sys::Imf_RgbaOutputFile_currentScanLine(self.0, &mut v); } v } pub fn header(&self) -> HeaderRef { unsafe { let mut ptr = std::ptr::null(); sys::Imf_RgbaOutputFile_head...
random
[ { "content": "type Result<T, E = Error> = std::result::Result<T, E>;\n\n\n\nuse std::alloc::{GlobalAlloc, Layout, System};\n\nuse std::ffi::{CStr, CString};\n\n\n\n/// The `Header` represents the header in the OpenEXR file and is typically read\n\n/// or written when the file is first opened.\n\n///\n\n/// Ther...
Rust
deprecated/query_analysis_deprecated/query_analyzer_old/src/tests/ddl/drop_statements.rs
Tolledo/database
65e7e5b2de3020000110a3883291377b8e3019af
use super::*; use crate::tests::ident; use description::{DropSchemasInfo, DropTablesInfo, SchemaId}; use sql_ast::{ObjectName, ObjectType, Statement}; fn drop(names: Vec<ObjectName>, object_type: ObjectType) -> Statement { Statement::Drop { object_type, if_exists: false, names, ca...
use super::*; use crate::tests::ident; use description::{DropSchemasInfo, DropTablesInfo, SchemaId}; use sql_ast::{ObjectName, ObjectType, Statement}; fn drop(names: Vec<ObjectName>, object_type: ObjectType) -> Statement { Statement::Drop { object_type, if_exists: false, names, ca...
fn drop_table() { let metadata = Arc::new(DatabaseHandle::in_memory()); let schema_id = metadata.create_schema(SCHEMA).expect("schema created"); metadata.create_table(schema_id, TABLE, &[]).expect("table created"); let analyzer = Analyzer::new(metadata); let description = analyzer.describe(&drop( ...
function_block-full_function
[ { "content": "fn create_schema(schema_name: ObjectName) -> Statement {\n\n Statement::CreateSchema {\n\n schema_name,\n\n if_not_exists: false,\n\n }\n\n}\n\n\n", "file_path": "deprecated/query_analysis_deprecated/query_analyzer_old/src/tests/ddl/create_schema.rs", "rank": 0, "sc...
Rust
src/bits.rs
pie-flavor/megaboz
8866a2062a3b10383c5a8173575e3aa74731e48b
use std::ops::{Add, AddAssign, Index, Range, RangeInclusive, Sub, SubAssign}; use bitvec::cursor::BigEndian; use bitvec::slice::BitSlice; mod consts; pub use self::consts::*; use crate::*; pub type Word = u16; pub type ZBitSlice = BEBitSlice<u8>; pub type BEBitSlice<T> = BitSlice<BigEndian, T>; #[derive(Debug, Co...
use std::ops::{Add, AddAssign, Index, Range, RangeInclusive, Sub, SubAssign}; use bitvec::cursor::BigEndian; use bitvec::slice::BitSlice; mod consts; pub use self::consts::*; use crate::*; pub type Word = u16; pub type ZBitSlice = BEBitSlice<u
fn sub(self, rhs: usize) -> Self::Output { Self(self.0 - rhs) } } impl Sub<ByteAddress> for ByteAddress { type Output = usize; fn sub(self, rhs: ByteAddress) -> Self::Output { self.0 - rhs.0 } } impl SubAssign<usize> for ByteAddress { fn sub_assign(&mut self, rhs: usize) { ...
8>; pub type BEBitSlice<T> = BitSlice<BigEndian, T>; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct ByteAddress(pub usize); #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct BitAddress(usize); impl ByteAddress { pub const ZERO: Self = Self(0); pub fn...
random
[ { "content": "type RoutineResult = Result<u16, ExecuteError>;\n\n\n", "file_path": "src/vm.rs", "rank": 0, "score": 54848.38635828699 }, { "content": "type ExecuteResult = Result<Action, ExecuteError>;\n", "file_path": "src/vm.rs", "rank": 1, "score": 27183.805458426108 }, { ...
Rust
src/numeric.rs
DoumanAsh/to-str
818e20b640cc834081ae3e7f7c940cbb3cc6689e
use crate::ToStr; use core::{ptr}; use core::str::from_utf8_unchecked; static DEC_DIGITS: &[u8; 200] = b"0001020304050607080910111213141516171819\ 2021222324252627282930313233343536373839\ 4041424344454647484950515253545556575859\ ...
use crate::ToStr; use core::{ptr}; use core::str::from_utf8_unchecked; static DEC_DIGITS: &[u8; 200] = b"0001020304050607080910111213141516171819\ 2021222324252627282930313233343536373839\ 4041424344454647484950515253545556575859\ ...
#[inline] pub fn udivmod_1e19(num: &mut u128) -> u64 { const DIV: u64 = 10_000_000_000_000_000_000; let high = (*num >> 64) as u64; if high == 0 { let low = *num as u64; *num = (low / DIV) as u128; return low % DIV; } let sr = 65 - high.leading_zeros(); let mut q: u1...
8); } else { let index = num as isize * 2; cursor -= 2; ptr::copy_nonoverlapping(digits_ptr.offset(index), buffer_ptr.offset(cursor), 2); } cursor }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn should_convert_u8() {\n\n let mut buffer = [0u8; u8::TEXT_SIZE];\n\n for num in u8::min_value()..=u8::max_value() {\n\n let expected = format!(\"{}\", num);\n\n assert_eq!(num.to_str(&mut buffer), expected);\n\n }\n\n}\n\n\n", "file_path": "tests/numeric.rs...
Rust
src/timer.rs
9names/bl602-hal
f958b3390509866a795c734c2408057f44e68727
/*! # Timer The chip has two 32-bit counters, each of which can independently control and configure its parameters and clock frequency ## Example ```rust let timers = dp.TIMER.split(); let ch0 = timers .channel0 .set_clock_source(ClockSource::Clock1Khz, 1_000u32.Hz()); ch0.enable_...
/*! # Timer The chip has two 32-bit counters, each of which can independently control and configure its parameters and clock frequency ## Example ```rust let timers = dp.TIMER.split(); let ch0 = timers .channel0 .set_clock_source(ClockSource::Clock1Khz, 1_000u32.Hz()); ch0.enable_...
} fn hertz(&self) -> Hertz { match self { ClockSource::Fclk(clocks) => clocks.sysclk(), ClockSource::Rc32Khz => 32_000.Hz(), ClockSource::Clock1Khz => 1_000.Hz(), ClockSource::Pll32Mhz => 32_000_000.Hz(), } } } pub enum Preload { No...
match self { ClockSource::Fclk(_) => 0, ClockSource::Rc32Khz => 1, ClockSource::Clock1Khz => 2, ClockSource::Pll32Mhz => 3, }
if_condition
[ { "content": "/// Gets the current bus clock rate\n\nfn calculate_bus_clock() -> Hertz {\n\n let root_clk_sel = unsafe { &*pac::GLB::ptr() }\n\n .clk_cfg0\n\n .read()\n\n .hbn_root_clk_sel()\n\n .bits();\n\n let pll_clk_sel = unsafe { &*pac::GLB::ptr() }\n\n .clk_cfg0\n\...
Rust
nestor/src/handler.rs
dgriffen/rustbot
bf3d500e3801c31aa355c6c51ca87f0da6d4c183
use std::collections::HashMap; use std::future::Future; use std::pin::Pin; use crate::config::Config; use crate::request::Request; use crate::response::{Outcome, Response}; use anyhow::Error; pub(crate) struct CommandRouter { commands: HashMap<&'static str, &'static dyn CommandHandler>, default: Option<&'sta...
use std::collections::HashMap; use std::future::Future; use std::pin::Pin; use crate::config::Config; use crate::request::Request; use crate::response::{Outcome, Response}; use anyhow::Error; pub(crate) struct CommandRouter { commands: HashMap<&'static str, &'static dyn CommandHandler>, default: Option<&'sta...
pub fn from_command_str(source_nick: &'a str, command_str: &str) -> Option<Command<'a>> { let mut parts = command_str.trim().split(' ').map(String::from); let command = parts.next()?; let args = parts.collect(); Some(Command { source_nick, command_str: comma...
1) } }) .nth(0)?; Command::from_command_str(source_nick, command_str) }
function_block-function_prefixed
[ { "content": "pub fn slice_to(slice: &str, mut n: usize) -> &str {\n\n if n >= slice.len() {\n\n return slice;\n\n }\n\n\n\n if !slice.is_char_boundary(n) && n > 0 {\n\n n -= 1;\n\n }\n\n\n\n &slice[..n]\n\n}\n", "file_path": "rustybot/src/commands/windows_error.rs", "rank":...
Rust
src/lib.rs
swidoff/wasm-game-of-life
865be05fa833ec7870f507d466a131585f1bf0ec
extern crate web_sys; use std::fmt; use fixedbitset::FixedBitSet; use itertools::Itertools; use js_sys::Math; use wasm_bindgen::__rt::core::fmt::Formatter; use wasm_bindgen::prelude::*; mod utils; mod timer; use timer::Timer; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee...
extern crate web_sys; use std::fmt; use fixedbitset::FixedBitSet; use itertools::Itertools; use js_sys::Math; use wasm_bindgen::__rt::core::fmt::Formatter; use wasm_bindgen::prelude::*; mod utils; mod timer; use timer::Timer; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee...
c) as usize; let value = img[img_index]; let index = self.get_index((row + r) % self.height, (col + c) % self.width); self.cells[self.i].set(index, value); self.deltas.push(index as u32); } } } pub fn render(&self) -> String {...
let _timer = Timer::new("Universe::tick"); let new_i = (self.i + 1) % 2; for row in 0..self.height { for col in 0..self.width { let idx = self.get_index(row, col); let cell = self.cells[self.i].contains(idx); let live_neighbors = self...
random
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
http/src/request/application/interaction/create_response.rs
oceaann/twilight
2cf4221b5d3c56def8e7083930f901c509d94255
use crate::{ client::Client, error::Error as HttpError, request::{attachment::AttachmentManager, Request, TryIntoRequest}, response::{marker::EmptyBody, ResponseFuture}, routing::Route, }; use twilight_model::{ http::interaction::InteractionResponse, id::{marker::InteractionMarker, Id}, }; ...
use crate::{ client::Client, error::Error as HttpError, request::{attachment::AttachmentManager, Request, TryIntoRequest}, response::{marker::EmptyBody, ResponseFuture}, routing::Route, }; use twilight_model::{ http::interaction::InteractionResponse, id::{marker::InteractionMarker, Id}, }; ...
pub fn exec(self) -> ResponseFuture<EmptyBody> { let http = self.http; match self.try_into_request() { Ok(request) => http.request(request), Err(source) => ResponseFuture::error(source), } } } impl TryIntoRequest for CreateResponse<'_> { fn ...
w( http: &'a Client, interaction_id: Id<InteractionMarker>, interaction_token: &'a str, response: &'a InteractionResponse, ) -> Self { Self { interaction_id, interaction_token, response, http, } }
function_block-function_prefixed
[ { "content": "/// Create a connector with the specified features.\n\npub fn create() -> Connector {\n\n #[cfg(not(feature = \"trust-dns\"))]\n\n let mut connector = hyper::client::HttpConnector::new();\n\n #[cfg(feature = \"trust-dns\")]\n\n let mut connector = hyper_trust_dns::new_trust_dns_http_co...