lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/render_context.rs
setzer22/blackjack
c03db3ac21e9eec19379379185cbafb59ab64885
use std::sync::Arc; use crate::{ prelude::*, rendergraph::{ face_routine::FaceRoutine, grid_routine::GridRoutine, point_cloud_routine::PointCloudRoutine, shader_manager::ShaderManager, wireframe_routine::WireframeRoutine, }, }; use glam::Mat4; use rend3_routine::pbr::PbrRoutine; us...
use std::sync::Arc; use crate::{ prelude::*, rendergraph::{ face_routine::FaceRoutine, grid_routine::GridRoutine, point_cloud_routine::PointCloudRoutine, shader_manager::ShaderManager, wireframe_routine::WireframeRoutine, }, }; use glam::Mat4; use rend3_routine::pbr::PbrRoutine; us...
pub fn clear_objects(&mut self) { self.objects.clear(); self.point_cloud_routine.clear(); self.wireframe_routine.clear(); self.face_routine.clear(); } pub fn add_mesh_as_object<M: r3::Material>(&mut self, mesh: r3::Mesh, material: Option<M>) { let mesh_handle = sel...
x, ); let renderer = r3::Renderer::new( iad, r3::Handedness::Left, Some(window_size.width as f32 / window_size.height as f32), ) .unwrap(); let base_graph = r3::BaseRenderGraph::new(&renderer); let mut data_core = renderer.data_core.l...
function_block-function_prefixed
[ { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn blackjack_viewport_rendergraph<'node>(\n\n graph: &mut r3::RenderGraph<'node>,\n\n ready: &r3::ReadyData,\n\n routines: ViewportRoutines<'node>,\n\n resolution: UVec2,\n\n samples: r3::SampleCount,\n\n ambient: Vec4,\n\n settings:...
Rust
db-migration/src/lib.rs
chuijiaolianying/ckb
04c8effb7c77f9cb86306090c7f7747dc122ada7
use ckb_db::RocksDB; use ckb_error::{Error, InternalErrorKind}; use ckb_logger::info; pub const VERSION_KEY: &[u8] = b"db-version"; fn internal_error(reason: String) -> Error { InternalErrorKind::Database.reason(reason).into() } #[derive(Default)] pub struct Migrations { migrations: Vec<Box<dyn Migration>>, ...
use ckb_db::RocksDB; use ckb_error::{Error, InternalErrorKind}; use ckb_logger::info; pub const VERSION_KEY: &[u8] = b"db-version"; fn internal_error(reason: String) -> Error { InternalErrorKind::Database.reason(reason).into() } #[derive(Default)] pub struct Migrations { migrations: Vec<Box<dyn Migration>>, ...
assert!( vec![2u8, 2, 2, 1].as_slice() == db.get_pinned(COLUMN, &[2, 2]).unwrap().unwrap().as_ref() ); assert_eq!( VERSION.as_bytes(), db.get_pinned_default(VERSION_KEY) .unwrap() ...
t r = migrations.migrate(RocksDB::open(&config, 1)).unwrap(); assert_eq!( b"20191116225943".to_vec(), r.get_pinned_default(VERSION_KEY).unwrap().unwrap().to_vec() ); } { let mut migrations = Migrations::default(); migrations...
random
[ { "content": "/// Return a random path located on temp_dir\n\n///\n\n/// We use `tempdir` only for generating a random path, and expect the corresponding directory\n\n/// that `tempdir` creates be deleted when go out of this function.\n\npub fn temp_path(case_name: &str, id: &str) -> String {\n\n let mut bui...
Rust
src/yabai/events.rs
tami5/yctrl
42c2d615993348220d51dd0a7a9e994ac1c91940
use crate::constants::*; use anyhow::{bail, Error, Result}; use std::fmt; use std::fmt::Debug; #[derive(Debug)] pub enum Event { NotSupported, MissionControl(MissionControlEvent), Window(WindowEvent), Display(DisplayEvent), Space(SpaceEvent), Application(ApplicationEven...
use crate::constants::*; use anyhow::{bail, Error, Result}; use std::fmt; use std::fmt::Debug; #[derive(Debug)] pub enum Event { NotSupported, MissionControl(MissionControlEvent), Window(WindowEvent), Display(DisplayEvent), Space(SpaceEvent), Application(ApplicationEven...
} impl fmt::Display for Event { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Event::NotSupported => write!(f, "Not Supported"), Event::MissionControl(event) => { let phase = if let MissionControlEvent::Enter = event { "...
fn try_from(args: Vec<&str>) -> Result<Self, Error> { let val = args.first().unwrap().as_bytes(); let event = if WINDOW_FOCUSED == val { Self::Window(WindowEvent::Focused { window_id: args.get(1).unwrap().parse::<u32>()?, }) } else if WINDOW_CREA...
function_block-full_function
[ { "content": "#[async_trait]\n\npub trait EventHandler {\n\n async fn handle(&self, state: SharedState) -> Result<()>;\n\n}\n\n\n\n#[async_trait]\n\nimpl EventHandler for Event {\n\n async fn handle(&self, state: SharedState) -> Result<()> {\n\n match self {\n\n Event::Window(e) => e.han...
Rust
src/sys/unix/awakener.rs
Thomasdezeeuw/mio-st
5335e5dd0a7694943b33a24a0a4a1f1b70733cfd
#[cfg(any(target_os = "linux", target_os = "android"))] mod eventfd { use std::fs::File; use std::io::{self, Read, Write}; use std::mem; use std::os::unix::io::FromRawFd; use crate::event; use crate::os::{Interests, RegisterOption}; use crate::sys::Selector; ...
#[cfg(any(target_os = "linux", target_os = "android"))] mod eventfd { use std::fs::File; use std::io::{self, Read, Write}; use std::mem; use std::os::unix::io::FromRawFd; use crate::event; use crate::os::{Interests, RegisterOption}; use crate::sys::Selector; ...
nterests, RegisterOption}; use crate::sys::Selector; use crate::unix::new_pipe; #[derive(Debug)] pub struct Awakener { sender: File, receiver: File, } impl Awakener { pub fn new(selector: &Selector, id: event::Id) -> io::Result<Awakener> { ...
return Err(io::Error::last_os_error()); } selector.register(fd, id, Interests::READABLE, RegisterOption::EDGE)?; Ok(Awakener { fd: unsafe { File::from_raw_fd(fd) }, }) } pub fn try_clone(&self) -> io::Result<Awakener> { ...
random
[ { "content": "/// Initialise the test setup, things like logging etc.\n\npub fn init() {\n\n // Logger could already be set, so we ignore the result.\n\n drop(std_logger::try_init());\n\n}\n\n\n", "file_path": "tests/util/mod.rs", "rank": 0, "score": 143312.86653738492 }, { "content": ...
Rust
src/shader.rs
h3r2tic/notorious6
b128f223934f1c6c52927ad099cbf9ecb7c80572
use anyhow::Context; use bytes::Bytes; use gl::types::*; use relative_path::RelativePathBuf; use shader_prepper::gl_compiler::{compile_shader, ShaderCompilerOutput}; use std::sync::Arc; use std::{ffi::CString, path::PathBuf}; use turbosloth::*; #[derive(Clone, Hash)] pub struct PreprocessShader { pub path: PathBuf...
use anyhow::Context; use bytes::Bytes; use gl::types::*; use relative_path::RelativePathBuf; use shader_prepper::gl_compiler::{compile_shader, ShaderCompilerOutput}; use std::sync::Arc; use std::{ffi::CString, path::PathBuf}; use turbosloth::*; #[derive(Clone, Hash)] pub struct PreprocessShader { pub path: PathBuf...
))?, resolved_path)) } } pub(crate) fn make_shader<'chunk>( gl: &gl::Gl, shader_type: GLenum, sources: impl Iterator<Item = &'chunk shader_prepper::SourceChunk>, ) -> anyhow::Result<u32> { unsafe { let compiled_shader = compile_shader(sources, |sources| { let handle = gl.CreateS...
folder.pop(); folder.join(path).as_str().to_string() }; let blob: Arc<Bytes> = smol::block_on( crate::file::LoadFile::new(&resolved_path) .with_context(|| format!("Failed loading shader include {}", path))? .into_lazy() .eval(&self...
function_block-random_span
[ { "content": "pub fn load_image(file_path: impl AsRef<Path>) -> anyhow::Result<ImageRgb32f> {\n\n let path = file_path.as_ref();\n\n let ext = path\n\n .extension()\n\n .map(|ext| ext.to_string_lossy().as_ref().to_owned());\n\n\n\n match ext.as_deref() {\n\n Some(\"exr\") => load_e...
Rust
src/sdio/tfrmode.rs
pablo-mansanet-bluefruit/efm32gg11b-hal
61a359e544b9dac336f58e51697d248daf658d59
#[doc = "Reader of register TFRMODE"] pub type R = crate::R<u32, super::TFRMODE>; #[doc = "Writer for register TFRMODE"] pub type W = crate::W<u32, super::TFRMODE>; #[doc = "Register TFRMODE `reset()`'s with value 0"] impl crate::ResetValue for super::TFRMODE { type Type = u32; #[inline(always)] fn reset_va...
#[doc = "Reader of register TFRMODE"] pub type R = crate::R<u32, super::TFRMODE>; #[doc = "Writer for register TFRMODE"] pub type W = crate::W<u32, super::TFRMODE>; #[doc = "Register TFRMODE `reset()`'s with value 0"] impl crate::ResetValue for super::TFRMODE { type Type = u32; #[inline(always)] fn reset_va...
} #[doc = "Checks if the value of the field is `NORESP`"] #[inline(always)] pub fn is_noresp(&self) -> bool { *self == RESPTYPESEL_A::NORESP } #[doc = "Checks if the value of the field is `RESP136`"] #[inline(always)] pub fn is_resp136(&self) -> bool { *self == RESPTYPESEL_A::RESP136 } ...
match self.bits { 0 => RESPTYPESEL_A::NORESP, 1 => RESPTYPESEL_A::RESP136, 2 => RESPTYPESEL_A::RESP48, 3 => RESPTYPESEL_A::BUSYAFTRESP, _ => unreachable!(), }
if_condition
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/interactive/interact.rs
nikita-skobov/interactive-term
d9982cdf4fa3feaf17120e26f4c2ebd4bb9a5c3d
use crossterm::{ TerminalCursor, input, InputEvent, KeyEvent, RawScreen, ClearType, Color, Crossterm, }; use std::{thread, io, time::Duration}; use super::super::utils::ListItem; use super::print_list; use super::get_key_char; use super::down_or_up; use super::KeyCharPressed; pub fn in...
use crossterm::{ TerminalCursor, input, InputEvent, KeyEvent, RawScreen, ClearType, Color, Crossterm, }; use std::{thread, io, time::Duration}; use super::super::utils::ListItem; use super::print_list; use super::get_key_char; use super::down_or_up; use super::KeyCharPressed; pub fn in...
?; cursor.goto(0, term_y - 2)?; println!("CTRL-g to quit. CTRL-w to edit"); continue }, KeyCharPressed::Quit => { cursor.show()?; break; }, ...
print_list( &cursor, max_cursor, max_width, out_vec, cursor_offset, cursor_position )
call_expression
[ { "content": "pub fn down_or_up(key_event: InputEvent) -> i32 {\n\n match key_event {\n\n InputEvent::Keyboard(k) => {\n\n match k {\n\n KeyEvent::Ctrl(c) => match c {\n\n 'w' => {\n\n return 254;\n\n },\n\n ...
Rust
cache/in-memory/src/config.rs
dlee13/dawn
3a1443e88bee0abc543b9cc92ed2e5665e685b84
use bitflags::bitflags; bitflags! { #[non_exhaustive] pub struct EventType: u64 { const BAN_ADD = 1; const BAN_REMOVE = 1 << 1; const CHANNEL_CREATE = 1 << 2; const CHANNEL_DELETE = 1 << 3; const CHANNEL_PINS_UPDATE = 1 << 4; const CHANNEL_UPDATE = 1 << 5; ...
use bitflags::bitflags; bitflags! { #[non_exhaustive] pub struct EventType: u64 { const BAN_ADD = 1; const BAN_REMOVE = 1 << 1; const CHANNEL_CREATE = 1 << 2; const CHANNEL_DELETE = 1 << 3; const CHANNEL_PINS_UPDATE = 1 << 4; const CHANNEL_UPDATE = 1 << 5; ...
#[test] fn test_defaults() { let conf = Config { event_types: EventType::all(), message_cache_size: 100, }; let default = Config::default(); assert_eq!(conf.event_types, default.event_types); assert_eq!(conf.message_cache_size, default.message_ca...
VAILABLE_GUILD.bits()); assert_eq!(1 << 29, EventType::USER_UPDATE.bits()); assert_eq!(1 << 30, EventType::VOICE_SERVER_UPDATE.bits()); assert_eq!(1 << 31, EventType::VOICE_STATE_UPDATE.bits()); assert_eq!(1 << 32, EventType::WEBHOOKS_UPDATE.bits()); }
function_block-function_prefixed
[ { "content": "pub fn get_reactions_limit(value: u64) -> bool {\n\n // <https://discordapp.com/developers/docs/resources/channel#get-reactions-query-string-params>\n\n value > 0 && value <= 100\n\n}\n\n\n", "file_path": "http/src/request/validate.rs", "rank": 0, "score": 201818.01856563083 },...
Rust
src/completion.rs
joshmeranda/wrash
c4e5c0adff8403416a3b48d41f4a8ffac530b2c2
use faccess::PathExt; use std::path::{Component, Path, PathBuf}; use glob::{self, PatternError}; fn merge_prefix_with_completion(original_path: &Path, new: &Path) -> Option<PathBuf> { if let Some(first) = original_path.components().next() { if matches!(first, Component::CurDir) { let merged: P...
use faccess::PathExt; use std::path::{Component, Path, PathBuf}; use glob::{self, PatternError}; fn merge_prefix_with_completion(original_path: &Path, new: &Path) -> Option<PathBuf> { if let Some(first) = original_path.components().next() {
pub fn search_prefix(prefix: &Path) -> Result<impl Iterator<Item = PathBuf>, PatternError> { let prefix_path = PathBuf::from(format!("{}*", prefix.to_str().unwrap())); Ok(glob::glob(prefix_path.to_str().unwrap())? .filter_map(Result::ok) .map(move |p| { if let Some(merged) = merge...
if matches!(first, Component::CurDir) { let merged: PathBuf = vec![first.as_os_str(), new.as_os_str()].iter().collect(); return Some(merged); } } None }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let matches = app_from_crate!()\n\n .arg(\n\n Arg::with_name(\"cmd\")\n\n .help(\"the base command for the shell to wrap around\")\n\n .required(true)\n\n .takes_value(true),\n\n )\n\n .arg(\n\n ...
Rust
src/platform/linux.rs
peddermaster2/wry
ecb7a78aa915c0abb3a2fb4617bb350349efc518
use crate::platform::{CALLBACKS, RPC}; use crate::{Dispatcher, Error, Result}; use std::rc::Rc; use gio::Cancellable; use gtk::{ApplicationWindow as Window, ApplicationWindowExt, ContainerExt, WidgetExt}; use webkit2gtk::{ SettingsExt, UserContentInjectedFrames, UserContentManager, UserContentManagerExt, UserScri...
use crate::platform::{CALLBACKS, RPC}; use crate::{Dispatcher, Error, Result}; use std::rc::Rc; use gio::Cancellable; use gtk::{ApplicationWindow as Window, ApplicationWindowExt, ContainerExt, WidgetExt}; use webkit2gtk::{ SettingsExt, UserContentInjectedFrames, UserContentManager, UserContentManagerExt, UserScri...
pub fn add_callback<F>(&self, name: &str, f: F, dispatcher: Dispatcher) where F: FnMut(&Dispatcher, i32, Vec<String>) -> i32 + Send + 'static, { CALLBACKS.lock().unwrap().insert( (self.window_id, name.to_string()), (Box::new(f), dispatcher), ); } pu...
w( js, UserContentInjectedFrames::TopFrame, UserScriptInjectionTime::Start, &[], &[], ); manager.add_script(&script); } else { return Err(Error::InitScriptError); } Ok(()) }
function_block-function_prefixed
[ { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct RPC {\n\n id: i32,\n\n method: String,\n\n params: Vec<String>,\n\n}\n", "file_path": "src/platform/mod.rs", "rank": 0, "score": 76068.22887345844 }, { "content": "fn main() -> Result<()> {\n\n let webview1_attribut...
Rust
egui_glow/src/lib.rs
rasmusgo/egui
6018c0e1944423734e9ec16270f5c2fa01dcd5ea
#![cfg_attr(not(debug_assertions), deny(warnings))] #![deny(unsafe_code)] #![warn( clippy::all, clippy::await_holding_lock, clippy::char_lit_as_u8, clippy::checked_conversions, clippy::dbg_macro, clippy::debug_assert_with_mut_call, clippy::disallowed_method, clippy::doc_markdown, c...
#![cfg_attr(not(debug_assertions), deny(warnings))] #![deny(unsafe_code)] #![warn( clippy::all, clippy::await_holding_lock, clippy::char_lit_as_u8, clippy::checked_conversions, clippy::dbg_macro, clippy::debug_assert_with_mut_call, clippy::disallowed_method, clippy::doc_markdown, c...
pub fn paint( &mut self, gl_window: &glutin::WindowedContext<glutin::PossiblyCurrent>, gl: &glow::Context, shapes: Vec<egui::epaint::ClippedShape>, ) { let clipped_meshes = self.egui_ctx.tessellate(shapes); let dimensions: [u32; 2] = gl_window.window().inner_siz...
window: &glutin::window::Window, run_ui: impl FnMut(&egui::CtxRef), ) -> (bool, Vec<egui::epaint::ClippedShape>) { let raw_input = self.egui_winit.take_egui_input(window); let (egui_output, shapes) = self.egui_ctx.run(raw_input, run_ui); let needs_repaint = egui_output.needs_repaint;...
function_block-function_prefix_line
[ { "content": "/// For use in tests; especially doctests.\n\npub fn __run_test_ctx(mut run_ui: impl FnMut(&CtxRef)) {\n\n let mut ctx = CtxRef::default();\n\n let _ = ctx.run(Default::default(), |ctx| {\n\n run_ui(ctx);\n\n });\n\n}\n\n\n", "file_path": "egui/src/lib.rs", "rank": 0, "...
Rust
cli/ops/runtime.rs
sobolevn/deno
88c4d3145b1e964387be487090bb6ec0a572b90f
use crate::colors; use crate::metrics::Metrics; use crate::permissions::Permissions; use crate::version; use deno_core::error::AnyError; use deno_core::serde_json; use deno_core::serde_json::json; use deno_core::serde_json::Value; use deno_core::ModuleSpecifier; use deno_core::OpState; use deno_core::ZeroCopyBuf; use...
use crate::colors; use crate::metrics::Metrics; use crate::permissions::Permissions; use crate::version; use deno_core::error::AnyError; use deno_core::serde_json; use deno_core::serde_json::json; use deno_core::serde_json::Value; use deno_core::ModuleSpecifier; use deno_core::OpState; use deno_core::ZeroCopyBuf; use...
fn op_main_module( state: &mut OpState, _args: Value, _zero_copy: &mut [ZeroCopyBuf], ) -> Result<Value, AnyError> { let main = state.borrow::<ModuleSpecifier>().to_string(); let main_url = ModuleSpecifier::resolve_url_or_path(&main)?; if main_url.as_url().scheme() == "file" { let main_path = std::env...
e(), "cwd": &env::current_dir().unwrap(), "debugFlag": gs.flags.log_level.map_or(false, |l| l == log::Level::Debug), "denoVersion": version::DENO, "noColor": !colors::use_color(), "pid": std::process::id(), "ppid": ppid(), "target": env!("TARGET"), "tsVersion": version::TYPESCRIPT, "...
function_block-function_prefixed
[ { "content": "fn emit(state: &mut State, args: Value) -> Result<Value, AnyError> {\n\n let v: EmitArgs = serde_json::from_value(args)\n\n .context(\"Invalid request from JavaScript for \\\"op_emit\\\".\")?;\n\n match v.file_name.as_ref() {\n\n \"deno:///.tsbuildinfo\" => state.maybe_tsbuildinfo = Some(v...
Rust
tremor-script/src/utils.rs
Voultapher/tremor-runtime
738f08e5b716826c5c959b4aa6bd4f8c34fde66e
use crate::errors::{Error, ErrorKind, Result}; use crate::prelude::*; use crate::Value; use std::{io::prelude::*, path::Path}; #[must_use] pub fn hostname() -> String { hostname::get() .map_err(|ioe| Error::from(ErrorKind::Io(ioe))) .and_then(|hostname| { hostname.into_string().map_er...
use crate::errors::{Error, ErrorKind, Result}; use crate::prelude::*; use crate::Value; use std::{io::prelude::*, path::Path}; #[must_use]
pub fn sorted_serialize(j: &Value) -> Result<String> { let mut w = Vec::with_capacity(512); sorted_serialize_(j, &mut w)?; Ok(std::str::from_utf8(&w)?.to_string()) } fn sorted_serialize_<'v, W: Write>(j: &Value<'v>, w: &mut W) -> Result<()> { match j { Value::Static(_) | Value::String(_)...
pub fn hostname() -> String { hostname::get() .map_err(|ioe| Error::from(ErrorKind::Io(ioe))) .and_then(|hostname| { hostname.into_string().map_err(|os_string| { ErrorKind::Msg(format!("Invalid hostname: {}", os_string.to_string_lossy())).into() }) }) ...
function_block-full_function
[ { "content": "fn to_pipe(file_name: String, query: &str) -> std::result::Result<(), CompilerError> {\n\n let reg = tremor_script::registry();\n\n let aggr_reg = tremor_script::aggr_registry();\n\n let module_path = tremor_script::path::load();\n\n let cus = vec![];\n\n let q = Query::parse(&modul...
Rust
martian-filetypes/src/tabular_file.rs
martian-lang/martian-rust
f4e16a69cd19c227d0fd853b1b32581c2930a166
use crate::{FileStorage, FileTypeIO, LazyAgents, LazyRead, LazyWrite}; use anyhow::format_err; use martian::{Error, MartianFileType}; use martian_derive::martian_filetype; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::fmt::Debug; use std::io::{Read, Write}; use std::marker::PhantomDat...
use crate::{FileStorage, FileTypeIO, LazyAgents, LazyRead, LazyWrite}; use anyhow::format_err; use martian::{Error, MartianFileType}; use martian_derive::martian_filetype; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::fmt::Debug; use std::io::{Read, Write}; use std::marker::PhantomDat...
#[test] fn test_csv_write() -> Result<(), Error> { let dir = tempfile::tempdir()?; let cells_csv = CsvFile::new(dir.path(), "test"); cells_csv.write(&cells())?; assert_eq!( std::fs::read_to_string(&cells_csv)?, "barcode,genome\nACGT,hg19\nTCAT,mm10\n" ...
fn cells() -> Vec<Cell> { vec![ Cell { barcode: "ACGT".to_string(), genome: "hg19".to_string(), }, Cell { barcode: "TCAT".to_string(), genome: "mm10".to_string(), }, ] }
function_block-full_function
[ { "content": "/// The trait lazy readers need to implement, which lets you read items one by one from a file\n\n/// that stores a list of items\n\npub trait LazyRead<T, R: io::Read>: Sized + Iterator<Item = Result<T, Error>> {\n\n type FileType: MartianFileType;\n\n fn with_reader(reader: R) -> Result<Sel...
Rust
src/delay.rs
rbtcollins/retry
378f42e2b04d3325af6b089d452fa30eb76653f4
use std::time::Duration; use std::u64::MAX as U64_MAX; use rand::{ distributions::{Distribution, Uniform}, random, rngs::ThreadRng, thread_rng, }; #[derive(Debug)] pub struct Exponential { base: u64, current: u64, } impl Exponential { pub fn from_millis(base: u64) -> Self { ...
use std::time::Duration; use std::u64::MAX as U64_MAX; use rand::{ distributions::{Distribution, Uniform}, random, rngs::ThreadRng, thread_rng, }; #[derive(Debug)] pub struct Exponential { base: u64, current: u64, } impl Exponential { pub fn from_millis(base: u64) -> Self { ...
Some(duration) } } #[test] fn fibonacci() { let mut iter = Fibonacci::from_millis(10); assert_eq!(iter.next(), Some(Duration::from_millis(10))); assert_eq!(iter.next(), Some(Duration::from_millis(10))); assert_eq!(iter.next(), Some(Duration::from_millis(20))); assert_eq!(iter.next(), ...
if let Some(next_next) = self.curr.checked_add(self.next) { self.curr = self.next; self.next = next_next; } else { self.curr = self.next; self.next = U64_MAX; }
if_condition
[ { "content": "/// Retry the given operation asynchronously until it succeeds, or until the given Duration iterator ends.\n\npub fn retry<S, I, O, A>(sleep: S, iterable: I, operation: O) -> RetryFuture<S, I, O, A> where S: Sleep, I: IntoIterator<Item = Duration>, A: IntoFuture, O: FnMut() -> A {\n\n RetryFutu...
Rust
nnef/src/deser.rs
mattalhonte/tract
67530c27fb757e116ed3cbcd2ff81cead05aaef2
use crate::ast::*; use crate::internal::*; pub struct ModelBuilder<'a> { pub framework: &'a Nnef, pub registries: Vec<String>, pub model: TypedModel, pub naming_scopes: Vec<String>, pub scopes: Vec<HashMap<String, Value>>, pub proto_model: &'a ProtoModel, } impl<'mb> ModelBuilder<'mb> { pu...
use crate::ast::*; use crate::internal::*; pub struct ModelBuilder<'a> { pub framework: &'a Nnef, pub registries: Vec<String>, pub model: TypedModel, pub naming_scopes: Vec<String>, pub scopes: Vec<HashMap<String, Value>>, pub proto_model: &'a ProtoModel, } impl<'mb> ModelBuilder<'mb> { pu...
self.model.wire_node(name, op, inputs).chain_err(|| format!("inputs are {:?}", inputs)) } } #[derive(Clone)] pub struct ResolvedInvocation<'a> { pub invocation: &'a Invocation, pub default_params: &'a [Parameter], } impl<'a> ResolvedInvocation<'a> { pub fn named_arg_as<T>(&self, builder: &mut...
if inputs.iter().all(|o| self.model.outlet_fact(*o).unwrap().konst.is_some()) { if op.as_op().is_stateless() { let inputs: TVec<Arc<Tensor>> = inputs .iter() .map(|o| self.model.outlet_fact(*o).unwrap().konst.clone().unwrap()) .coll...
if_condition
[ { "content": "pub fn multicast(builder: &mut ModelBuilder, inputs: &[OutletId]) -> TractResult<TVec<OutletId>> {\n\n let ranks = inputs\n\n .iter()\n\n .map(|&i| Ok(builder.model.outlet_fact(i)?.rank()))\n\n .collect::<TractResult<Vec<usize>>>()?;\n\n let max_rank = ranks.iter().copie...
Rust
src/settings.rs
adorton-adobe/frl-online-proxy
e373e476278272fe506fbe88b565e2b96e93513e
/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use crate::cli::FrlProxy; use config::{Config, Environment, File as ConfigFile, FileFormat}; use dialoguer::{Confirm, Input, Pa...
/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use crate::cli::FrlProxy; use config::{Config, Environment, File as ConfigFile, FileFormat}; use dialoguer::{Confirm, Input, Pa...
proxy will log errors, warnings and summary information."); choice = Confirm::new() .default(false) .wait_for_newline(false) .with_prompt("Do you want to adjust the level of logged information?") .interact()?; } ...
default) .with_prompt("Adobe licensing server") .interact()?; self.proxy.remote_host = if choice == 0usize { String::from("https://lcs-cops.adobe.io") } else { String::from("https://lcs-cops-proxy.adobe.com") }; eprintln!("MacOS application...
function_block-random_span
[ { "content": "pub fn init(conf: &Settings) -> Result<()> {\n\n let mut base_config = Dispatch::new().format(|out, message, record| {\n\n out.finish(format_args!(\n\n \"{}[{}][{}] {}\",\n\n chrono::Local::now().format(\"[%Y-%m-%d][%H:%M:%S]\"),\n\n record.target(),\n\n ...
Rust
physx/src/rigid_dynamic.rs
Hentropy/physx-rs
0cf18028a3a2f5d1b63f601a57851282bd720012
#![warn(clippy::all)] /*! Wrapper implementation for PxRigidDynamic */ use crate::{ geometry::Geometry, material::Material, math::PxTransform, owner::Owner, physics::Physics, rigid_actor::RigidActor, rigid_body::RigidBody, traits::{Class, PxFlags, UserData}, }; use enumflags2::BitFl...
#![warn(clippy::all)] /*! Wrapper implementation for PxRigidDynamic */ use crate::{ geometry::Geometry, material::Material, math::PxTransform, owner::Owner, physics::Physics, rigid_actor::RigidActor, rigid_body::RigidBody, traits::{Class, PxFlags, UserData}, }; use enumflags2::BitFl...
safe { PxRigidDynamic_setContactReportThreshold_mut(self.as_mut_ptr(), threshold) } } pub fn set_kinematic_target(&mut self, target: &PxTransform) { unsafe { PxRigidDynamic_setKinematicTarget_mut(self.as_mut_ptr(), target.as_ptr()) } } pub fn set_rigid_dynamic_lock_flag(&mut self, flag: RigidD...
_X, RigidDynamicLockFlag::LockAngularY => PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y, RigidDynamicLockFlag::LockAngularZ => PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z, } } } impl From<PxRigidDynamicLockFlag::Enum> for RigidDynamicLockFlag { fn from(flag: PxRigidDynamicLockFlag::Enum) ...
random
[ { "content": "pub fn PxGeometry_getType(self_: *const PxGeometry, ) -> PxGeometryType::Enum;\n", "file_path": "physx-sys/src/physx_generated.rs", "rank": 0, "score": 290238.49499440764 }, { "content": "pub fn PxActor_getType(self_: *const PxActor, ) -> PxActorType::Enum;\n", "file_path":...
Rust
src/read.rs
lengyijun/rust-snappy
bec32a9cd6cbd7476e30de67bcde49a5c091341a
/*! This module provides two `std::io::Read` implementations: * [`read::FrameDecoder`](struct.FrameDecoder.html) wraps another `std::io::Read` implemenation, and decompresses data encoded using the Snappy frame format. Use this if you have a compressed data source and wish to read it as uncompressed data. * [`re...
/*! This module provides two `std::io::Read` implementations: * [`read::FrameDecoder`](struct.FrameDecoder.html) wraps another `std::io::Read` implemenation, and decompresses data encoded using the Snappy frame format. Use this if you have a compressed data source and wish to read it as uncompressed data. * [`re...
pub fn get_ref(&self) -> &R { &self.r } pub fn get_mut(&mut self) -> &mut R { &mut self.r } } impl<R: io::Read> io::Read for FrameDecoder<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { macro_rules! fail { ($err:expr) =>...
pub fn new(rdr: R) -> FrameDecoder<R> { FrameDecoder { r: rdr, dec: Decoder::new(), checksummer: CheckSummer::new(), src: vec![0; MAX_COMPRESS_BLOCK_SIZE], dst: vec![0; MAX_BLOCK_SIZE], dsts: 0, dste: 0, read_stream_...
function_block-full_function
[ { "content": "/// Decompress the bytes in `src` into `dst`. `dst` must be big enough to\n\n/// hold the the uncompressed size of the bytes in `src`.\n\n///\n\n/// If there was a problem decompressing `src`, an error is returned.\n\npub fn decompress(src: &[u8], dst: &mut [u8]) -> Result<usize, String> {\n\n ...
Rust
examples/stress_tests/bevymark.rs
IyesGames/bevy
97759f36349612146a8cd9835e8a73a9482903d4
use bevy::{ core::FixedTimestep, diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, window::PresentMode, }; use rand::{thread_rng, Rng}; const BIRDS_PER_SECOND: u32 = 10000; const GRAVITY: f32 = -9.8 * 100.0; const MAX_VELOCITY: f32 = 750.; const BIRD_SCALE: f32 = ...
use bevy::{ core::FixedTimestep, diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, window::PresentMode, }; use rand::{thread_rng, Rng}; const BIRDS_PER_SECOND: u32 = 10000; const GRAVITY: f32 = -9.8 * 100.0; const MAX_VELOCITY: f32 = 750.; const BIRD_SCALE: f32 = ...
struct BirdScheduled { wave: usize, per_wave: usize, } fn scheduled_spawner( mut commands: Commands, windows: Res<Windows>, mut scheduled: ResMut<BirdScheduled>, mut counter: ResMut<BevyCounter>, bird_texture: Res<BirdTexture>, ) { if scheduled.wave > 0 { spawn_birds( ...
fn main() { App::new() .insert_resource(WindowDescriptor { title: "BevyMark".to_string(), width: 800., height: 600., present_mode: PresentMode::Immediate, resizable: true, ..default() }) .add_plugins(DefaultPlugins) ...
function_block-full_function
[ { "content": "#[derive(Component, Copy, Clone)]\n\nstruct Velocity<const X: usize>(Vec3);\n\n\n\npub struct Benchmark<'w>(\n\n World,\n\n QueryState<(\n\n &'w Velocity<0>,\n\n &'w mut Position<0>,\n\n &'w Velocity<1>,\n\n &'w mut Position<1>,\n\n &'w Velocity<2>,\n\n ...
Rust
capsules/src/virtual_hmac.rs
kevtan/tock
9eacdb8838872f137914918bbb8dabdef53f6128
use core::cell::Cell; use core::marker::PhantomData; use kernel::common::cells::OptionalCell; use kernel::common::leasable_buffer::LeasableBuffer; use kernel::common::{ListLink, ListNode}; use kernel::hil::digest; use kernel::hil::digest::DigestType; use kernel::ReturnCode; pub struct VirtualMuxHmac<'a, A: digest::D...
use core::cell::Cell; use core::marker::PhantomData; use kernel::common::cells::OptionalCell; use kernel::common::leasable_buffer::LeasableBuffer; use kernel::common::{ListLink, ListNode}; use kernel::hil::digest; use kernel::hil::digest::DigestType; use kernel::ReturnCode; pub struct VirtualMuxHmac<'a, A: digest::D...
phantom: PhantomData, } } }
{ MuxHmac { hmac, running: Cell::new(false), running_id: Cell::new(0), next_id: Cell::new(0),
function_block-random_span
[ { "content": "pub fn encode_u32(buf: &mut [u8], b: u32) -> SResult {\n\n stream_len_cond!(buf, 4);\n\n buf[0] = (b >> 24) as u8;\n\n buf[1] = (b >> 16) as u8;\n\n buf[2] = (b >> 8) as u8;\n\n buf[3] = b as u8;\n\n stream_done!(4);\n\n}\n\n\n", "file_path": "capsules/src/net/stream.rs", ...
Rust
chalk-solve/src/clauses/builtin_traits/unsize.rs
atouchet/chalk
514ca406190c3583b094eb920860a5924cd8197c
use std::collections::HashSet; use std::iter; use std::ops::ControlFlow; use crate::clauses::ClauseBuilder; use crate::rust_ir::AdtKind; use crate::{Interner, RustIrDatabase, TraitRef, WellKnownTrait}; use chalk_ir::{ cast::Cast, interner::HasInterner, visit::{SuperVisit, Visit, Visitor}, Binders, Cons...
use std::collections::HashSet; use std::iter; use std::ops::ControlFlow; use crate::clauses::ClauseBuilder; use crate::rust_ir::AdtKind; use crate::{Interner, RustIrDatabase, TraitRef, WellKnownTrait}; use chalk_ir::{ cast::Cast, interner::HasInterner, visit::{SuperVisit, Visit, Visitor}, Binders, Cons...
fn visit_const(&mut self, constant: &Const<I>, outer_binder: DebruijnIndex) -> ControlFlow<()> { let interner = self.interner; match constant.data(interner).value { ConstValue::BoundVar(bound_var) => { if bound_var.debruijn.shifted_in() == outer_binder ...
ControlFlow::Break(()) } else { ControlFlow::Continue(()) } } _ => ty.super_visit_with(self, outer_binder), } }
function_block-function_prefix_line
[ { "content": "// yields the types \"contained\" in `app_ty`\n\nfn constituent_types<I: Interner>(db: &dyn RustIrDatabase<I>, ty: &TyKind<I>) -> Vec<Ty<I>> {\n\n let interner = db.interner();\n\n\n\n match ty {\n\n // For non-phantom_data adts we collect its variants/fields\n\n TyKind::Adt(ad...
Rust
src/syntax.rs
openstax-poland/smtp-test-server
6ee14f1417b82589efd4e7497d5444d0bf6d4403
use std::{str, ops, borrow::Cow, marker::PhantomData, fmt}; use memchr::memmem; use serde::Serialize; use thiserror::Error; use crate::util; use self::SyntaxError::*; pub type Result<T, E = Located<SyntaxError>> = std::result::Result<T, E>; #[derive(Clone, Copy, Debug, Error, Serialize)] #[error("at {at} - {item}"...
use std::{str, ops, borrow::Cow, marker::PhantomData, fmt}; use memchr::memmem; use serde::Serialize; use thiserror::Error; use crate::util; use self::SyntaxError::*; pub type Result<T, E = Located<SyntaxError>> = std::result::Result<T, E>; #[derive(Clone, Copy, Debug, Error, Serialize)] #[error("at {at} - {item}"...
}) } pub struct ListOf<'a, T> { items: &'a [u8], separator: &'static [u8], _type: PhantomData<&'a [T]>, } impl<'a, T> ListOf<'a, T> { const fn new(separator: &'static [u8], items: &'a [u8]) -> Self { ListOf { items, separator, _type: PhantomData } } pub const fn empty() -> Self {...
if count < min_digits { buf.error(format!("expected at least {} digit{}", min_digits, if min_digits == 1 { "" } else { "s" })) } else { T::try_from(value).map_err(|err| Located::new(buf.location, err.to_string())) }
if_condition
[ { "content": "pub fn string<'a>(buf: &mut Buffer<'a>) -> Result<&'a str> {\n\n // String = Atom / Quoted-string\n\n atom(buf).or_else(|_| quoted_string(buf))\n\n}\n", "file_path": "src/smtp/syntax.rs", "rank": 1, "score": 287775.55512541125 }, { "content": "pub fn quoted_string<'a>(buf...
Rust
noodles-cram/src/reader.rs
natir/noodles
1ab5e60693ede58d800f247cd8ea3f561210e38e
mod container; pub(crate) mod data_container; pub(crate) mod num; pub(crate) mod record; mod records; pub use self::records::Records; use std::{ io::{self, Read, Seek, SeekFrom}, str, }; use byteorder::{LittleEndian, ReadBytesExt}; use noodles_fasta as fasta; use noodles_sam as sam; use self::container::r...
mod container; pub(crate) mod data_container; pub(crate) mod num; pub(crate) mod record; mod records; pub use self::records::Records; use std::{ io::{self, Read, Seek, SeekFrom}, str, }; use byteorder::{LittleEndian, ReadBytesExt}; use noodles_fasta as fasta; use noodles_sam as sam; use self::container::r...
pub fn read_data_container(&mut self) -> io::Result<Option<DataContainer>> { use self::data_container::read_data_container; read_data_container(&mut self.inner) } ...
mut self, ) -> io::Result<Option<(crate::container::Header, DataContainer)>> { use self::data_container::read_data_container_with_container_header; read_data_container_with_container_header(&mut self.inner) }
function_block-function_prefix_line
[ { "content": "pub fn read_block<R>(reader: &mut R) -> io::Result<Block>\n\nwhere\n\n R: Read,\n\n{\n\n let method = reader.read_u8().and_then(|b| {\n\n CompressionMethod::try_from(b).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))\n\n })?;\n\n\n\n let block_content_type_id = reader...
Rust
src/parse.rs
dac-gmbh/quoted-string
b0bdd921d26f3fe5891838143b0473e288fc3e49
use spec::{ScanAutomaton, GeneralQSSpec, PartialCodePoint}; use error::CoreError; pub fn validate<Spec: GeneralQSSpec>(input: &str) -> bool { parse::<Spec>(input) .map(|res|res.tail.is_empty()) .unwrap_or(false) } #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct Parsed<'a> { pub q...
use spec::{ScanAutomaton, GeneralQSSpec, PartialCodePoint}; use error::CoreError; pub fn validate<Spec: GeneralQSSpec>(input: &str) -> bool { parse::<Spec>(input) .map(|res|res.tail.is_empty()) .unwrap_or(false) } #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct Parsed<'a> { pub q...
!("[BUG] automaton.did_end() == false but automaton.end() does not trigger error"), Err(err) => { Err((input.len(), err.into())) } } } #[cfg(test)] mod test { mod parse { use test_utils::*; use error::CoreError; use super::super::parse; #[test] ...
ton.advance(PartialCodePoint::from_utf8_byte(bch)) .map_err(|err| (idx, err.into()))?; if automaton.did_end() { return Ok(Parsed { quoted_string: &input[0..idx + 1], tail: &input[idx + 1..] }) } } mat...
function_block-random_span
[ { "content": "fn iter_eq<I1, I2, E, FN>(mut left: I1, mut right: I2, cmp: FN) -> bool\n\n where I1: Iterator<Item=Result<char, E>>,\n\n I2: Iterator<Item=Result<char, E>>, FN: Fn(char, char) -> bool\n\n{\n\n loop {\n\n match (left.next(), right.next()) {\n\n (None, None) => retu...
Rust
data_types/src/consistent_hasher.rs
jeivardan/influxdb_iox
d6c71bae4fe0fd8af606c6643d7bd461c5d747d1
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct ConsistentHasher<T> where T: Copy + Hash, { ring: Vec<(u64, T)>, } impl<T> ConsistentHasher<T> where T: Copy + Hash, { pub fn new(nodes: &[T]) -> Self { let mut ring:...
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct ConsistentHasher<T> where T: Copy + Hash, { ring: Vec<(u64, T)>, } impl<T> ConsistentHasher<T> where T: Copy + Hash, { pub fn new(nodes: &[T]) -> Self { let mut ring:...
pub fn is_empty(&self) -> bool { self.ring.is_empty() } pub fn len(&self) -> usize { self.ring.len() } fn hash<H: Hash>(h: H) -> u64 { let mut hasher = DefaultHasher::new(); h.hash(&mut hasher); hasher.finish() } } impl<T> From<ConsistentHasher<T>> fo...
sh>(&self, point: H) -> Option<T> { let point_hash = Self::hash(point); self.ring .iter() .find(|(node_hash, _)| node_hash > &point_hash) .or_else(|| self.ring.first()) .map(|(_, node)| *node) }
function_block-function_prefixed
[ { "content": "// Run all benchmarks for `tag_values`.\n\npub fn benchmark_tag_values(c: &mut Criterion) {\n\n let scenarios = Runtime::new().unwrap().block_on(setup_scenarios());\n\n\n\n execute_benchmark_group(c, scenarios.as_slice());\n\n}\n\n\n", "file_path": "server/benches/tag_values.rs", "ra...
Rust
crypto-markets/tests/bitmex.rs
crypto-crawler/crypto-crawler-rs
e13e5493b530a7211479987c8b9209157ebdbaa2
use crypto_market_type::{get_market_types, MarketType}; use crypto_markets::{fetch_markets, fetch_symbols}; use crypto_pair::get_market_type; use test_case::test_case; #[macro_use] mod utils; const EXCHANGE_NAME: &str = "bitmex"; #[test] fn fetch_all_symbols() { gen_all_symbols!(); } #[test] fn fetch_all_symbol...
use crypto_market_type::{get_market_types, MarketType}; use crypto_markets::{fetch_markets, fetch_symbols}; use crypto_pair::get_market_type; use test_case::test_case; #[macro_use] mod utils; const EXCHANGE_NAME: &str = "bitmex"; #[test] fn fetch_all_symbols() { gen_all_symbols!(); } #[test] fn fetch_all_symbol...
MarketType::LinearFuture, get_market_type(symbol, EXCHANGE_NAME, None) ); } } #[test] fn fetch_inverse_swap_markets() { let markets = fetch_markets(EXCHANGE_NAME, MarketType::InverseSwap).unwrap(); assert!(!markets.is_empty()); let xbtusd = markets.iter().find(|m| m.symbol ...
te == "USD" || quote == "USDT"); assert_eq!( MarketType::QuantoFuture, get_market_type(symbol, EXCHANGE_NAME, None) ); } } #[test] fn fetch_linear_future_symbols() { let symbols = fetch_symbols(EXCHANGE_NAME, MarketType::LinearFuture).unwrap(); assert!(!symbols.is_em...
random
[ { "content": "#[test_case(\"BTC-PERPETUAL\")]\n\n#[test_case(\"BTC-30DEC22\")]\n\n#[test_case(\"BTC-29JUL22-20000-C\")]\n\nfn test_trades(symbol: &str) {\n\n let text = DeribitRestClient::fetch_trades(symbol).unwrap();\n\n\n\n let obj = serde_json::from_str::<HashMap<String, Value>>(&text).unwrap();\n\n ...
Rust
src/indexes/index.rs
oebb-digirail/parquet2
37748686c90956a8aeebc11e4cd7c583880ae91a
use std::any::Any; use parquet_format_async_temp::ColumnIndex; use crate::parquet_bridge::BoundaryOrder; use crate::schema::types::PrimitiveType; use crate::{error::Error, schema::types::PhysicalType, types::NativeType}; pub trait Index: Send + Sync + std::fmt::Debug { fn as_any(&self) -> &dyn Any; fn physi...
use std::any::Any; use parquet_format_async_temp::ColumnIndex; use crate::parquet_bridge::BoundaryOrder; use crate::schema::types::PrimitiveType; use crate::{error::Error, schema::types::PhysicalType, types::NativeType}; pub trait Index: Send + Sync + std::fmt::Debug { fn as_any(&self) -> &dyn Any; fn physi...
.collect::<Result<Vec<_>, Error>>()?; Ok(Self { primitive_type, indexes, boundary_order: index.boundary_order.try_into()?, }) } } impl Index for ByteIndex { fn as_any(&self) -> &dyn Any { self } fn physical_type(&self) -> &Physica...
type, indexes, boundary_order: index.boundary_order.try_into()?, }) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct PageIndex<T> { pub min: Option<T>, pub max: Option<T>, pub null_count: Option<i64>, } impl<T: NativeType> Index for NativeIndex...
random
[ { "content": "/// A physical native representation of a Parquet fixed-sized type.\n\npub trait NativeType: std::fmt::Debug + Send + Sync + 'static + Copy + Clone {\n\n type Bytes: AsRef<[u8]> + for<'a> TryFrom<&'a [u8], Error = std::array::TryFromSliceError>;\n\n\n\n fn to_le_bytes(&self) -> Self::Bytes;\...
Rust
src/io/stream/buffer.rs
icostin/halfbit
6d423c74fa07fb6ece29c99737b3e37fb8f1670c
use crate::io::IOResult; use crate::io::IOError; use crate::io::ErrorCode; use crate::ExecutionContext; use super::Read; use super::Write; use super::Seek; use super::SeekFrom; use super::Truncate; use super::relative_position; pub struct BufferAsOnePassROStream<'b> { buffer: &'b [u8], } impl<'b> BufferAsOnePassR...
use crate::io::IOResult; use crate::io::IOError; use crate::io::ErrorCode; use crate::ExecutionContext; use super::Read; use super::Write; use super::Seek; use super::SeekFrom; use super::Truncate; use super::relative_position; pub struct BufferAsOnePassROStream<'b> { buffer: &'b [u8], } impl<'b> BufferAsOnePassR...
nwrap(), 0); } #[test] fn buf_one_pass_ro_no_seek() { let mut f = BufferAsOnePassROStream::new(b"Hello world!"); let mut xc = ExecutionContext::nop(); assert!(f.seek(SeekFrom::Start(0), &mut xc).is_err()); assert!(f.seek(SeekFrom::Current(0), &mut xc).is_err()); asse...
() - pos); buf[0..n].copy_from_slice(&self.buffer[pos..pos + n]); self.position += n as u64; Ok(n) } } impl Seek for BufferAsROStream<'_> { fn seek<'a>( &mut self, target: SeekFrom, _xc: &mut ExecutionContext<'a> ) -> IOResult<'a, u64> { self.position ...
random
[ { "content": "pub fn single_alloc(buffer: &mut [u8]) -> SingleAlloc {\n\n SingleAlloc::new(buffer)\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn name_responds_appropriately() {\n\n let mut buf = [0u8; 7];\n\n let a = SingleAlloc::new(&mut buf);\n\...
Rust
futures-channel/src/oneshot.rs
cjayross/futures-rs
c19d43f750856904ff66e3d06b293185e2729b84
use alloc::sync::Arc; use core::fmt; use core::pin::Pin; use core::sync::atomic::AtomicBool; use core::sync::atomic::Ordering::SeqCst; use futures_core::future::Future; use futures_core::task::{Context, Poll, Waker}; use crate::lock::Lock; #[must_use = "futures do nothing unless you `.await` or poll them"] #[derive...
use alloc::sync::Arc; use core::fmt; use core::pin::Pin; use core::sync::atomic::AtomicBool; use core::sync::atomic::Ordering::SeqCst; use futures_core::future::Future; use futures_core::task::{Context, Poll, Waker}; use crate::lock::Lock; #[must_use = "futures do nothing unless you `.await` or poll them"] #[derive...
fn is_canceled(&self) -> bool { self.complete.load(SeqCst) } fn drop_tx(&self) { self.complete.store(true, Se...
te.load(SeqCst) { return Poll::Ready(()) } let handle = cx.waker().clone(); match self.tx_task.try_lock() { Some(mut p) => *p = Some(handle), ...
function_block-function_prefixed
[ { "content": "#[doc(hidden)]\n\npub fn poll<F: Future + Unpin>(future: F) -> PollOnce<F> {\n\n PollOnce { future }\n\n}\n\n\n\n#[allow(missing_debug_implementations)]\n\n#[doc(hidden)]\n\npub struct PollOnce<F: Future + Unpin> {\n\n future: F,\n\n}\n\n\n\nimpl<F: Future + Unpin> Future for PollOnce<F> {\n...
Rust
src/tools/measure.rs
mariocaiti/glif
6713988bc1e7f0599c5393cc204a6ce16656f975
use glifrenderer::constants::{self, OUTLINE_STROKE_THICKNESS}; use glifrenderer::string::{pointfont_from_size_and_factor, POINTFONTS, POINTFONTSIZE}; use num_traits::float::Float; use skulpin::skia_safe::{ dash_path_effect, AutoCanvasRestore, Canvas, Paint, Path, Point, TextBlob, }; use MFEKmath::Vector; use crate...
use glifrenderer::constants::{self, OUTLINE_STROKE_THICKNESS}; use glifrenderer::string::{pointfont_from_size_and_factor, POINTFONTS, POINTFONTSIZE}; use num_traits::float::Float; use skulpin::skia_safe::{ dash_path_effect, AutoCanvasRestore, Canvas, Paint, Path, Point, TextBlob, }; use MFEKmath::Vector; use crate...
fn draw(&self, _v: &Editor, i: &Interface, canvas: &mut Canvas) { self.draw_line(i, canvas); } } impl Measure { pub fn new() -> Self { Self { measure_from: None } } fn mouse_pressed(&mut self, _v: &Editor, mouse_info: MouseInfo) { self.measure_from = Some(mouse_info.posit...
fn event(&mut self, v: &mut Editor, _i: &mut Interface, event: EditorEvent) { if let EditorEvent::MouseEvent { mouse_info, event_type } = event { match event_type { MouseEventType::Pressed => self.mouse_pressed(v, mouse_info), MouseEventType::Released => self.mouse_re...
function_block-full_function
[ { "content": "pub trait Tool: DynClone + std::fmt::Debug + Send {\n\n fn event(&mut self, v: &mut Editor, i: &mut Interface, event: EditorEvent);\n\n\n\n // We provide empty default implementations for these two because not every tool needs these hooks.\n\n fn draw(&self, _v: &Editor, _i: &Interface, _...
Rust
crates/swc_html_minifier/tests/fixture.rs
iheyunfei/swc
4b340e2c1bfa00f19be5aecceb5c337487030046
#![deny(warnings)] use std::{ fs::read_to_string, path::{Path, PathBuf}, }; use swc_html_ast::Document; use swc_html_codegen::{ writer::basic::{BasicHtmlWriter, BasicHtmlWriterConfig}, CodeGenerator, CodegenConfig, Emit, }; use swc_html_minifier::{minify, option::MinifyOptions}; use swc_html_parser::p...
#![deny(warnings)] use std::{ fs::read_to_string, path::{Path, PathBuf}, }; use swc_html_ast::Document; use swc_html_codegen::{ writer::basic::{BasicHtmlWriter, BasicHtmlWriterConfig}, CodeGenerator, CodegenConfig, Emit, }; use swc_html_minifier::{minify, option::MinifyOptions}; use swc_html_parser::p...
fault::default() }, ); gen.emit(&ss).unwrap(); } NormalizedOutput::from(html_str) .compare_to_file(&output) .unwrap(); Ok(()) }) .unwrap(); if !recovered { panic!( "Parser should emit errors (reco...
function_block-function_prefixed
[]
Rust
edgelet/iotedged/src/settings.rs
darobs/iotedge-k8s
56819518ad8119e3aebd2e25f23e305f6e80dc95
use std::fs::{File as FsFile, OpenOptions}; use std::io::Read; use std::path::{Path, PathBuf}; use base64; use config::{Config, Environment, File, FileFormat}; use edgelet_utils::log_failure; use log::Level; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json; use sha2::{Digest, Sha256}; use url::U...
use std::fs::{File as FsFile, OpenOptions}; use std::io::Read; use std::path::{Path, PathBuf}; use base64; use config::{Config, Environment, File, FileFormat}; use edgelet_utils::log_failure; use log::Level; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json; use sha2::{Digest, Sha256}; use url::U...
time { uri: Url::parse("http://test").unwrap(), network: "".to_string(), }; assert_eq!(DEFAULT_NETWORKID, moby1.network()); let moby2 = MobyRuntime { uri: Url::parse("http://test").unwrap(), network: "some-network".to_string(), }; ...
ertificates(&self) -> Option<&Certificates> { self.certificates.as_ref() } pub fn diff_with_cached(&self, path: PathBuf) -> Result<bool, Error> { OpenOptions::new() .read(true) .open(path) .map_err(Error::from) .and_then(|mut file: FsFile| { ...
random
[ { "content": "fn vol_mount_uri(config: &mut DockerConfig, uris: &[&Url]) -> Result<(), Error> {\n\n let create_options = config.clone_create_options()?;\n\n let host_config = create_options\n\n .host_config()\n\n .cloned()\n\n .unwrap_or_else(HostConfig::new);\n\n let mut binds = h...
Rust
src/libstd/io/net/udp.rs
SiegeLord/rust
4bdda359c3cf41e36ba01ca6aef826aca7cc81c0
use option::{Option, Some, None}; use result::{Ok, Err}; use io::net::ip::SocketAddr; use io::{Reader, Writer}; use io::{io_error, EndOfFile}; use rt::rtio::{RtioSocket, RtioUdpSocket, IoFactory, LocalIo}; pub struct UdpSocket { priv obj: ~RtioUdpSocket } impl UdpSocket { pub fn bind(addr: SocketAddr) -> Op...
use option::{Option, Some, None}; use result::{Ok, Err}; use io::net::ip::SocketAddr; use io::{Reader, Writer}; use io::{io_error, EndOfFile}; use rt::rtio::{RtioSocket, RtioUdpSocket, IoFactory, LocalIo}; pub struct UdpSocket { priv obj: ~RtioUdpSocket } impl UdpSocket { pub fn bind(addr: SocketAddr) -> Op...
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) { match self.obj.sendto(buf, dst) { Ok(_) => (), Err(ioerr) => io_error::cond.raise(ioerr), } } pub fn connect(self, other: SocketAddr) -> UdpStream { UdpStream { socket: self, connectedTo: other } }...
if ioerr.kind != EndOfFile { io_error::cond.raise(ioerr); } None } } }
function_block-function_prefix_line
[ { "content": "#[doc(hidden)]\n\npub fn upperhex(buf: &[u8], f: &mut Formatter) {\n\n let mut local = [0u8, ..16];\n\n for i in ::iter::range(0, buf.len()) {\n\n local[i] = match buf[i] as char {\n\n 'a' .. 'f' => (buf[i] - 'a' as u8) + 'A' as u8,\n\n c => c as u8,\n\n }...
Rust
src/test_dispatcher.rs
lkadalski/minigun
fc48d3fa2c6d69f93896c7682e26eae685026647
use crate::options::{HttpClientType, Options, TargetParameters}; use crate::report_generator::ReportGenerator; use crate::test_runner::{TestRunner, TestStatus}; use async_std::channel::Receiver; use async_std::sync::Arc; use async_std::task; use femme::LevelFilter; use http_client::HttpClient; use itertools::Itertools;...
use crate::options::{HttpClientType, Options, TargetParameters}; use crate::report_generator::ReportGenerator; use crate::test_runner::{TestRunner, TestStatus}; use async_std::channel::Receiver; use async_std::sync::Arc; use async_std::task; use femme::LevelFilter; use http_client::HttpClient; use itertools::Itertools;...
pub fn calculate_duration(&self) -> Duration { self.finish_time.sub(self.start_time) } pub fn stop_timer(&mut self) { self.finish_time = Instant::now(); } } impl Default for TestState { fn default() -> Self { TestState::new(0) } } #[derive(Debug, Serialize)] pub struct...
t_results: vec![], expected_request_count: request_count, start_time: Instant::now(), finish_time: Instant::now(), } }
function_block-function_prefixed
[ { "content": "fn index_of_comma(header: &str) -> Result<usize, CliError> {\n\n match header.find(':') {\n\n None => Err(CliError::ValidationError(\n\n \"Could not find ':' pattern in Header String'\".to_string(),\n\n )),\n\n Some(index) => Ok(index),\n\n }\n\n}\n\n\n\n#[der...
Rust
build.rs
undingen/wasmtime
364300f6cff1ecf779a4f240946fe29237c76ca0
use std::env; use std::fs::{read_dir, DirEntry, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; fn main() { let out_dir = PathBuf::from(env::var("OUT_DIR").expect("The OUT_DIR environment variable must be set")); let mut out = File::create(out_dir.join("wast_testsuite_tests.rs")) ...
use std::env; use std::fs::{read_dir, DirEntry, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; fn main() { let out_dir = PathBuf::from(env::var("OUT_DIR").expect("The OUT_DIR environment variable must be set")); let mut out = File::create(out_dir.join("wast_testsuite_tests.rs")) ...
} fn ignore(testsuite: &str, name: &str) -> bool { if cfg!(windows) { return match (testsuite, name) { ("spec_testsuite", "address") => true, ("spec_testsuite", "align") => true, ("spec_testsuite", "call") => true, ("spec_testsuite", "call_indirect") => true...
match name { "if" => "if_", "loop" => "loop_", "type" => "type_", "const" => "const_", "return" => "return_", other => other, }
if_condition
[ { "content": "#[cfg(test)]\n\nfn native_isa() -> Box<dyn isa::TargetIsa> {\n\n let mut flag_builder = settings::builder();\n\n flag_builder.enable(\"enable_verifier\").unwrap();\n\n\n\n let isa_builder = cranelift_native::builder().unwrap_or_else(|_| {\n\n panic!(\"host machine is not a supporte...
Rust
datafusion/src/physical_plan/crypto_expressions.rs
boaz-codota/arrow-datafusion
00b4a845dc80aee59c1de36c9450f0b8f9ee2f36
use std::sync::Arc; use md5::Md5; use sha2::{ digest::Output as SHA2DigestOutput, Digest as SHA2Digest, Sha224, Sha256, Sha384, Sha512, }; use crate::{ error::{DataFusionError, Result}, scalar::ScalarValue, }; use arrow::{ array::{Array, BinaryArray, GenericStringArray, StringOffsetSizeTrait}, ...
use std::sync::Arc; use md5::Md5; use sha2::{ digest::Output as SHA2DigestOutput, Digest as SHA2Digest, Sha224, Sha256, Sha384, Sha512, }; use crate::{ error::{DataFusionError, Result}, scalar::ScalarValue, }; use arrow::{ array::{Array, BinaryArray, GenericStringArray, StringOffsetSizeTrait}, ...
let array = args[0] .as_any() .downcast_ref::<GenericStringArray<T>>() .ok_or_else(|| { DataFusionError::Internal("failed to downcast to string".to_string()) })?; Ok(array.iter().map(|x| x.map(|x| op(x))).collect()) } fn handle<F, R>(args: &[ColumnarValue], o...
if args.len() != 1 { return Err(DataFusionError::Internal(format!( "{:?} args were supplied but {} takes exactly one argument", args.len(), name, ))); }
if_condition
[ { "content": "fn handle<'a, F, R>(args: &'a [ColumnarValue], op: F, name: &str) -> Result<ColumnarValue>\n\nwhere\n\n R: AsRef<str>,\n\n F: Fn(&'a str) -> R,\n\n{\n\n match &args[0] {\n\n ColumnarValue::Array(a) => match a.data_type() {\n\n DataType::Utf8 => {\n\n Ok(Co...
Rust
libs/datamodel/connectors/sql-datamodel-connector/src/sqlite_datamodel_connector.rs
driimus/prisma-engines
ed52f779924814023825ec5bd164384102dbaecb
use datamodel_connector::{connector_error::ConnectorError, Connector, ConnectorCapability}; use dml::{ field::Field, model::Model, native_type_constructor::NativeTypeConstructor, native_type_instance::NativeTypeInstance, relation_info::ReferentialAction, scalars::ScalarType, }; use enumflags2::BitFlags; use std...
use datamodel_connector::{connector_error::ConnectorError, Connector, ConnectorCapability}; use dml::{ field::Field, model::Model, native_type_constructor::NativeTypeConstructor, native_type_instance::NativeTypeInstance, relation_info::ReferentialAction, scalars::ScalarType, }; use enumflags2::BitFlags; use std...
fn validate_field(&self, _field: &Field) -> Result<(), ConnectorError> { Ok(()) } fn validate_model(&self, _model: &Model) -> Result<(), ConnectorError> { Ok(()) } fn available_native_type_constructors(&self) -> &[NativeTypeConstructor] { &self.constructors } fn ...
fn native_type_is_default_for_scalar_type( &self, _native_type: serde_json::Value, _scalar_type: &ScalarType, ) -> bool { false }
function_block-full_function
[ { "content": "pub fn replace_field_names(target: &mut Vec<String>, old_name: &str, new_name: &str) {\n\n target\n\n .iter_mut()\n\n .map(|v| {\n\n if v == old_name {\n\n *v = new_name.to_string()\n\n }\n\n })\n\n .for_each(drop);\n\n}\n", "...
Rust
src/daemon.rs
vainiovano/swhkd
e8354a42da910d626ac453129fb1fa7208157803
use clap::{arg, Command}; use evdev::{AttributeSet, Device, InputEventKind, Key}; use nix::unistd::{Group, Uid}; use signal_hook_tokio::Signals; use std::{ collections::{HashMap, HashSet}, env, fs, io::prelude::*, os::unix::net::UnixStream, path::Path, process::{exit, id}, }; use sysinfo::{Proce...
use clap::{arg, Command}; use evdev::{AttributeSet, Device, InputEventKind, Key}; use nix::unistd::{Group, Uid}; use signal_hook_tokio::Signals; use std::{ collections::{HashMap, HashSet}, env, fs, io::prelude::*, os::unix::net::UnixStream, path::Path, process::{exit, id}, }; use sysinfo::{Proce...
ne()); hotkey_repeat_timer.as_mut().reset(Instant::now() + Duration::from_millis(repeat_cooldown_duration)); } Some(signal) = signals.next() => { match signal { SIGUSR1 => { paused = true; let key...
loop { select! { _ = &mut hotkey_repeat_timer, if &last_hotkey.is_some() => { let hotkey = last_hotkey.clone().unwrap(); send_command(hotkey.clo
random
[ { "content": "pub fn load_file_contents(path: path::PathBuf) -> Result<String, Error> {\n\n let mut file = File::open(path)?;\n\n let mut contents = String::new();\n\n file.read_to_string(&mut contents)?;\n\n Ok(contents)\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 0, "score": 158...
Rust
src/main.rs
jabwd/Gabby
2cc735bba9750c21c72e2e2d7cdc67b75e45fb26
extern crate dotenv; extern crate base64_stream; mod commands; mod tts; use tts::{ google_tts::*, models::Voice, }; use regex::Regex; use dotenv::dotenv; use std::{env, sync::Arc}; use serenity::client::bridge::voice::ClientVoiceManager; use serenity::{client::Context, prelude::Mutex}; use serenity::{ as...
extern crate dotenv; extern crate base64_stream; mod commands; mod tts; use tts::{ google_tts::*, models::Voice, }; use regex::Regex; use dotenv::dotenv; use std::{env, sync::Arc}; use serenity::client::bridge::voice::ClientVoiceManager; use serenity::{client::Context, prelude::Mutex}; use serenity::{ as...
Ok(()) } async fn handle_tts_message(ctx: &Context, msg: &Message) -> CommandResult { let guild_id = match ctx.cache.guild_channel(msg.channel_id).await { Some(channel) => { channel.guild_id }, None => { check_msg(msg.channel_id.say(&ctx.http, "Error finding ch...
if let Some(handler) = manager.get_mut(guild_id) { let source = match voice::ytdl(&url).await { Ok(source) => source, Err(why) => { println!("Err starting source: {:?}", why); check_msg(msg.channel_id.say(&ctx.http, "Error sourcing ffmpeg").await); ...
if_condition
[ { "content": "use crate::check_msg;\n\nuse crate::ChannelRegistry;\n\nuse serenity::prelude::*;\n\nuse serenity::model::prelude::*;\n\nuse serenity::framework::standard::{\n\n CommandResult,\n\n macros::command,\n\n};\n\n\n\n#[command]\n\nasync fn link(ctx: &Context, msg: &Message) -> CommandResult {\n\n ...
Rust
verdictd/app/src/key_provider/key_provider_grpc.rs
Xynnn007/inclavare-containers
7cfe10dd3e27685eaf6066c65fd5ccd88ba9d72e
use crate::crypto::aes256_cbc; use crate::key_manager::directory_key_manager; use crate::key_provider::annotation; use crate::key_provider::messages::*; use keyProvider::key_provider_service_server::{KeyProviderService, KeyProviderServiceServer}; use keyProvider::{KeyProviderKeyWrapProtocolInput, KeyProviderKeyWrapProt...
use crate::crypto::aes256_cbc; use crate::key_manager::directory_key_manager; use crate::key_provider::annotation; use crate::key_provider::messages::*; use keyProvid
} }; let decrypted_data = serde_json::from_str::<annotation::AnnotationPacket>(&annotation[..]) .and_then(|annotation| { let decrypted_data = directory_key_manager::get_key(&annotation.kid).and_then(|key| { let a = aes2...
er::key_provider_service_server::{KeyProviderService, KeyProviderServiceServer}; use keyProvider::{KeyProviderKeyWrapProtocolInput, KeyProviderKeyWrapProtocolOutput}; use rand::*; use tonic::{transport::Server, Request, Response, Status}; use uuid::Uuid; use base64; pub mod keyProvider { tonic::include_proto!("key...
random
[ { "content": "tls_wrapper_err_t nulltls_use_privkey(tls_wrapper_ctx_t *ctx, enclave_tls_cert_algo_t algo,\n\n\t\t\t\t void *privkey_buf, size_t privkey_len)\n\n{\n\n\tETLS_DEBUG(\"ctx %p, algo %ld, privkey_buf %p, privkey_len %ld\\n\", ctx, algo, privkey_buf,\n\n\t\t privkey_len);\n\n\n\n\treturn TLS_WRA...
Rust
pkg/crate/libzt/src/utils.rs
zkonge/libzt
85d5ffa59154ad3f341d6942f8b787da3178027b
/* * Copyright (c)2013-2021 ZeroTier, Inc. * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file in the project's root directory. * * Change Date: 2026-01-01 * * On the date above, in accordance with the Business Source License, use * of this software will be go...
/* * Copyright (c)2013-2021 ZeroTier, Inc. * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file in the project's root directory. * * Change Date: 2026-01-01 * * On the date above, in accordance with the Business Source License, use * of this software will be go...
pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int, val: c_int) -> io::Result<T> { unsafe { let mut slot: T = mem::zeroed(); let mut len = mem::size_of::<T>() as zts_socklen_t; cvt(zts_bsd_getsockopt( *sock.as_inner(), opt, val, &mut slot a...
cvt(zts_bsd_setsockopt( *sock.as_inner(), opt, val, payload, mem::size_of::<T>() as zts_socklen_t, ))?; Ok(()) } }
function_block-function_prefix_line
[ { "content": "struct zts_hostent* zts_bsd_gethostbyname(const char* name);\n\n\n", "file_path": "include/ZeroTierSockets.h", "rank": 12, "score": 112563.51555184783 }, { "content": "struct zts_hostent* zts_bsd_gethostbyname(const char* name);\n\n\n", "file_path": "pkg/crate/libzt/src/inc...
Rust
rust_package/brainflow/src/ffi/data_handler.rs
Andrey1994/brainflow
6b776859fba6a629b1acd471ae5d1320bffe9ca5
/* automatically generated by rust-bindgen 0.59.1 */ #![allow(non_camel_case_types)] extern "C" { pub fn perform_lowpass( data: *mut f64, data_len: ::std::os::raw::c_int, sampling_rate: ::std::os::raw::c_int, cutoff: f64, order: ::std::os::raw::c_int, filter_type: :...
/* automatically generated by rust-bindgen 0.59.1 */ #![allow(non_camel_case_types)] extern "C" { pub fn perform_lowpass( data: *mut f64, data_len: ::std::os::raw::c_int, sampling_rate: ::std::os::raw::c_int, cutoff: f64, order: ::std::os::raw::c_int, filter_type: :...
) -> ::std::os::raw::c_int; } extern "C" { pub fn get_psd_welch( data: *mut f64, data_len: ::std::os::raw::c_int, nfft: ::std::os::raw::c_int, overlap: ::std::os::raw::c_int, sampling_rate: ::std::os::raw::c_int, window_function: ::std::os::raw::c_int, out...
4, output_d: *mut f64, ) -> ::std::os::raw::c_int; } extern "C" { pub fn get_window( window_function: ::std::os::raw::c_int, window_len: ::std::os::raw::c_int, output_window: *mut f64, ) -> ::std::os::raw::c_int; } extern "C" { pub fn perform_fft( data: *mut f64, ...
random
[ { "content": "/// Detrend data.\n\npub fn detrend(data: &mut [f64], detrend_operation: DetrendOperations) -> Result<()> {\n\n let res = unsafe {\n\n data_handler::detrend(\n\n data.as_mut_ptr() as *mut c_double,\n\n data.len() as c_int,\n\n detrend_operation as c_int,\...
Rust
hphp/hack/src/typing/typing_inference_env.rs
tahmidbintaslim/hhvm
64adfea366cfcd3488bddd4b482d5d9963817db8
use arena_trait::{Arena, TrivialDrop}; use oxidized::ToOxidized; use oxidized_by_ref::aast; use oxidized_by_ref::ident::Ident; use oxidized_by_ref::pos::Pos; use std::collections::BTreeMap; use typing_collections_rust::*; use typing_defs_rust::typing_make_type::TypeBuilder; use typing_defs_rust::*; #[derive(Clone)]...
use arena_trait::{Arena, TrivialDrop}; use oxidized::ToOxidized; use oxidized_by_ref::aast; use oxidized_by_ref::ident::Ident; use oxidized_by_ref::pos::Pos; use std::collections::BTreeMap; use typing_collections_rust::*; use typing_defs_rust::typing_make_type::TypeBuilder; use typing_defs_rust::*; #[derive(Clone)]...
} impl<'a> InferenceEnv<'a> { pub fn new(bld: &'a TypeBuilder) -> Self { InferenceEnv { bld, tvenv: IMap::empty(), tyvars_stack: Vec::new_in(bld.bumpalo()), allow_solve_globals: false, var_id_counter: 0, } } fn new_var_id(&mut se...
fn to_oxidized(&self) -> oxidized::typing_inference_env::TypingInferenceEnv { let InferenceEnv { bld: _, tvenv, tyvars_stack: _, allow_solve_globals, var_id_counter: _, } = self; oxidized::typing_inference_env::TypingInferenceEnv { ...
function_block-function_prefixed
[]
Rust
src/calculate.rs
andete/show_bgs
4089d645c78ba7c6e98e8321aaee5862aec97228
use chrono::{Date, Utc}; use serde_json; use std::collections::{BTreeSet, HashMap}; use std::fs::File; use data; use webdata::*; use data::Government; use Config; pub fn calculate(config: &Config, yesterday: bool) { info!("Calculating data"); let mut system_warnings = HashMap::new(); let wanted_system_...
use chrono::{Date, Utc}; use serde_json; use std::collections::{BTreeSet, HashMap}; use std::fs::File; use data; use webdata::*; use data::Government; use Config; pub fn calculate(config: &Config, yesterday: bool) { info!("Calculating data"); let mut system_warnings = HashMap::new(); let wanted_system_...
Looking at {}...", system_name); let n = format!("{}/systems/{}.json", datadir, system_name); let f = File::open(&n).unwrap(); let s: data::System = serde_json::from_reader(&f).unwrap(); if let Some(d) = s.latest_day() { dates.insert(d); system_dates.push((system_...
function_block-function_prefixed
[ { "content": "pub fn webpage(config:&Config) {\n\n info!(\"Generating webpage.\");\n\n let datadir = config.datadir();\n\n let n = format!(\"{}/report.json\", datadir);\n\n let f = File::open(&n).unwrap();\n\n let systems:Systems = serde_json::from_reader(&f).unwrap();\n\n let templates_fn = f...
Rust
cli/compiler.rs
jasonrey/deno
482b68efdd084b58947613e591d2bc7f9cf0122a
use crate::diagnostics::Diagnostic; use crate::msg; use crate::resources; use crate::startup_data; use crate::state::*; use crate::tokio_util; use crate::worker::Worker; use deno::js_check; use deno::Buf; use futures::Future; use futures::Stream; use std::str; use std::sync::atomic::Ordering; #[derive(Debug, Clone)] ...
use crate::diagnostics::Diagnostic; use crate::msg; use crate::resources; use crate::startup_data; use crate::state::*; use crate::tokio_util; use crate::worker::Worker; use deno::js_check; use deno::Buf; use futures::Future; use futures::Stream; use std::str; use std::sync::atomic::Ordering; #[derive(Debug, Clone)] ...
}
fn test_bundle_async() { let specifier = "./tests/002_hello.ts"; use deno::ModuleSpecifier; let module_name = ModuleSpecifier::resolve_root(specifier) .unwrap() .to_string(); let state = ThreadSafeState::mock(vec![ String::from("./deno"), String::from("./tests/002_hello.ts"), ...
function_block-full_function
[ { "content": "pub fn panic_on_error<I, E, F>(f: F) -> impl Future<Item = I, Error = ()>\n\nwhere\n\n F: Future<Item = I, Error = E>,\n\n E: std::fmt::Debug,\n\n{\n\n f.map_err(|err| panic!(\"Future got unexpected error: {:?}\", err))\n\n}\n", "file_path": "cli/tokio_util.rs", "rank": 0, "score": ...
Rust
lib/rust/ensogl/component/list-view/src/lib.rs
IsaacTell/enso
178cfb0404909ed7b8d45abf1d0951157cc29b78
#![feature(option_result_contains)] #![feature(trait_alias)] #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #![warn(trivial_casts)] #![warn(trivial_numeric_casts)] #![warn(unsafe_code)] #![warn(unused_import_braces)] #![warn(unused_qualifications)] #![recursion_l...
#![feature(option_result_contains)] #![feature(trait_alias)] #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #![warn(trivial_casts)] #![warn(trivial_numeric_casts)] #![warn(unsafe_code)] #![warn(unused_import_braces)] #![warn(unused_qualifications)] #![recursion_l...
fn is_inside(&self, point: Vector2<f32>, size: Vector2<f32>) -> bool { let pos_obj_space = self.app.display.scene().screen_to_object_space(&self.background, point); let x_range = (-size.x / 2.0)..=(size.x / 2.0); let y_range = (-size.y / 2.0)..=(size.y / 2.0); x_ra...
fn visible_entries(View { position_y, size }: &View, entry_count: usize) -> Range<entry::Id> { if entry_count == 0 { 0..0 } else { let entry_at_y_saturating = |y: f32| match entry::List::<E>::entry_at_y_position(y, entry_count) { entry::list::I...
function_block-full_function
[ { "content": "/// Utility method to retrieve the size of the shadow. can be used to determine shape padding etc.\n\npub fn size(style: &StyleWatch) -> f32 {\n\n let parameters = parameters_from_style_path(style, theme::shadow);\n\n parameters.size\n\n}\n\n\n", "file_path": "lib/rust/ensogl/component/s...
Rust
core/node/statedb/src/trie.rs
felix9ia/wingchain
017031cc5381c660fe10751034efc528059065f4
use std::marker::PhantomData; use std::sync::Arc; use fixed_hash::construct_fixed_hash; use hash_db::Hasher; use memory_db::PrefixedKey; use mut_static::MutStatic; use reference_trie::ReferenceNodeCodec; use trie_db::{DBValue, TrieLayout}; use crypto::hash::{Hash, HashImpl}; use crypto::HashLength; use lazy_static:...
use std::marker::PhantomData; use std::sync::Arc; use fixed_hash::construct_fixed_hash; use hash_db::Hasher; use memory_db::PrefixedKey; use mut_static::MutStatic; use reference_trie::ReferenceNodeCodec; use trie_db::{DBValue, TrieLayout}; use crypto::hash::{Hash, HashImpl}; use crypto::HashLength; use lazy_static:...
pub type DefaultTrieDB<'a, H> = trie_db::TrieDB<'a, DefaultTrieLayout<H>>; pub type DefaultTrieDBMut<'a, H> = trie_db::TrieDBMut<'a, DefaultTrieLayout<H>>; pub type DefaultMemoryDB<H> = memory_db::MemoryDB<H, PrefixedKey<H>, DBValue>; pub struct DefaultTrieLayout<H>(PhantomData<H>); impl<H: Hasher> TrieLayout for...
e() == name => {} _ => { return Err(errors::ErrorKind::LoadHasherConflict( HASH_IMPL_32 .read() .map_err(|_| errors::ErrorKind::LoadHasherFail)? .name(), name, ) .into()); } } } } Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn gen_read_opts() -> ReadOptions {\n\n\tlet mut opts = ReadOptions::default();\n\n\topts.set_verify_checksums(false);\n\n\n\n\topts\n\n}\n", "file_path": "core/node/db/src/config.rs", "rank": 0, "score": 184172.74830766412 }, { "content": "pub fn pay_value_read() -> u64 {\...
Rust
test/src/e2e_vm_tests/harness.rs
mohammadfawaz/sway
45250e46d53a0bb7ab94349528e4875b67acf412
use anyhow::{bail, Result}; use forc::test::{ forc_abi_json, forc_build, forc_deploy, forc_run, BuildCommand, DeployCommand, JsonAbiCommand, RunCommand, }; use fuel_tx::Transaction; use fuel_vm::interpreter::Interpreter; use fuel_vm::prelude::*; use serde_json::Value; use std::fs; pub(crate) fn deploy_contract...
use anyhow::{bail, Result}; use forc::test::{ forc_abi_json, forc_build, forc_deploy, forc_run, BuildCommand, DeployCommand, JsonAbiCommand, RunCommand, }; use fuel_tx::Transaction; use fuel_vm::interpreter::Interpreter; use fuel_vm::prelude::*; use serde_json::Value; use std::fs; pub(crate) fn deploy_contract...
pub(crate) fn test_json_abi(file_name: &str) -> Result<()> { let _script = compile_to_json_abi(file_name)?; let manifest_dir = env!("CARGO_MANIFEST_DIR"); let oracle_path = format!( "{}/src/e2e_vm_tests/test_programs/{}/{}", manifest_dir, file_name, "json_abi_oracle.json" ); let ou...
pub(crate) fn compile_to_bytes(file_name: &str) -> Result<Vec<u8>> { println!(" Compiling {}", file_name); let manifest_dir = env!("CARGO_MANIFEST_DIR"); let (verbose, use_ir) = get_test_config_from_env(); forc_build::build(BuildCommand { path: Some(format!( "{}/src/e2e_vm_tests/test...
function_block-full_function
[ { "content": "/// The `pkg::Graph` is of *a -> b* where *a* depends on *b*. We can determine compilation order by\n\n/// performing a toposort of the graph with reversed weights. The resulting order ensures all\n\n/// dependencies are always compiled before their dependents.\n\npub fn compilation_order(graph: &...
Rust
src/subsystem/handle.rs
Trivernis/tokio-graceful-shutdown
2044eb9e380a4c74aefb1c702152768cefed5318
use std::future::Future; use std::sync::Arc; use anyhow::Result; use super::NestedSubsystem; use super::SubsystemData; use super::SubsystemHandle; use crate::runner::SubsystemRunner; use crate::PartialShutdownError; use crate::ShutdownToken; #[cfg(doc)] use crate::Toplevel; impl SubsystemHandle { #[doc(hidden)]...
use std::future::Future; use std::sync::Arc; use anyhow::Result; use super::NestedSubsystem; use super::SubsystemData; use super::SubsystemHandle; use crate::runner::SubsystemRunner; use crate::PartialShutdownError; use crate::ShutdownToken; #[cfg(doc)] use crate::Toplevel; impl SubsystemHandle { #[doc(hidden)]...
let subsystem_handle = SubsystemHandle::new(new_subsystem.clone()); let subsystem_runner = SubsystemRunner::new( name, subsystem_handle.global_shutdown_token().clone(), new_subsystem.local_shutdown_token.clone(), subsystem(subsystem_ha...
let new_subsystem = Arc::new(SubsystemData::new( &name, self.global_shutdown_token().clone(), self.local_shutdown_token().child_token(), ));
assignment_statement
[]
Rust
csml_engine/src/db_connectors/mongodb/bot.rs
rfbatista/csml-engine-fork
2b7754b8bf92d2ee864b3a5ebed7233106cca445
use crate::{ data::{CsmlBotBincode, MongoDbClient, SerializeCsmlBot}, db_connectors::{BotVersion, DbBot}, EngineError, }; use bson::{doc, Document}; use chrono::SecondsFormat; fn format_bot_struct(bot: bson::document::Document) -> Result<DbBot, EngineError> { Ok(DbBot { id: bot.get_object_id("_...
use crate::{ data::{CsmlBotBincode, MongoDbClient, SerializeCsmlBot}, db_connectors::{BotVersion, DbBot}, EngineError, }; use bson::{doc, Document}; use chrono::SecondsFormat; fn format_bot_struct(bot: bson::document::Document) -> Result<DbBot, EngineError> { Ok(DbBot { id: bot.get_object_id("_...
pub fn create_bot_version( bot_id: String, bot: String, db: &MongoDbClient, ) -> Result<String, EngineError> { let collection = db.client.collection::<Document>("bot"); let time = bson::DateTime::from_chrono(chrono::Utc::now()); let bot = doc! { "bot_id": bot_id, "bot": bot, ...
gine_version").unwrap().to_owned(), created_at: bot .get_datetime("created_at") .unwrap() .to_chrono() .to_rfc3339_opts(SecondsFormat::Millis, true), }) }
function_block-function_prefixed
[]
Rust
src/commands/classified.rs
vsaurabh04/nushell
97ef4aeca4831001a92d5b2eed6b6e17a8b00d0b
use crate::parser::{hir, TokenNode}; use crate::prelude::*; use bytes::{BufMut, BytesMut}; use derive_new::new; use futures::stream::StreamExt; use futures_codec::{Decoder, Encoder, Framed}; use log::{log_enabled, trace}; use std::io::{Error, ErrorKind}; use subprocess::Exec; pub struct LinesCodec {} impl Encoder for...
use crate::parser::{hir, TokenNode}; use crate::prelude::*; use bytes::{BufMut, BytesMut}; use derive_new::new; use futures::stream::StreamExt; use futures_codec::{Decoder, Encoder, Framed}; use log::{log_enabled, trace}; use std::io::{Error, ErrorKind}; use subprocess::Exec; pub struct LinesCodec {} impl Encoder for...
} pub(crate) struct ClassifiedInputStream { pub(crate) objects: InputStream, pub(crate) stdin: Option<std::fs::File>, } impl ClassifiedInputStream { pub(crate) fn new() -> ClassifiedInputStream { ClassifiedInputStream { objects: VecDeque::new().into(), stdin: None, ...
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { match src.iter().position(|b| b == &b'\n') { Some(pos) if !src.is_empty() => { let buf = src.split_to(pos + 1); String::from_utf8(buf.to_vec()) .map(Some) ...
function_block-full_function
[ { "content": "#[allow(unused)]\n\npub fn tag_for_tagged_list(mut iter: impl Iterator<Item = Tag>) -> Tag {\n\n let first = iter.next();\n\n\n\n let first = match first {\n\n None => return Tag::unknown(),\n\n Some(first) => first,\n\n };\n\n\n\n let last = iter.last();\n\n\n\n match...
Rust
rust/xaynet-server/src/state_machine/phases/update.rs
little-dude/xain-fl
9c421c03bf1b98c7717593c0856fe856b6f338f7
use std::sync::Arc; use xaynet_core::{ mask::{Aggregation, MaskObject}, LocalSeedDict, SeedDict, SumDict, UpdateParticipantPublicKey, }; use crate::state_machine::{ events::{DictionaryUpdate, MaskLengthUpdate}, phases::{Handler, Phase, PhaseName, PhaseState, Shared, StateError, Sum2}, ...
use std::sync::Arc; use xaynet_core::{ mask::{Aggregation, MaskObject}, LocalSeedDict, SeedDict, SumDict, UpdateParticipantPublicKey, }; use crate::state_machine::{ events::{DictionaryUpdate, MaskLengthUpdate}, phases::{Handler, Phase, PhaseName, PhaseState, Shared, StateError, Sum2}, ...
} impl PhaseState<Update> where Self: Handler + Phase, { async fn process_until_enough(&mut self) -> Result<(), StateError> { while !self.has_enough_updates() { debug!( "{} update messages handled (min {} required)", self.updater_count(), ...
fn next(self) -> Option<StateMachine> { let PhaseState { inner: Update { frozen_sum_dict, seed_dict, model_agg, scalar_agg, }, mut shared, } = self; info!("bro...
function_block-full_function
[ { "content": "/// A trait that must be implemented by a state to handle a request.\n\npub trait Handler {\n\n /// Handles a request.\n\n fn handle_request(&mut self, req: StateMachineRequest) -> Result<(), StateMachineError>;\n\n}\n\n\n\n/// I/O interfaces.\n\n#[derive(Debug)]\n\npub struct IO {\n\n //...
Rust
src/macros.rs
hatoo/glam-rs
029a036ee26329370ce45d722b7a342e2f0225b7
#[cfg(any( all(debug_assertions, feature = "debug-glam-assert"), feature = "glam-assert" ))] macro_rules! glam_assert { ($($arg:tt)*) => ( assert!($($arg)*); ) } #[cfg(not(any( all(debug_assertions, feature = "debug-glam-assert"), feature = "glam-assert" )))] macro_rules! glam_assert { ($($arg:t...
#[cfg(any( all(debug_assertions, feature = "debug-glam-assert"), feature = "glam-assert" ))] macro_rules! glam_assert { ($($arg:tt)*) => ( assert!($($arg)*); ) } #[cfg(not(any( all(debug_assertions, feature = "debug-glam-assert"), feature = "glam-assert" )))] macro_rules! glam_assert { ($($arg:t...
($fx4:expr) => { $crate::const_dmat2!( $crate::cast::DVec4Cast { fx4: $fx4 }.fx2x2[0], $crate::cast::DVec4Cast { fx4: $fx4 }.fx2x2[1] ) }; } #[macro_export] macro_rules! const_dmat3 { ($col0:expr, $col1:expr, $col2:expr) => { unsafe { $crate::cast::...
nst_mat3a { ($col0:expr, $col1:expr, $col2:expr) => { unsafe { $crate::cast::Mat3ACast { v3x3: [ $crate::const_vec3a!($col0), $crate::const_vec3a!($col1), $crate::const_vec3a!($col2), ], } ...
random
[ { "content": "#[inline(always)]\n\nfn dot3_in_x(lhs: v128, rhs: v128) -> v128 {\n\n let x2_y2_z2_w2 = f32x4_mul(lhs, rhs);\n\n let y2_0_0_0 = i32x4_shuffle::<1, 0, 0, 0>(x2_y2_z2_w2, x2_y2_z2_w2);\n\n let z2_0_0_0 = i32x4_shuffle::<2, 0, 0, 0>(x2_y2_z2_w2, x2_y2_z2_w2);\n\n let x2y2_0_0_0 = f32x4_ad...
Rust
artichoke-backend/src/block.rs
b-n/artichoke
af29747df98f72dc6c53f524530ad4ab3bd81182
use std::borrow::Cow; use std::error; use std::fmt; use crate::core::{ClassRegistry, TryConvertMut, Value as _}; use crate::error::{Error, RubyException}; use crate::exception_handler; use crate::extn::core::exception::{Fatal, TypeError}; use crate::sys::{self, protect}; use crate::types::{self, Ruby}; use crate::valu...
use std::borrow::Cow; use std::error; use std::fmt; use crate::core::{ClassRegistry, TryConvertMut, Value as _}; use crate::error::{Error, RubyException}; use crate::exception_handler; use crate::extn::core::exception::{Fatal, TypeError}; use crate::sys::{self, protect}; use crate::types::{self, Ruby}; use crate::valu...
} impl Block { #[must_use] pub fn new(block: sys::mrb_value) -> Option<Self> { if let Ruby::Nil = types::ruby_from_mrb_value(block) { None } else { Some(Self(block)) } } #[must_use] pub const unsafe fn new_unchecked(blo...
fn try_from(value: sys::mrb_value) -> Result<Self, Self::Error> { if let Some(block) = value.into() { Ok(block) } else { Err(NoBlockGiven::from(value)) } }
function_block-full_function
[ { "content": "pub fn ord(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {\n\n let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };\n\n let ord = s.ord().map_err(|err| ArgumentError::with_message(err.message()))?;\n\n Ok(interp.convert(ord))\n\n}\n\n\n", "file_...
Rust
onnx/src/ops/array/mod.rs
kali/tract
c569f283ac4622cef16bd2fca8de6dd11d884250
mod slice; use std::convert::TryInto; use tract_core::internal::*; use tract_core::ops as tractops; use crate::model::OnnxOpRegister; use crate::pb; use crate::pb::NodeProto; use num_traits::AsPrimitive; pub fn register_all_ops(reg: &mut OnnxOpRegister) { reg.insert("Concat", concat); reg.insert("ConstantLi...
mod slice; use std::convert::TryInto; use tract_core::internal::*; use tract_core::ops as tractops; use crate::model::OnnxOpRegister; use crate::pb; use crate::pb::NodeProto; use num_traits::AsPrimitive; pub fn register_all_ops(reg: &mut OnnxOpRegister) { reg.insert("Concat", concat); reg.insert("ConstantLi...
; let shape: Vec<usize> = node.get_attr_vec("shape")?; let tensor = dispatch_numbers!(self::make_const(dt)(&shape, value))?; Ok(Box::new(tractops::konst::Const::new(tensor))) } else { Ok(Box::new(tractops::array::ConstantLike::new(value))) } } pub fn constant_of_shape(node: &Nod...
match node.get_attr_opt("dtype")? { Some(dt) => pb::TensorProto_DataType::from_i32(dt) .ok_or_else(|| { format!("Can not convert integer {} into a TensorProto_DataType", dt) })? .try_into()?, None => f32::datum_type(), }
if_condition
[ { "content": "pub fn tensor_f32(dim:Vec<usize>, values:Vec<f32>) -> tensor::TensorProto {\n\n let mut tensor = tensor::TensorProto::new();\n\n tensor.set_dtype(types::DataType::DT_FLOAT);\n\n let mut shape = tensor_shape::TensorShapeProto::new();\n\n shape.set_dim(dim.into_iter().map(|i| {\n\n ...
Rust
libs/comms-service/tests/util/mod.rs
wau/kubos
074b61738a49ef87fbb08814285fa3173f4f32df
use comms_service::*; use std::cell::RefCell; use std::str; use std::sync::{Arc, Barrier, Mutex}; use std::thread; use warp::{self, Buf, Filter}; #[derive(Debug)] pub struct MockComms { pub read_buff: RefCell<Vec<Vec<u8>>>, pub write_buff: RefCell<Vec<Vec<u8>>>, } impl MockComms { pub fn new() -> Self {...
use comms_service::*; use std::cell::RefCell; use std::str; use std::sync::{Arc, Bar
str::from_utf8(&payload).unwrap().to_owned() }); let service_ip: std::net::SocketAddrV4 = service_ip.parse().unwrap(); thread::spawn(move || warp::serve(routes).run(service_ip)); }
rier, Mutex}; use std::thread; use warp::{self, Buf, Filter}; #[derive(Debug)] pub struct MockComms { pub read_buff: RefCell<Vec<Vec<u8>>>, pub write_buff: RefCell<Vec<Vec<u8>>>, } impl MockComms { pub fn new() -> Self { MockComms { read_buff: RefCell::new(Vec::<Vec<u8>>::with_capacity...
random
[ { "content": "static void test_fails_if_zero_count_used(void **state)\n\n{\n\n (void)state;\n\n expect_function_calls(mock_test_a_called, 0);\n\n\n\n mock_test_a_called();\n", "file_path": "cmocka/cmocka-1.1.0/test_ordering_fail.c", "rank": 0, "score": 38617.85045578367 }, { "conten...
Rust
comms/dht/src/test_utils/store_and_forward_mock.rs
DenisKolodin/tari
f8eeebf63124124722959b79b9238f086b4eddeb
use crate::store_forward::{StoreAndForwardRequest, StoreAndForwardRequester, StoredMessage}; use chrono::Utc; use digest::Digest; use log::*; use rand::{rngs::OsRng, RngCore}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use tari_comms::types::Challenge; use tari_utilities::hex; use tokio::{ ...
use crate::store_forward::{StoreAndForwardRequest, StoreAndForwardRequester, StoredMessage}; use chrono::Utc; use digest::Digest; use log::*; use rand::{rngs::OsRng, RngCore}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use tari_comms::types::Challenge; use tari_utilities::hex; use tokio::{ ...
}, InsertMessage(msg, reply_tx) => { self.state.stored_messages.write().await.push(StoredMessage { id: OsRng.next_u32() as i32, version: msg.version, origin_pubkey: msg.origin_pubkey, message_type: m...
let _ = reply_tx.send(Ok(msgs .clone() .drain(..) .filter(|m| m.stored_at >= since.naive_utc()) .collect()));
assignment_statement
[ { "content": "/// Creates a mock outbound request \"handler\" for testing purposes.\n\n///\n\n/// Each time a request is expected, handle_next should be called.\n\npub fn create_outbound_service_mock(size: usize) -> (OutboundMessageRequester, OutboundServiceMock) {\n\n let (tx, rx) = mpsc::channel(size);\n\n...
Rust
rust/cubestore/cubestore/src/metastore/table.rs
AlbanCrepel/cube.js
49f47a6344889af74a8f3004d3925b2e3ba69535
use super::{ BaseRocksSecondaryIndex, Column, ColumnType, IndexId, RocksSecondaryIndex, RocksTable, TableId, }; use crate::data_frame_from; use crate::metastore::{IdRow, ImportFormat, MetaStoreEvent, Schema}; use crate::rocks_table_impl; use crate::{base_rocks_secondary_index, CubeError}; use byteorder::{BigEndian,...
use super::{ BaseRocksSecondaryIndex, Column, ColumnType, IndexId, RocksSecondaryIndex, RocksTable, TableId, }; use crate::data_frame_from; use crate::metastore::{IdRow, ImportFormat, MetaStoreEvent, Schema}; use crate::rocks_table_impl; use crate::{base_rocks_secondary_index, CubeError}; use byteorder::{BigEndian,...
pub fn is_ready_default() -> bool { true } pub fn created_at(&self) -> &Option<DateTime<Utc>> { &self.created_at } pub fn unique_key_columns(&self) -> Option<Vec<&Column>> { self.unique_key_column_indices .as_ref() .map(|indices| indices.iter().map...
pub fn total_download_size(&self) -> u64 { self.location_download_sizes .as_ref() .map(|sizes| sizes.iter().sum::<u64>()) .unwrap_or(0) }
function_block-full_function
[ { "content": "pub fn new_string_array_with_placeholder(size: usize, default: Option<String>) -> StringArray {\n\n let mut builder = StringBuilder::new(size);\n\n\n\n if let Some(d) = default {\n\n for _ in 0..size {\n\n builder.append_value(d.as_str()).unwrap();\n\n }\n\n } els...
Rust
simple-api/src/lib.rs
Toddez/imgui-wgpu-rs
1f1a9deb22596e2bd1cbad6c50c1a4d095a29451
/*! A simple API to get an imgui context in only a few lines of code. This API only provides stability on a best efforts basis because its meant for small/ temporary projects like if you need to quickly plot something and just need a context do some imgui work. It aims to make updating the wgpu imgui bindings easier ...
/*! A simple API to get an imgui context in only a few lines of code. This API only provides stability on a best efforts basis because its meant for small/ temporary projects like if you need to quickly plot something and just need a context do some imgui work. It aims to make updating the wgpu imgui bindings easier ...
, }]); let renderer_config = RendererConfig { texture_format: surface_desc.format, ..Default::default() }; let mut renderer = Renderer::new(&mut imgui, &device, &queue, renderer_config); let mut last_frame = Instant::now(); let mut last_cursor = None; ...
Some(imgui::FontConfig { oversample_h: 1, pixel_snap_h: true, size_pixels: font_size, ..Default::default() })
call_expression
[ { "content": "struct State {\n\n last_frame: std::time::Instant,\n\n height: f32,\n\n width: f32,\n\n high_dpi_factor: f64,\n\n}\n\n\n", "file_path": "simple-api/examples/fullscreen-simple-api.rs", "rank": 1, "score": 137547.82877194893 }, { "content": "fn main() {\n\n imgui_w...
Rust
src/gen/param/mod.rs
Healer-fuzz/healer-fuzz
89b3bb04150042fc1ccefa186fdf7667921607b2
use super::{context::ProgContext, len}; use crate::model::*; use std::iter::Iterator; use rand::prelude::*; pub mod alloc; pub mod buffer; pub mod scalar; #[derive(Default)] pub(crate) struct GenParamContext { pub(crate) len_type_count: u32, } pub(super) fn gen(ctx: &mut ProgContext, ty: TypeRef, dir: Dir)...
use super::{context::ProgContext, len}; use crate::model::*; use std::iter::Iterator; use rand::prelude::*; pub mod alloc; pub mod buffer; pub mod scalar; #[derive(Default)] pub(crate) struct GenParamContext { pub(crate) len_type_count: u32, } pub(super) fn gen(ctx: &mut ProgContext, ty: TypeRef, dir: Dir)...
y, elem_dir); let addr = ctx.mem_alloc.alloc(elem_val.size(), elem_ty.align); if ty.optional && matches!( elem_ty.kind, TypeKind::Struct { .. } | TypeKind::Union { .. } | TypeKind::Array { .. } ) { ctx.dec_rec_depth(elem_ty); } Value::new(dir, ty,...
elem_ty.kind, TypeKind::Struct { .. } | TypeKind::Union { .. } | TypeKind::Array { .. } ) { let depth = ctx.inc_rec_depth(elem_ty); if depth >= 3 { ctx.dec_rec_depth(elem_ty); return Value::new(dir, ty, ValueKind::new_ptr_null()); } } let ...
function_block-random_span
[ { "content": "pub fn filter_range((min, max): (u64, u64)) -> (u64, u64) {\n\n if min >= max {\n\n (u64::MIN, u64::MAX)\n\n } else {\n\n (min, max)\n\n }\n\n}\n\n\n", "file_path": "src/gen/param/scalar.rs", "rank": 1, "score": 336997.0818207379 }, { "content": "fn gen_b...
Rust
src/test/compile-fail/lint-stability.rs
adevore/rust
edf351e9f7d17777b1385093bfa7b6654e662d44
#[feature(globs)]; #[deny(unstable)]; #[deny(deprecated)]; #[deny(experimental)]; #[allow(dead_code)]; mod cross_crate { extern crate lint_stability; use self::lint_stability::*; fn test() { let foo = MethodTester; deprecated(); foo.method_deprecated(); foo.tr...
#[feature(globs)]; #[deny(unstable)]; #[deny(deprecated)]; #[deny(experimental)]; #[allow(dead_code)]; mod cross_crate { extern crate lint_stability; use self::lint_stability::*; fn test() { let foo = MethodTester; deprecated(); foo.method_deprecated(); foo.tr...
xt(&self) {} #[experimental] fn trait_experimental(&self) {} #[experimental="text"] fn trait_experimental_text(&self) {} #[unstable] fn trait_unstable(&self) {} #[unstable="text"] fn trait_unstable_text(&self) {} fn trait_unmarked(&self) {} ...
0 }; let _ = DeprecatedUnitStruct; let _ = ExperimentalUnitStruct; let _ = UnstableUnitStruct; let _ = UnmarkedUnitStruct; let _ = StableUnitStruct; let _ = FrozenUnitStruct; let _ = LockedUnitStruct; let _ = DeprecatedVariant; let _ = Expe...
random
[]
Rust
src/plugin.rs
neosam/bevy_svg
2e703f97254ff518bf9655a0d745a30f69e7b202
use crate::{Convert, svg::Svg, tessellation, loader::SvgAssetLoader, prelude::Origin}; use bevy::{ app::{App, Plugin}, asset::{AddAsset, Assets, Handle, HandleUntyped}, ecs::{ schedule::{StageLabel, SystemStage}, system::{Query, Res, ResMut} }, reflect::TypeUuid, render::{ ...
use crate::{Convert, svg::Svg, tessellation, loader::SvgAssetLoader, prelude::Origin}; use bevy::{ app::{App, Plugin}, asset::{AddAsset, Assets, Handle, HandleUntyped}, ecs::{ schedule::{StageLabel, SystemStage}, system::{Query, Res, ResMut} }, reflect::TypeUuid, render::{ ...
const VERTEX_SHADER: &str = r#" #version 450 layout(location = 0) in vec3 Vertex_Position; layout(location = 1) in vec4 Vertex_Color; layout(location = 0) out vec4 v_color; layout(set = 0, binding = 0) uniform CameraViewProj { mat4 ViewProj; }; layout(set = 1, binding = 0) uniform Transform { mat4 Model; };...
h event { AssetEvent::Created { handle } | AssetEvent::Modified { handle } => { let bundle = query.iter_mut().filter(|(_, svg, _, _, _)| svg == &handle).next(); if let Some((_, _, mut mesh, origin, mut transform)) = bundle { let svg = svgs.get(handle).unwr...
function_block-function_prefixed
[ { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"twinkle.svg\");\n\n commands.spawn_bundle(PerspectiveCameraBundle::new_3d());\n\n let mut transform = Transform::from_xyz(0.0, 0.0, -1.0);\n\n transform.scale = Vec3...
Rust
crate/yew_styles/src/components/card.rs
philip-peterson/yew_styles
14be67e91668e0d7b169364d8c20d0ca33744d32
use crate::layouts::{ container::{AlignContent, Container, Direction, Mode, Wrap}, item::{Item, ItemLayout}, }; use crate::styles::{get_palette, get_size, get_style, Palette, Size, Style}; use wasm_bindgen_test::*; use yew::prelude::*; use yew::{utils, App}; pub struct Card { link: ComponentLink<Self>, ...
use crate::layouts::{ container::{AlignContent, Container, Direction, Mode, Wrap}, item::{Item, ItemLayout}, }; use crate::styles::{get_palette, get_size, get_style, Palette, Size, Style}; use wasm_bindgen_test::*; use yew::prelude::*; use yew::{utils, App}; pub struct Card { link: ComponentLink<Self>, ...
#[wasm_bindgen_test] fn should_ignore_parts_when_single_content_exist() { let props = Props { ondrag_signal: Callback::noop(), ondragend_signal: Callback::noop(), ondragenter_signal: Callback::noop(), ondragexit_signal: Callback::noop(), ondragleave_signal: Callback::noop()...
gnal: Callback::noop(), draggable: false, header: None, header_size: 4, body: None, body_size: 6, footer: None, footer_size: 2, single_content: Some(html! { <div id="single-content">{"single content"}</div> }), card_palette: Pal...
function_block-function_prefixed
[ { "content": "fn get_items(show: bool, key: String, children: Children) -> Html {\n\n html! {\n\n <ul class=(format!(\"navbar-dropdown-container-{}\", key), if show { \"active\"} else {\"inactive\"})>\n\n {children.clone()}\n\n </ul>\n\n }\n\n}\n\n\n", "file_path": "crate/yew_...
Rust
src/signature.rs
yu-re-ka/ring
f0cad0ad07e2ed4fb0f043e917084dee1a3f1d09
use crate::{cpu, ec, error, sealed}; pub use crate::ec::{ curve25519::ed25519::{ signing::Ed25519KeyPair, verification::{EdDSAParameters, ED25519}, ED25519_PUBLIC_KEY_LEN, }, suite_b::ecdsa::{ signing::{ EcdsaKeyPair, EcdsaSigningAlgorithm, ECDSA_P256_SHA256_AS...
use crate::{cpu, ec, error, sealed}; pub use crate::ec::{ curve25519::ed25519::{ signing::Ed25519KeyPair, verification::{EdDSAParameters, ED25519}, ED25519_PUBLIC_KEY_LEN, }, suite_b::ecdsa::{ signing::{ EcdsaKeyPair, EcdsaSigningAlgorithm, ECDSA_P256_SHA256_AS...
type PublicKey: AsRef<[u8]> + core::fmt::Debug + Clone + Send + Sized + Sync; fn public_key(&self) -> &Self::PublicKey; } pub(crate) const MAX_LEN: usize = 1/*tag:SEQUENCE*/ + 2/*len*/ + (2 * (1/*tag:INTEGER*/ + 1/*len*/ + 1/*zero*/ + ec::SCALAR_MAX_BYTES)); pub trait VerificationAlgorithm: core:...
RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY, RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY, RSA_PKCS1_2048_8192_SHA1_FOR_LEGACY_USE_ONLY, RSA_PKCS1_2048_8192_SHA256, RSA_PKCS1_2048_8192_SHA384, RSA_PKCS1_2048_8192_SHA512, RSA_PKCS1_3072_8192_SHA384, RSA_PSS_2048_8192_SHA256, RSA_P...
random
[ { "content": "/// Verification of an RSA signature encoding as described in\n\n/// [RFC 3447 Section 8].\n\n///\n\n/// [RFC 3447 Section 8]: https://tools.ietf.org/html/rfc3447#section-8\n\npub trait Verification: Padding {\n\n fn verify(\n\n &self,\n\n m_hash: digest::Digest,\n\n m: &mu...
Rust
core/src/mothra_api/api.rs
ajsutton/mothra
84078c2dcd1b0ebc0679b480c5636ea760d07fc2
use clap::ArgMatches; use futures::prelude::*; use std::sync::mpsc as sync; use std::time::{Duration, Instant}; use std::env; use std::process; use std::{thread, time}; use slog::{debug, info, o, warn}; use tokio::runtime::TaskExecutor; use tokio::runtime::Builder; use tokio::timer::Interval; use tokio_timer::clock::Cl...
use clap::ArgMatches; use futures::prelude::*; use std::sync::mpsc as sync; use std::time::{Duration, Instant}; use std::env; use std::process; use std::{thread, time}; use slog::{debug, info, o, warn}; use tokio::runtime::TaskExecutor; use tokio::runtime::Builder; use tokio::timer::Interval; use tokio_timer::clock::Cl...
ics: vec![Topic::new(topic)], message: data,}) .unwrap_or_else(|_| { warn!( log, "Could not send gossip message." ) }); } fn rpc_request( mut network_send: mpsc::UnboundedSender<Netwo...
c::UnboundedSender<NetworkMessage>, topic: String, data: Vec<u8>, log: slog::Logger){ network_send.try_send(NetworkMessage::Publish { top
function_block-random_span
[ { "content": "type FnMapErr<TSocket> = fn(timeout::Error<(RPCError, InboundFramed<TSocket>)>) -> RPCError;\n\n\n\nimpl<TSocket> InboundUpgrade<TSocket> for RPCProtocol\n\nwhere\n\n TSocket: AsyncRead + AsyncWrite,\n\n{\n\n type Output = InboundOutput<TSocket>;\n\n type Error = RPCError;\n\n\n\n type...
Rust
src/eth/ctrl.rs
crawford/efm32gg11b820
390142de0a68b55a142bb16d31634cebf2289209
#[doc = "Reader of register CTRL"] pub type R = crate::R<u32, super::CTRL>; #[doc = "Writer for register CTRL"] pub type W = crate::W<u32, super::CTRL>; #[doc = "Register CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register CTRL"] pub type R = crate::R<u32, super::CTRL>; #[doc = "Writer for register CTRL"] pub type W = crate::W<u32, super::CTRL>; #[doc = "Register CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
} #[doc = "Checks if the value of the field is `NOCLOCK`"] #[inline(always)] pub fn is_noclock(&self) -> bool { *self == TSUCLKSEL_A::NOCLOCK } #[doc = "Checks if the value of the field is `PLL`"] #[inline(always)] pub fn is_pll(&self) -> bool { *self == TSUCLKSEL_A::PLL...
match self.bits { 0 => Val(TSUCLKSEL_A::NOCLOCK), 1 => Val(TSUCLKSEL_A::PLL), 2 => Val(TSUCLKSEL_A::RXCLK), 3 => Val(TSUCLKSEL_A::REFCLK), 4 => Val(TSUCLKSEL_A::TSUEXTCLK), i => Res(i), }
if_condition
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
components/core/src/os/process/windows.rs
bodymindarts/habitat
242310a9a4b09b2df653bdbd486d415d67aa138c
use std::ffi::OsString; use std::path::PathBuf; use std::process::{self, Command}; use std::ptr; use std::io; use time::{Duration, SteadyTime}; use kernel32; use winapi; use error::{Error, Result}; use super::{HabExitStatus, ExitStatusExt, ShutdownMethod}; const STILL_ACTIVE: u32 = 259; pub fn become_command(com...
use std::ffi::OsString; use std::path::PathBuf; use std::process::{self, Command}; use std::ptr; use std::io; use time::{Duration, SteadyTime}; use kernel32; use winapi; use error::{Error, Result}; use super::{HabExitStatus, ExitStatusExt, ShutdownMethod}; const STILL_ACTIVE: u32 = 259; pub fn become_command(com...
pub struct Child { handle: Option<winapi::HANDLE>, last_status: Option<u32>, pid: u32, } impl Child { pub fn new(child: &mut process::Child) -> Result<Child> { let (win_handle, status) = match handle_from_pid(child.id()) { Some(handle) => (Some(handle), Ok...
fn handle_from_pid(pid: u32) -> Option<winapi::HANDLE> { unsafe { let proc_handle = kernel32::OpenProcess(winapi::PROCESS_QUERY_LIMITED_INFORMATION | winapi::PROCESS_TERMINATE, winapi::FALSE, ...
function_block-full_function
[ { "content": "pub fn become_command(command: PathBuf, args: Vec<OsString>) -> Result<()> {\n\n become_exec_command(command, args)\n\n}\n\n\n", "file_path": "components/core/src/os/process/linux.rs", "rank": 1, "score": 363932.7341970798 }, { "content": "/// Makes an `execvp(3)` system cal...
Rust
src/transaction.rs
OneSignal/hyper-client-pool
d521cb9b37b4f82e7dad43e9c2d9381e984ba084
use std::fmt; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::prelude::*; use hyper::client::connect::Connect; use hyper::{self, client::Client, Request}; use hyper::{Body, Response}; use crate::deliverable::Deliverable; use raii_counter::Counter; use tracing::{debug_span, trace, Instrument}; #[...
use std::fmt; use std::sync::Arc; use std::time::{Duration, Instant}; use futures::prelude::*; use hyper::client::connect::Connect; use hyper::{self, client::Client, Request}; use hyper::{Body, Response}; use crate::deliverable::Deliverable; use raii_counter::Counter; use tracing::{debug_span, trace, Instrument}; #[...
; let transaction = Transaction::new( counter.clone(), Request::get(url).body(Body::empty()).unwrap(), false, ); transaction.spawn_request(Arc::clone(&client), Duration::from_secs(2), Counter::new()); } } fn test_hyper...
if i < TIMEOUT_COUNT { "https://httpbin.org/delay/4" } else { "https://httpbin.org/delay/0" }
if_condition
[ { "content": "fn check_successful_result(result: DeliveryResult) -> (bool, DeliveryResult) {\n\n let successful = match result {\n\n DeliveryResult::Response { ref response, .. } => response.status().is_success(),\n\n _ => false,\n\n };\n\n (successful, result)\n\n}\n\n\n", "file_path...
Rust
src/core/msg/content/request/transform.rs
chipsenkbeil/over-there
059a58441f3ec8fe9a371bc8210c956a3be33071
use crate::core::{Reply, Request}; use derive_more::{Display, Error}; use jsonpath_lib as jsonpath; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Debug, Display, Error)] pub enum TransformRequestError { RequestToJsonFailed(serde_json::Error), JsonToRequestFailed(serde_json::Error), ...
use crate::core::{Reply, Request}; use derive_more::{Display, Error}; use jsonpath_lib as jsonpath; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Debug, Display, Error)] pub enum TransformRequestError { RequestToJsonFailed(serde_json::Error), JsonToRequestFailed(serde_json::Error), ...
le(Default::default()); let reply = Reply::FileOpened(FileOpenedArgs { id: 123, sig: 456, ..Default::default() }); let lazy_request = LazilyTransformedRequest { raw_request: raw_request.clone(), rules: vec![TransformRule { ...
&self, reply: &Reply, ) -> Result<Request, TransformRequestError> { let mut value = serde_json::to_value(&self.raw_request) .map_err(TransformRequestError::RequestToJsonFailed)?; let reply_value = serde_json::to_value(reply) .map_err(TransformRequestError::RequestToJ...
random
[ { "content": "// deserializer for io::Errorkind, originally auto-generated by serde-derive\n\npub fn deserialize<'de, D>(\n\n deserializer: D,\n\n) -> serde::export::Result<io::ErrorKind, D::Error>\n\nwhere\n\n D: serde::Deserializer<'de>,\n\n{\n\n #[allow(non_camel_case_types)]\n\n enum Field {\n\n...
Rust
compiler/blir/src/typ/mod.rs
pallyj/boltc
51ef5322a31d14c651ae8f2841a1871c7d13895b
mod struct_; mod enum_; mod case_; use std::{fmt::Debug, hash::Hash, ops::{Deref, DerefMut}, sync::atomic::{AtomicU64, Ordering}}; use errors::Span; use mangle::MangledType; pub use struct_::*; pub use enum_::*; pub use case_::*; use crate::{scope::ScopeRef, Symbol}; static NEXT_INFER_...
mod struct_; mod enum_; mod case_; use std::{fmt::Debug, hash::Hash, ops::{Deref, DerefMut}, sync::atomic::{AtomicU64, Ordering}}; use errors::Span; use mangle::MangledType; pub use struct_::*; pub use enum_::*; pub use case_::*; use crate::{scope::ScopeRef, Symbol}; static NEXT_INFER_...
pub fn mangle(&self) -> MangledType { match self.kind() { TypeKind::Named(_) => MangledType::Void, TypeKind::Member { .. } => panic!(), TypeKind::Infer { .. } => panic!(), TypeKind::Integer { bits: 1 } => MangledType::Integer1, TypeKind::Integer...
e()), params, labels: vec![] } } _ => TypeKind::Function { return_type: Box::new(self.clone()), params: vec![self.clone()], labels: vec...
function_block-function_prefixed
[]
Rust
runebender-lib/src/guides.rs
raphlinus/runebender
f1ae9cf9cf4e91dcc87eaca3cd497413a9051835
use druid::kurbo::{Line, ParamCurve, ParamCurveNearest, Point, Vec2}; use druid::Data; use crate::design_space::{DPoint, DVec2, ViewPort}; use crate::point::EntityId; #[derive(Debug, Clone, Data)] pub struct Guide { pub id: EntityId, pub guide: GuideLine, } #[derive(Debug, Clone, Data)] pub enum GuideLine { ...
use druid::kurbo::{Line, ParamCurve, ParamCurveNearest, Point, Vec2}; use druid::Data; use crate::design_space::{DPoint, DVec2, ViewPort}; use crate::point::EntityId; #[derive(Debug, Clone, Data)] pub struct Guide { pub id: EntityId, pub guide: GuideLine, } #[derive(Debug, Clone, Data)] pub enum GuideLine { ...
let degrees = angle.to_raw().atan2() as f32; norad::Line::Angle { x, y, degrees } } }; norad::Guideline::new(line, None, None, None, None) } }
ide } } pub fn horiz(p1: DPoint) -> Self { Guide::new(GuideLine::Horiz(p1)) } pub fn vertical(p1: DPoint) -> Self { Guide::new(GuideLine::Vertical(p1)) } pub fn angle(p1: DPoint, p2: DPoint) -> Self { Guide::new(GuideLine::Angle { p1, p2 }) } pub fn toggle_ver...
random
[ { "content": "pub fn wrap_in_theme_loader<T: Data>(widget: impl Widget<T>) -> impl Widget<T> {\n\n druid_theme_loader::ThemeLoader::new(THEME_FILE_PATH, MyTheme, widget)\n\n}\n", "file_path": "runebender-lib/src/theme.rs", "rank": 0, "score": 233753.64303154172 }, { "content": "/// Contex...
Rust
src/cobalt_model/site.rs
nott/cobalt.rs
250c792842805dc3531feeac9345aca0c655283d
use std::ffi::OsStr; use std::fs; use std::path; use cobalt_config::DateTime; use failure::ResultExt; use liquid; use serde_json; use serde_yaml; use toml; use crate::error::*; use super::files; #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct Sit...
use std::ffi::OsStr; use std::fs; use std::path; use cobalt_config::DateTime; use failure::ResultExt; use liquid; use serde_json; use serde_yaml; use toml; use crate::error::*; use super::files; #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct Sit...
let data_path = source.join(&self.data_dir); insert_data_dir(&mut data, &data_path)?; if !data.is_empty() { attributes.insert("data".into(), liquid::model::Value::Object(data)); } Ok(attributes) } } fn deep_insert( data_map: &mut liquid::Object, file_path...
(config: cobalt_config::Site) -> Self { let cobalt_config::Site { title, description, base_url, sitemap, data, data_dir, } = config; let base_url = base_url.map(|mut l| { if l.ends_with('/') { le...
random
[ { "content": "#[test]\n\npub fn sitemap() {\n\n test_with_expected(\"sitemap\").expect(\"Build error\");\n\n}\n\n\n", "file_path": "tests/mod.rs", "rank": 1, "score": 194627.76820762167 }, { "content": "pub fn split_ext(name: &str) -> (&str, Option<&str>) {\n\n name.rsplit_once('.')\n\...
Rust
fltk/examples/spreadsheet.rs
tris790/fltk-rs
302c74c911bd24e53ff1ba93ed6c30962ea47c87
use fltk::{ app, draw, enums, input, prelude::{GroupExt, InputExt, TableExt, WidgetBase, WidgetExt}, table, window, }; use std::cell::RefCell; use std::rc::Rc; pub type MyData = Vec<Vec<String>>; #[derive(Default)] struct CellData { row: i32, col: i32, x: i32, y: i32, w: i32, h...
use fltk::{ app, draw, enums, input, prelude::{GroupExt, InputExt, TableExt, WidgetBase, WidgetExt}, table, window, }; use std::cell::RefCell; use std::rc::Rc; pub type MyData = Vec<Vec<String>>; #[derive(Default)] struct CellData { row: i32, col: i32, x: i32, y: i32, w: i32, h...
pub fn redraw(&mut self) { self.table.redraw() } fn draw_header(txt: &str, x: i32, y: i32, w: i32, h: i32) { draw::push_clip(x, y, w, h); draw::draw_box( enums::FrameType::ThinUpBox, x, y, w, h, enums::Color::...
h) } table::TableContext::RowHeader => { Self::draw_header(&format!("{}", row + 1), x, y, w, h) } table::TableContext::Cell => { if t.is_selected(row, col) { cell_c.borrow_mut().select(row, col, x, y, w, h); ...
function_block-function_prefixed
[ { "content": "/// Returns the next window in order\n\npub fn next_window<W: WindowExt>(w: &W) -> Option<impl WindowExt> {\n\n unsafe {\n\n let x = fl::Fl_next_window(w.as_widget_ptr() as *const raw::c_void);\n\n if x.is_null() {\n\n None\n\n } else {\n\n let x = Win...
Rust
src/map/lite_map.rs
dumpmemory/Lightning
a0f4fd8fb20f37eed3b7d7d39ab88472ad9ef024
use super::base::*; use super::word_map::*; use super::*; #[repr(C, align(8))] struct AlignedLiteObj<T> { data: T, _marker: PhantomData<T>, } pub type LiteTable<V, H, ALLOC> = Table<(), (), LiteAttachment<V>, H, ALLOC>; pub struct LiteHashMap< K: Clone + Hash + Eq, V: Clone, ALLOC: GlobalAlloc + ...
use super::base::*; use super::word_map::*; use super::*; #[repr(C, align(8))] struct AlignedLiteObj<T> { data: T, _marker: PhantomData<T>, } pub type LiteTable<V, H, ALLOC> = Table<(), (), LiteAttachment<V>, H, ALLOC>; pub struct LiteHashMap< K: Clone + Hash + Eq, V: Clone, ALLOC: GlobalAlloc + ...
let ptr = &num as *const u64 as *const AlignedLiteObj<V>; unsafe { mem::drop(ptr::read(ptr)) } } } #[cfg(test)] mod lite_tests { use crate::map::*; use std::{alloc::System, sync::Arc}; #[test] fn no_resize() { let _ = env_logger::try_init(); let map = LiteHashMap::<usi...
.len() } #[inline(always)] fn clear(&self) { self.table.clear(); } } pub struct LiteMutexGuard< 'a, K: Clone + Hash + Eq, V: Clone, ALLOC: GlobalAlloc + Default, H: Hasher + Default, > { map: &'a LiteHashMap<K, V, ALLOC, H>, fkey: usize, value: V, } impl<'a, K:...
random
[ { "content": "#[inline(always)]\n\npub fn hash_key<K: Hash, H: Hasher + Default>(key: &K) -> usize {\n\n let mut hasher = H::default();\n\n key.hash(&mut hasher);\n\n hasher.finish() as usize\n\n}\n\n\n", "file_path": "src/map/mod.rs", "rank": 0, "score": 301467.88367682806 }, { "co...
Rust
crates/tx-filter/src/polyjuice_contract_creator_allowlist.rs
sopium/godwoken
70c341ff4e7a4749181adfb57f02e4b45325ddcb
use gw_common::state::State; use gw_common::H256; use gw_config::RPCConfig; use gw_traits::CodeStore; use gw_types::bytes::Bytes; use gw_types::packed::RawL2Transaction; use gw_types::prelude::Unpack; use std::collections::HashSet; #[derive(thiserror::Error, Debug)] pub enum Error { #[error("Permission denied, ca...
use gw_common::state::State; use gw_common::H256; use gw_config::RPCConfig; use gw_traits::CodeStore; use gw_types::bytes::Bytes; use gw_types::packed::RawL2Transaction; use gw_types::prelude::Unpack; use std::collections::HashSet; #[derive(thiserror::Error, Debug)] pub enum Error { #[error("Permission denied, ca...
Unpack::<H256>::unpack(&to_script.code_hash()) == self.polyjuice_code_hash && PolyjuiceArgs::is_contract_create(&Unpack::<Bytes>::unpack(&tx.args())) }; if is_meta_create || is_polyjuice_create { return Err(Error::PermissionDenied { account_id: f...
let to_script = state .get_script(&script_hash) .ok_or(gw_common::error::Error::MissingKey)?;
assignment_statement
[ { "content": "/// build_script_hash_to_account_id_key\n\n/// value format:\n\n/// id(4 bytes) | exists flag(1 byte) | zeros bytes\n\n/// if script_hash is exists the exists flag turn into 1, otherwise it is 0.\n\npub fn build_script_hash_to_account_id_key(script_hash: &[u8]) -> H256 {\n\n let mut key: [u8; 3...
Rust
src/main.rs
HazyAlex/taskbar-twitch
2cc22d125d2df1f6085a7b3760c852c19ac670ca
#![windows_subsystem = "windows"] mod config; use config::OpenStreamUsing; use config::State; mod twitch; use std::path::Path; use std::path::PathBuf; use std::sync::mpsc; use std::sync::Arc; use std::sync::Mutex; use enum_iterator::IntoEnumIterator; use winit::{ event::{Event, WindowEvent}, event_loop::{C...
#![windows_subsystem = "windows"] mod config; use config::OpenStreamUsing; use config::State; mod twitch; use std::path::Path; use std::path::PathBuf; use std::sync::mpsc; use std::sync::Arc; use std::sync::Mutex; use enum_iterator::IntoEnumIterator; use winit::{ event::{Event, WindowEvent}, event_loop::{C...
fn create_players_menu(config: &Arc<Mutex<State>>) -> MenuBuilder<Events> { let mut menu_builder: MenuBuilder<Events> = MenuBuilder::new(); let config = config.lock().unwrap(); for player in OpenStreamUsing::into_enum_iter() { let is_selected = if let Some(session_player) = con...
fn create_channels_menu(config: &Arc<Mutex<State>>) -> MenuBuilder<Events> { let mut menu_builder: MenuBuilder<Events> = MenuBuilder::new(); let config = config.lock().unwrap(); for (index, channel) in config.channels.iter().enumerate() { let mut result = channel.name.to_string(); if chan...
function_block-full_function
[ { "content": "pub fn migrate(config: &Arc<Mutex<State>>, new_config: State) {\n\n let mut local_config = config.lock().unwrap();\n\n\n\n local_config.client = new_config.client.clone();\n\n local_config.secret = new_config.secret.clone();\n\n local_config.player = new_config.player;\n\n local_con...
Rust
src/editorconfig.rs
koyashiro/genec
0a69e8aa117fc48efdce8d2ae617712c8c469f82
use std::fmt; #[allow(dead_code)] #[derive(Debug, PartialEq)] pub enum IndentStyle { Space, Tab, None, } impl fmt::Display for IndentStyle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { IndentStyle::Tab => write!(f, "tab"), IndentStyle::Space => w...
use std::fmt; #[allow(dead_code)] #[derive(Debug, PartialEq)] pub enum IndentStyle { Space, Tab, None, } impl fmt::Display for IndentStyle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { IndentStyle::Tab => write!(f, "tab"), IndentStyle::Space => w...
nal_newline)?; } Ok(()) } } #[allow(dead_code)] #[derive(Debug, PartialEq)] pub struct EditorConfig { pub root: bool, pub configs: Vec<Config>, } #[allow(dead_code)] impl EditorConfig { pub fn new() -> Self { EditorConfig { root: true, configs: vec![], ...
indent_size { writeln!(f)?; write!(f, "indent_size = {}", &indent_size)?; } match self.end_of_line { EndOfLine::None => {} _ => { writeln!(f)?; write!(f, "end_of_line = {}", &self.end_of_line)?; } } ...
function_block-random_span
[ { "content": "fn write_editor_config(w: &mut impl io::Write, editor_config: &EditorConfig) -> Result<()> {\n\n writeln!(w, \"{}\", editor_config)?;\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod genec_test {\n\n use super::*;\n\n\n\n #[test]\n\n fn write_editor_config_test() -> Result<()> {\n\n ...
Rust
src/fiber.rs
slide-rs/bran
0b00f98c474dfe1558dd05f7989efb6c2e8544bd
/* Here is the coroutine(with scheduler) workflow: * * -------------------------------- * -------------------------- | | * | | v | * | ---------------- | ...
/* Here is the coroutine(with scheduler) workflow: * * -------------------------------- * -------------------------- | | * | | v | * | ---------------- | ...
#[inline(always)] pub fn finished(&self) -> bool { match self.state() { State::Finished => true, _ => false } } } struct Parent { context: Context, running: *mut Fiber } thread_local!(static PARENT_CONTEXT: UnsafeCell<*mut Parent> = UnsafeCell::new(pt...
pub fn panicking(&self) -> bool { match self.state() { State::Panicked => true, _ => false } }
function_block-full_function
[ { "content": "/// Spawn a new Fiber\n\n///\n\n/// Equavalent to `Fiber::spawn`.\n\npub fn spawn<F>(f: F) -> Handle\n\n where F: FnOnce() + Send + 'static\n\n{\n\n Builder::new().spawn(f)\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 129535.13538605208 }, { "content": "#[cfg(w...
Rust
rust/datafusion/src/optimizer/projection_push_down.rs
palmerlao/arrow
4e680c46ad5aa76ba1dc85574c4e96a51450364f
use crate::error::{ExecutionError, Result}; use crate::logicalplan::Expr; use crate::logicalplan::LogicalPlan; use crate::optimizer::optimizer::OptimizerRule; use crate::optimizer::utils; use arrow::datatypes::{Field, Schema}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; pub struct ProjectionPushDow...
use crate::error::{ExecutionError, Result}; use crate::logicalplan::Expr; use crate::logicalplan::LogicalPlan; use crate::optimizer::optimizer::OptimizerRule; use crate::optimizer::utils; use arrow::datatypes::{Field, Schema}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; pub struct ProjectionPushDow...
assert_optimized_plan_eq( &projection, "Projection: CAST(#0 AS Float64)\n TableScan: test projection=Some([2])", ); } #[test] fn table_scan_projected_schema() { let table_scan = test_table_scan(); assert_eq!(3, table_scan.schema().fields().len()); ...
: vec![Column(1)], schema: Arc::new(Schema::new(vec![ Field::new("c", DataType::UInt32, false), Field::new("MAX(b)", DataType::UInt32, false), ])), input: Arc::new(table_scan), }; assert_optimized_plan_eq(&aggregate, "Aggregate: groupB...
random
[ { "content": "/// Create field meta-data from an expression, for use in a result set schema\n\npub fn exprlist_to_fields(expr: &Vec<Expr>, input_schema: &Schema) -> Result<Vec<Field>> {\n\n expr.iter()\n\n .map(|e| expr_to_field(e, input_schema))\n\n .collect()\n\n}\n\n\n", "file_path": "ru...
Rust
src/services/sentry.rs
guanqun/sentry
eb7f524dadecb16b3077062dc8b12eb0179b8e06
use crate::{ eth::*, grpc::sentry::{ sentry_server::*, InboundMessage, MessageId as ProtoMessageId, OutboundMessageData, PeerMinBlockRequest, SentPeers, }, CapabilityServerImpl, }; use async_trait::async_trait; use devp2p::*; use futures::{stream::FuturesUnordered, Stream}; use num_trait...
use crate::{ eth::*, grpc::sentry::{ sentry_server::*, InboundMessage, MessageId as ProtoMessageId, OutboundMessageData, PeerMinBlockRequest, SentPeers, }, CapabilityServerImpl, }; use async_trait::async_trait; use devp2p::*; use futures::{stream::FuturesUnordered, Stream}; use num_trait...
}
Result<Response<Self::ReceiveTxMessagesStream>, tonic::Status> { Ok(self.make_channel(|c| &c.tx_message_sender)) }
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\n#[auto_impl(&, Box, Arc)]\n\npub trait CapabilityServer: Send + Sync + 'static {\n\n /// Should be used to set up relevant state for the peer.\n\n fn on_peer_connect(&self, peer: PeerId, caps: HashMap<CapabilityName, CapabilityVersion>);\n\n /// Called on the next event ...
Rust
src/options/session_options_tests.rs
AntonGepting/tmux-interface
7a1dea0ad658e2cb8743311480d207ad1d196a48
#[test] fn show_generated_struct() { use crate::SessionOptions; let _session_options = SessionOptions { ..Default::default() }; } #[test] fn bitflags() { use crate::{SESSION_OPTIONS_ALL, SESSION_OPTIONS_NONE}; let bitflags = 0b_011111111111111111__11111111111111111111...
#[test] fn show_generated_struct() { use crate::SessionOptions; let _session_options = SessionOptions { ..Default::default() }; } #[test]
#[test] #[cfg(feature = "tmux_0_8")] fn activity() { use crate::Activity; assert_eq!(Activity::On.to_string(), "on"); assert_eq!(Activity::Off.to_string(), "off"); #[cfg(feature = "tmux_2_6")] assert_eq!(Activity::Both.to_string(), "both"); } #[test] #[cfg(feature = "tmux_0_8")] fn action() { ...
fn bitflags() { use crate::{SESSION_OPTIONS_ALL, SESSION_OPTIONS_NONE}; let bitflags = 0b_011111111111111111__11111111111111111111111111111111__11111111111111111111111111111111; assert_eq!(bitflags, SESSION_OPTIONS_ALL); assert_eq!(0, SESSION_OPTIONS_NONE); }
function_block-full_function
[ { "content": "#[test]\n\nfn show_generated_struct() {\n\n use crate::Session;\n\n\n\n let _session = Session {\n\n ..Default::default()\n\n };\n\n //dbg!(_session);\n\n}\n\n\n", "file_path": "src/variables/session/session_tests.rs", "rank": 0, "score": 114038.13302766239 }, { ...
Rust
src/graph_iterator.rs
ChengyangLiu/COST
c81d6c3a9901a1feea49b037dce4f9dc9acca8ed
use std::io::Read; use hilbert_curve::BytewiseCached; use typedrw::TypedMemoryMap; pub trait EdgeMapper { fn map_edges(&self, action: impl FnMut(u32, u32)); } pub struct DeltaCompressedReaderMapper<R: Read, F: Fn()->R> { reader: F, } impl<R: Read, F: Fn()->R> DeltaCompressedReaderMapper<R, F> { pub fn ne...
use std::io::Read; use hilbert_curve::BytewiseCached; use typedrw::TypedMemoryMap; pub trait EdgeMapper { fn map_edges(&self, action: impl FnMut(u32, u32)); } pub struct DeltaCompressedReaderMapper<R: Read, F: Fn()->R> { reader: F, } impl<R: Read, F: Fn()->R> DeltaCompressedReaderMapper<R, F> { pub fn ne...
std::io::BufRead, RF: Fn() -> R> EdgeMapper for ReaderMapper<R, RF> { fn map_edges(&self, mut action: impl FnMut(u32, u32)) { let reader = (self.reader)(); for readline in reader.lines() { let line = readline.ok().expect("read error"); if !line.starts_with('#') { ...
ltaCompressedReaderMapper<R, F> { DeltaCompressedReaderMapper { reader: reader, } } } impl<R: Read, F: Fn()->R> EdgeMapper for DeltaCompressedReaderMapper<R, F> { fn map_edges(&self, mut action: impl FnMut(u32, u32)) { let mut hilbert = BytewiseCached::new(); let mu...
random
[ { "content": "#[inline]\n\npub fn decode<R: Read>(reader: &mut R) -> Option<u64> {\n\n if let Ok(mut read) = reader.read_u8() {\n\n let mut count = 0u64;\n\n while read == 0 {\n\n count += 1;\n\n read = reader.read_u8().unwrap();\n\n }\n\n\n\n let mut diff = ...
Rust
src/duo/intersection.rs
Kerollmops/setiter
fae9a7f6ec2e31e7c141ea6966e38ca1f863c300
use std::cmp; use crate::set::Set; use crate::{exponential_offset_ge, SetOperation, Collection}; #[derive(Copy, Clone)] pub struct Intersection<'a, T: 'a> { a: &'a [T], b: &'a [T], } impl<'a, T> Intersection<'a, T> { pub fn new(a: &'a Set<T>, b: &'a Set<T>) -> Self { Self { a: a.a...
use std::cmp; use crate::set::Set; use crate::{exponential_offset_ge, SetOperation, Collection}; #[derive(Copy, Clone)] pub struct Intersection<'a, T: 'a> { a: &'a [T], b: &'a [T], } impl<'a, T> Intersection<'a, T> { pub fn new(a: &'a Set<T>, b: &'a Set<T>) -> Self { Self { a: a.a...
quickcheck! { fn qc_intersection(a: Vec<i32>, b: Vec<i32>) -> bool { use std::collections::BTreeSet; use std::iter::FromIterator; let mut a = a; let mut b = b; sort_dedup_vec(&mut a); sort_dedup_vec(&mut b); let x: SetB...
fn two_slices() { let a = &[1, 2, 3]; let b = &[2, 3, 4]; let intersection_: SetBuf<i32> = Intersection { a: a, b: b }.into_set_buf(); assert_eq!(&intersection_[..], &[2, 3]); }
function_block-full_function
[ { "content": "#[inline]\n\npub fn exponential_search_by_key<T, B, F>(slice: &[T], b: &B, mut f: F) -> Result<usize, usize>\n\nwhere F: FnMut(&T) -> B,\n\n B: Ord\n\n{\n\n exponential_search_by(slice, |k| f(k).cmp(b))\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 202007.04868515...
Rust
tests/support/macros.rs
CAD97/glam-rs
556ff78d1a555dfc218489335142c59aa60b4353
#[macro_export] macro_rules! assert_approx_eq { ($a:expr, $b:expr) => {{ #[allow(unused_imports)] use crate::support::FloatCompare; let eps = core::f32::EPSILON; let (a, b) = (&$a, &$b); assert!( a.approx_eq(b, eps), "assertion failed: `(left !== right...
#[macro_export] macro_rules! assert_approx_eq { ($a:expr, $b:expr) => {{ #[allow(unused_imports)] use crate::support::FloatCompare; let eps = core::f32::EPSILON; let (a, b) = (&$a, &$b); assert!( a.approx_eq(b, eps), "assertion failed: `(left !== right...
$vec3::new(1.0, 1e-15, 0.0), $vec3::new(1.0, 1e-16, 0.0), $vec3::new(0.1, 0.2, 0.3), $vec3::new(0.2, 0.3, 0.4), $vec3::new(4.0, -5.0, 6.0), $vec3::new(-2.0, 0.5, -1.0), $vec3::new(0.00038527316, 0.00038460016, -0.99999988079), ...
assert_eq!(from_x_y(MIN_POSITIVE, 0.0).normalize_or_zero(), $vec::ZERO); assert_eq!(from_x_y(INFINITY, 0.0).normalize_or_zero(), $vec::ZERO); assert_eq!(from_x_y(NAN, 0.0).normalize_or_zero(), $vec::ZERO); assert_eq!(from_x_y(MAX, 0.0).normalize...
random
[ { "content": "#[test]\n\nfn test_ivec4_swizzles() {\n\n let v = ivec4(1_i32, 2_i32, 3_i32, 4_i32);\n\n assert_eq!(v.xxxx(), ivec4(1_i32, 1_i32, 1_i32, 1_i32));\n\n assert_eq!(v.xxxy(), ivec4(1_i32, 1_i32, 1_i32, 2_i32));\n\n assert_eq!(v.xxxz(), ivec4(1_i32, 1_i32, 1_i32, 3_i32));\n\n assert_eq!(...
Rust
src/file.rs
kinshukdua/fat32
e71b6daaf26c197e1ea235817307fd1615d7c9f2
#![feature(nll)] use core::cmp; use block_device::BlockDevice; use crate::bpb::BIOSParameterBlock; use crate::directory_item::DirectoryItem; use crate::fat::FAT; use crate::BUFFER_SIZE; use crate::dir::DirIter; use crate::tool::get_needed_sector; #[derive(Debug)] pub enum FileError { BufTooSmall, WriteError, }...
#![feature(nll)] use core::cmp; use block_device::BlockDevice; use crate::bpb::BIOSParameterBlock; use crate::directory_item::DirectoryItem; use crate::fat::FAT; use crate::BUFFER_SIZE; use crate::dir::DirIter; use crate::tool::get_needed_sector; #[derive(Debug)] pub enum FileError { BufTooSmall, WriteError, }...
}
self.read_count % spc) * BUFFER_SIZE; self.device.read(&mut self.buffer, offset, 1).unwrap(); self.read_count += 1; Some(if self.read_count == self.need_count { (self.buffer, self.left_length) } else { self.left_l...
function_block-function_prefix_line
[ { "content": "/// Define BIOS Parameters\n\n#[derive(Debug, Copy, Clone)]\n\npub struct BIOSParameterBlock {\n\n pub(crate) byte_per_sector: u16,\n\n pub(crate) sector_per_cluster: u8,\n\n pub(crate) reserved_sector: u16,\n\n pub(crate) num_fat: u8,\n\n pub(crate) total_sector: u32,\n\n pub(cr...
Rust
src/main.rs
rcos/observatory-new
62f4f72c022fe592a31dbed80cd41cc73a803786
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate askama; #[macro_use] extern crate diesel; #[doc(hidden)] #[macro_use] extern crate rocket; #[doc(hidden)] #[macro_use] extern crate rocket_contrib; #[macro_use] extern crate rust_embed; #[macro_use] extern crate serde_derive; #[macro_use] extern c...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate askama; #[macro_use] extern crate diesel; #[doc(hidden)] #[macro_use] extern crate rocket; #[doc(hidden)] #[macro_use] extern crate rocket_contrib; #[macro_use] extern crate rust_embed; #[macro_use] extern crate serde_derive; #[macro_use] extern c...
fn main() { Logger::with_env_or_str("info") .print_message() .log_to_file() .directory(LOG_DIR) .add_writer("Audit", audit_writer()) .duplicate_to_stderr(if cfg!(debug_assertions) { flexi_logger::Duplicate::All } else { flexi_logger::Duplicat...
new, event_new_post, signup, signup_post, login, login_post, logout, attend, attend_post, user, user_by_handl...
function_block-function_prefixed
[ { "content": "#[get(\"/attend?<e>\")]\n\npub fn attend(l: UserGuard, e: Option<FormError>) -> AttendTemplate {\n\n AttendTemplate {\n\n logged_in: Some(l.0),\n\n error: e,\n\n }\n\n}\n\n\n\n/// An attendance code\n\n///\n\n/// Used to parse the incoming form in `attend_post`\n\n#[derive(From...
Rust
src/jwt.rs
hildaaaaa/firestore-db-and-auth-rs
9076cbf09b7a1b3956f3e942c6b18be4d8960583
use super::credentials::Credentials; use serde::{Deserialize, Serialize}; use chrono::{Duration, Utc}; use std::collections::HashSet; use std::slice::Iter; use crate::errors::FirebaseError; use biscuit::jwa::SignatureAlgorithm; use biscuit::{ClaimPresenceOptions, SingleOrMultiple, ValidationOptions}; use std::ops:...
use super::credentials::Credentials; use serde::{Deserialize, Serialize}; use chrono::{Duration, Utc}; use std::collections::HashSet; use std::slice::Iter; use crate::errors::FirebaseError; use biscuit::jwa::SignatureAlgorithm; use biscuit::{ClaimPresenceOptions, SingleOrMultiple, ValidationOptions}; use std::ops:...
sence_options: ClaimPresenceOptions { issued_at: Required, not_before: Optional, expiry: Required, issuer: Required, audience: Required, subject: Required, id: Optional, }, ..Default::default() }; let c...
token( credentials: &Credentials, access_token: &str, ) -> Result<TokenValidationResult, Error> { let token = AuthClaimsJWT::new_encoded(&access_token); let header = token.unverified_header()?; let kid = header .registered .key_id .as_ref() .ok_or(FirebaseError::Gene...
random
[ { "content": "///\n\n/// Deletes the document at the given path.\n\n///\n\n/// You cannot use this directly with paths from [`list`] and [`query`] document metadata objects.\n\n/// Those contain an absolute document path. Use [`abs_to_rel`] to convert to a relative path.\n\n///\n\n/// ## Arguments\n\n/// * 'aut...
Rust
src/messaging.rs
ebbflow-io/ebb-client
0f1bfc988bedba7dee93e90e523cdacf1fb13ccb
use std::collections::HashMap; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); #[derive(Debug)] pub enum MessageError { Parse, UnknownMessage, Internal(&'static str), } #[derive(Debug, PartialEq)] pub enum Message { HelloV0(HelloV0), StatusRequestV0, StatusResponseV0(StatusRespo...
use std::collections::HashMap; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); #[derive(Debug)] pub enum MessageError { Parse, UnknownMessage, Internal(&'static str), } #[derive(Debug, PartialEq)] pub enum Message { HelloV0(HelloV0), StatusRequestV0, StatusResponseV0(StatusRespo...
fn message_id(&self) -> u32 { use Message::*; match self { HelloV0(_) => 1, StatusRequestV0 => 2, StatusResponseV0(_) => 3, EnableDisableRequestV0(_) => 4, EnableDisableResponseV0 => 5, HelloResponseV0(_) => 6, Sta...
StatusRequestV0 => vec![], StatusResponseV0(x) => serde_cbor::to_vec(&x)?, EnableDisableRequestV0(x) => serde_cbor::to_vec(&x)?, EnableDisableResponseV0 => vec![], HelloResponseV0(x) => serde_cbor::to_vec(&x)?, StartTrafficV0 => vec![], StartTraffi...
function_block-function_prefixed
[ { "content": "/// PANICS!!\n\npub fn load_private_key(filename: &str) -> PrivateKey {\n\n let rsa_keys = {\n\n let keyfile = fs::File::open(filename).expect(\"cannot open private key file\");\n\n let mut reader = BufReader::new(keyfile);\n\n rustls::internal::pemfile::rsa_private_keys(&m...
Rust
crates/ra_ide_api_light/src/lib.rs
andrew-w-ross/rust-analyzer
6d25f6409ed31fd7015fa4746f18c408ec80f42b
pub mod assists; mod extend_selection; mod folding_ranges; mod line_index; mod line_index_utils; mod structure; #[cfg(test)] mod test_utils; mod join_lines; mod typing; mod diagnostics; pub(crate) mod formatting; pub use self::{ assists::LocalEdit, extend_selection::extend_selection, folding_ranges::{fol...
pub mod assists; mod extend_selection; mod folding_ranges; mod line_index; mod line_index_utils; mod structure; #[cfg(test)] mod test_utils; mod join_lines; mod typing; mod diagnostics; pub(crate) mod formatting; pub use self::{ assists::LocalEdit, extend_selection::extend_selection, folding_ranges::{fol...
pub fn syntax_tree(file: &SourceFile) -> String { ::ra_syntax::utils::dump_tree(file.syntax()) } #[cfg(test)] mod tests { use ra_syntax::AstNode; use insta::assert_debug_snapshot_matches; use crate::test_utils::{add_cursor, assert_eq_text, extract_offset}; use super::*; #[test] fn test...
d(), _ => (), } } res.push(HighlightedRange { range: TextRange::from_to(range_start, range_end), tag: "macro...
function_block-function_prefixed
[ { "content": "/// Extracts ranges, marked with `<tag> </tag>` paris from the `text`\n\npub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) {\n\n let open = format!(\"<{}>\", tag);\n\n let close = format!(\"</{}>\", tag);\n\n let mut ranges = Vec::new();\n\n let mut res = Str...
Rust
src/datatypes/field.rs
abreis/arrow2
982454620d1db7964a4e272b3f74745563b6ba5a
use std::collections::BTreeMap; use crate::error::{ArrowError, Result}; use super::DataType; #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Field { pub(super) name: String, pub(super) data_type: DataType, pub(super) nullable: bool, pub(super) dict_id: i64, pub(super) d...
use std::collections::BTreeMap; use crate::error::{ArrowError, Result}; use super::DataType; #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Field { pub(super) name: String, pub(super) data_type: DataType, pub(super) nullable: bool, pub(super) dict_id: i64, pub(super) d...
pub fn new_dict( name: &str, data_type: DataType, nullable: bool, dict_id: i64, dict_is_ordered: bool, ) -> Self { Field { name: name.to_string(), data_type, nullable, dict_id, dict_is_ordered, ...
pub fn new(name: &str, data_type: DataType, nullable: bool) -> Self { Field { name: name.to_string(), data_type, nullable, dict_id: 0, dict_is_ordered: false, metadata: None, } }
function_block-full_function
[ { "content": "/// Parse a `metadata` definition from a JSON representation.\n\n/// The JSON can either be an Object or an Array of Objects.\n\nfn from_metadata(json: &Value) -> Result<HashMap<String, String>, ArrowError> {\n\n match json {\n\n Value::Array(_) => {\n\n let mut hashmap = Hash...
Rust
src/rust/generators/sysmon-generator/src/models/mod.rs
grapl-security/grapl
24caa7fb4424645495d99fb338e2231fc4f66712
use chrono::{ DateTime, NaiveDateTime, Utc, }; use rust_proto::graph_descriptions::*; use sysmon::Event; use crate::generator::SysmonGeneratorError; mod file; mod network; mod process; pub(crate) trait SysmonTryFrom<T>: Sized { type Error; fn try_from(instance: T) -> Result<Self, Self::Error>; }...
use chrono::{ DateTime, NaiveDateTime, Utc, }; use rust_proto::graph_descriptions::*; use sysmon::Event; use crate::generator::SysmonGeneratorError; mod file; mod network; mod process; pub(crate) trait SysmonTryFrom<T>: Sized { type Error; fn try_from(instance: T) -> Result<Self, Self::Error>; }...
} fn strip_file_zone_identifier(path: &str) -> &str { if path.ends_with(":Zone.Identifier") { &path[0..path.len() - ":Zone.Identifier".len()] } else { path } } fn get_image_name(image_path: &str) -> Option<String> { image_path .split('\\') .last() .map(|name| n...
t => { let message = format!("Unsupported event_type: {:?}", unsupported_event); tracing::warn!(message =% message); Err(SysmonGeneratorError::UnsupportedEventType(get_event_type( unsupported_event, ))) } } }
function_block-function_prefixed
[ { "content": "fn get_proto_files(path: &str, paths: &mut Vec<String>) -> Result<(), Box<dyn std::error::Error>> {\n\n for entry in std::fs::read_dir(path)? {\n\n let entry = entry?;\n\n if entry.metadata()?.is_file() {\n\n if let Some(\"proto\") = entry.path().extension().and_then(Os...
Rust
src/testdrive/src/lib.rs
xudong963/materialize
6f3b81c36b8b8a2812acdf0faa978d5aa3938bdb
#![warn(missing_docs)] use std::fs::File; use std::io::{self, Read}; use self::error::InputError; use self::parser::LineReader; mod action; mod error; mod format; mod parser; mod util; pub use self::action::Config; pub use self::error::{Error, ResultExt}; pub async fn run_file(config: &Config, filename: &str) ->...
#![warn(missing_docs)] use std::fs::File; use std::io::{self, Read}; use self::error::InputError; use self::parser::LineReader; mod action; mod error; mod format; mod parser; mod util; pub use self::action::Config; pub use self::error::{Error, ResultExt}; pub async fn run_file(config: &Config, filename: &str) ->...
async fn run_line_reader(config: &Config, line_reader: &mut LineReader<'_>) -> Result<(), Error> { let cmds = parser::parse(line_reader)?; let mut cmds_exec = cmds.clone(); let mut execution_count = 1; if let Some(command) = cmds_exec.iter_mut().find(|el| { if let parser::Com...
function_block-full_function
[ { "content": "/// Constructs a URL from PostgreSQL configuration parameters.\n\n///\n\n/// Returns an error if the set of configuration parameters is not representable\n\n/// as a URL, e.g., if there are multiple hosts.\n\npub fn config_url(config: &Config) -> Result<Url, Error> {\n\n let mut url = Url::pars...
Rust
gpu_display/src/gpu_display_wl.rs
Mikewyf/crosvm
b0ae5378c618322320217fab5d258f26b1bb9802
extern crate base; extern crate data_model; #[path = "dwl.rs"] mod dwl; use dwl::*; use crate::{DisplayT, EventDevice, GpuDisplayError, GpuDisplayFramebuffer, GpuDisplayResult}; use std::cell::Cell; use std::collections::HashMap; use std::ffi::{CStr, CString}; use std::path::Path; use std::ptr::{null, null_mut}; ...
extern crate base; extern crate data_model; #[path = "dwl.rs"] mod dwl; use dwl::*; use crate::{DisplayT, EventDevice, GpuDisplayError, GpuDisplayFramebuffer, GpuDisplayResult}; use std::cell::Cell; use std::collections::HashMap; use std::ffi::{CStr, CString}; use std::path::Path; use std::ptr::{null, null_mut}; ...
(surface.surface(), next_buffer_index) } } None => { debug_assert!(false, "invalid surface_id {}", surface_id); false } } } fn flip(&mut self, surface_id: u32) { match self.get_surface(surface_id) { Some(surface) =>...
reate_surface( &mut self, parent_surface_id: Option<u32>, width: u32, height: u32, ) -> GpuDisplayResult<u32> { let parent_ptr = match parent_surface_id { Some(id) => match self.get_surface(id).map(|p| p.surface()) { Some(ptr) => ptr, ...
random
[ { "content": "fn map_func(resource_id: u32) -> ExternalMappingResult<(u64, usize)> {\n\n let mut map: *mut c_void = null_mut();\n\n let map_ptr: *mut *mut c_void = &mut map;\n\n let mut size: u64 = 0;\n\n\n\n // Safe because the Stream renderer wraps and validates use of vkMapMemory.\n\n let ret ...
Rust
rpc/src/client/transport/http.rs
interchainio/tendermint-rs
27e7f60faa4521d893262c3c13e90fc5af361811
use core::{ convert::{TryFrom, TryInto}, str::FromStr, }; use async_trait::async_trait; use tendermint_config::net; use crate::{client::Client, prelude::*, Error, Scheme, SimpleRequest, Url}; #[derive(Debug, Clone)] pub struct HttpClient { inner: sealed::HttpClient, } impl HttpClient { p...
use core::{ convert::{TryFrom, TryInto}, str::FromStr, }; use async_trait::async_trait; use tendermint_config::net; use crate::{client::Client, prelude::*, Error, Scheme, SimpleRequest, Url}; #[derive(Debug, Clone)] pub struct HttpClient { inner: sealed::HttpClient, } impl HttpClient { p...
g::debug!("Incoming response: {}", response_body); R::Response::from_string(&response_body) } } impl<C> HyperClient<C> { pub fn build_request<R: SimpleRequest>( &self, request: R, ) -> Result<hyper::Request<hyper::Body>, Error> { ...
rl> for Url { fn from(url: HttpClientUrl) -> Self { url.0 } } impl TryFrom<HttpClientUrl> for hyper::Uri { type Error = Error; fn try_from(value: HttpClientUrl) -> Result<Self, Error> { value.0.to_string().parse().map_err(Error::invalid_uri) } } mod sealed { use std::io::Read;...
random
[ { "content": "/// A trait that allows to generate complex objects from simple companion objects.\n\n/// A companion type should have a simple API, leaving most fields optional.\n\npub trait Generator<Output: Serialize>: FromStr<Err = SimpleError> + Clone {\n\n /// Merge this companion with the another, defau...
Rust
roa-core/src/body.rs
JohnTitor/roa
ecba50ef1601435f0654707cb32ec845ea006fe5
use bytes::{Buf, Bytes, BytesMut}; use futures::future::ok; use futures::io::{self, AsyncRead}; use futures::stream::{once, Stream, StreamExt}; use std::mem; use std::pin::Pin; use std::task::{Context, Poll}; const DEFAULT_CHUNK_SIZE: usize = 4096; pub enum Body { Empty, Once(Bytes), Stre...
use bytes::{Buf, Bytes, BytesMut}; use futures::future::ok; use futures::io::{self, AsyncRead}; use futures::stream::{once, Stream, StreamExt}; use std::mem; use std::pin::Pin; use std::task::{Context, Poll}; const DEFAULT_CHUNK_SIZE: usize = 4096; pub enum Body { Empty, Once(Bytes), Stre...
}
async fn body_composed() -> std::io::Result<()> { let mut body = Body::empty(); body.write("He") .write("llo, ") .write_reader(File::open("../assets/author.txt").await?) .write_reader(File::open("../assets/author.txt").await?) .write("."); assert_e...
function_block-full_function
[ { "content": "#[cfg_attr(feature = \"docs\", doc(spotlight))]\n\n#[async_trait(?Send)]\n\npub trait Endpoint<'a, S = ()>: 'static + Sync + Send {\n\n /// Call this endpoint.\n\n async fn call(&'a self, ctx: &'a mut Context<S>) -> Result;\n\n}\n\n\n\n#[async_trait(?Send)]\n\nimpl<'a, S, T, F> Endpoint<'a, ...
Rust
crates/wasm-mutate/src/mutators/add_function.rs
salewski/wasm-tools
e57bf54280c7b3dc937e8fa3f60e786f920cdb61
use super::Mutator; use crate::module::{PrimitiveTypeInfo, TypeInfo}; use crate::{Error, Result, WasmMutate}; use rand::Rng; use std::convert::TryFrom; use wasm_encoder::{Instruction, Module, ValType}; #[derive(Clone, Copy)] pub struct AddFunctionMutator; impl Mutator for AddFunctionMutator { fn mutate<'a>( ...
use super::Mutator; use crate::module::{PrimitiveTypeInfo, TypeInfo}; use crate::{Error, Result, WasmMutate}; use rand::Rng; use std::convert::TryFrom; use wasm_encoder::{Instruction, Module, ValType}; #[derive(Clone, Copy)] pub struct AddFunctionMutator; impl Mutator for AddFunctionMutator { fn mutate<'a>( ...
}
AddFunctionMutator, r#" (module (type (;0;) (func (param i32 f32) (result i64 f64))) (func (;0;) (type 0) (param i32 f32) (result i64 f64) i64.const 0 f64.const 0.0 ) ...
function_block-function_prefix_line
[ { "content": "pub fn ty(_t: &mut dyn Translator, ty: &Type) -> Result<ValType> {\n\n match ty {\n\n Type::I32 => Ok(ValType::I32),\n\n Type::I64 => Ok(ValType::I64),\n\n Type::F32 => Ok(ValType::F32),\n\n Type::F64 => Ok(ValType::F64),\n\n Type::V128 => Ok(ValType::V128),\n...
Rust
src/api/text/dom/query.rs
kokizzu/blueboat
12c9c982736787d27cf4cb59db4d9f3e5ac1814d
use std::rc::Rc; use anyhow::Result; use markup5ever_rcdom::{Handle, Node, NodeData}; use serde::Deserialize; use v8; use crate::{ api::util::v8_deserialize, registry::SymbolRegistry, v8util::FunctionCallbackArgumentsExt, }; use super::Dom; #[derive(Deserialize)] #[serde(rename_all = "camelCase", tag = "type")] e...
use std::rc::Rc; use anyhow::Result; use markup5ever_rcdom::{Handle, Node, NodeData}; use serde::Deserialize; use v8; use crate::{ api::util::v8_deserialize, registry::SymbolRegistry, v8util::FunctionCallbackArgumentsExt, }; use super::Dom; #[derive(Deserialize)] #[serde(rename_all = "camelCase", tag = "type")] e...
x).clone(), Err(_) => return true, }; for child in &children { if !walk(scope, expr, callback, root, child) { return false; } } true } #[cfg(test)] mod tests { use crate::api::testutil::ApiTester; use serde::Deserialize; #[test] fn test_query_count() { #[derive(Deserialize)] ...
.any(|x| x == class_name) { return true; } } } } } return false; } Self::Text => matches!(&node.data, NodeData::Text { .. }), Self::True => true, Self::False => false, } } } pub fn ap...
random
[ { "content": "fn get_face_name(face: &Face) -> Option<String> {\n\n for name in face.names() {\n\n if name.name_id() == 4 && name.is_unicode() {\n\n let mut name = name.name();\n\n if name.len() % 2 == 0 {\n\n let mut buf: Vec<u16> = Vec::with_capacity(name.len() / 2);\n\n for _ in 0...
Rust
imxrt1060-hal/src/dma/memcpy.rs
mciantyre/imxrt-hal
b77d7ff67684fb6084d8877f6f014cfa5fba5d45
use super::{buffer, Channel, Element, Error}; use core::{ marker::PhantomData, sync::atomic::{compiler_fence, Ordering}, }; pub struct Memcpy<E, S, D> { channel: Channel, buffers: Option<(S, D)>, _element: PhantomData<E>, } impl<E: Element, S, D> Memcpy<E, S, D> where S: buffer::Source<E>, ...
use super::{buffer, Channel, Element, Error}; use core::{ marker::PhantomData, sync::atomic::{compiler_fence, Ordering}, }; pub struct Memcpy<E, S, D> { channel: Channel, buffers: Option<(S, D)>, _element: PhantomData<E>, } impl<E: Element, S, D> Memcpy<E, S, D> where S: buffer::Source<E>, ...
}
pub fn complete(&mut self) -> Option<Result<(S, D), (S, D)>> { self.buffers.take().map(|(mut source, mut destination)| { if self.is_complete() { self.channel.clear_complete(); source.complete_source(); destination.complete_destination(); ...
function_block-full_function
[ { "content": "/// Chain two timers together, returning a `ChainedPIT` timer that can\n\n/// count twice as many ticks.\n\n///\n\n/// The API enforces that channel 1 is chained to channel 0, or channel 2 is\n\n/// chained to channel 1, or channel 3 is chained to channel 2. Any other\n\n/// combination of chainin...
Rust
poem/src/request.rs
Choi-Jungwoo/poem
32c155e3f3f2ca1d11b445e47fc4df88b79882b6
use std::{ any::Any, convert::TryInto, fmt::{self, Debug, Formatter}, }; #[cfg(feature = "websocket")] use hyper::upgrade::OnUpgrade; use once_cell::sync::Lazy; #[cfg(feature = "websocket")] use parking_lot::Mutex; use crate::{ body::Body, http::{ header::{self, HeaderMap, HeaderName, Head...
use std::{ any::Any, convert::TryInto, fmt::{self, Debug, Formatter}, }; #[cfg(feature = "websocket")] use hyper::upgrade::OnUpgrade; use once_cell::sync::Lazy; #[cfg(feature = "websocket")] use parking_lot::Mutex; use crate::{ body::Body, http::{ header::{self, HeaderMap, HeaderName, Head...
pub fn content_type(&self) -> Option<&str> { self.headers() .get(header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) } #[inline] pub fn extensions(&self) -> &Extensions { &self.extensions } #[inline] pub fn extensions_mut(&m...
e .match_params .iter() .find(|(key, _)| key == name) .map(|(_, value)| value.as_str()) }
function_block-function_prefixed
[ { "content": "/// Create an endpoint with a function.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use poem::{endpoint::make_sync, http::Method, Endpoint, Request};\n\n///\n\n/// let ep = make_sync(|req| req.method().to_string());\n\n///\n\n/// # tokio::runtime::Runtime::new().unwrap().block_on(async {\n\n/...