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
crates/sauron-core/src/dom/window.rs
gbj/sauron
cce5c5001efb37dcacebee596f75972c2338b44c
use crate::{ dom::created_node::create_closure_wrap, Application, Attribute, Cmd, Dispatch, }; use std::fmt::Debug; use wasm_bindgen::{self, prelude::*, JsCast}; use web_sys::EventTarget; use web_sys::ScrollToOptions; #[derive(Copy, Clone, Debug)] pub struct Window; impl Window { pub fn add_event_lis...
use crate::{ dom::created_node::create_closure_wrap, Application, Attribute, Cmd, Dispatch, }; use std::fmt::Debug; use wasm_bindgen::{self, prelude::*, JsCast}; use web_sys::EventTarget; use web_sys::ScrollToOptions; #[derive(Copy, Clone, Debug)] pub struct Window; impl Window { pub fn add_event_lis...
MSG: 'static, { Cmd::new(|_program| { let mut options = ScrollToOptions::new(); options.top(0.0); options.left(0.0); crate::window().scroll_to_with_scroll_to_options(&options); }) } pub fn set_location_hash(hash: &str) { let ...
let window = crate::window(); window.location().hash().expect("must have a hash") } pub fn scroll_to_top<APP, MSG>() -> Cmd<APP, MSG> where APP: 'static,
random
[ { "content": "/// an event builder\n\npub fn on<F, MSG>(event_name: &'static str, f: F) -> Attribute<MSG>\n\nwhere\n\n F: Fn(Event) -> MSG + 'static,\n\n MSG: 'static,\n\n{\n\n mt_dom::attr(event_name, AttributeValue::EventListener(Listener::from(f)))\n\n}\n\n\n", "file_path": "crates/sauron-core/s...
Rust
src/main.rs
xiv/wireguard-rs
525c7bd73476e20525f20010aa1f5003cc9913dc
#![cfg_attr(feature = "unstable", feature(test))] extern crate alloc; #[cfg(feature = "profiler")] extern crate cpuprofiler; #[cfg(feature = "profiler")] use cpuprofiler::PROFILER; mod configuration; mod platform; mod wireguard; mod util; use std::env; use std::process::exit; use std::thread; use configuration::...
#![cfg_attr(feature = "unstable", feature(test))] extern crate alloc; #[cfg(feature = "profiler")] extern crate cpuprofiler; #[cfg(feature = "profiler")] use cpuprofiler::PROFILER; mod configuration; mod platform; mod wireguard; mod util; use std::env; use std::process::exit; use std::thread; use configuration::...
fn main() { let mut name = None; let mut drop_privileges = true; let mut foreground = false; let mut args = env::args(); args.next(); for arg in args { match arg.as_str() { "--foreground" | "-f" => { foreground = true; } "-...
let mut n = 0; loop { let path = format!("./{}-{}.profile", name, n); if !Path::new(path.as_str()).exists() { println!("Starting profiler: {}", path); PROFILER.lock().unwrap().start(path).unwrap(); break; }; n += 1; } }
function_block-function_prefix_line
[ { "content": "#[cfg(feature = \"profiler\")]\n\nfn profiler_start(name: &str) {\n\n use std::path::Path;\n\n\n\n // find first available path to save profiler output\n\n let mut n = 0;\n\n loop {\n\n let path = format!(\"./{}-{}.profile\", name, n);\n\n if !Path::new(path.as_str()).exi...
Rust
src/lib.rs
zenria/recurrent
8720e99cc46be2c4c4bad7b03d99f991f1326681
use chrono::{DateTime, Datelike, Duration, NaiveTime, TimeZone, Timelike, Weekday}; use std::collections::BTreeSet; mod conv; #[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)] pub enum OrderedWeekday { Mon = 0, Tue = 1, Wed = 2, Thu = 3, Fri = 4, Sat...
use chrono::{DateTime, Datelike, Duration, NaiveTime, TimeZone, Timelike, Weekday}; use std::collections::BTreeSet; mod conv; #[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)] pub enum OrderedWeekday { Mon = 0, Tue = 1, Wed = 2, Thu = 3, Fri = 4, Sat...
pub fn prev<T: TimeZone>(&self, date: &DateTime<T>) -> DateTime<T> { let current_day: OrderedWeekday = date.weekday().into(); let days_to_add = if self.days.contains(&current_day) && date.time() > self.time { Duration::days(0) } else { let ...
pub fn next<T: TimeZone>(&self, date: &DateTime<T>) -> DateTime<T> { let current_day: OrderedWeekday = date.weekday().into(); let days_to_add = if self.days.contains(&current_day) && date.time() < self.time { Duration::days(0) } else { let next_...
function_block-full_function
[ { "content": " Weekday,\n\n Weekday,\n\n )\n\n{\n\n fn week_days(&self) -> Vec<Weekday> {\n\n vec![self.0, self.1, self.2, self.3, self.4, self.5, self.6]\n\n }\n\n}\n\nimpl From<Weekday> for OrderedWeekday {\n\n fn from(w: Weekday) -> Self {\n\n use OrderedWeekday::*;\n\...
Rust
cov/src/error.rs
mmullis/cov
a81e6304a5d05568b06c394d706f95a100b7aa53
#![allow(renamed_and_removed_lints, unused_doc_comments)] use raw::{Ident, Type, Version}; use std::{fmt, io}; use std::error::Error as StdError; use std::path::PathBuf; use std::result::Result as StdResult; error_chain! { foreign_links { Io(io::Error) /** Wrapper of standard I/O error. */; Jso...
#![allow(renamed_and_removed_lints, unused_doc_comments)] use raw::{Ident, Type, Version}; use std::{fmt, io}; use std::error::Error as StdError; use std::path::PathBuf; use std::result::Result as StdResult; error_chain! { foreign_links { Io(io::Error) /** Wrapper of standard I/O error. */; Jso...
} #[derive(Debug)] struct AtError { location: Location, cause: Option<Box<StdError + Send + 'static>>, } impl fmt::Display for AtError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.location { Location::Cursor(cursor) => write!(fmt, "reading at file position {0}...
r { location: self, cause: error.1.next_error, }); error.1.next_error = Some(cause); } error }
function_block-function_prefixed
[ { "content": "#[cfg(windows)]\n\npub fn set_executable(file: &File) -> io::Result<()> {\n\n Ok(())\n\n}\n\n\n", "file_path": "cargo-cov/src/utils.rs", "rank": 0, "score": 213178.65893600846 }, { "content": "/// Analyzes the the source path and obtain its corresponding [`SourceType`].\n\n/...
Rust
tests/exec_test.rs
rami3l/bollard
c720ee74c0172a0aa88c9780fdbbea9e71221090
#![type_length_limit = "2097152"] use bollard::container::*; use bollard::errors::Error; use bollard::exec::*; use bollard::Docker; use futures_util::stream::TryStreamExt; use tokio::runtime::Runtime; #[macro_use] pub mod common; use crate::common::*; async fn start_exec_test(docker: Docker) -> Result<(), Error> { ...
#![type_length_limit = "2097152"] use bollard::container::*; use bollard::errors::Error; use bollard::exec::*; use bollard::Docker; use futures_util::stream::TryStreamExt; use tokio::runtime::Runtime; #[macro_use] pub mod common; use crate::common::*;
async fn inspect_exec_test(docker: Docker) -> Result<(), Error> { create_daemon(&docker, "integration_test_inspect_exec_test").await?; let message = &docker .create_exec( "integration_test_inspect_exec_test", CreateExecOptions { attach_stdout: Some(true), ...
async fn start_exec_test(docker: Docker) -> Result<(), Error> { create_daemon(&docker, "integration_test_start_exec_test").await?; let message = &docker .create_exec( "integration_test_start_exec_test", CreateExecOptions { attach_stdout: Some(true), ...
function_block-full_function
[ { "content": "pub fn integration_test_registry_credentials() -> DockerCredentials {\n\n DockerCredentials {\n\n username: Some(\"bollard\".to_string()),\n\n password: std::env::var(\"REGISTRY_PASSWORD\").ok(),\n\n ..Default::default()\n\n }\n\n}\n\n\n\npub(crate) fn registry_http_addr...
Rust
movegen/src/makeunmake.rs
InterestingBrainPoops/shrimp
cf9ad088d4cfd5cfe4c98480a6d7b8aabab34172
use board::{ board::Coordinate, small::{SmallRequest, SNAKE_MAX}, }; use tinyvec::*; pub struct Delta { eaten_food: ArrayVec<[Coordinate; SNAKE_MAX]>, died: ArrayVec<[u8; SNAKE_MAX]>, prev_health: ArrayVec<[(u8, u8); SNAKE_MAX]>, tails: ArrayVec<[(u8, Coordinate); SNAKE_MAX]...
use board::{ board::Coordinate, small::{SmallRequest, SNAKE_MAX}, }; use tinyvec::*; pub struct Delta { eaten_food: ArrayVec<[Coordinate; SNAKE_MAX]>, died: ArrayVec<[u8; SNAKE_MAX]>, prev_health: ArrayVec<[(u8, u8); SNAKE_MAX]>, tails: ArrayVec<[(u8, Coordinate); SNAKE_MAX]...
fn maybe_eliminiate_snakes(&mut self, delta: &mut Delta) { for snake in &mut self.board.snakes { if !snake.alive { continue; } if snake.health == 0 { snake.alive = false; delta.died.push(snake.id); continue...
nakes(&mut self, delta: &mut Delta) { for snake in &mut self.board.snakes { if (snake.head_bb & self.board.food_bb) != 0 { delta.prev_health.push((snake.id, snake.health)); snake.body.push(*snake.body.last().unwrap()); snake.health = 100; ...
function_block-function_prefixed
[ { "content": "fn perft(state: &mut SmallRequest, depth: u8, player: bool, you_move: Option<Move>) {\n\n if state.amount_alive() as usize == 0\n\n || !state.board.snakes[state.you].alive\n\n || state.amount_alive() as usize == 1\n\n || depth == 0\n\n {\n\n // im the only one lef...
Rust
oapth/src/back_end_impls/tiberius.rs
c410-f3r/oapth
be797e63d9fbe468ce9a79bdb0b85953ead8d2e2
use crate::{ fixed_sql_commands::{ delete_migrations, insert_migrations, migrations_by_mg_version_query, mssql::{tables, CREATE_MIGRATION_TABLES}, }, BackEnd, BackEndGeneric, BoxFut, DbMigration, MigrationRef, MigrationGroupRef, OAPTH_SCHEMA_PREFIX, }; use alloc::string::String; use oapth_commons::Databas...
use crate::{ fixed_sql_commands::{ delete_migrations, insert_migrations, migrations_by_mg_version_query, mssql::{tables, CREATE_MIGRATION_TABLES}, }, BackEnd, BackEndGeneric, BoxFut, DbMigration, MigrationRef, MigrationGroupRef, OAPTH_SCHEMA_PREFIX, }; use alloc::string::String; use oapth_commons::Databas...
#[inline] fn insert_migrations<'a, 'b, 'c, 'ret, I>( &'a mut self, migrations: I, mg: MigrationGroupRef<'b>, ) -> BoxFut<'ret, crate::Result<()>> where 'a: 'ret, 'b: 'ret, 'c: 'ret, I: Clone + Iterator<Item = MigrationRef<'c, 'c>> + 'ret, Self: 'ret { Box::pin(insert_migr...
fn execute<'a, 'b, 'ret>(&'a mut self, command: &'b str) -> BoxFut<'ret, crate::Result<()>> where 'a: 'ret, 'b: 'ret, Self: 'ret, { Box::pin(async move { Ok(self.conn.execute(command, &[][..]).await.map(|_| ())?) }) }
function_block-full_function
[ { "content": "#[inline]\n\npub fn calc_checksum(name: &str, sql_up: &str, sql_down: &str, version: i32) -> u64 {\n\n let mut hasher = SipHasher13::new();\n\n name.hash(&mut hasher);\n\n sql_up.hash(&mut hasher);\n\n sql_down.hash(&mut hasher);\n\n version.hash(&mut hasher);\n\n hasher.finish()\n\n}\n\n\n\...
Rust
crates/nu-plugin/src/serializers/json.rs
hustcer/nushell
cb66d2bcad6db50a71d0accba0f76afe0ec12cac
use nu_protocol::ShellError; use crate::{plugin::PluginEncoder, protocol::PluginResponse}; #[derive(Clone)] pub struct JsonSerializer; impl PluginEncoder for JsonSerializer { fn encode_call( &self, plugin_call: &crate::protocol::PluginCall, writer: &mut impl std::io::Write, ) -> Resul...
use nu_protocol::ShellError; use crate::{plugin::PluginEncoder, protocol::PluginResponse}; #[derive(Clone)] pub struct JsonSerializer; impl PluginEncoder for JsonSerializer { fn encode_call( &self, plugin_call: &crate::protocol::PluginCall, writer: &mut impl std::io::Write, ) -> Resul...
fn decode_call( &self, reader: &mut impl std::io::BufRead, ) -> Result<crate::protocol::PluginCall, nu_protocol::ShellError> { serde_json::from_reader(reader) .map_err(|err| ShellError::PluginFailedToEncode(err.to_string())) } fn encode_response( &self, ...
serde_json::to_writer(writer, plugin_call) .map_err(|err| ShellError::PluginFailedToEncode(err.to_string())) }
function_block-function_prefix_line
[ { "content": "pub fn logger(f: impl FnOnce(&mut Builder) -> Result<(), ShellError>) -> Result<(), ShellError> {\n\n let mut builder = my_formatted_timed_builder();\n\n f(&mut builder)?;\n\n let _ = builder.try_init();\n\n Ok(())\n\n}\n\n\n", "file_path": "src/logger.rs", "rank": 0, "scor...
Rust
client/src/tab.rs
jasperla/icb-rs
2a9b8fcaadc172327db6a8f67a2cbcceb701cfe6
use chrono::Local; use std::convert::TryFrom; use std::io::Error; use std::path::PathBuf; use tui::backend::Backend; use tui::layout::{Alignment, Constraint, Direction, Layout, Rect}; use tui::style::{Modifier, Style}; use tui::terminal::Frame; use tui::widgets::{Block, Borders, Paragraph, Text, Widget}; use crate::me...
use chrono::Local; use std::convert::TryFrom; use std::io::Error; use std::path::PathBuf; use tui::backend::Backend; use tui::layout::{Alignment, Constraint, Direction, Layout, Rect}; use tui::style::{Modifier, Style}; use tui::terminal::Frame; use tui::widgets::{Block, Borders, Paragraph, Text, Widget}; use crate::me...
} pub struct Tabs { tabs: Vec<Tab>, current_tab: usize, log_path: Option<PathBuf>, log_default: bool, } impl Tabs { pub fn new() -> Tabs { let mut v = Vec::new(); v.push(Tab::new(ChatType::Status(STATUS.to_string()), None)); Tabs { tabs: v, current...
e { ChatType::Personal(ref user) => Command::Personal(user.clone(), msg.to_string()), _ => Command::Open(msg.to_string()), } }
function_block-function_prefixed
[ { "content": "#[cfg(debug_assertions)]\n\npub fn q<T: std::fmt::Debug>(msg: &str, thing: &T) -> std::io::Result<()> {\n\n let mut file = File::create(\"/tmp/q.log\")?;\n\n file.write_all(format!(\"{}: {:?}\\n\", msg, thing).as_bytes())?;\n\n Ok(())\n\n}\n\n\n", "file_path": "icb/src/util.rs", "...
Rust
src/redis_rs/mod.rs
chridou/reool
e8661777f84b9be931fede4624fbd069e0220884
use std::sync::Arc; use std::time::Instant; use future::BoxFuture; use futures::prelude::*; use redis::{Client as RedisClient, IntoConnectionInfo}; use tokio::time::timeout_at; use trust_dns_resolver::TokioAsyncResolver; use crate::connection_factory::ConnectionFactory; use crate::error::{Error, InitializationResult}...
use std::sync::Arc; use std::time::Instant; use future::BoxFuture; use futures::prelude::*; use redis::{Client as RedisClient, IntoConnectionInfo}; use tokio::time::timeout_at; use trust_dns_resolver::TokioAsyncResolver; use crate::connection_factory::ConnectionFactory; use crate::error::{Error, InitializationResult}...
}
e, latency, total_time: started_at.elapsed(), } }; timeout_at(timeout.into(), ping_future) .unwrap_or_else(move |_| { let total_time = started_at.elapsed(); let uri = self.connecting_to().to_owned(); ...
function_block-function_prefixed
[ { "content": "fn parse_connect_to(what: &str) -> Vec<String> {\n\n what.split(';')\n\n .filter(|s| !s.is_empty())\n\n .map(str::trim)\n\n .map(ToOwned::to_owned)\n\n .collect()\n\n}\n\n\n", "file_path": "src/helpers.rs", "rank": 0, "score": 153558.28088435478 }, { ...
Rust
examples/ecs.rs
attackgoat/screen-13
de1ce897fe96ed25078e32f7aa40e73f356e8185
#[macro_use] extern crate log; #[macro_use] extern crate paste; macro_rules! ecs_sys { ($name: ident) => { paste! { #[allow(dead_code)] mod [<$name:snake _sys>] { use { super::PakFile, screen_13::prelude_rc::*, ...
#[macro_use] extern crate log; #[macro_use] extern crate paste; macro_rules! ecs_sys { ($name: ident) => { paste! { #[allow(dead_code)] mod [<$name:snake _sys>] { use { super::PakFile, screen_13::prelude_rc::*, ...
fn update(self: Box<Self>, _: &Gpu, _: &Input) -> DynScreen { self } } #[derive(Clone, Copy)] pub struct Light { pub color: Color, pub power: f32, pub radius: f32, } #[derive(Clone, Copy)] pub struct Material { pub color: Bitmap, pub metal_rough: Bitmap, pub normal: Bitmap, }...
m) }), ); draws.extend(self.ecs.query::<(&Light, &Position)>().iter().map( |(_, (light, position))| { Draw::point_light(position.into(), light.color, light.power, light.radius) }, )); let camera = Perspective::default(); ...
function_block-function_prefixed
[ { "content": "#[cfg(not(target_arch = \"wasm32\"))]\n\npub fn root(name: &'static str, author: &'static str) -> Result<PathBuf, Error> {\n\n // Converts the app_dirs crate AppDirsError to a regular IO Error\n\n match ProjectDirs::from(\"\", author, name) {\n\n None => Err(Error::from(ErrorKind::Inv...
Rust
bench/src/main.rs
nkbai/learnrustbynats
68977a48a67a68059fd1463bee82c0ae3313fbbc
mod bench; mod wait_group; use crate::bench::{msgs_per_client, Benchmark, Sample}; use client::client::Client; use std::error::Error; use std::sync::Arc; use structopt::StructOpt; use tokio::sync::{oneshot, Mutex}; use tokio::time::Instant; use wait_group::WaitGroup; #[derive(StructOpt, Debug, Clone)] #[structopt(name...
mod bench; mod wait_group; use crate::bench::{msgs_per_client, Benchmark, Sample}; use client::client::Client; use std::error::Error; use std::sync::Arc; use structopt::StructOpt; use tokio::sync::{oneshot, Mutex}; use tokio::time::Instant; use wait_group::WaitGroup; #[derive(StructOpt, Debug, Clone)] #[structopt(name...
async fn run_publiser( c: &mut Client, mut start_wg: WaitGroup, mut done_wg: WaitGroup, num_msgs: usize, opt: Opt, bench: Arc<Mutex<Benchmark>>, ) { start_wg.done().await; let msg = vec![0x4a; opt.msg_size]; let start = Instant::now(); let t = 0..num_msgs; let mut i = 0; ...
e(); let bench = bench.clone(); let opt = opt.clone(); tokio::spawn(async move { run_subscriber(&mut c, start_wg, done_wg, opt, bench).await; c.close(); println!("run_subscriber finished"); }); } println!("startwg1 start wait"); start_wg.wa...
function_block-function_prefixed
[ { "content": "#[derive(Debug, Default, Clone)]\n\nstruct SampleGroup {\n\n group_sample: Sample,\n\n samples: Vec<Sample>,\n\n}\n\nimpl SampleGroup {\n\n // AddSample adds a Sample to the SampleGroup. After adding a Sample it shouldn't be modified.\n\n pub fn add_sample(&mut self, s: Sample) {\n\n ...
Rust
pallets/utils/src/lib.rs
F3Joule/substrate-node-template
b3308e9eb021d994e6a60e127dd9199d9c240b0e
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use scale_info::TypeInfo; use frame_support::{ decl_error, decl_module, decl_storage, decl_event, dispatch::{DispatchError, DispatchResult}, ensure, traits::{ Currency, Get, Imbalance, OnUnbalanced, }, }; use frame_...
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use scale_info::TypeInfo; use frame_support::{ decl_error, decl_module, decl_storage, decl_event, dispatch::{DispatchError, DispatchResult}, ensure, traits::{ Currency, Get, Imbalance, OnUnbalanced, }, }; use frame_...
ocked, ContentIsBlocked, PostIsBlocked, InvalidIpfsCid, RawContentTypeNotSupported, HypercoreContentTypeNotSupported, HandleIsTooShort, HandleIsTooLong, HandleContainsInvalidChars, ...
ec_u8) => vec_u8, Content::Hyper(vec_u8) => vec_u8, } } } impl Default for Content { fn default() -> Self { Self::None } } impl Content { pub fn is_none(&self) -> bool { self == &Self::None } pub fn is_some(&self) -> bool { !self.is_none() } ...
random
[ { "content": "type Block = frame_system::mocking::MockBlock<Test>;\n\n\n\nframe_support::construct_runtime!(\n\n pub enum Test where\n\n Block = Block,\n\n NodeBlock = Block,\n\n UncheckedExtrinsic = UncheckedExtrinsic,\n\n {\n\n System: system::{Pallet, Call, Config, Storage, ...
Rust
voxelli/src/objects/loader.rs
GuMiner/rust-experiments
2ad3224e011632a9162fe21796e396ebf6a79c71
extern crate byteorder; extern crate nalgebra; use std::io::{BufReader, Read}; use std::fs::File; use std::str; use objects::loader::byteorder::{ByteOrder, LittleEndian}; use nalgebra::{Point3, Point4}; use objects::object::{Voxel, SubObject, Object}; use objects::palette::Palette; enum ChunkType { Main, P...
extern crate byteorder; extern crate nalgebra; use std::io::{BufReader, Read}; use std::fs::File; use std::str; use objects::loader::byteorder::{ByteOrder, LittleEndian}; use nalgebra::{Point3, Point4}; use objects::object::{Voxel, SubObject, Object}; use objects::palette::Palette; enum ChunkType { Main, P...
fn is_not_size(&self) -> bool { match *self { ChunkType::Size(xyzi) => false, _ => true } } fn chunk_name(&self) -> String { match *self { ChunkType::Main => String::from("Main"), ChunkType::Pack(models) => String::from("Pack"), ...
fn is_not_main(&self) -> bool { match *self { ChunkType::Main => false, _ => true } }
function_block-full_function
[ { "content": "// Enums are a lot more powerful, they can hold random data.\n\nenum Shapes {\n\n Triangle,\n\n Rectangle { width: i32, height: i32 },\n\n Hexagon,\n\n Circle(i32), // 'Clearly' radius\n\n}\n\n\n\n// Demo matching to implement pretty-printing for shapes\n\nimpl fmt::Display for Shapes ...
Rust
server/src/api.rs
pascalw/pragma
b5d6f41239bff0e8c276590cf81da286cb818c3d
use actix_web::http::{Method, StatusCode}; use actix_web::{App, AsyncResponder, Error, HttpRequest, HttpResponse, Json, Path, Query}; use chrono::prelude::*; use super::actix_state::State; use super::auth; use super::build_info; use super::data::*; use super::repo_actor::*; use futures::future::Future; #[derive(Seria...
use actix_web::http::{Method, StatusCode}; use actix_web::{App, AsyncResponder, Error, HttpRequest, HttpResponse, Json, Path, Query}; use chrono::prelude::*; use super::actix_state::State; use super::auth; use super::build_info; use super::data::*; use super::repo_actor::*; use futures::future::Future; #[derive(Seria...
fn update_content_block( (req, params, content_block_update): ( HttpRequest<State>, Path<String>, Json<ContentBlockUpdate>, ), ) -> Box<Future<Item = HttpResponse, Error = Error>> { let id = params.into_inner(); let db = &req.state().db; db.send(UpdateContentBlockMessage ...
fn create_content_block( (req, new_content_block): (HttpRequest<State>, Json<NewContentBlock>), ) -> Box<Future<Item = HttpResponse, Error = Error>> { let db = &req.state().db; db.send(CreateContentBlockMessage { new_content_block: new_content_block.into_inner(), }) .from_err() .and_the...
function_block-full_function
[ { "content": "pub fn delete_notebook(notebook_id: String, connection: &SqliteConnection) -> Result<(), String> {\n\n use super::schema::notebooks::dsl::*;\n\n\n\n let result = diesel::delete(notebooks.filter(id.eq(notebook_id))).execute(connection);\n\n\n\n match result {\n\n Ok(_num_rows) => Ok...
Rust
src/fcfg1/flash_e_p.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register FLASH_E_P"] pub type R = crate::R<u32, super::FLASH_E_P>; #[doc = "Writer for register FLASH_E_P"] pub type W = crate::W<u32, super::FLASH_E_P>; #[doc = "Register FLASH_E_P `reset()`'s with value 0x4c64_4c64"] impl crate::ResetValue for super::FLASH_E_P { type Type = u32; #[inline(al...
#[doc = "Reader of register FLASH_E_P"] pub type R = crate::R<u32, super::FLASH_E_P>; #[doc = "Writer for register FLASH_E_P"] pub type W = crate::W<u32, super::FLASH_E_P>; #[doc = "Register FLASH_E_P `reset()`'s with value 0x4c64_4c64"] impl crate::ResetValue for super::FLASH_E_P { type Type = u32; #[inline(al...
Internal. Only to be used through TI provided API."] #[inline(always)] pub fn pvsu(&mut self) -> PVSU_W { PVSU_W { w: self } } #[doc = "Bits 0:7 - 7:0\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn evsu(&mut self) -> EVSU_W { EVSU_W { w: self } ...
'a> { w: &'a mut W, } impl<'a> ESU_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `PVSU`"] pub typ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/rendering/window.rs
dithpri/wired-notify
04522ed4178a524d8e2aa19b677956c64c7c37b6
use std::time::Duration; use winit::{ dpi::{PhysicalPosition, PhysicalSize}, event_loop::EventLoopWindowTarget, platform::unix::{WindowBuilderExtUnix, WindowExtUnix, XWindowType}, window::{Window, WindowBuilder}, }; use chrono::{DateTime, Local}; use cairo::{Context, Surface}; use cairo_sys; use cra...
use std::time::Duration; use winit::{ dpi::{PhysicalPosition, PhysicalSize}, event_loop::EventLoopWindowTarget, platform::unix::{WindowBuilderExtUnix, WindowExtUnix, XWindowType}, window::{Window, WindowBuilder}, }; use chrono::{DateTime, Local}; use cairo::{Context, Surface}; use cairo_sys; use cra...
pub fn process_mouse_click(&mut self) { let mut layout = self.layout_take(); self.dirty |= layout.check_and_send_click(&self.last_mouse_pos, self); self.layout = Some(layout); } pub fn process_mouse_move(&mut self, position: PhysicalPosition<f64>) { self.last_mouse_pos.x =...
pub fn update(&mut self, delta_time: Duration) -> bool { if self.update_mode.contains(UpdateModes::FUSE) { self.fuse -= delta_time.as_millis() as i32; if self.fuse <= 0 { self.marked_for_destroy = true; return true; ...
function_block-function_prefix_line
[]
Rust
tests/relay.rs
thespis-rs/thespis_remote
21b1eb1d7567369738b233f73a18bb7ff5647c24
mod common; use common::* ; use common::import::{ *, assert_eq }; #[async_std::test] async fn relay_once() { let (ab, ba) = Endpoint::pair( 64, 64 ); let (bc, cb) = Endpoint::pair( 64, 64 ); let provider = async move { debug!( "start mailbox for handler" ); let addr_handler ...
mod common; use common::* ; use common::import::{ *, assert_eq }; #[async_std::test] async fn relay_once() { let (ab, ba) = Endpoint::pair( 64, 64 ); let (bc, cb) = Endpoint::pair( 64, 64 ); let provider = async move { debug!( "start mailbox for handler" ); let addr_handler ...
andle = AsyncStd.spawn_handle( provider ).expect( "Spawn provider" ); let relay_handle = AsyncStd.spawn_handle( relay ).expect( "Spawn relays" ); join( provi_handle, relay_handle ).await; }
r_handler.clone_box() ); sm.register_handler::<Show>( addr_handler.clone_box() ); debug!( "start mailbox for provider" ); let (peer_addr, _peer_evts, handle) = peer_listen( ab, Arc::new( sm ), AsyncStd, "provider" ).await; drop( peer_addr ); handle.await; trace!( "End of provider" ); }; let ...
random
[ { "content": "pub fn add_show_sum() -> remotes::Services\n\n{\n\n\t// Create mailbox for our handler\n\n\t//\n\n\tlet addr_handler = Addr::builder().start( Sum(0), &AsyncStd ).expect( \"spawn actor mailbox\" );\n\n\n\n\t// Create a service map\n\n\t//\n\n\tlet mut sm = remotes::Services::new();\n\n\n\n\t// Regi...
Rust
src/transaction/txin.rs
repzip/bsv-wasm
32778f1f45de96da97fa88c1b1ae670a655530d3
use std::io::Cursor; use std::io::Read; use std::io::Write; use crate::{Script, VarInt, utils::{to_hex, from_hex}}; use wasm_bindgen::{JsValue, prelude::*, throw_str}; use serde::*; use snafu::*; use anyhow::*; use byteorder::*; #[derive(Debug, Snafu)] pub enum TxInErrors { #[snafu(display("Error deserialising Tx...
use std::io::Cursor; use std::io::Read; use std::io::Write; use crate::{Script, VarInt, utils::{to_hex, from_hex}}; use wasm_bindgen::{JsValue, prelude::*, throw_str}; use serde::*; use snafu::*; use anyhow::*; use byteorder::*; #[derive(Debug, Snafu)] pub enum TxInErrors { #[snafu(display("Error deserialising Tx...
pub(crate) fn to_hex_impl(&self) -> Result<String, TxInErrors> { Ok(hex::encode(&self.to_bytes_impl()?)) } } /** * Platform Agnostic Functions * ie. Don't need Result<T, E> */ #[wasm_bindgen] impl TxIn { #[wasm_bindgen(constructor)] pub fn new( prev_tx_id: Vec<u8>, vout: u32, script_sig: V...
e) => return Err(TxInErrors::Serialise { field: Some("vout".to_string()), error: anyhow!(e) }), _ => () }; match cursor.write_varint(self.get_script_sig_size()) { Ok(v) => v, Err(e) => return Err(TxInErrors::Serialise { field: Some("script_sig_size".to_string()), error: anyhow!(e) }), ...
function_block-function_prefixed
[ { "content": "pub fn to_hex<S>(vec: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error>\n\n where S: Serializer\n\n{\n\n let hex = hex::encode(vec);\n\n\n\n serializer.serialize_str(&hex)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 0, "score": 131584.8126912852 }, { "content": "pu...
Rust
src/pasta.rs
hashblock/Nova
a7da105677542eaa217a77aff2200ed449f9a923
use crate::{ poseidon::PoseidonRO, traits::{ChallengeTrait, CompressedGroup, Group}, }; use digest::{ExtendableOutput, Input}; use ff::Field; use merlin::Transcript; use num_bigint::BigInt; use num_traits::Num; use pasta_curves::{ self, arithmetic::{CurveAffine, CurveExt}, group::{Curve, GroupEncoding}, pa...
use crate::{ poseidon::PoseidonRO, traits::{ChallengeTrait, CompressedGroup, Group}, }; use digest::{ExtendableOutput, Input}; use ff::Field; use merlin::Transcript; use num_bigint::BigInt; use num_traits::Num; use pasta_curves::{ self, arithmetic::{CurveAffine, CurveExt}, group::{Curve, GroupEncoding}, pa...
} impl CompressedGroup for VestaCompressedElementWrapper { type GroupElement = vesta::Point; fn decompress(&self) -> Option<vesta::Point> { Some(Eq::from_bytes(&self.repr).unwrap()) } fn as_bytes(&self) -> &[u8] { &self.repr } }
fn challenge(label: &'static [u8], transcript: &mut Transcript) -> Self { let mut key: <ChaCha20Rng as SeedableRng>::Seed = Default::default(); transcript.challenge_bytes(label, &mut key); let mut rng = ChaCha20Rng::from_seed(key); vesta::Scalar::random(&mut rng) }
function_block-function_prefix_line
[ { "content": "/// interepret scalar as base\n\npub fn scalar_as_base<G: Group>(input: G::Scalar) -> G::Base {\n\n let input_bits = input.to_le_bits();\n\n let mut mult = G::Base::one();\n\n let mut val = G::Base::zero();\n\n for bit in input_bits {\n\n if bit {\n\n val += mult;\n\n }\n\n mult ...
Rust
examples/src/bin/appsrc.rs
thiagoss/gstreamer-rs
8bd66abac47d409865f74a6ecd2a6b5fbeb1dc18
extern crate gstreamer as gst; use gst::prelude::*; extern crate gstreamer_app as gst_app; extern crate gstreamer_video as gst_video; extern crate glib; use std::thread; use std::error::Error as StdError; extern crate failure; use failure::Error; #[macro_use] extern crate failure_derive; #[path = "../examples-com...
extern crate gstreamer as gst; use gst::prelude::*; extern crate gstreamer_app as gst_app; extern crate gstreamer_video as gst_video; extern crate glib; use std::thread; use std::error::Error as StdError; extern crate failure; use failure::Error; #[macro_use] extern crate failure_derive; #[path = "../examples-com...
fn main() { examples_common::run(example_main); }
fn example_main() { match create_pipeline().and_then(|(pipeline, appsrc)| main_loop(pipeline, appsrc)) { Ok(r) => r, Err(e) => eprintln!("Error! {}", e), } }
function_block-full_function
[ { "content": "pub fn missing_uri_sink_message_new<P: IsA<gst::Element>>(element: &P, protocol: &str) -> Option<gst::Message> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n from_glib_full(ffi::gst_missing_uri_sink_message_new(element.to_glib_none().0, protocol.to_glib_none().0))\n\n }\...
Rust
common/functions/src/window/window_frame.rs
b41sh/databend
16e1cc5c5d26d14daef753df877a3597469d5812
use std::cmp::Ordering; use std::fmt; use std::hash::Hash; use std::hash::Hasher; use common_exception::ErrorCode; use sqlparser::ast; #[derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash, serde::Serialize, serde::Deserialize, )] pub struct WindowFrame { pub units: WindowFrameUnits, pub start_b...
use std::cmp::Ordering; use std::fmt; use std::hash::Hash; use std::hash::Hasher; use common_exception::ErrorCode; use sqlparser::ast; #[derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash, serde::Serialize, serde::Deserialize, )] pub struct WindowFrame { pub units: WindowFrameUnits, pub start_b...
ound) -> Self { match value { ast::WindowFrameBound::Preceding(v) => Self::Preceding(v), ast::WindowFrameBound::Following(v) => Self::Following(v), ast::WindowFrameBound::CurrentRow => Self::CurrentRow, } } } impl fmt::Display for WindowFrameBound { fn fmt(&s...
dowFrame) -> Result<Self, Self::Error> { let start_bound = value.start_bound.into(); let end_bound = value .end_bound .map(WindowFrameBound::from) .unwrap_or(WindowFrameBound::CurrentRow); if let WindowFrameBound::Following(None) = start_bound { E...
random
[ { "content": "pub fn equal(lhs: &DataTypeImpl, rhs: &DataTypeImpl) -> bool {\n\n if lhs.data_type_id() != rhs.data_type_id() {\n\n return false;\n\n }\n\n\n\n use crate::prelude::TypeID::*;\n\n match lhs.data_type_id() {\n\n Boolean | UInt8 | UInt16 | UInt32 | UInt64 | Int8 | Int16 | I...
Rust
contracts/anchor_beth_token/src/testing/tests.rs
MSNTCS/anchor-bEth-contracts
eefacdd5b1dd48dc915214dd6dfcbe255402347a
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{ coins, to_binary, Api, CosmosMsg, DepsMut, OwnedDeps, Querier, Storage, SubMsg, Uint128, WasmMsg, }; use beth::reward::ExecuteMsg::{DecreaseBalance, IncreaseBalance}; use cw20::{Cw20ReceiveMsg, MinterResponse, TokenInfoRes...
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{ coins, to_binary, Api, CosmosMsg, DepsMut, OwnedDeps, Querier, Storage, SubMsg, Uint128, WasmMsg, }; use beth::reward::ExecuteMsg::{DecreaseBalance, IncreaseBalance}; use cw20::{Cw20ReceiveMsg, MinterResponse, TokenInfoRes...
res.messages[2], SubMsg::new( Cw20ReceiveMsg { sender: addr2, amount: Uint128::new(1), msg: to_binary(&dummy_msg).unwrap(), } .into_cosmos_msg(dummny_contract_addr) .unwrap() ) ); }
function_block-function_prefix_line
[ { "content": "pub fn query_decimals(deps: Deps, contract_addr: Addr) -> StdResult<u8> {\n\n // load price form the oracle\n\n let token_info: TokenInfoResponse =\n\n deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {\n\n contract_addr: contract_addr.to_string(),\n\n msg...
Rust
src/emu.rs
cjburkey01/cjemu
c0285e171e01935b6bea545ac3b243c21d619acd
use cjemu_runtime::cjemu_api::VirtualMachine; use cjemu_runtime::CJEmuVirtualMachine; use std::sync::{mpsc, Arc, RwLock}; use std::thread; use std::thread::JoinHandle; use std::time::{Duration, SystemTime}; #[derive(Copy, Clone)] #[allow(dead_code)] enum EmulationEvent { Exit, Tick, Cycle { ticks: u64, tic...
use cjemu_runtime::cjemu_api::VirtualMachine; use cjemu_runtime::CJEmuVirtualMachine; use std::sync::{mpsc, Arc, RwLock}; use std::thread; use std::thread::JoinHandle; use std::time::{Duration, SystemTime}; #[derive(Copy, Clone)] #[allow(dead_code)] enum EmulationEvent { Exit, Tick, Cycle { ticks: u64, tic...
if elapsed_time_secs > secs_per_tick { last_tick_time = current_time; virtual_machine .write() ...
if elapsed_print_secs > 1.0 { last_print_time = current_time; let t = past_ticks - last_print_ticks; last_print_ticks = past_ticks; println!("processed {} cycles (of {}) in 1 second", t, ticks...
if_condition
[ { "content": "/// Represents a container for the virtual machine's data.\n\npub trait VirtualMachine<Rom: ReadableMemory, Ram: ReadableMemory> {\n\n /// Possible errors during a tick.\n\n type TickErrorTy;\n\n\n\n /// Retrieve the last state of the ALU outputs.\n\n fn last_alu(&self) -> AluOutputs;\...
Rust
cc3200-hal/src/sysctl.rs
emgre/cc3200-rs
68f6321ba894c402ee949698de5707e1d641a47e
use cc3200_pac::ARCM; pub struct Sysctl { arcm: ARCM, } impl Sysctl { pub fn new(arcm: ARCM) -> Self { Self { arcm } } pub fn free(self) -> ARCM { self.arcm } pub fn control_power(&mut self, peripheral: Peripheral, mode: RunMode, state: PowerState) { match m...
use cc3200_pac::ARCM; pub struct Sysctl { arcm: ARCM, } impl Sysctl { pub fn new(arcm: ARCM) -> Self { Self { arcm } } pub fn free(self) -> ARCM { self.arcm } pub fn control_power(&mut self, peripheral: Peripheral, mode: RunMode, state: PowerState) { match m...
}
fn from(from: PowerState) -> Self { match from { PowerState::On => true, PowerState::Off => false, } }
function_block-full_function
[ { "content": " &self.0\n\n }\n\n}\n\nimpl core::ops::DerefMut for W {\n\n #[inline(always)]\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n &mut self.0\n\n }\n\n}\n\nimpl core::convert::From<crate::W<CAMCLKEN_SPEC>> for W {\n\n fn from(writer: crate::W<CAMCLKEN_SPEC>) -> Self...
Rust
crates/tor-bytes/src/impls.rs
Mohsen7s/arti
1dbb23982fa36d431f2dd2b501cfc043438d9de5
use super::*; use generic_array::GenericArray; impl Writer for Vec<u8> { fn write_all(&mut self, bytes: &[u8]) { self.extend_from_slice(bytes); } fn write_u8(&mut self, byte: u8) { self.push(byte); } fn write_zeros(&mut self, n: usize) { let new_len = sel...
use super::*; use generic_array::GenericArray; impl Writer for Vec<u8> { fn write_all(&mut self, bytes: &[u8]) { self.extend_from_slice(bytes); } fn write_u8(&mut self, byte: u8) { self.push(byte); } fn write_zeros(&mut self, n: usize) { let new_len = sel...
} } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use crate::{Reader, Writer}; use hex_literal::hex; macro_rules! check_encode { ($e:expr, $e2:expr) => { let mut w = Vec::new(); w.write(&$e); assert_eq!(&w[..], &$e2[..]); }; } m...
fn take_from(r: &mut Reader<'_>) -> Result<Self> { let mut array = [0_u8; N]; r.take_into(&mut array[..])?; Ok(array) }
function_block-function_prefix_line
[ { "content": "#[cfg(feature = \"hsv3-client\")]\n\npub fn blind_pubkey(pk: &PublicKey, mut param: [u8; 32]) -> Result<PublicKey, BlindingError> {\n\n use curve25519_dalek::edwards::CompressedEdwardsY;\n\n use curve25519_dalek::scalar::Scalar;\n\n\n\n // Clamp the blinding parameter\n\n param[0] &= 2...
Rust
src/lib.rs
apasel422/binomial-heap
586170213ea1e6fa1158c206383ce12fed546e28
#![deny(missing_docs)] use std::fmt::{self, Debug}; use std::marker::PhantomData; use std::mem; mod node; pub use node::{IntoIter, Iter}; #[derive(Clone)] pub struct BinomialHeap<T: Ord> { root: Option<Box<node::Node<T>>>, len: usize, } impl<T: Ord> BinomialHeap<T> { pub fn new() -> Self { ...
#![deny(missing_docs)] use std::fmt::{self, Debug}; use std::marker::PhantomData; use std::mem; mod node; pub use node::{IntoIter, Iter}; #[derive(Clone)] pub struct BinomialHeap<T: Ord> { root: Option<Box<node::Node<T>>>, len: usize, } impl<T: Ord> BinomialHeap<T> { pub fn new() -> Self { ...
ovariance() { fn heap<'a, T: Ord>(heap: BinomialHeap<&'static T>) -> BinomialHeap<&'a T> { heap } fn into_iter<'a, T: Ord>(iter: IntoIter<&'static T>) -> IntoIter<&'a T> { iter } fn iter<'i, 'a, T: Ord>(iter: Iter<'i, &'static T>) -> Iter<'i, &'a T> { iter } }
function_block-function_prefixed
[ { "content": "pub fn pop<T: Ord>(root: &mut Option<Box<Node<T>>>, len: &mut usize) -> Option<T> {\n\n remove_max(root).map(|max| {\n\n let max = *max;\n\n let Node { item, child, order: _order, next: _next } = max;\n\n\n\n match *root {\n\n None => *root = child,\n\n ...
Rust
src/lib.rs
tmiasko/dbus-launch-rs
164d98f4a82199ae900fcc2ddc41bab89969258b
use crate::process::Process; use crate::xml::XmlWriter; use std::ffi::{OsStr, OsString}; use std::fs; use std::io; use std::os::unix::ffi::*; use std::os::unix::io::AsRawFd; use std::os::unix::net::UnixListener; use std::path::{Path, PathBuf}; use std::time::Duration; mod pipe; mod process; mod sys; mod xml; #[deri...
use crate::process::Process; use crate::xml::XmlWriter; use std::ffi::{OsStr, OsString}; use std::fs; use std::io; use std::os::unix::ffi::*; use std::os::unix::io::AsRawFd; use std::os::unix::net::UnixListener; use std::path::{Path, PathBuf}; use std::time::Duration; mod pipe; mod process; mod sys; mod xml; #[deri...
d_tag("allow"); xml.end_tag("policy"); xml.end_tag("busconfig"); s } } #[cfg(test)] mod tests { use super::*; #[test] fn to_xml() { let mut c = Config::default(); c.bus_type = Some(BusType::Session); c.listen.push("unix:tmpdir=/tmp".into()); ...
Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum DaemonType { DBusDaemon, DBusBroker, } #[derive(Clone, Debug)] struct Service { name: String, exec: PathBuf, } #[derive(Debug)] pub struct Daemon { address: String, tmp_dir: tempfile::TempDir, process: Process, } #[derive(Clone, C...
random
[ { "content": "struct Pipe {\n\n fds: [c_int; 2],\n\n}\n\n\n\nimpl Pipe {\n\n fn new() -> Self {\n\n let mut fds = [0; 2];\n\n assert_ne!(unsafe { libc::pipe(fds.as_mut_ptr()) }, -1);\n\n Pipe { fds }\n\n }\n\n}\n\n\n\nimpl Drop for Pipe {\n\n fn drop(&mut self) {\n\n asse...
Rust
oak_functions/loader/src/attestation.rs
DavidKorczynski/oak
fa53908358dd9e9b37f21e4aca17fb41485f5f33
use crate::{ logger::Logger, proto::{streaming_session_server::StreamingSession, StreamingRequest, StreamingResponse}, }; use anyhow::Context; use futures::{Stream, StreamExt}; use log::Level; use oak_functions_abi::proto::ConfigurationInfo; use oak_remote_attestation::handshaker::{AttestationBehavior, Encryp...
use crate::{ logger::Logger, proto::{streaming_session_server::StreamingSession, StreamingRequest, StreamingResponse}, }; use anyhow::Context; use futures::{Stream, StreamExt}; use log::Level; use oak_functions_abi::proto::ConfigurationInfo; use oak_remote_attestation::handshaker::{AttestationBehavior, Encryp...
} } #[tonic::async_trait] impl<F, S> StreamingSession for AttestationServer<F> where F: 'static + Send + Sync + Clone + FnOnce(oak_functions_abi::proto::Request) -> S, S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync + 'static, { type StreamStream = Pin<Box<dyn Stream<Ite...
Ok(Self { tee_certificate, request_handler, config_info, logger, })
call_expression
[ { "content": "/// Process the stream of messages coming in on `receiver` using the provided handler.\n\n///\n\n/// If the runtime signals that the node is being terminated while waiting for new commands, the\n\n/// loop will terminate and this function will return without completing the `handler` future.\n\n///...
Rust
src/header/content_description.rs
jchv/asf-rs
33544df1555662de314e4584ac3c81b8ff3b8f9d
use crate::{span::Span, widestr::*}; use nom::{bytes::streaming::take, error::ParseError, number::streaming::le_u16, IResult}; use std::{convert::TryInto, io::Write}; #[derive(Debug, PartialEq)] pub struct ContentDescriptionData { pub title: WideStr, pub author: WideStr, pub copyright: WideStr, pub des...
use crate::{span::Span, widestr::*}; use nom::{bytes::streaming::take, error::ParseError, number::streaming::le_u16, IResult}; use std::{convert::TryInto, io::Write}; #[derive(Debug, PartialEq)] pub struct ContentDescriptionData { pub title: WideStr, pub author: WideStr, pub copyright: WideStr, pub des...
pub fn size_of(&self) -> usize { let mut len = 0; len += 2; len += 2; len += 2; len += 2; len += 2; len += self.title.size_of(); len += self.author.size_of(); len += self.copyright.size_of(); len += self.description.size_of(); ...
pub fn write<T: Write>(&self, w: &mut T) -> Result<(), Box<dyn std::error::Error>> { let title_len: u16 = self.title.size_of().try_into()?; let author_len: u16 = self.author.size_of().try_into()?; let copyright_len: u16 = self.copyright.size_of().try_into()?; let description_len: u16 = s...
function_block-full_function
[ { "content": "pub fn guid<I, E>(input: I) -> IResult<I, Uuid, E>\n\nwhere\n\n I: InputLength + InputTake + InputIter + AsBytes,\n\n E: ParseError<I>,\n\n{\n\n map(take(16usize), |i: I| {\n\n let b = i.as_bytes();\n\n Uuid::from_bytes([\n\n b[3], b[2], b[1], b[0], b[5], b[4], b[...
Rust
src/vector_clock.rs
saethlin/miri
03a05ae2114602140403aeb5b14cce4f5964bbe3
use rustc_index::vec::Idx; use smallvec::SmallVec; use std::{cmp::Ordering, fmt::Debug, ops::Index}; #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct VectorIdx(u32); impl VectorIdx { #[inline(always)] pub fn to_u32(self) -> u32 { self.0 } pub const MAX_INDEX: Vec...
use rustc_index::vec::Idx; use smallvec::SmallVec; use std::{cmp::Ordering, fmt::Debug, ops::Index}; #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct VectorIdx(u32); impl VectorIdx { #[inline(always)] pub fn to_u32(self) -> u32 { self.0 } pub const MAX_INDEX: Vec...
}
assert_eq!( matches!(compare, Some(Ordering::Greater)), l > r, "Invalid (>):\n l: {:?}\n r: {:?}", l, r ); assert_eq!( matches!(compare, Some(Ordering::Greater) | Some(Ordering::Equal)), l >= r, "Invalid (>=)...
function_block-function_prefix_line
[ { "content": "// compile-flags: -Zmiri-strict-provenance\n\n// Gather all references from a mutable iterator and make sure Miri notices if\n\n// using them is dangerous.\n\nfn test_all_refs<'a, T: 'a>(dummy: &mut T, iter: impl Iterator<Item = &'a mut T>) {\n\n // Gather all those references.\n\n let mut r...
Rust
src/pass/ecm.rs
maerhart/llhd-rust
40142f9ee20bee32d6942a35138b60902d981f57
use crate::{analysis::DominatorTree, ir::prelude::*, opt::prelude::*}; use std::collections::{HashMap, HashSet}; pub struct EarlyCodeMotion; impl Pass for EarlyCodeMotion { fn run_on_cfg(ctx: &PassContext, unit: &mut UnitBuilder) -> bool { info!("ECM [{}]", unit.name()); let mut modified = false...
use crate::{analysis::DominatorTree, ir::prelude::*, opt::prelude::*}; use std::collections::{HashMap, HashSet}; pub struct EarlyCodeMotion; impl Pass for EarlyCodeMotion { fn run_on_cfg(ctx: &PassContext, unit: &mut UnitBuilder) -> bool { info!("ECM [{}]", unit.name()); let mut modified = false...
trace!(" Working on {}", inst.dump(&unit)); let doms: Vec<_> = unit[inst] .args() .iter() .flat_map(|&arg| unit.get_value_inst(arg)) .map(|inst| unit.inst_block(inst).unwrap()) .map(|block| dt.dominated_by(block)) .collect(); if doms.is...
if op == Opcode::Ld || op == Opcode::St || op == Opcode::Prb || op == Opcode::Drv || op == Opcode::Phi || op.is_terminator() { return false; }
if_condition
[ { "content": "/// Fold a single instruction.\n\n///\n\n/// Returns `true` if the unit that contains the instruction was modified.\n\npub fn run_on_inst(unit: &mut UnitBuilder, inst: Inst) -> bool {\n\n unit.insert_before(inst);\n\n\n\n // Don't bother folding instructions which don't yield a result.\n\n ...
Rust
src/command/processor.rs
jujinesy/storycraft_loco-protocol-rs
9b83430d66caf31e06f26d66b782fabc2619b275
/* * Created on Mon Nov 30 2020 * * Copyright (c) storycraft. Licensed under the MIT Licence. */ use std::io::{Cursor, Read, Write}; use super::{Command, Error, Header, ReadHeader, WriteCommand}; pub struct CommandProcessor<S: Read + Write> { stream: S, current: Option<Header>, read_buffer: Vec...
/* * Created on Mon Nov 30 2020 * * Copyright (c) storycraft. Licensed under the MIT Licence. */ use std::io::{Cursor, Read, Write}; use super::{Command, Error, Header, ReadHeader, WriteCommand}; pub struct CommandProcessor<S: Read + Write> { stream: S, current: Option<Header>, read_buffer: Vec...
pub fn read_command(&mut self) -> Result<Option<Command>, Error> { match self.try_read_command() { Ok(read) => { match read { Some(command) => Ok(Some(command)), None => { let mut buf = [0_u8; 2...
header: self.current.unwrap(), data: self.read_buffer.drain(..command_size).collect::<Vec<u8>>() }; self.current = None; Ok(Some(command)) } else { Ok(None) } }
function_block-function_prefix_line
[ { "content": "pub trait WriteCommand {\n\n\n\n fn write_command(&mut self, command: Command) -> Result<usize, Error>;\n\n\n\n}\n\n\n\nimpl<T: Write + WriteHeader> WriteCommand for T {\n\n\n\n fn write_command(&mut self, command: Command) -> Result<usize, Error> {\n\n let header_written = self.write...
Rust
simple-dns/src/dns/resource_record.rs
Disasm/simple-dns
64248bae1f4a0e075cd1800ab9159cb1370cbff7
use crate::{QCLASS, QTYPE}; use super::{rdata::RData, DnsPacketContent, Name, CLASS, TYPE}; use core::fmt::Debug; use std::{collections::HashMap, convert::TryInto, hash::Hash}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct ResourceRecord<'a> { pub name: Name<'a>, pub class: CLASS, ...
use crate::{QCLASS, QTYPE}; use super::{rdata::RData, DnsPacketContent, Name, CLASS, TYPE}; use core::fmt::Debug; use std::{collections::HashMap, convert::TryInto, hash::Hash}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct ResourceRecord<'a> { pub name: Name<'a>, pub class: CLASS, ...
#[test] fn test_hash_ignore_ttl() { let a = ResourceRecord::new( Name::new_unchecked("_srv.local"), CLASS::IN, 10, RData::TXT(TXT::new().with_string("text").unwrap()), ); let mut b = ResourceRecord::new( Name::new_unchecked("_...
fn test_eq() { let a = ResourceRecord::new( Name::new_unchecked("_srv.local"), CLASS::IN, 10, RData::TXT(TXT::new().with_string("text").unwrap()), ); let b = ResourceRecord::new( Name::new_unchecked("_srv.local"), CLASS::IN,...
function_block-full_function
[ { "content": "/// Convert the port to an SRV record. The provided name will be used as resource name and target\n\npub fn port_to_srv_record<'a>(name: &Name<'a>, port: u16, rr_ttl: u32) -> ResourceRecord<'a> {\n\n ResourceRecord::new(\n\n name.clone(),\n\n CLASS::IN,\n\n rr_ttl,\n\n ...
Rust
src/gint0/ctrl.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[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 `OR`"] #[inline(always)] pub fn is_or(&self) -> bool { *self == COMB_A::OR } #[doc = "Checks if the value of the field is `AND`"] #[inline(always)] pub fn is_and(&self) -> bool { *self == COMB_A::AND } } #[doc = "Write proxy f...
pub fn variant(&self) -> COMB_A { match self.bits { false => COMB_A::OR, true => COMB_A::AND, } }
function_block-full_function
[ { "content": "#[doc = \"Reader of register INT_ENABLE\"]\n\npub type R = crate::R<u32, super::INT_ENABLE>;\n\n#[doc = \"Writer for register INT_ENABLE\"]\n\npub type W = crate::W<u32, super::INT_ENABLE>;\n\n#[doc = \"Register INT_ENABLE `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::INT_ENABLE...
Rust
src/structs/drawing/outline.rs
Schiznitz/umya-spreadsheet
fdeafcf9e3272655b863c7320f16df7df5424ae9
use super::TailEnd; use super::SolidFill; use super::NoFill; use writer::driver::*; use reader::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use quick_xml::Writer; use std::io::Cursor; #[derive(Default, Debug)] pub struct Outline { width: u32, compound_line_type: Option<String...
use super::TailEnd; use super::SolidFill; use super::NoFill; use writer::driver::*; use reader::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use quick_xml::Writer; use std::io::Cursor; #[derive(Default, Debug)] pub struct Outline { width: u32, compound_line_type: Option<String...
}, Ok(Event::Empty(ref e)) => { match e.name() { b"a:tailEnd" => { let mut obj = TailEnd::default(); obj.set_attributes(reader, e); &mut self.set_tail_end(obj)...
match e.name() { b"a:solidFill" => { let mut solid_fill = SolidFill::default(); solid_fill.set_attributes(reader, e); &mut self.set_solid_fill(solid_fill); }, _ => ...
if_condition
[ { "content": "/// create new spreadsheet file.\n\n/// # Arguments\n\n/// # Return value\n\n/// * Spreadsheet structs object.\n\n/// # Examples\n\n/// ```\n\n/// let mut book = umya_spreadsheet::new_file();\n\n/// ```\n\npub fn new_file()->structs::Spreadsheet {\n\n let mut spreadsheet = structs::Spreadsheet:...
Rust
cargo-cov/src/main.rs
quark-zju/cov
e25378a75cbae647e6c5363ced948565f8b26631
#![recursion_limit = "128"] #![cfg_attr(feature = "cargo-clippy", warn(warnings, clippy_pedantic))] #![cfg_attr(feature = "cargo-clippy", allow(missing_docs_in_private_items, non_ascii_literal, shadow_reuse, unused_results))] #[macro_use] extern crate bitflags; #[macro_use] extern crate clap; #[macro_use] extern c...
#![recursion_limit = "128"] #![cfg_attr(feature = "cargo-clippy", warn(warnings, clippy_pedantic))] #![cfg_attr(feature = "cargo-clippy", allow(missing_docs_in_private_items, non_ascii_literal, shadow_reuse, unused_results))] #[macro_use] extern crate bitflags; #[macro_
h") [PATH] +global "Path to the manifest of the package") (@subcommand clean => (about: "Clean coverage artifacts") (@setting UnifiedHelpMessage) (@group build => (@arg gcda: --gcda "Remove the profile data only (*.gcda)") ...
use] extern crate clap; #[macro_use] extern crate error_chain; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_json; extern crate cov; extern crate env_logger; extern crate fs_extra; extern crate fs2; extern crate glob; extern...
random
[ { "content": "/// Analyzes the the source path and obtain its corresponding [`SourceType`].\n\n///\n\n/// `crates_path` should be the string representation of the workspace path. If the `path` starts with `crates_path`, it\n\n/// will be considered to be [`SourceType::LOCAL`].\n\n///\n\n/// The return type is a...
Rust
matrix_sdk_base/src/models/message.rs
stoically/matrix-rust-sdk
34cdf31cc5e03e763e794c662ec239c452a74829
use std::{time::SystemTime, vec::IntoIter}; use matrix_sdk_common::{ events::AnyPossiblyRedactedSyncMessageEvent, identifiers::{EventId, UserId}, }; use serde::{de, ser, Serialize}; pub trait PossiblyRedactedExt { fn event_id(&self) -> &EventId; fn origin_server_ts(&self) -> &SystemTime; ...
use std::{time::SystemTime, vec::IntoIter}; use matrix_sdk_common::{ events::AnyPossiblyRedactedSyncMessageEvent, identifiers::{EventId, UserId}, }; use serde::{de, ser, Serialize}; pub trait PossiblyRedactedExt { fn event_id(&self) -> &EventId; fn origin_server_ts(&self) -> &SystemTime; ...
pl IntoIterator for MessageQueue { type Item = AnyPossiblyRedactedSyncMessageEvent; type IntoIter = IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.msgs.into_iter() } } pub(crate) mod ser_deser { use std::fmt; use super::*; struct MessageQueueDeserializer; ...
, other: &MessageQueue) -> bool { self.msgs .iter() .zip(other.msgs.iter()) .all(|(a, b)| a.event_id() == b.event_id()) } } im
random
[ { "content": "#[async_trait]\n\n#[allow(clippy::type_complexity)]\n\n#[cfg_attr(not(target_arch = \"wasm32\"), send_sync)]\n\npub trait CryptoStore: Debug {\n\n /// Load an account that was previously stored.\n\n async fn load_account(&self) -> Result<Option<Account>>;\n\n\n\n /// Save the given accoun...
Rust
slimchain-network/src/p2p/control.rs
hkbudb/slimchain
acd527b1cc00d5b87170de5cecfcbf6db0dfa12f
use async_trait::async_trait; use futures::{ channel::{mpsc, oneshot}, future::poll_fn, prelude::*, }; use libp2p::{ core::{muxing, transport}, identity::Keypair, swarm::{ protocols_handler::ProtocolsHandler, IntoProtocolsHandler, NetworkBehaviour, Swarm, SwarmEvent, }, M...
use async_trait::async_trait; use futures::{ channel::{mpsc, oneshot}, future::poll_fn, prelude::*, }; use libp2p::{ core::{muxing, transport}, identity::Keypair, swarm::{ protocols_handler::ProtocolsHandler, IntoProtocolsHandler, NetworkBehaviour, Swarm, SwarmEvent, }, M...
; match msg { ControlMsg::Shutdown => { swarm_tx.start_send(swarm.take().expect("Failed to get the swarm.")).ok(); return Poll::Ready(()) }, ControlMsg::Call(func) => func...
match Pin::new(&mut rx).poll_next(cx) { Poll::Ready(Some(msg)) => msg, Poll::Ready(None) => return Poll::Ready(()), Poll::Pending => break, }
if_condition
[ { "content": "pub fn init_metrics_subscriber(writer: impl Write + Send + Sync + 'static) -> Result<Guard> {\n\n Guard::new(writer)\n\n}\n\n\n", "file_path": "slimchain-utils/src/metrics.rs", "rank": 0, "score": 286311.7114532734 }, { "content": "#[inline]\n\nfn get_code_len(id: TxTaskId, ...
Rust
src/pki.rs
saschagrunert/kubernix
ff7f5ba871b8c8959312889a469f017dc3688975
use crate::{network::Network, node::Node, Config}; use anyhow::{bail, Context, Result}; use getset::Getters; use log::{debug, info}; use serde_json::{json, to_string_pretty}; use std::{ fs::{self, create_dir_all}, net::Ipv4Addr, path::{Path, PathBuf}, process::{Command, Stdio}, }; #[derive(Getters)] pu...
use crate::{network::Network, node::Node, Config}; use anyhow::{bail, Context, Result}; use getset::Getters; use log::{debug, info}; use serde_json::{json, to_string_pretty}; use std::{ fs::{self, create_dir_all}, net::Ipv4Addr, path::{Path, PathBuf}, process::{Command, Stdio}, }; #[derive(Getters)] pu...
fn node_user(node: &str) -> String { format!("system:node:{}", node) } } #[cfg(test)] mod tests { use super::*; use crate::{ config::tests::{test_config, test_config_wrong_root}, network::tests::test_network, }; #[test] fn new_success() -> Result<()> { ...
fn write_ca_config(dir: &Path) -> Result<PathBuf> { let cfg = json!({ "signing": { "default": { "expiry": "8760h" }, "profiles": { "kubernetes": { "usages": [ "...
function_block-full_function
[ { "content": "pub fn run_root(test: &str) -> PathBuf {\n\n test_dir(test).join(\"run\")\n\n}\n\n\n", "file_path": "tests/common.rs", "rank": 0, "score": 125360.46859835027 }, { "content": "fn run_container_test(test: &str, command: &str, args: Option<&[&str]>) -> Result<()> {\n\n let i...
Rust
qirlib/src/codegen/rt.rs
nilslice/pyqir
9ae0395e5a0fe52221be16322256629e891d63c6
use inkwell::{ module::{Linkage, Module}, values::FunctionValue, AddressSpace, }; use super::types::{self, qubit, result}; pub(crate) fn result_get_zero<'ctx>( context: &'ctx inkwell::context::Context, module: &Module<'ctx>, ) -> FunctionValue<'ctx> { if let Some(function) = get_function(mod...
use inkwell::{ module::{Linkage, Module}, values::FunctionValue, AddressSpace, }; use super::types::{self, qubit, result}; pub(crate) fn result_get_zero<'ctx>( context: &'ctx inkwell::context::Context, module: &Module<'ctx>, ) -> FunctionValue<'ctx> { if let Some(function) = get_function(mod...
pub(crate) fn result_equal<'ctx>( context: &'ctx inkwell::context::Context, module: &Module<'ctx>, ) -> FunctionValue<'ctx> { if let Some(function) = get_function(module, "result_equal") { function } else { let result_ptr_type = result(context, module).ptr_type(AddressSpace::Generic); ...
get_function_name("result_get_one").as_str(), fn_type, Some(Linkage::External), ); fn_value } }
function_block-function_prefix_line
[ { "content": "fn module_functions<'ctx>(module: &Module<'ctx>) -> impl Iterator<Item = FunctionValue<'ctx>> {\n\n struct FunctionValueIter<'ctx>(Option<FunctionValue<'ctx>>);\n\n\n\n impl<'ctx> Iterator for FunctionValueIter<'ctx> {\n\n type Item = FunctionValue<'ctx>;\n\n\n\n fn next(&mut s...
Rust
src/libedgedns/src/config.rs
jedisct1/edgedns
c501833eb08edce517400bff956b18da6cf0f192
use coarsetime::Duration; use resolver::LoadBalancingMode; use std::io::prelude::*; use std::fs::File; use std::io::{Error, ErrorKind}; use std::path::Path; use toml; #[derive(Clone, Debug)] pub struct Config { pub decrement_ttl: bool, pub upstream_servers: Vec<String>, pub lbmode: LoadBalancingMode, ...
use coarsetime::Duration; use resolver::LoadBalancingMode; use std::io::prelude::*; use std::fs::File; use std::io::{Error, ErrorKind}; use std::path::Path; use toml; #[derive(Clone, Debug)] pub struct Config { pub decrement_ttl: bool, pub upstream_servers: Vec<String>, pub lbmode: LoadBalancingMode, ...
let config_webservice = toml_config.get("webservice"); let webservice_enabled = config_webservice.and_then(|x| x.get("enabled")).map_or( false, |x| x.as_bool().expect("webservice.enabled must be a boolean"), ); let webservice_listen_addr = config_webservice ...
let config_cache = toml_config.get("cache"); let cache_size = config_cache.and_then(|x| x.get("max_items")).map_or( 250_000, |x| x.as_integer().expect("cache.max_items must be an integer"), ) as usize; let min_ttl = config_cache.and_then(|x| x.get("min_ttl")).map_...
random
[ { "content": "#[inline]\n\npub fn set_ancount(packet: &mut [u8], value: u16) {\n\n packet[6] = (value >> 8) as u8;\n\n packet[7] = value as u8;\n\n}\n\n\n", "file_path": "src/libedgedns/src/dns.rs", "rank": 0, "score": 160932.5777090759 }, { "content": "#[inline]\n\npub fn set_qdcount(...
Rust
gullery/src/vertex/vao/raw.rs
Osspial/gl_raii
b747cbe5f72590d7ba42b656db14dfab0cf7f3c9
use crate::gl::{self, types::*, Gl}; use crate::{ buffer::Buffer, geometry::{Scalar, ScalarBase, ScalarType, TransparentType, TypeTagSingle}, vertex::{Index, Vertex, VertexMemberRegistry}, ContextState, GLObject, Handle, }; use std::{cell::Cell, marker::PhantomData, mem}; pub struct RawVAO<V: Verte...
use crate::gl::{self, types::*, Gl}; use crate::{ buffer::Buffer, geometry::{Scalar, ScalarBase, ScalarType, TransparentType, TypeTagSingle}, vertex::{Index, Vertex, VertexMemberRegistry}, ContextState, GLObject, Handle, }; use std::{cell::Cell, marker::PhantomData, mem}; pub struct RawVAO<V: Verte...
#[inline] pub unsafe fn reset_bind(&self, gl: &Gl) { self.bound_vao.set(None); gl.BindVertexArray(0); } } impl<'a, V: Vertex> VertexMemberRegistry for VertexAttribBuilder<'a, V> { type Group = V; fn add_member<T>(&mut self, name: &str, get_type: fn(*const V) -> *const T) wher...
let ibuf_handle_opt = ibuf.as_ref().map(|ib| ib.handle()); if ibuf_handle_opt != vao.ibuf.get() { gl.BindBuffer( gl::ELEMENT_ARRAY_BUFFER, ibuf_handle_opt.map(|h| h.get()).unwrap_or(0), ); vao.ibuf.set(ibuf_handle_opt); } RawBo...
function_block-function_prefix_line
[ { "content": "pub fn set_viewport(gl: &Gl, min: GLVec2<u32, NonNormalized>, max: GLVec2<u32, NonNormalized>) {\n\n let width = max.x - min.x;\n\n let height = max.y - min.y;\n\n assert!(width < GLint::max_value() as u32);\n\n assert!(width < GLint::max_value() as u32);\n\n unsafe {\n\n gl....
Rust
src/day03/bin/main.rs
hsaunders1904/advent-of-code-2021
09ed82266c59e4edcbb58033092321e52855ddd0
use advent_of_code::cli; use bit_field::BitField; use std::io::BufRead; fn read_lines_to_decimal<T>(lines: std::io::Lines<T>) -> Vec<u64> where T: std::io::BufRead, { let mut decimals: Vec<u64> = Vec::new(); for (line_num, line) in lines .map(|x| u64::from_str_radix(&x.unwrap(), 2)) .enumer...
use advent_of_code::cli; use bit_field::BitField; use std::io::BufRead; fn read_lines_to_decimal<T>(lines: std::io::Lines<T>) -> Vec<u64> where T: std::io::BufRead, { let mut decimals: Vec<u64> = Vec::new(); for (line_num, line) in lines .map(|x| u64::from_str_radix(&x.unwrap(), 2)) .enumer...
; println!("co2_rating: {}", co2_rating); oxygen_rating * co2_rating } fn main() { let args = cli::parse_args(); let file = match std::fs::File::open(&args.file_path) { Err(why) => panic!( "Could not open file '{}': {}", args.file_path, std::io::Error::to_st...
} }) .collect(); } values[0] } fn get_life_support_rating(values: &Vec<u64>, num_bits: usize) -> u64 { let oxygen_rating = get_oxygen_rating(values.clone(), num_bits); println!("oxygen_rating: {}", oxygen_rating); let co2_rating = get_co2_rating(values.clone(), num_b...
random
[ { "content": "\n\n InputArgs {\n\n file_path: matches.value_of(\"data_file\").unwrap().to_owned(),\n\n }\n\n }\n\n}\n\n\n\npub mod aoc_io {\n\n use std::fs::File;\n\n use std::io::BufRead;\n\n use std::path::Path;\n\n\n\n pub fn read_lines<P>(filename: P) -> std::io::Resu...
Rust
src/core/search/scorer/disjunction_scorer.rs
unix1986/rucene
bf4de84dafb58eeedfc2b975556890ed3e5dc1f6
use core::search::scorer::Scorer; use core::search::{DocIterator, NO_MORE_DOCS}; use core::util::DocId; use error::Result; use std::f32; pub struct DisjunctionSumScorer<T: Scorer> { sub_scorers: Vec<T>, curr_doc: DocId, cost: usize, } impl<T: Scorer> DisjunctionSumScorer<T> { pub fn new(children: V...
use core::search::scorer::Scorer; use core::search::{DocIterator, NO_MORE_DOCS}; use core::util::DocId; use error::Result; use std::f32; pub struct DisjunctionSumScorer<T: Scorer> { sub_scorers: Vec<T>, curr_doc: DocId, cost: usize, } impl<T: Scorer> DisjunctionSumScorer<T> { pub fn new(children: V...
fn approximate_advance(&mut self, target: DocId) -> Result<DocId> { let mut min_doc = NO_MORE_DOCS; for s in self.sub_scorers.iter_mut() { if s.doc_id() < target { s.approximate_advance(target)?; } min_doc = min_doc.min(s.doc_id()); } ...
S; for s in self.sub_scorers.iter_mut() { if s.doc_id() == curr_doc { s.approximate_next()?; } min_doc = min_doc.min(s.doc_id()); } self.curr_doc = min_doc; Ok(self.doc_id()) }
function_block-function_prefixed
[ { "content": "/// helper function for doc iterator support two phase\n\npub fn two_phase_next(scorer: &mut dyn Scorer) -> Result<DocId> {\n\n let mut doc = scorer.doc_id();\n\n loop {\n\n if doc == NO_MORE_DOCS {\n\n return Ok(NO_MORE_DOCS);\n\n } else if scorer.matches()? {\n\n ...
Rust
algebra/primefield/src/fft.rs
nondejus/OpenZKP
3d37eb21d99673fed2d86940da779cf9e741c54e
#![allow(clippy::module_name_repetitions)] use crate::FieldElement; use std::prelude::v1::*; pub fn permute_index(size: usize, index: usize) -> usize { const USIZE_BITS: usize = 0_usize.count_zeros() as usize; debug_assert!(index < size); if size == 1 { 0 } else { debug_assert!(size.is...
#![allow(clippy::module_name_repetitions)] use crate::FieldElement; use std::prelude::v1::*; pub fn permute_index(size: usize, index: usize) -> usize { const USIZE_BITS: usize = 0_usize.count_zeros() as usize; debug_assert!(index < size); if size == 1 { 0 } else { debug_assert!(size.is...
0bdce513eb42295402eb5dde3d13abfc0325f277f507bc") ); assert_eq!( U256::from(&res[7]), u256h!("034738bd5956b1df55369cdc211109fd67e6ffd2ffbb08e856b1b4d1b1a2c6ae") ); } #[quickcheck] fn ifft_is_inverse(v: Vec<FieldElement>) -> bool { if v.is_empty() { ...
se zkp_macros_decl::u256h; use zkp_u256::U256; fn reference_fft(x: &[FieldElement]) -> Vec<FieldElement> { let root = FieldElement::root(x.len()).unwrap(); let mut result = Vec::with_capacity(x.len()); let mut root_i = FieldElement::ONE; for _ in 0..x.len() { ...
random
[]
Rust
src/fiat_shamir/constraints.rs
AleoHQ/marlin
d78863356cefd50ec23bd131d37f6bdbf2fb8b28
use crate::fiat_shamir::{AlgebraicSponge, FiatShamirAlgebraicSpongeRng, FiatShamirRng}; use crate::{overhead, Vec}; use ark_ff::PrimeField; use ark_nonnative_field::params::{get_params, OptimizationType}; use ark_nonnative_field::{AllocatedNonNativeFieldVar, NonNativeFieldVar}; use ark_r1cs_std::{ alloc::AllocVar, ...
use crate::fiat_shamir::{AlgebraicSponge, FiatShamirAlgebraicSpongeRng, FiatShamirRng}; use crate::{overhead, Vec}; use ark_ff::PrimeField; use ark_nonnative_field::params::{get_params, OptimizationType}; use ark_nonnative_field::{AllocatedNonNativeFieldVar, NonNativeFieldVar}; use ark_r1cs_std::{ alloc::AllocVar, ...
#[tracing::instrument(target = "r1cs", skip(self))] fn squeeze_128_bits_field_elements( &mut self, num: usize, ) -> Result<Vec<NonNativeFieldVar<F, CF>>, SynthesisError> { Self::get_gadgets_from_sponge(&mut self.s, num, true) } #[tracing::instrument(target = "r1cs", skip(s...
fn squeeze_field_elements_and_bits( &mut self, num: usize, ) -> Result<(Vec<NonNativeFieldVar<F, CF>>, Vec<Vec<Boolean<CF>>>), SynthesisError> { Self::get_gadgets_and_bits_from_sponge(&mut self.s, num, false) }
function_block-function_prefix_line
[ { "content": "/// the trait for algebraic sponge\n\npub trait AlgebraicSponge<CF: PrimeField>: Clone {\n\n /// initialize the sponge\n\n fn new() -> Self;\n\n /// take in field elements\n\n fn absorb(&mut self, elems: &[CF]);\n\n /// take out field elements\n\n fn squeeze(&mut self, num: usize...
Rust
src/cmds/machines/list.rs
apognu/htb
57168bc61021fc79d1ccfacd3e9cc3280c515009
use crate::{ api::{self, HtbError}, args::MachineListArgs, }; use colored::*; use prettytable::{format::consts::*, Cell, Row, Table}; use std::error::Error; pub async fn list(args: &MachineListArgs) -> Result<(), Box<dyn Error>> { let mut machines = api::machines::list().await?; let spawned = api::mach...
use crate::{ api::{self, HtbError}, args::MachineListArgs, }; use colored::*; use prettytable::{format::consts::*, Cell, Row, Table}; use std::error::Error; pub async fn list(args: &MachineListArgs) -> Result<(), Box<dyn Error>> { let mut machines = api::machines::list().await?; let spawned = api::mach...
l::new("⚫").style_spec("Fg") } else { Cell::new("⚫").style_spec("Fr") }; table.add_row(Row::new(vec![ spawned, Cell::new(&machine.name), Cell::new(&machine.os), Cell::new(&format!("👤 {}", machine.user_owns)).style_spec(if *user { ...
function_block-function_prefixed
[ { "content": "pub fn client() -> Result<Client, Box<dyn Error>> {\n\n let creds = format!(\"Bearer {}\", *API_KEY);\n\n\n\n let mut headers = HeaderMap::new();\n\n headers.insert(header::AUTHORIZATION, HeaderValue::from_str(&creds.trim())?);\n\n\n\n Ok(ClientBuilder::new()\n\n .user_agent(\"h...
Rust
vm/actor/src/builtin/miner/sectors.rs
willeslau/forest
1aec44b1ba6d13e62449411683588f11564cbd16
use super::SectorOnChainInfo; use crate::{actor_error, ActorDowncast, ActorError, ExitCode}; use ahash::AHashSet; use bitfield::BitField; use cid::Cid; use fil_types::{SectorNumber, MAX_SECTOR_NUMBER}; use ipld_amt::{Amt, Error as AmtError}; use ipld_blockstore::BlockStore; use std::collections::HashSet; use std::err...
use super::SectorOnChainInfo; use crate::{actor_error, ActorDowncast, ActorError, ExitCode}; use ahash::AHashSet; use bitfield::BitField; use cid::Cid; use fil_types::{SectorNumber, MAX_SECTOR_NUMBER}; use ipld_amt::{Amt, Error as AmtError}; use ipld_blockstore::BlockStore; use std::collections::HashSet; use std::err...
} pub(crate) fn select_sectors( sectors: &[SectorOnChainInfo], field: &BitField, ) -> Result<Vec<SectorOnChainInfo>, Box<dyn StdError>> { let mut to_include: AHashSet<_> = field.iter().collect(); let mut included = Vec::with_capacity(to_include.len()); for s in sectors { let sec = s.secto...
let sector_count = sectors.len(); let fault_set: HashSet<usize> = faults.iter().collect(); let mut sector_infos = Vec::with_capacity(sector_count); for i in sectors.iter() { let faulty = fault_set.contains(&i); let sector = if !faulty { self.must_get(i a...
function_block-function_prefix_line
[ { "content": "/// Returns a vector of cids from provided root cid\n\nfn read_amt_cids<DB>(db: &DB, root: &Cid) -> Result<Vec<Cid>, Error>\n\nwhere\n\n DB: BlockStore,\n\n{\n\n let amt = Amt::<Cid, _>::load(root, db)?;\n\n\n\n let mut cids = Vec::new();\n\n for i in 0..amt.count() {\n\n if let...
Rust
tss-esapi/src/context/tpm_commands/attestation_commands.rs
Superhepper/rust-tss-esapi
a6ae84793e73b10dd672b613ada820566c84fe85
use crate::{ handles::{KeyHandle, ObjectHandle}, structures::{Attest, AttestBuffer, Data, PcrSelectionList, Signature, SignatureScheme}, tss2_esys::*, Context, Error, Result, }; use log::error; use mbox::MBox; use std::convert::TryFrom; use std::ptr::null_mut; impl Context { ...
use crate::{ handles::{KeyHandle, ObjectHandle}, structures::{Attest, AttestBuffer, Data, PcrSelectionList, Signature, SignatureScheme}, tss2_esys::*, Context, Error, Resu
rom(*certify_info)?)?, Signature::try_from(*signature)?, )) } else { error!("Error in certifying: {}", ret); Err(ret) } } pub fn quote( &mut self, signing_key_handle: KeyHandle, qualifying_data...
lt, }; use log::error; use mbox::MBox; use std::convert::TryFrom; use std::ptr::null_mut; impl Context { ...
random
[ { "content": "fn get_ek_object_public(context: &mut crate::Context) -> Result<PublicKey> {\n\n let key_handle = ek::create_ek_object(context, AsymmetricAlgorithm::Rsa, None)?;\n\n let (attesting_key_pub, _, _) = context.read_public(key_handle).or_else(|e| {\n\n context.flush_context(key_handle.into...
Rust
codegen_test/src/lib.rs
Kimundi/index_many
0e5523d2979389709c2218989514ec7effe74190
macro_rules! generate { ( header { $( $item:item )* } $( $id:literal: fn $name:ident($( $arg:ident: $argty:ty ),* $(,)?) -> $ret:ty $blk:block )* ) => { use index_many::*; $( ...
macro_rules! generate { ( header { $( $item:item )* } $( $id:literal: fn $name:ident($( $arg:ident: $argty:ty ),* $(,)?) -> $ret:ty $blk:block )* ) => { use index_many::*; $( ...
ice: &mut [Elem], indices: generic::UnsortedSpecializedIndices<4>, ) -> [&mut Elem; 4] { generic::index_many_mut(slice, indices) } 6: fn std_option( slice: &mut [Elem], indices: [usize; LEN], ) -> Option<[&mut Elem; LEN]> { std_proposal::SliceExt::get_many_mut_op...
header { #[allow(unused_imports)] use std::ops::Range; #[allow(unused_imports)] use simple_result::{GetManyError, GetManyErrorKind}; #[allow(unused_imports)] use std_proposal::{ErrorKind, Error, ErrorNiche, ErrorSimple}; pub type Elem = usize; pub c...
random
[ { "content": "pub fn get_many<'a, T, const N: usize>(\n\n slice: &[T],\n\n indices: [usize; N],\n\n) -> Result<[&T; N], GetManyError<N>> {\n\n if !check_indices_valid(&indices, slice.len()) {\n\n return Err(GetManyError {\n\n indices,\n\n len: slice.len(),\n\n });\n\...
Rust
crates/core/src/manager/buckets.rs
chawyehsu/scoop-rs
2abb48295297346ed41b0a19af3fed343d6461fe
use crate::model::Bucket; use crate::util::leaf; use crate::Config; use crate::Git; use crate::ScoopResult; use indexmap::IndexMap; use once_cell::sync::Lazy; use rayon::iter::{ParallelBridge, ParallelIterator}; use std::result::Result; use std::sync::{Arc, Mutex}; static KNOWN_BUCKETS: Lazy<IndexMap<&'static str, &'...
use crate::model::Bucket; use crate::util::leaf; use crate::Config; use crate::Git; use crate::ScoopResult; use indexmap::IndexMap; use once_cell::sync::Lazy; use rayon::iter::{ParallelBridge, ParallelIterator}; use std::result::Result; use std::sync::{Arc, Mutex}; static KNOWN_BUCKETS: Lazy<IndexMap<&'static str, &'...
; git.clone(local_path, remote_url) } pub fn remove_bucket<S: AsRef<str>>(&self, name: S) -> ScoopResult<()> { let bucket_name = name.as_ref(); if !self.contains(bucket_name) { anyhow::bail!("bucket '{}' does not exist", bucket_name); } let bucket_path =...
match repo { Some(repo) => repo.as_ref().to_owned(), None => self.known_bucket_url(bucket_name).to_owned(), }
if_condition
[ { "content": "pub fn installed_apps<'cfg>(config: &'cfg Config) -> ScoopResult<Vec<InstalledApp<'cfg>>> {\n\n let mut apps = config\n\n .apps_path()\n\n .read_dir()?\n\n .par_bridge()\n\n .filter_map(|de| {\n\n if de.is_err() {\n\n return None;\n\n ...
Rust
beacon_node/eth2-libp2p/src/rpc/methods.rs
mslipper/lighthouse
389951530afa4a9b3a924b8b3b5fd9e80e29ce3c
use ssz::{impl_decode_via_from, impl_encode_via_from}; use ssz_derive::{Decode, Encode}; use types::{BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; #[derive(Debug)] pub enum RPCMethod { Hello, Goodbye, BeaconBlockRoots, BeaconBlockHeaders, BeaconBlockBodies, ...
use ssz::{impl_decode_via_from, impl_encode_via_from}; use ssz_derive::{Decode, Encode}; use types::{BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; #[derive(Debug)] pub enum RPCMethod { Hello, Goodbye, BeaconBlockRoots, BeaconBlockHeaders, BeaconBlockBodies, ...
method.into() } } /* Request/Response data structures for RPC methods */ #[derive(Encode, Decode, Clone, Debug)] pub struct HelloMessage { pub network_id: u8, pub latest_finalized_root: Hash256, pub latest_finalized_epoch: Epoch, pub best_root: Hash256, pub be...
let method = match self { RPCResponse::Hello(_) => RPCMethod::Hello, RPCResponse::BeaconBlockRoots(_) => RPCMethod::BeaconBlockRoots, RPCResponse::BeaconBlockHeaders(_) => RPCMethod::BeaconBlockHeaders, RPCResponse::BeaconBlockBodies(_) => RPCMethod::BeaconBlockBodies, ...
assignment_statement
[ { "content": "/// Returns a list of all `validator_registry` indices where the validator is active at the given\n\n/// `epoch`.\n\n///\n\n/// Spec v0.5.1\n\npub fn get_active_validator_indices(validators: &[Validator], epoch: Epoch) -> Vec<usize> {\n\n let mut active = Vec::with_capacity(validators.len());\n...
Rust
src/store/analyze.rs
JoshBrudnak/askalono
6a6da879c0a9a8a3ee5a758356cfb363711871ab
use std::cmp::Ordering; use std::fmt; use failure::Error; use license::LicenseType; use license::TextData; use store::base::Store; #[derive(Clone)] pub struct Match<'a> { pub score: f32, pub name: String, #[deprecated] pub aliases: Vec<String>, pub licens...
use std::cmp::Ordering; use std::fmt; use failure::Error; use license::LicenseType; use license::TextData; use store::base::Store; #[derive(Clone)] pub struct Match<'a> { pub score: f32, pub name: String, #[deprecated] pub aliases: Vec<String>, pub licens...
data: alt, }) }); data.headers.iter().for_each(|head| { acc.push(PartialMatch { score: head.match_score(text), name, license_type: LicenseType::Header, ...
"wasm32"))] { self.analyze_parallel(text) } } #[allow(unused)] #[cfg(not(target_arch = "wasm32"))] fn analyze_parallel(&self, text: &TextData) -> Result<Match, Error> { use rayon::prelude::*; let mut res: Vec<PartialMatch> = self .licenses ...
random
[ { "content": "pub fn apply_aggressive(text: &str) -> String {\n\n let mut out = text.to_owned();\n\n for preproc in &PREPROC_AGGRESSIVE {\n\n out = preproc(&out);\n\n }\n\n debug!(\"Aggressively normalized to:\\n{}\\n---\", out);\n\n out\n\n}\n\n\n\n// Line-by-line normalizers\n\n\n", ...
Rust
src/wasi_runtime.rs
deislabs/krustlet-wasm3
9f4faa34fdc77181df956864edc0c0600dc4d2d4
use futures::task; use log::{error, info, trace}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::task::{Context, Poll}; use tempfile::NamedTempFile; use tokio::sync::mpsc::Sender; use tokio::task::JoinHandle; use wasm3::{Environment, Module}; use kubelet::container::Handle...
use futures::task; use log::{error, info, trace}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::task::{Context, Poll}; use tempfile::NamedTempFile; use tokio::sync::mpsc::Sender; use tokio::t
message: message.into(), timestamp: chrono::Utc::now(), }, &mut cx, ); return Err(anyhow::anyhow!("{}: {}", message, e)); } }; let modul...
ask::JoinHandle; use wasm3::{Environment, Module}; use kubelet::container::Handle as ContainerHandle; use kubelet::container::Status; use kubelet::handle::StopHandler; pub struct Runtime { handle: JoinHandle<anyhow::Result<()>>, } #[async_trait::async_trait] impl StopHandler for Runtime { async fn stop(&mut ...
random
[ { "content": "use log::{error, info};\n\n\n\nuse super::error::Error;\n\nuse super::image_pull::ImagePull;\n\nuse crate::PodState;\n\nuse kubelet::container::Container;\n\nuse kubelet::state::prelude::*;\n\n\n", "file_path": "src/states/registered.rs", "rank": 1, "score": 5.735025228935494 }, { ...
Rust
tools/ssp16asm/src/asm/registers.rs
jdesiloniz/svpdev
13438d71c9cd45c8f78f9768732c40ddec2548d9
#[derive(Debug, Copy, Clone, PartialEq)] pub enum SspGeneralRegister { Dummy, X, Y, A, St, Stack, Pc, P, Ext0, Ext1, Ext2, Ext3, Ext4, Ext5, Ext6, Ext7, } impl SspGeneralRegister { pub fn new(reg: &str) -> Option<SspGeneralRegister> { match re...
#[derive(Debug, Copy, Clone, PartialEq)] pub enum SspGeneralRegister { Dummy, X, Y, A, St, Stack, Pc, P, Ext0, Ext1, Ext2, Ext3, Ext4, Ext5, Ext6, Ext7, } impl SspGeneralRegister { pub fn new(reg: &str) -> Option<SspGeneralRegister> { match re...
"r1-" => Some(SspPointerRegister::R1(SspModifier::PostDecrementModulo)), "r2-" => Some(SspPointerRegister::R2(SspModifier::PostDecrementModulo)), "r4-" => Some(SspPointerRegister::R4(SspModifier::PostDecrementModulo)), "r5-" => Some(SspPointerRegister::R5(SspModifier::PostDecreme...
Some(SspGeneralRegister::Y), "a" => Some(SspGeneralRegister::A), "st" => Some(SspGeneralRegister::St), "stack" => Some(SspGeneralRegister::Stack), "pc" => Some(SspGeneralRegister::Pc), "p" => Some(SspGeneralRegister::P), "ext0" => Some(SspGeneralR...
random
[ { "content": "pub fn split_line(line: &str) -> Vec<&str> {\n\n line.split_whitespace()\n\n .map(|slice| slice.trim_matches(','))\n\n .fold(Vec::new(), |mut acc, mut x| {\n\n if x.contains(',') {\n\n let mut split = x.split(\",\").collect::<Vec<&str>>();\n\n ...
Rust
src/conventional/commit.rs
pjvds/cocogitto
635a043c04a37a4b355b473759ab4071e91530cf
use crate::conventional::commit::CommitType::*; use crate::error::ErrorKind::CommitFormat; use crate::AUTHORS; use crate::COMMITS_METADATA; use crate::REMOTE_URL; use anyhow::Result; use chrono::{NaiveDateTime, Utc}; use colored::*; use git2::Commit as Git2Commit; use serde::export::Formatter; use std::cmp::Ordering; u...
use crate::conventional::commit::CommitType::*; use crate::error::ErrorKind::CommitFormat; use crate::AUTHORS; use crate::COMMITS_METADATA; use crate::REMOTE_URL; use anyhow::Result; use chrono::{NaiveDateTime, Utc}; use colored::*; use git2::Commit as Git2Commit; use serde::export::Formatter; use std::cmp::Ordering; u...
pub(crate) fn shorthand(&self) -> &str { if self.oid != "not committed" { &self.oid[0..6] } else { &self.oid } } pub(crate) fn parse_commit_message(message: &str) -> Result<CommitMessage> { let type_separator = message.find(": "); if ty...
2_message); match message { Ok(message) => Ok(Commit { oid, message, author, date, }), Err(err) => { let additional_info = if commit.parent_count() == 0 { format!( ...
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn git_commit(message: &str) -> Result<()> {\n\n let mut rng = rand::thread_rng();\n\n let random: f64 = rng.gen();\n\n std::fs::write(random.to_string(), \"dummy\")?;\n\n\n\n println!(\"git add .\");\n\n Command::new(\"git\")\n\n .arg(\"add\")\n\n ...
Rust
src/type_.rs
sapir/rustc_codegen_gcc
ebe6f6785c5f3ba6c2a18876829774bc215476f5
use std::convert::TryInto; use gccjit::{RValue, Struct, Type}; use rustc_codegen_ssa::traits::{BaseTypeMethods, DerivedTypeMethods}; use rustc_codegen_ssa::common::TypeKind; use rustc_middle::bug; use rustc_middle::ty::layout::TyAndLayout; use rustc_target::abi::{AddressSpace, Align, Integer, Size}; use crate::common...
use std::convert::TryInto; use gccjit::{RValue, Struct, Type}; use rustc_codegen_ssa::traits::{BaseTypeMethods, DerivedTypeMethods}; use rustc_codegen_ssa::common::TypeKind; use rustc_middle::bug; use rustc_middle::ty::layout::TyAndLayout; use rustc_target::abi::{AddressSpace, Align, Integer, Size}; use crate::common...
fn vector_length(&self, _ty: Type<'gcc>) -> usize { unimplemented!(); } fn float_width(&self, typ: Type<'gcc>) -> usize { let f32 = self.context.new_type::<f32>(); let f64 = self.context.new_type::<f64>(); if typ == f32 { 32 } else if typ == f64...
vector_type.get_element_type() } else if let Some(typ) = ty.get_pointee() { typ } else { unreachable!() } }
function_block-function_prefix_line
[ { "content": "pub fn type_is_pointer<'gcc>(typ: Type<'gcc>) -> bool {\n\n typ.get_pointee().is_some()\n\n}\n\n\n\nimpl<'gcc, 'tcx> ConstMethods<'tcx> for CodegenCx<'gcc, 'tcx> {\n\n fn const_null(&self, typ: Type<'gcc>) -> RValue<'gcc> {\n\n if type_is_pointer(typ) {\n\n self.context.new...
Rust
vulkano/src/command_buffer/validity/vertex_buffers.rs
Amjad50/vulkano
619af8239c1f7f9da6138f2d817f235fe3971142
use crate::command_buffer::synced::CommandBufferState; use crate::pipeline::graphics::vertex_input::VertexInputRate; use crate::pipeline::GraphicsPipeline; use crate::DeviceSize; use std::convert::TryInto; use std::error; use std::fmt; pub(in super::super) fn check_vertex_buffers( current_state: CommandBufferSta...
use crate::command_buffer::synced::CommandBufferState; use crate::pipeline::graphics::vertex_input::VertexInputRate; use crate::pipeline::GraphicsPipeline; use crate::DeviceSize; use std::convert::TryInto; use std::error; use std::fmt; pub(in super::super) fn check_vertex_buffers( current_state: CommandBufferSta...
}
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( fmt, "{}", match *self { CheckVertexBufferError::BufferNotBound { .. } => { "no buffer was bound to a binding slot needed by the pipeline" } ...
function_block-full_function
[ { "content": "/// Checks whether the dispatch dimensions are supported by the device.\n\npub fn check_dispatch(device: &Device, dimensions: [u32; 3]) -> Result<(), CheckDispatchError> {\n\n let max = device\n\n .physical_device()\n\n .properties()\n\n .max_compute_work_group_count;\n\n\n...
Rust
src/config/loading.rs
f1shl3gs/vertex
8911e1956ee5ed5ba0d7123d775df315f13ca7be
use regex::{Captures, Regex}; use std::collections::HashMap; use std::fs::File; use std::path::{Path, PathBuf}; use std::sync::Mutex; use super::validation; use crate::config::{format, Builder, Config, ConfigPath, Format, FormatHint}; use crate::signal; lazy_static! { pub static ref CONFIG_PATHS: Mutex<Vec<Config...
use regex::{Captures, Regex}; use std::collections::HashMap; use std::fs::File; use std::path::{Path, PathBuf}; use std::sync::Mutex; use super::validation; use crate::config::{format, Builder, Config, ConfigPath, Format, FormatHint}; use crate::signal; lazy_static! { pub static ref CONFIG_PATHS: Mutex<Vec<Config...
onfigPath::Dir(path)); } } } } paths.sort(); paths.dedup(); std::mem::drop(CONFIG_PATHS.lock().map(|mut guard| *guard = paths.clone())); Some(paths) } #[cfg(test)] mod tests { use super::*; const INPUT: &str = r#" global: data_dir: ./temp ...
: Format) -> Result<Config, Vec<String>> { let (builder, load_warnings) = load_from_inputs(std::iter::once((content.as_bytes(), Some(format))))?; let (config, build_warnings) = builder.build_with_warnings()?; load_warnings .into_iter() .chain(build_warnings) .for_each(|warni...
random
[ { "content": "pub fn pathbuf_to_string(path: &Path) -> Result<&str, Error> {\n\n path.to_str()\n\n .ok_or_else(|| KafkaError::InvalidPath { path: path.into() }.into())\n\n}\n\n\n\npub struct KafkaStatisticsContext;\n\n\n\nimpl ClientContext for KafkaStatisticsContext {\n\n fn stats(&self, statistic...
Rust
sulis_view/src/world_map_window.rs
ThyWoof/sulis
e89eda94a1a72228224e1926d307aa4c9228bdcb
use std::any::Any; use std::cell::RefCell; use std::rc::Rc; use sulis_core::ui::{animation_state, Callback, Widget, WidgetKind}; use sulis_core::util::Point; use sulis_core::widgets::{Button, TextArea}; use sulis_module::{campaign::WorldMapLocation, Module, Time}; use sulis_state::GameState; pub const NAME: &str = ...
use std::any::Any; use std::cell::RefCell; use std::rc::Rc; use sulis_core::ui::{animation_state, Callback, Widget, WidgetKind}; use sulis_core::util::Point; use sulis_core::widgets::{Button, TextArea}; use sulis_module::{campaign::WorldMapLocation, Module, Time}; use sulis_state::GameState; pub const NAME: &str = ...
let label = Widget::with_theme(TextArea::empty(), "label"); label .borrow_mut() .state .add_text_arg("name", &location.name); label.borrow_mut().state.set_visible(is_visible); ( ...
if !self.transition_enabled { state.animation_state.add(animation_state::Kind::Custom1); }
if_condition
[]
Rust
src/parser.rs
JakeStanger/corn
c8b2cb5c9f7f3458bfd0b758e0735b058a22d655
use std::collections::{BTreeMap, HashMap}; use std::env; use std::fmt::Formatter; use pest::iterators::Pair; use pest::Parser; use crate::error::{Error, InputResolveError, Result}; use crate::{Config, Inputs, Value}; #[derive(pest_derive::Parser)] #[grammar = "grammar.pest"] pub struct ConfigParser; impl std::fmt::...
use std::collections::{BTreeMap, HashMap}; use std::env; use std::fmt::Formatter; use pest::iterators::Pair; use pest::Parser; use crate::error::{Error, InputResolveError, Result}; use crate::{Config, Inputs, Value}; #[derive(pest_derive::Parser)] #[grammar = "grammar.pest"] pub struct ConfigParser; impl std::fmt::...
rap(), &inputs)?; inputs.insert(name, value); } Ok(inputs) } pub fn parse(file: &str) -> Result<Config> { let rules = ConfigParser::parse(Rule::config, file); match rules { Ok(mut rules) => { let first_block = rules.next().unwrap(); match first_block.as_rule(...
t mut assign_rules = pair.into_inner(); let name = assign_rules.next().unwrap().as_str(); let value = parse_value(assign_rules.next().unw
function_block-random_span
[ { "content": "#[wasm_bindgen]\n\npub fn parse(corn: &str) -> Result<JsValue, JsValue> {\n\n console_error_panic_hook::set_once();\n\n\n\n let res = crate::parse(corn);\n\n\n\n match res {\n\n Ok(parsed) => Ok(JsValue::from_serde(&parsed).unwrap()),\n\n Err(err) => Err(JsValue::from_str(er...
Rust
lib/segment/src/id_tracker/simple_id_tracker.rs
eadventurous/qdrant
ec4c0205955ad889a068537f5ab297223d239bfe
use crate::entry::entry_point::OperationResult; use crate::id_tracker::IdTracker; use crate::types::{ExtendedPointId, PointIdType, PointOffsetType, SeqNumberType}; use bincode; use rocksdb::{IteratorMode, Options, DB}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; use std::path::Path; ...
use crate::entry::entry_point::OperationResult; use crate::id_tracker::IdTracker; use crate::types::{ExtendedPointId, PointIdType, PointOffsetType, SeqNumberType}; use bincode; use rocksdb::{IteratorMode, Options, DB}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; use std::path::Path; ...
Box::new(range.map(|(key, value)| (*key, *value))) } fn flush(&self) -> OperationResult<()> { self.store .flush_cf(self.store.cf_handle(MAPPING_CF).unwrap())?; self.store .flush_cf(self.store.cf_handle(VERSIONS_CF).unwrap())?; Ok(self.store.flush()?) ...
let range = match external_id { None => self.external_to_internal.range(..), Some(offset) => self.external_to_internal.range(offset..), };
assignment_statement
[ { "content": "pub fn read_json<N: DeserializeOwned + Serialize>(path: &Path) -> OperationResult<N> {\n\n let mut contents = String::new();\n\n\n\n let mut file = File::open(path)?;\n\n file.read_to_string(&mut contents)?;\n\n\n\n let result: N =\n\n serde_json::from_str(&contents).map_err(|er...
Rust
src/regex/state_machine/machine.rs
magnunm/fst
12083707eef4ff45bfce2c65a8f28d9b3d876532
use std::fmt; use std::vec::Vec; pub struct NFA<'a> { pub state_register: StateRegister<'a>, pub start_state: usize, } impl<'a> NFA<'a> { pub fn simulate(&self, input: &str, greedy: bool) -> Option<usize> { let mut simulation = NFASimulation::new(self);...
use std::fmt; use std::vec::Vec; pub struct NFA<'a> { pub state_register: StateRegister<'a>, pub start_state: usize, } impl<'a> NFA<'a> { pub fn simulate(&self, input: &str, greedy: bool) -> Option<usize> { let mut simulation = NFASimulation::new(self);...
_matching_char_index } } struct NFASimulation<'a> { nfa: &'a NFA<'a>, current_states: Vec<usize>, in_match_state: bool, } impl<'a> NFASimulation<'a> { fn new(nfa: &'a NFA) -> NFASimulation<'a> { let mut new_simulation = NFASimulation { nfa, curre...
atching_char_index; } } if simulation.current_states.is_empty() { return first_non_matching_char_index; } simulation.update_states(character); } if simulation.in_match_state { first_n...
function_block-random_span
[ { "content": "#[inline]\n\nfn nfa_match_substring(nfa: &NFA, input: &str, from_start: bool) -> Option<(usize, usize)> {\n\n if from_start {\n\n if let Some(match_end_byte_index) = nfa.simulate(input, true) {\n\n return Some((0, match_end_byte_index));\n\n }\n\n return None;\n\...
Rust
tests/test.rs
mesalock-linux/deflate-rs-sgx
352f2d27c2b4cd816892a3c7080ab92d1877a6c4
extern crate deflate; extern crate miniz_oxide; use deflate::CompressionOptions; use std::io::{Read, Write}; fn get_test_file_data(name: &str) -> Vec<u8> { use std::fs::File; let mut input = Vec::new(); let mut f = File::open(name).unwrap(); f.read_to_end(&mut input).unwrap(); input } fn get_tes...
extern crate deflate; extern crate miniz_oxide; use deflate::CompressionOptions; use std::io::{Read, Write}; fn get_test_file_data(name: &str) -> Vec<u8> { use std::fs::File; let mut input = Vec::new(); let mut f = File::open(name).unwrap(); f.read_to_end(&mut input).unwrap(); input } fn get_tes...
#[test] fn issue_26() { use deflate::write::ZlibEncoder; let fp = Vec::new(); let mut fp = ZlibEncoder::new(fp, CompressionOptions::default()); fp.write(&[0]).unwrap(); fp.flush().unwrap(); fp.write(&[0]).unwrap(); fp.write(&[0, 0]).unwrap(); } #[cfg(feature = "gzip")] #[test] fn issue_2...
fn rle() { use deflate::{deflate_bytes_conf, CompressionOptions}; let test_data = get_test_data(); let compressed = deflate_bytes_conf(&test_data, CompressionOptions::rle()); let decompressed = miniz_oxide::inflate::decompress_to_vec(&compressed).expect("Decompression failed!"); println!("I...
function_block-full_function
[ { "content": "fn deflate_bytes_flate2_zlib(level: Compression, input: &[u8]) -> Vec<u8> {\n\n use flate2::write::ZlibEncoder;\n\n\n\n let mut e = ZlibEncoder::new(Vec::with_capacity(input.len() / 3), level);\n\n e.write_all(input).unwrap();\n\n e.finish().unwrap()\n\n}\n\n\n", "file_path": "benc...
Rust
src/app.rs
EwoutH/broot
bdd4ff99c72ad8a8d86d21fcd5cb0e56a63a00ed
use std::io::{self, stdin, Write}; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc}; use std::thread; use termion::input::TermRead; use crate::app_context::AppContext; use crate::browser_states::BrowserState; use crate::commands::Command; use crate::external::Launcha...
use std::io::{self, stdin, Write}; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc}; use std::thread; use termion::input::TermRead; use crate::app_context::AppContext; use crate::browser_states::BrowserState; use crate::commands::Command; use crate::external::Launcha...
} pub trait AppState { fn apply(&mut self, cmd: &mut Command, screen: &Screen, con: &AppContext) -> io::Result<AppStateCmdResult>; fn has_pending_tasks(&self) -> bool; fn do_pending_task(&mut self, screen: &Screen, tl: &TaskLifetime); fn display(&mut self, screen: &mut Screen, con: &AppContext) -> io:...
te(os: Option<BrowserState>) -> AppStateCmdResult { match os { Some(os) => AppStateCmdResult::NewState(Box::new(os)), None => AppStateCmdResult::Keep, } }
function_block-function_prefixed
[ { "content": "// do some simple markdown-like formatting to ease text generation:\n\n// - bold: **bold text**\n\n// - code: `some code`\n\nfn md(s: &str) -> String {\n\n lazy_static! {\n\n static ref bold_regex: Regex = Regex::new(r\"\\*\\*([^*]+)\\*\\*\").unwrap();\n\n static ref bold_repl: St...
Rust
bindings/java/native/src/classes/client/full_node_api.rs
gotakk/iota.rs
34bfa88d4cc286b73c4c51ed5b3cd4219154ba40
use anyhow::{anyhow, Result}; use std::{ convert::{From, Into}, str::FromStr, }; use iota_client::{ bee_message::{input::UtxoInput as RustUtxoInput, payload::transaction::TransactionId, MessageId}, client::Client as ClientRust, }; use crate::{ address::*, balance::GetBalanceBuilderApi, ...
use anyhow::{anyhow, Result}; use std::{ convert::{From, Into}, str::FromStr, }; use iota_client::{ bee_message::{input::UtxoInput as RustUtxoInput, payload::transaction::TransactionId, MessageId}, client::Client as ClientRust, }; use crate::{ address::*, balance::GetBalanceBuilderApi, ...
pub fn get_addresses_balances(&self, addresses: Vec<String>) -> Result<Vec<BalanceAddressResponse>> { let result: Vec<BalanceAddressResponse> = crate::block_on(async { self.0.get_address_balances(&addresses).await })? .into_iter() .map(|b| b.into()) ...
pub fn get_address_balance(&self, address: &str) -> Result<BalanceAddressResponse> { let mut result: BalanceAddressResponse = crate::block_on(async { self.0.get_address().balance(&String::from(address)).await })?.into(); result.address = crate::block_on(async { self.0.hex_to_bech32(&result.a...
function_block-function_prefix_line
[ { "content": "/// Parses a bech32 address string.\n\nfn parse_address(address: &str) -> crate::Result<Address> {\n\n Ok(Address::try_from_bech32(address).map_err(|_| anyhow::anyhow!(\"invalid address\"))?)\n\n}\n\n\n\n#[derive(Deserialize)]\n\n#[serde(tag = \"type\")]\n\npub enum OutputTypeDto {\n\n Signa...
Rust
src/toolchains.rs
srijs/cargo-cross
cbb792e7ba4d8d0ce1cf67e764f0df3fd394ecc6
use std::ffi::OsString; use std::path::PathBuf; use directories::ProjectDirs; use failure::Error; use heck::ShoutySnakeCase; use platforms; use semver::VersionReq; use cargo::{CargoPackage, CargoProject}; use package::{PackageInstall, PackageManager}; pub struct ToolchainManager { dirs: ProjectDirs, host: pl...
use std::ffi::OsString; use std::path::PathBuf; use directories::ProjectDirs; use failure::Error; use heck::ShoutySnakeCase; use platforms; use semver::VersionReq; use cargo::{CargoPackage, CargoProject}; use package::{PackageInstall, PackageManager}; pub struct ToolchainManager { dirs: ProjectDirs, host: pl...
} struct ToolchainBase { target_platform_triple: &'static str, host_platform_triple: &'static str, gcc_version: &'static str, path: &'static str, checksum: &'static str, size: u64, } static TOOLCHAIN_MIRROR: &str = "https://d3ojaw7tkwhzj5.cloudfront.net"; static TOOLCHAINS_BASE: &[ToolchainB...
t dir = self.dirs.cache_dir().to_path_buf(); dir.extend(&[ "target", feature.target_platform_triple, "feature", &feature.checksum, ]); dir }
function_block-function_prefixed
[ { "content": "pub fn build<I, K, V>(opts: &CargoOptions, envs: I) -> Result<process::ExitStatus, Error>\n\nwhere\n\n I: IntoIterator<Item = (K, V)>,\n\n K: AsRef<OsStr>,\n\n V: AsRef<OsStr>,\n\n{\n\n let mut command = process::Command::new(\"cargo\");\n\n command.arg(\"build\");\n\n opts.apply...
Rust
src/service_dispatcher.rs
njeffords/winsvc
50b909f526741dc328bd2b40c2148cf8e7c6babd
use std::{ ptr::null_mut, sync::mpsc, ffi::c_void, }; use winapi::{ shared::winerror::{ NO_ERROR, ERROR_CALL_NOT_IMPLEMENTED, }, um::{ winsvc::{ SERVICE_RUNNING, SERVICE_START_PENDING, SERVICE_PAUSE_PENDING, SERVICE_STOP_P...
use std::{ ptr::null_mut, sync::mpsc, ffi::c_void, }; use winapi::{ shared::winerror::{ NO_ERROR, ERROR_CALL_NOT_IMPLEMENTED, }, um::{ winsvc::{ SERVICE_RUNNING, SERVICE_START_PENDING, SERVICE_PAUSE_PENDING, SERVICE_STOP_P...
}; if handle != null_mut() { let status = SERVICE_STATUS{ dwServiceType: SERVICE_WIN32_OWN_PROCESS, dwCurrentState: SERVICE_START_PENDING, dwControlsAccepted: 0, dwWin32ExitCode: 0, dwServiceSpecificExitCode: 0, dwCheckPoint: 0, ...
RegisterServiceCtrlHandlerExW( service_name.as_ptr(), Some(handler_function_ex::<T>), context as *mut _, )
call_expression
[ { "content": "fn extra_raw_enum_value(key: HKEY, index: u32, name: &mut [u16], (value_ptr, value_len): (*mut u8, u32)) -> Result<(u32,u32,u32)> {\n\n\n\n let (name, mut name_len) = (name.as_mut_ptr(), name.len () as u32);\n\n let mut value_type : u32 = 0;\n\n let mut value_len = value_len;\n\n\n\n E...
Rust
src/triangulate.rs
Kurble/amethyst_voxel
c992c355301ff29c56a66984393860be57d7fac4
use crate::ambient_occlusion::*; use crate::context::Context; use crate::material::{AtlasAccess, AtlasMaterialHandle}; use crate::pass::Surface; use crate::side::*; use crate::voxel::*; use amethyst::renderer::{ rendy::{ command::QueueId, factory::Factory, mesh::MeshBuilder, mesh::{N...
use crate::ambient_occlusion::*; use crate::context::Context; use crate::material::{AtlasAccess, AtlasMaterialHandle}; use crate::pass::Surface; use crate::side::*; use crate::voxel::*; use amethyst::renderer::{ rendy::{ command::QueueId, factory::Factory, mesh::MeshBuilder, mesh::{N...
pub fn triangulate_face<S: Side>( triangulation: &mut Triangulation, shared: &SharedVertexData, origin: Vec3, scale: f32, material: AtlasMaterialHandle, ) { let sc = scale * 0.5; let quad = [ vec3(-sc, sc, sc), vec3(sc, sc, sc), vec3(sc, -sc, sc), vec3(-sc, ...
S: Side, T: Voxel, C: Context<T>, { let scale = scale * T::SCALE; for i in 0..T::COUNT { if sub[i].visible() { let x = (i) & T::LAST; let y = (i >> <T::Data as Data>::SUBDIV) & T::LAST; let z = (i >> (<T::Data as Data>::SUBDIV * 2)) & T::LAST; ...
function_block-function_prefix_line
[ { "content": "fn build_mesh<'a, 'c, B, V, C, A, I>(\n\n iter: I,\n\n atlas: &A,\n\n queue: QueueId,\n\n factory: &Factory<B>,\n\n) -> Option<amethyst::renderer::types::Mesh>\n\nwhere\n\n B: Backend,\n\n V: Voxel,\n\n C: Context<V> + 'c,\n\n A: AtlasAccess,\n\n I: IntoIterator<Item = (...
Rust
packages/sycamore/src/noderef.rs
jafioti/sycamore
9fdff59b9c0c399cd8793ae73fe7fd1e7d7ec3a3
use std::cell::RefCell; use std::fmt; use std::rc::Rc; use wasm_bindgen::prelude::*; use crate::generic_node::GenericNode; use crate::reactive::Scope; use std::any::Any; #[derive(Clone, PartialEq, Eq)] pub struct NodeRef<G: GenericNode>(Rc<RefCell<Option<G>>>); impl<G: GenericNode + Any> NodeRef<G> { ...
use std::cell::RefCell; use std::fmt; use std::rc::Rc; use wasm_bindgen::prelude::*; use crate::generic_node::GenericNode; use crate::reactive::Scope; use std::any::Any; #[derive(Clone, PartialEq, Eq)] pub struct NodeRef<G: GenericNode>(Rc<RefCell<Option<G>>>); impl<G: GenericNode + Any> NodeRef<G> { ...
}
fn noderef_with_ssrnode() { create_scope_immediate(|ctx| { let noderef = ctx.create_node_ref(); let _: View<SsrNode> = view! { ctx, div(ref=noderef) }; assert!(noderef.try_get::<SsrNode>().is_some()); }); }
function_block-full_function
[]
Rust
src/limb.rs
susytech/ring
0ccbdcbfa04b8bed51d1f22cb17d2f415a86b7e7
#![cfg_attr(not(feature = "use_heap"), allow(dead_code))] use {polyfill, c, error, untrusted}; #[cfg(target_pointer_width = "64")] pub type Limb = u64; #[cfg(target_pointer_width = "32")] pub type Limb = u32; #[cfg(target_pointer_width = "64")] pub const LIMB_BITS: usize = 64; #[cfg(target_pointer_width = "32")] pu...
#![cfg_attr(not(feature = "use_heap"), allow(dead_code))] use {polyfill, c, error, untrusted}; #[cfg(target_pointer_width = "64")] pub type Limb = u64; #[cfg(target_pointer_width = "32")] pub type Limb = u32; #[cfg(target_pointer_width = "64")] pub const LIMB_BITS: usize = 64; #[cfg(target_pointer_width = "32")] pu...
pub fn big_endian_from_limbs_padded(limbs: &[Limb], out: &mut [u8]) { let num_limbs = limbs.len(); let out_len = out.len(); let (to_zero, dest) = out.split_at_mut(out_len - (num_limbs * LIMB_BYTES)); for i in 0..num_limbs { let mut limb = limbs[i]; for j in 0..LIMB_BYTES { ...
pub fn parse_big_endian_and_pad_consttime( input: untrusted::Input, result: &mut [Limb]) -> Result<(), error::Unspecified> { if input.is_empty() { return Err(error::Unspecified); } let mut bytes_in_current_limb = input.len() % LIMB_BYTES; if bytes_in_current_limb ...
function_block-full_function
[ { "content": "#[inline(always)]\n\npub fn u64_from_usize(x: usize) -> u64 { x as u64 }\n\n\n\n/// `core::num::Wrapping` doesn't support `rotate_left`.\n\n/// There is no usable trait for `rotate_left`, so this polyfill just\n\n/// hard-codes u32. https://github.com/rust-lang/rust/issues/32463\n", "file_path...
Rust
src/resource/mod.rs
deckarep/huelib-rs
ffcfe527d0c01cf54052e053bb492988b92249a2
pub mod capabilities; pub mod config; pub mod group; pub mod light; pub mod resourcelink; pub mod rule; pub mod scene; pub mod schedule; pub mod sensor; pub use capabilities::Capabilities; pub use config::Config; pub use group::Group; pub use light::Light; pub use resourcelink::Resourcelink; pub use rule::Ru...
pub mod capabilities; pub mod config; pub mod group; pub mod light; pub mod resourcelink; pub mod rule; pub mod scene; pub mod schedule; pub mod sensor; pub use capabilities::Capabilities; pub use config::Config; pub use group::Group; pub use light::Light; pub use resourcelink::Resourcelink; pub use rule::Ru...
} #[derive(Clone, Debug, Eq, PartialEq)] pub enum LastScan { DateTime(chrono::NaiveDateTime), Active, None, } impl<'de> Deserialize<'de> for LastScan { fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { let value: String = Deserialize::deseria...
s = Vec::new(); let mut last_scan = None; while let Some(key) = map.next_key()? { match key { Field::LastScan => { last_scan = serde_json::from_value(map.next_value()?) .map_err(V::Err...
function_block-function_prefixed
[ { "content": "fn deserialize_whitelist<'de, D: de::Deserializer<'de>>(\n\n deserializer: D,\n\n) -> Result<Vec<User>, D::Error> {\n\n let map: std::collections::HashMap<String, User> = Deserialize::deserialize(deserializer)?;\n\n let mut users = Vec::new();\n\n for (id, user) in map {\n\n use...
Rust
tests/vec4.rs
bvrner/glam-rs
2cc97be73b91530cb28af7e0ede78c9c5b12b126
mod support; use glam::*; #[cfg(feature = "rand")] use rand::{Rng, SeedableRng}; #[cfg(feature = "rand")] use rand_xoshiro::Xoshiro256Plus; use std::f32; #[test] fn test_vec4_align() { use std::mem; assert_eq!(16, mem::size_of::<Vec4>()); assert_eq!(16, mem::size_of::<Vec4Mask>()); if cfg!(feature = "...
mod support; use glam::*; #[cfg(feature = "rand")] use rand::{Rng, SeedableRng}; #[cfg(feature = "rand")] use rand_xoshiro::Xoshiro256Plus; use std::f32; #[test] fn test_vec4_align() { use std::mem; assert_eq!(16, mem::size_of::<Vec4>()); assert_eq!(16, mem::size_of::<Vec4Mask>()); if cfg!(feature = "...
#[cfg(feature = "rand")] #[test] fn test_vec4_rand() { let mut rng1 = Xoshiro256Plus::seed_from_u64(0); let a: (f32, f32, f32, f32) = rng1.gen(); let mut rng2 = Xoshiro256Plus::seed_from_u64(0); let b: Vec4 = rng2.gen(); assert_eq!(a, b.into()); } #[test] fn test_vec4_slice() { let a = [1.0, ...
assert!(c.cmpge(c).all()); assert!(a.cmpeq(a).all()); assert!(!a.cmpeq(b).all()); assert!(a.cmpeq(c).any()); assert!(!a.cmpne(a).all()); assert!(a.cmpne(b).all()); assert!(a.cmpne(c).any()); }
function_block-function_prefix_line
[]
Rust
boa/src/object/gcobject.rs
arpit-saxena/boa
3d023350b0fed9906a54985f01e770346ad01218
use super::{Object, PROTOTYPE}; use crate::{ builtins::function::{ create_unmapped_arguments_object, BuiltInFunction, Function, NativeFunction, }, environment::{ function_environment_record::BindingStatus, lexical_environment::new_function_environment, }, syntax::ast::node::RcState...
use super::{Object, PROTOTYPE}; use crate::{ builtins::function::{ create_unmapped_arguments_object, BuiltInFunction, Function, NativeFunction, }, environment::{ function_environment_record::BindingStatus, lexical_environment::new_function_environment, }, syntax::ast::node::RcState...
ad_local! { static VISITED: RefCell<HashSet<usize>> = RefCell::new(HashSet::new()); } fn new(o: &GcObject) -> Self { let ptr = (o.as_ref() as *const _) as usize; let (free, first) = Self::VISITED.with(|hs| { let mut hs = hs.borrow_m...
} } } #[track_caller] pub fn construct(&self, args: &[Value], ctx: &mut Context) -> Result<Value> { let this: Value = Object::create(self.borrow().get(&PROTOTYPE.into())).into(); let this_function_object = self.clone(); let body = if let Some(...
random
[ { "content": "/// Create new function `[[Construct]]`\n\n///\n\n// This gets called when a new Function() is created.\n\npub fn make_function(this: &Value, _: &[Value], _: &mut Context) -> Result<Value> {\n\n this.set_data(ObjectData::Function(Function::BuiltIn(\n\n BuiltInFunction(|_, _, _| Ok(Value:...
Rust
src/webserver/wshandler.rs
wiguy/tellstickreport
c926c591734bb556f7fec6cc6bdd967980dbbbd6
use websocket::header::WebSocketProtocol; use websocket::{Server, Message, Sender, Receiver}; use websocket::message::Type; use websocket::server::sender; use websocket::stream::WebSocketStream; use std::thread; use std::sync::Arc; use std::sync::mpsc; use rustc_serialize::json::{self}; use std::str; use webserver::web...
use websocket::header::WebSocketProtocol; use websocket::{Server, Message, Sender, Receiver}; use websocket::message::Type; use websocket::server::sender; use websocket::stream::WebSocketStream; use std::thread; use std::sync::Arc; use std::sync::mpsc; use rustc_serialize::json::{self}; use std::str; use webserver::web...
fn sender_thread(sender: &mut sender::Sender<WebSocketStream>, rx: &mpsc::Receiver<WebsocketSendAction>) { loop { let action = rx.recv().unwrap(); match action { WebsocketSendAction::Message(text) => { sender.send_message(&Message::text(text)).unwrap(); }, WebsocketSendAction::Close => { break; } ...
fn handle_message(msg: String, hash: &String, tx: &mpsc::Sender<InternalAction>) -> MessageResponse { let message = webtypes::Message::from_string(msg.clone()).unwrap(); if str::from_utf8(message.hash.as_bytes()).unwrap() != str::from_utf8(hash.as_bytes()).unwrap() { println!("Got message with wrong hash. Silently ...
function_block-full_function
[ { "content": "pub fn receive_status(config: &Arc<config::Config>, tx: mpsc::Sender<internaltypes::InternalAction>) {\n\n\tlet addr = format!(\"0.0.0.0:{}\", config.status_port);\n\n\tlet socket_str = str::from_utf8(addr.as_bytes()).unwrap();\n\n\tlet result = UdpSocket::bind(socket_str);\n\n\tlet socket = match...
Rust
crates/tor-dirmgr/src/config.rs
yzernik/arti
64c8ee0d1fa589125b74ac99ce5672eada41a421
use crate::retry::DownloadSchedule; use crate::storage::DynStore; use crate::{Authority, Result}; use tor_config::ConfigBuildError; use tor_netdir::fallback::FallbackDir; use tor_netdoc::doc::netstatus; use derive_builder::Builder; use std::path::PathBuf; use serde::Deserialize; #[derive(Deserialize, Debug, Clone,...
use crate::retry::DownloadSchedule; use crate::storage::DynStore; use crate::{Authority, Result}; use tor_config::ConfigBuildError; use tor_netdir::fallback::FallbackDir; use tor_netdoc::doc::netstatus; use derive_builder::Builder; use std::path::PathBuf; use serde::Deserialize; #[derive(Deserialize, Debug, Clone,...
Ok(()) } } #[derive(Deserialize, Debug, Clone, Builder, Eq, PartialEq)] #[serde(deny_unknown_fields)] #[builder(build_fn(error = "ConfigBuildError"))] pub struct DownloadScheduleConfig { #[serde(default = "default_retry_bootstrap")] #[builder(default = "default_retry_bootstrap()")] retry...
if self.authorities.is_some() && self.fallback_caches.is_none() { return Err(ConfigBuildError::Inconsistent { fields: vec!["authorities".to_owned(), "fallbacks".to_owned()], problem: "Non-default authorities are use, but the fallback list is not overridden" ...
if_condition
[ { "content": "#[cfg(feature = \"hsv3-client\")]\n\npub fn blind_pubkey(pk: &PublicKey, mut param: [u8; 32]) -> Result<PublicKey, BlindingError> {\n\n use curve25519_dalek::edwards::CompressedEdwardsY;\n\n use curve25519_dalek::scalar::Scalar;\n\n\n\n // Clamp the blinding parameter\n\n param[0] &= 2...
Rust
azure-functions-durable/src/endpoint.rs
MutedExclamation/azure-functions-rs
bb1c7457ccfa65d8b29c74902eae1b61706f2033
use std::fmt::Write; use url::Url; #[derive(Debug, Clone)] pub struct Endpoint { base_uri: Url, task_hub: String, connection: String, code: String, } impl Endpoint { pub fn new(status_query_url: Url) -> Self { let mut task_hub = None; let mut connection = None; let mut...
use std::fmt::Write; use url::Url; #[derive(Debug, Clone)] pub struct Endpoint { base_uri: Url, task_hub: String, connection: String, code: String, } impl Endpoint {
pub fn task_hub(&self) -> &str { &self.task_hub } pub fn create_new_instance_url(&self, function_name: &str, instance_id: Option<&str>) -> Url { let mut url = self.base_uri.clone(); let path = match instance_id { Some(id) => format!( "/runtim...
pub fn new(status_query_url: Url) -> Self { let mut task_hub = None; let mut connection = None; let mut code = None; for (k, v) in status_query_url.query_pairs() { match k.to_ascii_lowercase().as_ref() { "taskhub" => task_hub = Some(v.into_owned()), ...
function_block-full_function
[ { "content": "/// The main entry point for the Azure Functions for Rust worker.\n\n///\n\n/// This entry point does not use any additional Azure Functions binding extensions.\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust,ignore\n\n/// mod example;\n\n///\n\n/// azure_functions::export! {\n\n/// example::fu...
Rust
dftk-database/src/user.rs
GDGToulouse/devfest-toolkit-rs
34b0f12441f3e7cc000e492b975484b95f18d423
use anyhow::{anyhow, Result}; use argon2::Config; use bson::Document; use chbs::passphrase; use mongodb::bson::doc; use mongodb::options::{FindOneAndUpdateOptions, FindOptions}; use mongodb::{Collection, Database}; use rand::Rng; use serde::Serialize; use tokio::stream::StreamExt; use dftk_common::acl::user::{Email, U...
use anyhow::{anyhow, Result}; use argon2::Config; use bson::Document; use chbs::passphrase; use mongodb::bson::doc; use mongodb::options::{FindOneAndUpdateOptions, FindOptions}; use mongodb::{Collection, Database}; use rand::Rng; use serde::Serialize; use tokio::stream::StreamExt; use dftk_common::acl::user::{Email, U...
user": 1, } } fn get_user(doc: &Document) -> Result<User> { let doc = doc.get_document("user")?; let user = from_document::<User>(doc.clone())?; Ok(user) } fn get_password(doc: &Document) -> Result<Password> { let pwd = doc.get_str("password")?; let result = Password(pwd.into()); Ok(resu...
if db_password.verify(password) { let user_info = get_user_info(&doc)?; Ok(user_info) } else { Err(anyhow!("No user found this e-mail & password")) } } else { Err(anyhow!("No user found this e-mail & password")) ...
random
[ { "content": "pub fn to_user(user: &UserCreateInput) -> Result<User> {\n\n let UserCreateInput { kind, email, key } = user;\n\n let email = Email::from_str(email.as_str())?;\n\n let user = match kind {\n\n UserKind::Admin => User::Admin { email },\n\n UserKind::Team => User::Team { email ...
Rust
src/tests/rpc_api_service.rs
net3f/polkadot-registrar-challenger
a0a114fbe8eda2c30b0bcfa5b5c0701fcd1c030b
use super::{ApiBackend, ApiClient, InMemBackend}; use crate::aggregate::verifier::{VerifierAggregate, VerifierAggregateId, VerifierCommand}; use crate::aggregate::Repository; use crate::api::ConnectionPool; use crate::event::{ErrorMessage, ExternalMessage, ExternalOrigin, IdentityInserted, StateWrapper}; use crate::man...
use super::{ApiBackend, ApiClient, InMemBackend}; use crate::aggregate::verifier::{VerifierAggregate, VerifierAggregateId, VerifierCommand}; use crate::aggregate::Repository; use crate::api::ConnectionPool; use crate::event::{ErrorMessage, ExternalMessage, ExternalOrigin, IdentityInserted, StateWrapper}; use crate::man...
#[test] fn subscribe_status_verified_changes_in_steps() { let shared_port = Arc::new(AtomicUsize::new(0)); let (tokenv1, tokenv2) = Regulator::new(); let alice = IdentityState::alice(); let bob = IdentityState::bob(); let t_alice = alice.clone(); tokenv1.me_first(); let t_shared_po...
fn subscribe_status_newly_inserted_identity_in_steps() { let shared_port = Arc::new(AtomicUsize::new(0)); let (tokenv1, tokenv2) = Regulator::new(); let alice = IdentityState::alice(); let bob = IdentityState::bob(); let t_alice = alice.clone(); tokenv1.me_first(); let t_shared_port ...
function_block-full_function
[ { "content": "// Must be called in a tokio v0.2 context.\n\nstruct ApiClient {\n\n client: RawClient,\n\n}\n\n\n\nimpl ApiClient {\n\n async fn new(rpc_port: usize) -> ApiClient {\n\n ApiClient {\n\n client: connect::<RawClient>(&format!(\"ws://127.0.0.1:{}\", rpc_port).parse().unwrap())...
Rust
third_party/rust_crates/vendor/base64ct/tests/url.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
#[macro_use] mod common; mod padded { use crate::common::*; use base64ct::Base64Url; const TEST_VECTORS: &[TestVector] = &[ TestVector { raw: b"", b64: "" }, TestVector { raw: b"\0", b64: "AA==", }, TestVector { raw: b"***", ...
#[macro_use] mod common; mod padded { use crate::common::*; use base64ct::Base64Url; const TEST_VECTORS: &[TestVector] = &[ TestVector { raw: b"", b64: "" }, TestVector { raw: b"\0", b64: "AA==", }, TestVector { raw: b"***", ...
raw: b"\xFF\xFF\xFF\xFF\xFF", b64: "______8", }, TestVector { raw: b"\x40\xC1\x3F\xBD\x05\x4C\x72\x2A\xA3\xC2\xF2\x11\x73\xC0\x69\xEA\ \x49\x7D\x35\x29\x6B\xCC\x24\x65\xF6\xF9\xD0\x41\x08\x7B\xD7\xA9", b64: "QME_vQVMciqjwvIRc8Bp6kl9NSlrz...
\x49\x7D\x35\x29\x6B\xCC\x24\x65\xF6\xF9\xD0\x41\x08\x7B\xD7\xA9", b64: "QME_vQVMciqjwvIRc8Bp6kl9NSlrzCRl9vnQQQh716k=", }, TestVector { raw: b"\x00\x10\x83\x10Q\x87 \x92\x8B0\xD3\x8FA\x14\x93QU\x97a\x96\x9Bq\ \xD7\x9F\x82\x18\xA3\x92Y\xA7\xA2\x9A...
random
[]
Rust
crates/ike-render/src/cube_texture.rs
ChangeCaps/ike
2ab1ee68cd50dc4f3eb0b852286549e59f007727
use bytemuck::bytes_of; use once_cell::sync::OnceCell; use crate::{render_device, render_queue, HdrTexture}; pub struct Environment { pub env_texture: CubeTexture, pub irradiance_texture: CubeTexture, } impl Default for Environment { #[inline] fn default() -> Self { Self { env_tex...
use bytemuck::bytes_of; use once_cell::sync::OnceCell; use crate::{render_device, render_queue, HdrTexture}; pub struct Environment { pub env_texture: CubeTexture, pub irradiance_texture: CubeTexture, } impl Default for Environment { #[inline] fn default() -> Self { Self { env_tex...
#[inline] pub fn inner(&self) -> &ike_wgpu::Texture { self.texture.get_or_init(|| { render_device().create_texture(&ike_wgpu::TextureDescriptor { label: None, size: ike_wgpu::Extent3d { width: self.size, height: self.s...
min_binding_size: None, has_dynamic_offset: false, }, visibility: ike_wgpu::ShaderStages::COMPUTE, count: None, }, ], }); let cube_groups = (0..stages) .into_iter() .m...
function_block-function_prefix_line
[ { "content": "fn create_pipeline(format: ike_wgpu::TextureFormat, sample_count: u32) -> ike_wgpu::RenderPipeline {\n\n let device = render_device();\n\n\n\n let module = device.create_shader_module(&ike_wgpu::include_wgsl!(\"shader.wgsl\"));\n\n\n\n device.create_render_pipeline(&ike_wgpu::RenderPipeli...
Rust
psilocyn/src/mesh/buffers.rs
ginger-code/cubensis
57189bc3bfd46066d392df09e155986082799200
use hyphae::scene::geometry::GeometrySource; use hyphae::scene::primitives::PrimitiveType; use wgpu::util::DeviceExt; #[repr(C)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct Vertex { position: [f32; 3], uv: [f32; 2], } impl Vertex { pub fn desc<'a>() -> wgpu::VertexBufferLayo...
use hyphae::scene::geometry::GeometrySource; use hyphae::scene::primitives::PrimitiveType; use wgpu::util::DeviceExt; #[repr(C)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct Vertex { position: [f32; 3], uv: [f32; 2], } impl Vertex { pub fn desc<'a>() -> wgpu::VertexBufferLayo...
pub const QUAD_VERTICES: &[Vertex] = &[ Vertex { position: [-1.0, 1.0, 0.0], uv: [0.0, 1.0], }, Vertex { position: [1.0, -1.0, 0.0], uv: [1.0, 0.0], }, Vertex { position: [-1.0, -1.0, 0.0], uv: [0.0, 0.0], }, Vertex { position: [1.0, ...
fn get_indices(geometry: &GeometrySource) -> &[u16] { log::trace!("Retrieving indices"); match geometry { GeometrySource::Primitive(primitive) => match primitive { PrimitiveType::Quad => QUAD_INDICES, }, GeometrySource::ComputeShader(_) => QUAD_INDICES, } }
function_block-function_prefix_line
[ { "content": "#[repr(C)]\n\n#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]\n\nstruct TimeBufferData {\n\n frame_index: u32,\n\n time_seconds: f32,\n\n frame_time_seconds: f32,\n\n}\n\nimpl TimeBufferData {\n\n fn new() -> Self {\n\n Self {\n\n frame_index: 0,\n\n ...
Rust
debug/src/lib.rs
ThisSeanZhang/proc-macro-workshop
03586bdb8d50d0622571d379f3694a4fb31d319a
use std::collections::HashMap; use proc_macro::TokenStream; use syn::{self, Attribute, parse_quote, spanned::Spanned}; use quote::{ToTokens, quote}; use syn::visit::{self, Visit}; #[proc_macro_derive(CustomDebug ,attributes(debug))] pub fn derive(input: TokenStream) -> TokenStream { let st = syn::parse_macro_inpu...
use std::collections::HashMap; use proc_macro::TokenStream; use syn::{self, Attribute, parse_quote, spanned::Spanned}; use quote::{ToTokens, quote}; use syn::visit::{self, Visit}; #[proc_macro_derive(CustomDebug ,attributes(debug))] pub fn derive(input: TokenStream) -> TokenStream { let st = syn::parse_macro_inpu...
ruct_name_ident = &st.ident; let fmt_body_stream = generate_debug_trait_core(st)?; let fields = get_fields_from_derive_input(st)?; let mut field_type_names = Vec::new(); let mut phantomdata_type_param_names = Vec::new(); for field in fields{ if let Some(s) = get_field_type_name(field)?...
return None }).collect(); let mut visitor = TypePathVisitor { generic_type_names: origin_generic_param_names, associated_types: HashMap::new(), }; visitor.visit_derive_input(st); return visitor.associated_types; } fn do_expand(st: &syn::DeriveInput) -> syn::Result<p...
random
[ { "content": "fn generate_build_function(fields: &StructFields, source_ident: &syn::Ident) -> syn::Result<proc_macro2::TokenStream>{\n\n \n\n let judge_fields = fields.iter()\n\n .filter(|f| {\n\n get_optional_inner_type(&f.ty, \"Option\").is_none()\n\n })\n\n .filter(|f| {\n\n if l...
Rust
mqtt/mqtt-broker/src/tls.rs
brotherneeru/iotedge
830259ad2f748db58f7271101ed58fdf5fc7bf3f
use std::{ fs, path::{Path, PathBuf}, }; use chrono::{DateTime, NaiveDateTime, ParseResult, Utc}; use openssl::{ asn1::Asn1TimeRef, pkey::{PKey, Private}, x509::X509, }; #[derive(Debug)] pub struct ServerCertificate { private_key: PKey<Private>, certificate: X509, chain: Option<Vec<X50...
use std::{ fs, path::{Path, PathBuf}, }; use chrono::{DateTime, NaiveDateTime, ParseResult, Utc}; use openssl::{ asn1::Asn1TimeRef, pkey::{PKey, Private}, x509::X509, }; #[derive(Debug)] pub struct ServerCertificate { private_key: PKey<Private>, certificate: X509, chain: Option<Vec<X50...
buffer).await.unwrap() > 0 { assert_eq!(buffer.len(), stream.write(&buffer).await.unwrap()); } }); } }); addr.port() } async fn run_echo_client(port: u16, message: &[u8]) -> Vec<u8> { let mut builder = SslConnecto...
tokio::spawn(async move { while let Some(Ok(mut stream)) = incoming.next().await { tokio::spawn(async move { let mut buffer = [0_u8; 1024]; while stream.read(&mut
function_block-random_span
[ { "content": "pub fn write_binary_to_file<P: AsRef<Path>>(content: &[u8], path: P) -> Result<()> {\n\n let mut f = File::create(path).context(\"Cannot create file\")?;\n\n f.write_all(content)\n\n .context(\"File: Cannot write to file \")?;\n\n f.sync_data().context(\"File: cannot sync data\")?;...
Rust
src/expiring_publisher.rs
Logicalshift/flo_stream
a54149c61ce114158fca31866b53fe1188c76bdd
use super::subscriber::*; use super::pubsub_core::*; use super::message_publisher::*; use futures::future::{BoxFuture}; use std::sync::*; use std::collections::{HashMap, VecDeque}; pub struct ExpiringPublisher<Message> { core: Arc<Mutex<PubCore<Message>>> } impl<Message: Clone> ExpiringPublisher<Message> {...
use super::subscriber::*; use super::pubsub_core::*; use super::message_publisher::*; use futures::future::{BoxFuture}; use std::sync::*; use std::collections::{HashMap, VecDeque}; pub struct ExpiringPublisher<Message> { core: Arc<Mutex<PubCore<Message>>> } impl<Message: Clone> ExpiringPublisher<Message> {...
pub fn count_subscribers(&self) -> usize { self.core.lock().unwrap().subscribers.len() } pub fn republish(&self) -> Self { self.core.lock().unwrap().publisher_count += 1; ExpiringPublisher { core: Arc::clone(&self.core) } } ...
publisher_count: 1, subscribers: HashMap::new(), notify_closed: HashMap::new(), waiting: vec![], max_queue_size: buffer_size }; ExpiringPublisher { core: Arc::new(Mutex::new(core)) } }
function_block-function_prefix_line
[ { "content": "pub trait PubSubSpawn<Message: Clone> {\n\n ///\n\n /// Creates a new subscriber for this publisher\n\n /// \n\n fn subscribe(&mut self) -> Subscriber<Message>;\n\n}\n\n\n\n///\n\n/// For convenience, makes it possible to subscribe() to spawned publishers without having to call get_mut...
Rust
runner/src/manual.rs
multifacet/0sim-workspace
a59fee39b900c550e86198b1001198680bda0631
use clap::{clap_app, ArgMatches}; use spurs::{cmd, Execute, SshShell}; use crate::common::{ exp_0sim::{ initial_reboot, set_kernel_printk_level, set_perf_scaling_gov, setup_swapping, start_vagrant, turn_on_ssdswap, ZeroSim, VAGRANT_CORES, VAGRANT_MEM, ZEROSIM_LAPIC_ADJUST, ZEROSIM_SKIP_H...
use clap::{clap_app, ArgMatches}; use spurs::{cmd, Execute, SshShell}; use crate::common::{ exp_0sim::{ initial_reboot, set_kernel_printk_level, set_perf_scaling_gov, setup_swapping, start_vagrant, turn_on_ssdswap, ZeroSim, VAGRANT_CORES, VAGRANT_MEM, ZEROSIM_LAPIC_ADJUST, ZEROSIM_SKIP_H...
m_cores) = vm_cores { vm_cores } else { VAGRANT_CORES }; let _ = start_vagrant( &ushell, &login.host, vm_size, vm_cores, disable_tsc, ZEROSIM_SKIP_HALT, ZEROSIM_LAPIC_ADJUST, ...
function_block-function_prefixed
[ { "content": "/// Set the kernel `printk` level that gets logged to `dmesg`. `0` is only high-priority\n\n/// messages. `7` is all messages.\n\npub fn set_kernel_printk_level(shell: &SshShell, level: usize) -> Result<(), failure::Error> {\n\n assert!(level <= 7);\n\n shell.run(cmd!(\"echo {} | sudo tee /p...
Rust
mayastor/src/rebuild/rebuild_api.rs
reitermarkus/mayastor
8b88fd46021ec25193080af6f8c29fda0d41f0ed
#![warn(missing_docs)] use std::fmt; use crossbeam::channel::{Receiver, Sender}; use futures::channel::oneshot; use snafu::Snafu; use crate::{ bdev::nexus::VerboseError, core::{BlockDeviceDescriptor, CoreError, Descriptor}, nexus_uri::NexusBdevError, }; use spdk_rs::DmaError; use super::rebuild_impl::*;...
#![warn(missing_docs)] use std::fmt; use crossbeam::channel::{Receiver, Sender}; use futures::channel::oneshot; use snafu::Snafu; use crate::{ bdev::nexus::VerboseError, core::{BlockDeviceDescriptor, CoreError, Descriptor}, nexus_uri::NexusBdevError, }; use spdk_rs::DmaError; use super::rebuild_impl::*;...
fn stats(&self) -> RebuildStats; fn start( &mut self, ) -> Result<oneshot::Receiver<RebuildState>, RebuildError>; fn stop(&mut self) -> Result<(), RebuildError>; fn pause(&mut self) -> Result<(), RebuildError>; fn resume(&mut self) -> Result<(), RebuildE...
, PartialEq, Copy, Clone)] pub enum RebuildState { Init, Running, Stopped, Paused, Failed, Completed, } impl fmt::Display for RebuildState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RebuildState::Init =...
random
[ { "content": "pub fn bdev_get_name(uri: &str) -> Result<String, NexusBdevError> {\n\n Ok(uri::parse(uri)?.get_name())\n\n}\n\n\n\nimpl std::cmp::PartialEq<url::Url> for &Bdev {\n\n fn eq(&self, uri: &url::Url) -> bool {\n\n match uri::parse(&uri.to_string()) {\n\n Ok(device) if device.ge...
Rust
src/lookup.rs
belltoy/nsq-in-rust
ef61540c5438555ab529ad49c8d3f3c448f75094
use std::time::Duration; use crate::error::{UrlParseError, Error, Result}; use serde::Deserialize; use reqwest::Url; pub static DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); pub struct Lookup { http_addr: Url, client: reqwest::Client, } #[derive(Debug, Deserialize)] pub struct LookupResponse { pub...
use std::time::Duration; use crate::error::{UrlParseError, Error, Result}; use serde::Deserialize; use reqwest::Url; pub static DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); pub struct Lookup { http_addr: Url, client: reqwest:
let resp = self.client.get(self.url("/ping")?).send().await?; if resp.status().is_success() { Ok(()) } else { Err(Error::UnknownError("Unknown ping error from lookupd".into())) } } pub async fn info(&self) -> Result<InfoResponse> { self.client.get...
:Client, } #[derive(Debug, Deserialize)] pub struct LookupResponse { pub channels: Vec<String>, pub producers: Vec<Producer>, } #[derive(Debug, Deserialize)] pub struct Producer { pub broadcast_address: String, pub hostname: String, pub remote_address: String, pub tcp_port: u16, pub http_p...
random
[ { "content": "fn duration_to_ms<S: Serializer>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error> {\n\n serializer.serialize_u64(duration.as_millis() as u64)\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 0, "score": 73463.76322704993 }, { "content": "type ProducerClient =...
Rust
examples/mem.rs
reitermarkus/esp32-hal
95c7596c78a8e380b858d34f4f0ad1170a5b259a
#![no_std] #![no_main] #![feature(alloc_error_handler)] #![feature(raw_vec_internals)] use core::fmt::Write; use core::panic::PanicInfo; use esp32_hal::prelude::*; use esp32_hal::alloc::{Allocator, DRAM_ALLOCATOR}; use esp32_hal::clock_control::{sleep, CPUSource::PLL, ClockControl, ClockControlConfig}; use esp32_ha...
#![no_std] #![no_main] #![feature(alloc_error_handler)] #![feature(raw_vec_internals)] use core::fmt::Write; use core::panic::PanicInfo; use esp32_hal::prelude::*; use esp32_hal::alloc::{Allocator, DRAM_ALLOCATOR}; use esp32_hal::clock_control::{sleep, CPUSource::PLL, ClockControl, ClockControlConfig}; use esp32_ha...
clock_control .set_cpu_frequencies(PLL, 240.MHz(), PLL, 240.MHz(), PLL, 240.MHz()) .unwrap(); let (clock_control_config, mut watchdog) = clock_control.freeze().unwrap(); watchdog.start(20.s()); let mut uart0 = Serial::uart0( dp.UART0, (NoTx, NoRx), ...
let mut clock_control = ClockControl::new( dp.RTCCNTL, dp.APB_CTRL, dport_clock_control, esp32_hal::clock_control::XTAL_FREQUENCY_AUTO, ) .unwrap();
assignment_statement
[ { "content": "fn disable_timg_wdts(timg0: &mut target::TIMG0, timg1: &mut target::TIMG1) {\n\n timg0\n\n .wdtwprotect\n\n .write(|w| unsafe { w.bits(WDT_WKEY_VALUE) });\n\n timg1\n\n .wdtwprotect\n\n .write(|w| unsafe { w.bits(WDT_WKEY_VALUE) });\n\n\n\n timg0.wdtconfig0.wri...
Rust
src/matcher/header.rs
rustyhorde/libdeadmock
839e665be5597b1dacc4aa2c3d1351c68b70414f
use crate::config::{self, HeaderPattern, Request as RequestConfig}; use crate::error::Error; use crate::matcher::{self, RequestMatch, Slogger}; use cached::{cached_key_result, UnboundCache}; use http::Request; use libeither::Either; use regex::Regex; use slog::{trace, Logger}; use slog_try::try_trace; use std::fmt; ...
use crate::config::{self, HeaderPattern, Request as RequestConfig}; use crate::error::Error; use crate::matcher::{self, RequestMatch, Slogger}; use cached::{cached_key_result, UnboundCache}; use http::Request; use libeither::Either; use regex::Regex; use slog::{trace, Logger}; use slog_try::try_trace; use std::fmt; ...
} } impl Slogger for PatternMatch { fn set_stdout(mut self, stdout: Option<Logger>) -> Self { self.stdout = stdout; self } fn set_stderr(mut self, stderr: Option<Logger>) -> Self { self.stderr = stderr; self } } cached_key_result! { REGEX: UnboundCac...
Some( self.is_match_either(actual.0, expected.key(), true) && self.is_match_either(actual.1, expected.value(), false), )
call_expression
[]
Rust
src/rust/emit-ast/main.rs
alex-ozdemir/unsafe-ast
01c98f846ed663c260e075a86084d2841783b2a9
#![feature(box_syntax,box_patterns,rustc_private)] extern crate getopts; extern crate syntax; #[macro_use] extern crate rustc; extern crate rustc_driver; extern crate rustc_serialize; extern crate rustc_data_structures; mod unsafe_ast; use rustc_serialize::json; use rustc::hir; use rustc::ty; use rustc::session::{c...
#![feature(box_syntax,box_patterns,rustc_private)] extern crate getopts; extern crate syntax; #[macro_use] extern crate rustc; extern crate rustc_driver; extern crate rustc_serialize; extern crate rustc_data_structures; mod unsafe_ast; use rustc_serialize::json; use rustc::hir; use rustc::ty; use rustc::session::{c...
emit_unsafe_ast(crate_name.to_string(), crate_type, krate, session, tcx); })) } } impl<'a,'callback: 'a> CompilerCalls<'a> for AnalyzeUnsafe<'callback> { fn early_callback(&mut self, matches: &getopts::Matches, sopts: &config::Options, ...
let crate_type = state.session.opts.crate_types.iter() .next().map(|t| format!("{:?}",t)).unwrap_or("????".to_string());
assignment_statement
[ { "content": "fn write_crates(f: &mut File) {\n\n fetch_index();\n\n\n\n let mut opts = glob::MatchOptions::new();\n\n opts.require_literal_leading_dot = true;\n\n\n\n let index_paths1 = glob::glob_with(\"crates.io-index/*/*/*\", &opts).unwrap();\n\n\n\n let index_paths2 = glob::glob_with(\"crate...
Rust
rs/minsk/src/analysis/binding/binder.rs
Phytolizer/Minsk
5fb59f0d5d8cf1f0046471b91e2f5d0c41fc874c
use std::collections::HashMap; use crate::analysis::diagnostic::Diagnostic; use crate::analysis::diagnostic_bag::DiagnosticBag; use crate::analysis::syntax::node::expression::assignment::AssignmentExpressionSyntax; use crate::analysis::syntax::node::expression::binary::BinaryExpressionSyntax; use crate::analysis::synt...
use std::collections::HashMap; use crate::analysis::diagnostic::Diagnostic; use crate::analysis::diagnostic_bag::DiagnosticBag; use crate::analysis::syntax::node::expression::assignment::AssignmentExpressionSyntax; use crate::analysis::syntax::node::expression::binary::BinaryExpressionSyntax; use crate::analysis::synt...
fn bind_expression(&mut self, syntax: &ExpressionSyntax) -> BoundExpression { match syntax { ExpressionSyntax::Assignment(a) => self.bind_assignment_expression(a), ExpressionSyntax::Binary(b) => self.bind_binary_expression(b), ExpressionSyntax::Literal(lit) => self.bind...
pub(crate) fn into_expression_and_diagnostics( mut self, syntax: &mut SyntaxTree, ) -> (BoundExpression, Vec<Diagnostic>) { let mut dummy_diagnostics = Vec::new(); std::mem::swap(&mut dummy_diagnostics, &mut syntax.diagnostics); ( self.bind_expression(&syntax.root...
function_block-full_function
[ { "content": "class DiagnosticBag:\n\n _diagnostics: list[Diagnostic]\n\n\n\n def __init__(self):\n\n self._diagnostics = []\n\n\n\n def _report(self, span: TextSpan, message: str):\n\n self._diagnostics.append(Diagnostic(span, message))\n\n\n\n def report_bad_character(self, position:...
Rust
src/socket/mod.rs
rapnis/netlink-rs
b2bf6581f8816912da3c62f1aaf026e663864b85
mod socket_impl; mod address; pub use self::address::*; mod msg; pub use self::msg::*; use socket::socket_impl::Socket as SocketImpl; use std::mem::{size_of}; use libc::{c_int, AF_NETLINK, SOCK_RAW}; use std::convert::Into; use std::io::{self, Write, Cursor}; use std::iter::{repeat}; use byteorder::{NativeEndian...
mod socket_impl; mod address; pub use self::address::*; mod msg; pub use self::msg::*; use socket::socket_impl::Socket as SocketImpl; use std::mem::{size_of}; use libc::{c_int, AF_NETLINK, SOCK_RAW}; use std::convert::Into; use std::io::{self, Write, Cursor}; use std::iter::{repeat}; use byteorder::{NativeEndian...
} #[derive(Clone, Eq, PartialEq, Debug)] pub struct Msg<'a> { header: NlMsgHeader, payload: Payload<'a>, } impl<'a> Msg<'a> { pub fn from_bytes(bytes: &'a [u8]) -> io::Result<(Msg<'a>, usize)> { let (hdr, n) = (NlMsgHeader::from_bytes(bytes))?; let end: usize = hdr.msg_length() ...
fn bytes(&self) -> io::Result<Vec<u8>> { match *self { Payload::None => { Ok(vec!()) }, Payload::Data(b) => { Ok(b.into()) }, Payload::Ack(h) => { let mut vec = vec![]; (vec.write_u32::<Na...
function_block-full_function
[ { "content": "fn sockaddr_len() -> socklen_t {\n\n let struct_size = mem::size_of::<sockaddr>();\n\n let v = struct_size as socklen_t;\n\n assert_eq!(v as usize, struct_size);\n\n v\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Socket {\n\n fd: i32,\n\n}\n\n\n\n\n\nimpl Socket {\n\n pub fn new(fa...
Rust
src/puzzles/day_14.rs
siku2/aoc_2019
c86e2cc436573f54bdb148594f551f982c405678
use crate::input::Input; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::fmt::Write; use std::ops; use std::str::FromStr; fn div_ceil(a: usize, b: usize) -> usize { (a - 1) / b + 1 } #[derive(Clone, Debug)] struct ChemicalQty { name: String, amount: usize, } impl ChemicalQty ...
use crate::input::Input; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::fmt::Write; use std::ops; use std::str::FromStr; fn div_ceil(a: usize, b: usize) -> usize { (a - 1) / b + 1 } #[derive(Clone, Debug)] struct ChemicalQty { name: String, amount: usize, } impl ChemicalQty ...
} impl fmt::Display for Reaction { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let inp = join_iter(&mut self.input.iter().map(|c| c.to_string()), ", ")?; write!(f, "{} => {}", inp, self.output) } } impl FromStr for Reaction { type Err = Box<dyn Error>; fn from_str(s: &str)...
t, current_amount); for c in self.input.iter_mut() { *c *= factor; } self.output *= factor; }
function_block-function_prefixed
[ { "content": "type PuzzleFn = dyn Fn(&Input) -> Result<String, Box<dyn Error>>;\n", "file_path": "src/puzzles/mod.rs", "rank": 0, "score": 323304.03652232484 }, { "content": "fn get_output(m: &mut intcode::Machine) -> Result<String, Box<dyn Error>> {\n\n let out = m.take_output();\n\n ...
Rust
contract/src/lib.rs
mikedotexe/near-dns
d7fcd043406fec4678ef54a1ccebdc185b104e0e
/* * NEAR DNS */ use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::wee_alloc; use near_sdk::{env, near_bindgen}; use near_sdk::collections::UnorderedMap; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[near_bindgen] #[derive(Default, BorshDeserialize,...
/* * NEAR DNS */ use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::wee_alloc; use near_sdk::{env, near_bindgen}; use near_sdk::collections::UnorderedMap; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[near_bindgen] #[derive(Default, BorshDeserialize,...
to_string(), input, block_index: 0, block_timestamp: 0, account_balance: 0, account_locked_balance: 0, storage_usage: 0, attached_deposit: 0, prepaid_gas: 10u64.pow(18), random_seed: vec![0, 1, 2], is...
: * cargo test -- --nocapture */ #[cfg(test)] mod tests { use super::*; use near_sdk::MockedBlockchain; use near_sdk::{testing_env, VMContext}; fn get_context(input: Vec<u8>, is_view: bool) -> VMContext { VMContext { current_account_id: "alice_near".to_string(), s...
random
[ { "content": " getAccountId() {\n\n return window.accountId\n", "file_path": "src/main.test.js", "rank": 0, "score": 33461.435851052964 }, { "content": "const shell = require('shelljs')\n", "file_path": "contract/build.js", "rank": 1, "score": 33155.70168802807 }, { ...
Rust
akaibu_gui/src/ui/resource.rs
Forlos/akaibu
8be6e7bbd463e76971f64975a35732a2cbb3c967
use super::footer::Footer; use crate::{ message::{Message, Status}, style, }; use akaibu::resource::ResourceType; use iced::{ button, image::{viewer, Viewer}, pick_list, Button, Column, Container, Element, HorizontalAlignment, Length, PickList, Row, Space, Text, VerticalAlignment, }; use image::...
use super::footer::Footer; use crate::{ message::{Message, Status}, style, }; use akaibu::resource::ResourceType; use iced::{ button, image::{viewer, Viewer}, pick_list, Button, Column, Container, Element, HorizontalAlignment, Length, PickList, Row, Space, Text, VerticalAlignment, }; use image::...
ark::default()); if self.sprite_index > 0 { prev = prev.on_press(Message::PrevSprite); } let mut next = Button::new( &mut self.next_sprite_button_state, Container::new(Text::new(" > ").size(16)) .center_x() ...
.horizontal_alignment(HorizontalAlignment::Center), ) .width(Length::Fill) .height(Length::Fill), }; if let ResourceType::RgbaImage { image: _ } = &self.resource { header = header .push(Space::new(Length::Fill, Length::Units(0)...
function_block-random_span
[ { "content": "pub fn write_resource_with_format(\n\n resource: ResourceType,\n\n mut file_name: PathBuf,\n\n format: ConvertFormat,\n\n) -> anyhow::Result<PathBuf> {\n\n match resource {\n\n ResourceType::RgbaImage { image } => {\n\n file_name.set_extension(format!(\"{}\", format))...
Rust
crates/ra_hir/src/source_binder.rs
eulerdisk/rust-analyzer
154ab4206d2fd9493a3665fb72f9bd710a577944
use ra_db::{FileId, FilePosition}; use ra_syntax::{ SmolStr, TextRange, SyntaxNode, ast::{self, AstNode, NameOwner}, algo::find_node_at_offset, }; use crate::{ HirDatabase, Function, SourceItemId, ModuleDef, AsName, Module, ids::LocationCtx, }; pub fn module_from_file_id(db: &impl HirDatabas...
use ra_db::{FileId, FilePosition}; use ra_syntax::{ SmolStr, TextRange, SyntaxNode, ast::{self, AstNode, NameOwner}, algo::find_node_at_offset, }; use crate::{ HirDatabase, Function, SourceItemId, ModuleDef, AsName, Module, ids::LocationCtx, }; pub fn module_from_file_id(db: &impl HirDatabas...
m_id: Some(item_id), }; module_from_source(db, source) } pub fn module_from_child_node( db: &impl HirDatabase, file_id: FileId, child: &SyntaxNode, ) -> Option<Module> { if let Some(m) = child .ancestors() .filter_map(ast::Module::cast) .find(|it| !it.has_semi()) { ...
module, child_name) { (Some(parent_module), Some(child_name)) => parent_module.child(db, &child_name.as_name()), _ => None, } } pub fn module_from_position(db: &impl HirDatabase, position: FilePosition) -> Option<Module> { let file = db.source_file(position.file_id); match find_node_at_offs...
random
[ { "content": "pub fn infer(db: &impl HirDatabase, func: Function) -> Arc<InferenceResult> {\n\n db.check_canceled();\n\n let body = func.body(db);\n\n let scopes = db.fn_scopes(func);\n\n let module = func.module(db);\n\n let impl_block = func.impl_block(db);\n\n let mut ctx = InferenceContext...
Rust
src/parser.rs
mominul/okkhor-lib
ebc3219b407c45ab7cc45644359d4e03c87c1689
use crate::{ models::{Match, Match::*, MatchType::*, Pattern}, patterns::PHONETIC_PATTERNS, }; use std::collections::BTreeMap; fn conditional_lowercase(c: char) -> char { const CASE_SENSITIVE_CHARS: &str = "oiudgjnrstyz"; let lowercase_c = c.to_ascii_lowercase(); if CASE_SENSITIVE_CHARS.contains(lo...
use crate::{ models::{Match, Match::*, MatchType::*, Pattern}, patterns::PHONETIC_PATTERNS, }; use std::collections::BTreeMap; fn conditional_lower
'U' => true, _ => false, } } fn is_consonant(c: char) -> bool { !is_vowel(c) && c.is_ascii_alphabetic() } fn is_punctuation(c: char) -> bool { !c.is_ascii_alphabetic() } fn does_match(_match: &Match, prefix: char, suffix: char) -> bool { match _match { PrefixIs(Vowel) => is_vowel(pref...
case(c: char) -> char { const CASE_SENSITIVE_CHARS: &str = "oiudgjnrstyz"; let lowercase_c = c.to_ascii_lowercase(); if CASE_SENSITIVE_CHARS.contains(lowercase_c) { c } else { lowercase_c } } fn is_vowel(c: char) -> bool { match c { 'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E...
random
[ { "content": "#[test]\n\nfn regex_word() {\n\n let p = Parser::new_regex();\n\n assert_eq!(p.convert_regex(\"osthir\"), \"^([ওোঅ]|(অ্য)|(য়ো?))(্[যবম])?(্?)([ঃঁ]?)([সশষ])(্[যবম])?(্?)([ঃঁ]?)(থ|ঠ|([তটৎ]্?(হ|ঃ|(হ্\\u{200C}?))))(্[যবম])?(্?)([ঃঁ]?)([ইঈিী]|(য়[িী]))(্[যবম])?(্?)([ঃঁ]?)([রড়ঢ়]|(হ্র))(্[যবম])?(্?)...
Rust
examples/src/bin/lighting/scr/camera.rs
littleTitan/feo-engine
374d242a15588947cce3ed2f956585eb9f9f4444
use std::any::Any; use { feo_oop_engine::{ scene::{ game_object::camera::fpv_camera::FpvCamera, }, scripting::{ globals::{ Global, EngineGlobals }, Scriptable, swap::Swap }, ...
use std::any::Any; use { feo_oop_engine::{ scene::{ game_object::camera::fpv_camera::FpvCamera, }, scripting::{ globals::{ Global, EngineGlobals
w(globals) as Box<dyn Global>).unwrap(); Swap::None } #[macro_rules_attribute(event_handler!)] pub async fn event_handler<'r>(this: Arc<RwLock<FpvCamera>>, _: EngineGlobals, event: Event<'static, UserEvent<Arc<dyn Any + Send + Sync>>>) -> Swap { let this = this.clone(); let mut this = this.writ...
}, Scriptable, swap::Swap }, event::UserEvent }, feo_math::{ rotation::quaternion::Quaternion, axes::Axes, linear_algebra::vector3::Vector3, }, std::{ sync::{ Arc, RwLock }, ...
random
[ { "content": "pub trait Global: GlobalClone + Debug + Any + Send + Sync + 'static {\n\n fn as_any(&self) -> &dyn Any;\n\n}\n\n\n", "file_path": "feo-oop-engine/src/scripting/globals.rs", "rank": 0, "score": 86363.5826194592 }, { "content": "pub trait GlobalClone {\n\n fn clone_global(&...