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
lisp/src/toplevel.rs
jorendorff/cellgc
1d73457069b93b6af1adbfeb390ba1fbae8a291a
use builtins; use cell_gc::{self, GcHeapSession, GcLeaf}; use compile; use env::{Environment, EnvironmentRef}; use errors::*; use parse; use std::path::Path; use value::{BuiltinFnPtr, InternedString, Value}; use vm; pub fn core_env<'h>(hs: &mut GcHeapSession<'h>) -> EnvironmentRef<'h> { let env = Environment::em...
use builtins; use cell_gc::{self, GcHeapSession, GcLeaf}; use compile; use env::{Environment, EnvironmentRef}; use errors::*; use parse; use std::path::Path; use value::{BuiltinFnPtr, InternedString, Value}; use vm; pub fn core_env<'h>(hs: &mut GcHeapSession<'h>) -> EnvironmentRef<'h> { let env = Environment::em...
pub fn repl() -> Result<()> { const REPL_CODE: &'static str = include_str!("repl.scm"); cell_gc::with_heap(|hs| { let env = default_env(hs); eval_str(hs, &env, REPL_CODE)?; Ok(()) }) } #[cfg(test)] use value::RetType; #[cfg(test)] #[allow(dead_code)] enum Env { Core, Expa...
pub fn load<'h>( hs: &mut GcHeapSession<'h>, env: &EnvironmentRef<'h>, filename: &Path, ) -> Result<Value<'h>> { use std::fs::File; use std::io::prelude::*; let mut file = File::open(Path::new(filename)) .chain_err(|| format!("opening file {:?}", filename))?; let mut code = String:...
function_block-full_function
[ { "content": "fn check_done<'h>(proc_name: &str, iter: &mut vec::IntoIter<Value<'h>>) -> Result<()> {\n\n match iter.next() {\n\n Some(_) => Err(format!(\"{}: too many arguments\", proc_name).into()),\n\n None => Ok(())\n\n }\n\n}\n\n\n\nmacro_rules! builtins {\n\n {\n\n $(\n\n ...
Rust
auth_server_lib/src/session_data.rs
ddboline/auth_server_rust
2bac8d2091172e63dac4206caaef48e8669b7939
use anyhow::Error; use chrono::{DateTime, Utc}; use postgres_query::{client::GenericClient, query, FromSqlRow}; use serde::{Deserialize, Serialize}; use serde_json::Value; use stack_string::StackString; use uuid::Uuid; use crate::pgpool::{PgPool, PgTransaction}; #[derive(FromSqlRow, Serialize, Deserialize, PartialEq,...
use anyhow::Error; use chrono::{DateTime, Utc}; use postgres_query::{client::GenericClient, query, FromSqlRow}; use serde::{Deserialize, Serialize}; use serde_json::Value; use stack_string::StackString; use uuid::Uuid; use crate::pgpool::{PgPool, PgTransaction}; #[derive(FromSqlRow, Serialize, Deserialize, PartialEq,...
let query = query!("DELETE FROM session_values WHERE id = $id", id = self.id); query.execute(&conn).await?; Ok(()) } }
id, pub session_id: Uuid, pub session_key: StackString, pub session_value: Value, pub created_at: DateTime<Utc>, pub modified_at: DateTime<Utc>, } impl SessionData { pub fn new(session_id: Uuid, key: impl Into<StackString>, value: Value) -> Self { Self { id: Uuid::new_v4(), ...
random
[ { "content": "#[derive(Serialize)]\n\nstruct ErrorMessage {\n\n code: u16,\n\n message: String,\n\n}\n\n\n", "file_path": "auth_server_http/src/errors.rs", "rank": 0, "score": 55711.957398504324 }, { "content": "#[derive(Schema, Serialize)]\n\nstruct SessionDataObj {\n\n #[schema(de...
Rust
src/server.rs
miquels/speedtest-xxx-mb
010b805f77b145386229c337b0076264e78ffe6d
use std::sync::{Arc, Mutex}; use http::{Response, StatusCode}; use human_size::{Byte, ParsingError, Size, SpecificSize}; use hyper::body::Body; use tokio_stream::StreamExt; use tokio::time::{Duration, Instant}; use warp::reply::Response as HyperResponse; use warp::{filters::BoxedFilter, Filter, Reply}; use crate::l...
use std::sync::{Arc, Mutex}; use http::{Response, StatusCode}; use human_size::{Byte, ParsingError, Size, SpecificSize}; use hyper::body::Body; use tokio_stream::StreamExt; use tokio::time::{Duration, Instant}; use warp::reply::Response as HyperResponse; use warp::{filters::BoxedFilter, Filter, Reply}; use crate::l...
pub fn routes(&self, redirect_uri: Option<&http::Uri>) -> BoxedFilter<(impl Reply,)> { let config = self.config.clone(); let this = self.clone(); let index = warp::path::end() .and(warp::header("user-agent")) .map(move |agent: String| this.index(agent, &config)...
fn redirect( &self, uri: Option<&http::Uri>, ) -> impl Filter<Extract = (impl Reply,), Error = warp::reject::Rejection> + Clone { let uri = uri.cloned(); warp::any() .map(move || uri.clone()) .and_then(|uri: Option<http::Uri>| async move { matc...
function_block-full_function
[ { "content": "pub fn build(config: &Config, agent: String) -> Result<String, Box<dyn Error + Sync + Send>> {\n\n let mut hbs = Handlebars::new();\n\n if let Some(file) = config.index.file.as_ref() {\n\n hbs.register_template_file(\"index\", file)?;\n\n } else {\n\n let index = include_str...
Rust
web/src/layout.rs
pfwangdx/elvis
fcdec4b6148d842f7884e8e3f97c2492e3b58d58
use crate::{ AlignStyle, ContainerStyle, FlexStyle, GridStyle, MultiColumnStyle, SizedBoxStyle, Widget, }; use elvis::{ Align, Center, Col as ElvisCol, Container, Flex, Grid as ElvisGrid, List as ElvisList, MultiColumn as ElvisMultiColumn, Row as ElvisRow, SizedBox, }; use wasm_bindgen::prelude::*; #[wasm_...
use crate::{ AlignStyle, ContainerStyle, FlexStyle, GridStyle, MultiColumnStyle, SizedBoxStyle, Widget, }; use elvis::{ Align, Center, Col as ElvisCol, Container, Flex, Grid as ElvisGrid, List as ElvisList, MultiColumn as ElvisMultiColumn, Row as ElvisRow, SizedBox, }; use wasm_bindgen::prelude::*; #[wasm_...
n sized_box(child: Widget, style: Option<SizedBoxStyle>) -> Widget { Widget::new(SizedBox { child: child.into(), style: style.unwrap_or_default().into(), }) } #[wasm_bindgen(js_name = "Align")] pub fn align(child: Widget, style: Option<AlignStyle>) -> Widget { Widget::new(Align { ch...
ld: Widget, style: Option<ContainerStyle>) -> Widget { Widget::new(Container { child: child.into(), style: style.unwrap_or_default().into(), }) } #[wasm_bindgen(js_name = "SizedBox")] pub f
random
[ { "content": "#[wasm_bindgen(js_name = \"Text\")]\n\npub fn text(text: Option<String>, style: Option<TextStyle>) -> Widget {\n\n Widget::new(Text::new(\n\n text.unwrap_or_default(),\n\n style.unwrap_or_default().into(),\n\n ))\n\n}\n\n\n\n/// If you don't want Image playing in background ano...
Rust
src/graphics/shader.rs
ggez-dev/ggez
f6c34de7a14859bef05d02aef8a2e12d2b6fc19e
use std::marker::PhantomData; use crate::context::{Has, HasMut}; use super::{ context::GraphicsContext, gpu::{ arc::{ArcBindGroup, ArcBindGroupLayout, ArcBuffer, ArcShaderModule}, bind_group::BindGroupBuilder, }, image::Image, sampler::Sampler, }; use crevice::std140::Std140; use w...
use std::marker::PhantomData; use crate::context::{Has, HasMut}; use super::{ context::GraphicsContext, gpu::{ arc::{ArcBindGroup, ArcBindGroupLayout, ArcBuffer, ArcShaderModule}, bind_group::BindGroupBuilder, }, image::Image, sampler::Sampler, }; use crevice::std140::Std140; use w...
} pub use crevice::std140::AsStd140; #[derive(Debug, PartialEq, Eq)] pub struct ShaderParams<Uniforms: AsStd140> { pub(crate) uniforms: ArcBuffer, pub(crate) layout: ArcBindGroupLayout, pub(crate) bind_group: ArcBindGroup, _marker: PhantomData<Uniforms>, } impl<Uniforms: AsStd140> ShaderParams<Unifo...
pub fn from_wgsl(gfx: &impl Has<GraphicsContext>, wgsl: &str, fs_entry: &str) -> Self { let gfx = gfx.retrieve(); let module = ArcShaderModule::new(gfx.wgpu.device.create_shader_module( &wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::W...
function_block-full_function
[ { "content": "#[derive(AsStd140)]\n\nstruct Dim {\n\n rate: f32,\n\n}\n\n\n", "file_path": "examples/shader.rs", "rank": 0, "score": 113333.3584019915 }, { "content": "struct MainState {\n\n dim: Dim,\n\n shader: graphics::Shader,\n\n params: graphics::ShaderParams<Dim>,\n\n}\n\n...
Rust
src/term.rs
Malmz/md407
a2302e74244a6dcb733b912c15993e078853813a
use anyhow::{anyhow, Context, Result}; use indicatif::ProgressBar; use serialport::SerialPort; use std::io::{self, Write}; use std::ops::{Deref, DerefMut}; use std::thread::{self, JoinHandle}; use std::{fs::File, io::Read}; pub struct Term { port: Box<dyn SerialPort>, } impl Term { pub fn open(path: &str...
use anyhow::{anyhow, Context, Result}; use indicatif::ProgressBar; use serialport::SerialPort; use std::io::{self, Write}; use std::ops::{Deref, DerefMut}; use std::thread::{self, JoinHandle}; use std::{fs::File, io::Read}; pub struct Term { port: Box<dyn SerialPort>, } impl Term { pub fn open(path: &str...
let n = self.port.read(&mut buf); if let Err(ref e) = n { dbg!(e); } let n = n?; if n > 0 { println!("{:?}", &buf[..n]); } } } } impl Deref for Term { type Target = dyn SerialP...
rt .write_all(b"mm\n") .context("Error sending mm command") } pub fn dasm(&mut self) -> Result<()> { self.port .write_all(b"dasm\n") .context("Error sending dasm command") } pub fn bp(&mut self) -> Result<()> { self.port .writ...
random
[ { "content": "fn go(tty: &mut Term) -> Result<()> {\n\n tty.go()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 126725.06370381035 }, { "content": "fn run(tty: &mut Term, source: &mut File) -> Result<()> {\n\n tty.flash(source)?;\n\n tty.go()?;\n\n O...
Rust
src/host.rs
htrefil/benet
c7ddcd85a6c58cbc2181c6d337799ffb7f642f72
use crate::compress::{Compressor, InputBuffer, OutputBuffer}; use crate::error::Error; use crate::event::{Event, EventKind}; use crate::init::InitGuard; use crate::packet::Packet; use crate::peer::{self, Peer, PeerMut}; use core::slice; use enet_sys::{ENetAddress, ENetBuffer, ENetCompressor, ENetEvent, ENetHost}; use ...
use crate::compress::{Compressor, InputBuffer, OutputBuffer}; use crate::error::Error; use crate::event::{Event, EventKind}; use crate::init::InitGuard; use crate::packet::Packet; use crate::peer::{self, Peer, PeerMut}; use core::slice; use enet_sys::{ENetAddress, ENetBuffer, ENetCompressor, ENetEvent, ENetHost}; use ...
} impl<T: Debug + Default> Debug for Host<T> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct("Host").finish_non_exhaustive() } } impl<T> Drop for Host<T> { fn drop(&mut self) { unsafe { let host = &*self.host; for i in 0..host.peerCount { ...
unsafe fn translate_event(&self, event: ENetEvent) -> Option<Event<'_, T>> { let (kind, peer) = match event.type_ { enet_sys::_ENetEventType_ENET_EVENT_TYPE_NONE => return None, enet_sys::_ENetEventType_ENET_EVENT_TYPE_CONNECT => ( EventKind::Connect(event.data), ...
function_block-full_function
[ { "content": "fn run() -> Result<(), Error> {\n\n const ADDR: &str = \"127.0.0.1:8080\";\n\n\n\n // Create a server host that will listen on 127.0.0.1:8080, with one channel\n\n // and a maximum of 32 peers and store the time of connection for each peer.\n\n let mut host = Host::<Option<Instant>>::b...
Rust
benches/benchmarks.rs
sruggier/rust-disruptor
ca380768ba58acf7ff63b2146f32e92c035594b3
#![feature(test)] extern crate disruptor; extern crate time; extern crate test; use disruptor::{SinglePublisher, ProcessingWaitStrategy, SpinWaitStrategy, YieldWaitStrategy, BlockingWaitStrategy, PipelineInit, Publisher, Consumer, FinalConsumer}; use test::Bencher; use std::u64; use std::thread::{spawn}; /** * R...
#![feature(test)] extern crate disruptor; extern crate time; extern crate test; use disruptor::{SinglePublisher, ProcessingWaitStrategy, SpinWaitStrategy, YieldWaitStrategy, BlockingWaitStrategy, PipelineInit, Publisher, Consumer, FinalConsumer}; use test::Bencher; use std::u64; use std::thread::{spawn}; /** * R...
&mut Bencher) { let w = BlockingWaitStrategy::new(); measure_ping_pong_latency_two_ringbuffers_generic(b, w); } /** * Run a one-disruptor ping-pong latency benchmark with the given wait strategy and spawn function. * In this version, a single disruptor is used to synchronize the two tasks, which avoids some...
tatic>( b: &mut Bencher, w: W ) { let mut ping_publisher = SinglePublisher::<u64, W>::new(8192, w.clone()); let ping_consumer = ping_publisher.create_single_consumer_pipeline(); let mut pong_publisher = SinglePublisher::<u64, W>::new(8192, w.clone()); let pong_consumer = pong_publisher.create_si...
random
[ { "content": "fn run_nonresizing_disruptor_benchmark<W: ProcessingWaitStrategy + fmt::Debug + 'static>(\n\n iterations: u64,\n\n w: W\n\n) {\n\n let desc = format!(\"{:?}\", w);\n\n let mut publisher = SinglePublisher::<u64, W>::new(8192, w);\n\n let consumer = publisher.create_single_consumer_pi...
Rust
shared/rust/src/api/endpoints/image.rs
Sheng-Long/ji-cloud
d12741467eb5d0ae15e3cece9d3428ef9d0050e3
use super::ApiEndpoint; use crate::{ api::Method, domain::image::{ CreateRequest, CreateResponse, GetResponse, SearchQuery, SearchResponse, UpdateRequest, }, error::{ image::{CreateError, SearchError, UpdateError, UploadError}, DeleteError, GetError, }, }; pub mod user { ...
use super::ApiEndpoint; use crate::{ api::Method, domain::image::{ CreateRequest, CreateResponse, GetResponse, SearchQuery, SearchResponse, UpdateRequest, }, error::{ image::{CreateError, SearchError, UpdateError, UploadError}, DeleteError, GetError, }, }; pub mod user { ...
type Req = (); type Res = (); type Err = UploadError; const PATH: &'static str = "/v1/user/me/image/{id}/raw"; const METHOD: Method = Method::Put; } pub struct Delete; impl ApiEndpoint for Delete { type Req = (); type Res = (); type Err = De...
rror}, }; pub struct List; impl ApiEndpoint for List { type Req = (); type Res = ListResponse; type Err = GetError; const PATH: &'static str = "/v1/user/me/image"; const METHOD: Method = Method::Get; } pub struct Get; impl ApiEndpoint for ...
random
[ { "content": "pub fn signin() -> HtmlElement {\n\n TEMPLATES.with(|t| t.cache.render_elem_plain(SIGNIN))\n\n}\n", "file_path": "frontend/apps/crates/entry/user/src/templates.rs", "rank": 0, "score": 168421.6279699683 }, { "content": "pub fn profile() -> HtmlElement {\n\n TEMPLATES.with...
Rust
sdk/rust/oak_config_serializer/src/main.rs
aferr/oak
7b89fbdada697230672eae48b10fbe7904a33b2f
use anyhow::{anyhow, Context}; use log::debug; use oak_abi::proto::oak::application::{ node_configuration::ConfigType, ApplicationConfiguration, NodeConfiguration, WebAssemblyConfiguration, }; use prost::Message; use reqwest::Url; use sha2::{Digest, Sha256}; use std::{collections::HashMap, fs}; use structopt:...
use anyhow::{anyhow, Context}; use log::debug; use oak_abi::proto::oak::application::{ node_configuration::ConfigType, ApplicationConfiguration, NodeConfiguration, WebAssemblyConfiguration, }; use prost::Message; use reqwest::Url; use sha2::{Digest, Sha256}; use std::{collections::HashMap, fs}; use structopt:...
e(&module).await.context("Couldn't load module")?; modules.insert(name.to_string(), loaded_module); } let app_config = ApplicationConfiguration { wasm_modules: modules, initial_node_configuration: Some(NodeConfiguration { name: config.name, config_type: Some...
lt for InitialNodeConfig { fn default() -> Self { Self { wasm_module_name: "app".to_string(), wasm_entrypoint_name: "oak_main".to_string(), } } } fn get_sha256(data: &[u8]) -> String { let mut hasher = Sha256::new(); hasher.update(data); hex::encode(hasher.fi...
random
[ { "content": "/// Parse application configuration into an instance of [`ApplicationConfiguration`]\n\nfn create_app_config(opt: &Opt) -> anyhow::Result<ApplicationConfiguration> {\n\n let app_config_data =\n\n read(&opt.application).context(\"could not read application configuration\")?;\n\n Ok(App...
Rust
core/src/query/type_check/type_checker.rs
dark-flames/Yukino
63324fc6e8adfe8586b3f64ceb79e16298d694af
use crate::definitions::FieldDefinition; use crate::query::ast::error::{SyntaxError, SyntaxErrorWithPos}; use crate::query::ast::{JoinClause, Locatable}; use crate::types::{ExprWrapper, TypeInfo, TypeResolver}; use std::collections::HashMap; pub struct TypeChecker<F> where F: Fn(&str, &str) -> Option<FieldDefiniti...
use crate::definitions::FieldDefinition; use crate::query::ast::error::{SyntaxError, SyntaxErrorWithPos}; use crate::query::ast::{JoinClause, Locatable}; use crate::types::{ExprWrapper, TypeInfo, TypeResolver}; use std::collections::HashMap; pub struct TypeChecker<F> where F: Fn(&str, &str) -> Option<FieldDefiniti...
pub fn add_external_value_assertion( &mut self, ident: String, ty: String, ) -> Result<(), SyntaxError> { if self.external_value_assertion.contains_key(&ident) { Err(SyntaxError::ConflictValueAssertion(ident)) } else { self.external_value_asserti...
resolvers: Vec<Box<dyn TypeResolver>>, alias: HashMap<String, String>, definition_getter: F, ) -> Self { TypeChecker { external_value_assertion: Default::default(), result_type: Default::default(), generated_join: Default::default(), resolvers:...
function_block-function_prefix_line
[]
Rust
examples/demos/src/base.rs
kainino0x/rust-vulkan
91074f42509f95134e4d9289714dd2e0002982b5
use std::mem; use std::os::raw::c_void; use std::ptr::{null, null_mut}; use std::ffi::CString; use xcb::ffi::base::*; use xcb::ffi::xproto::*; use cgmath::{Vector2, Vector3}; use vulkan_bind::vk; use tools; use swapchain::*; use textureloader::*; use util::*; pub struct DepthStencil { pub image: vk::Image, ...
use std::mem; use std::os::raw::c_void; use std::ptr::{null, null_mut}; use std::ffi::CString; use xcb::ffi::base::*; use xcb::ffi::xproto::*; use cgmath::{Vector2, Vector3}; use vulkan_bind::vk; use tools; use swapchain::*; use textureloader::*; use util::*; pub struct DepthStencil { pub image: vk::Image, ...
fn create_command_buffers(&mut self) { unimplemented!() } fn destroy_command_buffers(&mut self) { unimplemented!() } fn create_setup_command_buffer(&mut self) { unimplemented!() } fn flush_setup_command_buffer(&mut self) { unimplemented!() } fn c...
fn check_command_buffers(&mut self) -> bool { for &cmd_buffer in &self.draw_cmd_buffers { if cmd_buffer == null_mut() { return false; } } true }
function_block-full_function
[ { "content": "/// Load a binary file into a buffer (e.g. SPIR-V)\n\npub fn read_binary_file(filename: &str) -> io::Result<Vec<u8>> {\n\n let mut f = try!(std::fs::File::open(filename));\n\n let mut v = Vec::new();\n\n try!(f.read_to_end(&mut v));\n\n Ok(v)\n\n}\n\n\n", "file_path": "examples/dem...
Rust
core/src/services/orchestrator/core/jobs/slot_reclaim.rs
jpJuni0r/WebGrid
26e21637ef88e8af9d64c6fce0de55890eaa6dec
use super::super::Context; use crate::libraries::helpers::lua::terminate_session; use crate::libraries::resources::{ResourceManager, ResourceManagerProvider}; use crate::with_shared_redis_resource; use anyhow::Result; use async_trait::async_trait; use chrono::offset::Utc; use jatsl::{Job, TaskManager}; use log::{error,...
use super::super::Context; use crate::libraries::helpers::lua::terminate_session; use crate::libraries::resources::{ResourceManager, ResourceManagerProvider}; use crate::with_shared_redis_resource; use anyhow::Result; use async_trait::async_trait; use chrono::offset::Utc; use jatsl::{Job, TaskManager}; use log::{error,...
} }
match res { Ok(mut result) => { let dead_slots = result.remove(0); let orphaned_slots = result.remove(0); Ok((dead_slots, orphaned_slots)) } Err(e) => Err(e), }
if_condition
[ { "content": "/// Parses a Duration from a string containing seconds.\n\n/// Useful for command line parsing\n\npub fn parse_seconds(src: &str) -> Result<Duration, ParseIntError> {\n\n let seconds = src.parse::<u64>()?;\n\n Ok(Duration::from_secs(seconds))\n\n}\n", "file_path": "core/src/libraries/hel...
Rust
substudy/src/time.rs
sykul/subtitles-rs
f8a8b824070c1f397c4c22e4da7738562c147585
use common_failures::prelude::*; use serde::{Serialize, Serializer}; use serde::ser::SerializeTuple; use std::result; pub const MIN_SPACING: f32 = 0.001; fn decompose_time(time: f32) -> (u32, u32, f32) { let mut seconds = time; let hours = (seconds / 3600.0).floor() as u32; seconds %= 3600.0; let mi...
use common_failures::prelude::*; use serde::{Serialize, Serializer}; use serde::ser::SerializeTuple; use std::result; pub const MIN_SPACING: f32 = 0.001; fn decompose_time(time: f32) -> (u32, u32, f32) { let mut seconds = time; let hours = (seconds / 3600.0).floor() as u32; seconds %= 3600.0; let mi...
pub fn begin_after(&mut self, limit: f32) -> Result<()> { if limit > self.end - 2.0 * MIN_SPACING { Err(format_err!( "Cannot begin time period {:?} after {}", self, limit ))?; } self.begin = self.begin.max(limit ...
pub fn union(&self, other: Period) -> Period { Period { begin: self.begin.min(other.begin), end: self.end.max(other.end), } }
function_block-full_function
[ { "content": "/// Format seconds using the standard SRT time format.\n\npub fn format_time(time: f32) -> String {\n\n let (h, rem) = ((time / 3600.0).trunc(), time % 3600.0);\n\n let (m, s) = ((rem / 60.0).trunc(), rem % 60.0);\n\n (format!(\"{:02}:{:02}:{:0>6.3}\", h, m, s)).replace(\".\", \",\")\n\n}...
Rust
rrule/src/tests/serde.rs
omid/rust_rrule
c8903f8cf959f65703f30ecae2cbe6887be34982
use crate::tests::common::ymd_hms; use crate::{Frequency, NWeekday, Unvalidated, Weekday}; use crate::{RRule, RRuleSet}; use std::str::FromStr; #[test] fn rrule_from_str() { let test_str_cases = vec![ "RRULE:UNTIL=19990404T110000Z;FREQ=WEEKLY;BYDAY=TU,WE", "UNTIL=20190101T230000Z;FREQ=WEEKLY;BYDAY=...
use crate::tests::common::ymd_hms; use crate::{Frequency, NWeekday, Unvalidated, Weekday}; use crate::{RRule, RRuleSet}; use std::str::FromStr; #[test] fn rrule_from_str() { let test_str_cases = vec![ "RRULE:UNTIL=19990404T110000Z;FREQ=WEEKLY;BYDAY=TU,WE", "UNTIL=20190101T230000Z;FREQ=WEEKLY;BYDAY=...
y, count: Some(3), ..Default::default() }, RRule { freq: Frequency::Weekly, interval: 5, by_weekday: vec![ NWeekday::Nth(-2, Weekday::Mon), NWeekday::Every(Weekday::Fri), ], ..Default::def...
function_block-function_prefixed
[]
Rust
libs/text/src/text.rs
Ryan1729/256_squared
72bc46794236939f43246ae7822644e3a33d7e3c
macro_rules! test_log { ($($arg:tt)*) => {}; } #[macro_export] macro_rules! bytes_concat { ($($byte_strings:expr),*$(,)*) => {{ &[$($byte_strings),*].concat() }} } pub fn bytes_lines<'a>(bytes: &'a [u8]) -> impl Iterator<Item = &'a [u8]> { bytes.split(|&b| b == b'\n') } pub fn ...
macro_rules! test_log { ($($arg:tt)*) => {}; } #[macro_export] macro_rules! bytes_concat { ($($byte_strings:expr),*$(,)*) => {{ &[$($byte_strings),*].concat() }} } pub fn bytes_lines<'a>(bytes: &'a [u8]) -> impl Iterator<Item = &'a [u8]> { bytes.split(|&b| b == b'\n') } pub fn ...
#[test] fn test_bytes_next_word_matches_bytes_split_whitespace_A() { let r = bytes_next_word_matches_bytes_split_whitespace(vec![0, 26]); assert!(!r.is_failure()); } fn byte_reflow_early_out(bytes: &[u8], width: usize) -> bool { bytes.iter().cloned().all(is_byte_white...
p(); assert_eq!(len, word.len()); let mut i = w_i; for c in word { assert_eq!(*c, bytes[i]); i += 1; } } TestResult::from_bool(true) }
function_block-function_prefixed
[ { "content": "pub fn center_rect_in_rect<R: Into<Rect>>((width, height): (u8, u8), r: R) -> (u8, u8) {\n\n let Rect { x, y, w, h } = r.into();\n\n let middle_x = x + (w / 2);\n\n let middle_y = y + (h / 2);\n\n\n\n let left_x = middle_x.saturating_sub(width / 2);\n\n let top_y = middle_y.saturati...
Rust
benches/bench.rs
AleoHQ/marlin
d78863356cefd50ec23bd131d37f6bdbf2fb8b28
use ark_bls12_381::{Bls12_381, Fq as BlsFq, Fr as BlsFr}; use ark_ff::PrimeField; use ark_marlin::fiat_shamir::FiatShamirChaChaRng; use ark_marlin::Marlin; use ark_marlin::MarlinDefaultConfig; use ark_mnt4_298::{Fq as MNT4Fq, Fr as MNT4Fr, MNT4_298}; use ark_mnt4_753::{Fq as MNT4BigFq, Fr as MNT4BigFr, MNT4_753}; use...
use ark_bls12_381::{Bls12_381, Fq as BlsFq, Fr as BlsFr}; use ark_ff::PrimeField; use ark_marlin::fiat_shamir::FiatShamirChaChaRng; use ark_marlin::Marlin; use ark_marlin::MarlinDefaultConfig; use ark_mnt4_298::{Fq as MNT4Fq, Fr as MNT4Fr, MNT4_298}; use ark_mnt4_753::{Fq as MNT4BigFq, Fr as MNT4BigFr, MNT4_753}; use...
fn bench_verify() { marlin_verify_bench!(bls, BlsFr, BlsFq, Bls12_381); marlin_verify_bench!(mnt4, MNT4Fr, MNT4Fq, MNT4_298); marlin_verify_bench!(mnt6, MNT6Fr, MNT6Fq, MNT6_298); marlin_verify_bench!(mnt4big, MNT4BigFr, MNT4BigFq, MNT4_753); marlin_verify_bench!(mnt6big, MNT6BigFr, MNT6BigFq, MNT...
fn bench_prove() { marlin_prove_bench!(bls, BlsFr, BlsFq, Bls12_381); marlin_prove_bench!(mnt4, MNT4Fr, MNT4Fq, MNT4_298); marlin_prove_bench!(mnt6, MNT6Fr, MNT6Fq, MNT6_298); marlin_prove_bench!(mnt4big, MNT4BigFr, MNT4BigFq, MNT4_753); marlin_prove_bench!(mnt6big, MNT6BigFr, MNT6BigFq, MNT6_753); ...
function_block-full_function
[ { "content": "pub trait MarlinConfig: Clone {\n\n const FOR_RECURSION: bool;\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct MarlinDefaultConfig;\n\n\n\nimpl MarlinConfig for MarlinDefaultConfig {\n\n const FOR_RECURSION: bool = false;\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct MarlinRecursiveConfig;\n\n\n\nim...
Rust
device_model/src/legacy/pl031.rs
focus-zhaos/UringForStratoVirt
f85c6c17906758b887b28739ee17a67aecdc02d6
use std::time::{Instant, SystemTime, UNIX_EPOCH}; use address_space::GuestAddress; use byteorder::{ByteOrder, LittleEndian}; use kvm_ioctls::VmFd; use vmm_sys_util::eventfd::EventFd; use super::super::mmio::errors::{Result, ResultExt}; use super::super::mmio::{DeviceOps, DeviceResource, DeviceType, MmioDeviceOps}; ...
use std::time::{Instant, SystemTime, UNIX_EPOCH}; use address_space::GuestAddress; use byteorder::{ByteOrder, LittleEndian}; use kvm_ioctls::VmFd; use vmm_sys_util::eventfd::EventFd; use super::super::mmio::errors::{Result, ResultExt}; use super::super::mmio::{DeviceOps, DeviceResource, DeviceType, MmioDeviceOps}; ...
} impl MmioDeviceOps for PL031 { fn realize(&mut self, vm_fd: &VmFd, resource: DeviceResource) -> Result<()> { match EventFd::new(libc::EFD_NONBLOCK) { Ok(evt) => { vm_fd .register_irqfd(&evt, resource.irq) .chain_err(|| "Failed to r...
self.imsr = value & 1; self.interrupt(); } RTC_ICR => { self.risr = 0; self.interrupt(); } _ => {} } true }
function_block-function_prefix_line
[ { "content": "/// Write the given u32 to the first or second half in u64,\n\n/// returns the u64 value.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `value` - The origin u32 value.\n\n/// * `page` - Value is 0 or 1, determines which half to write.\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust\n\n/// extern crate ...
Rust
src/lib.rs
Darksonn/prefix_sum
0f263637ea9e704b16b14e29909fd7b4a6be03a6
pub mod iter; pub mod range; pub mod sum2d; pub mod summable; use crate::iter::Iter; use crate::summable::Summable; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct PrefixSum<T: Summable> { values: Vec<T>, } impl<T: Summable> PrefixSum<T> { pub fn new(len: usize) -> PrefixSum<T> { ...
pub mod iter; pub mod range; pub mod sum2d; pub mod summable; use crate::iter::Iter; use crate::summable::Summable; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct PrefixSum<T: Summable> { values: Vec<T>, } impl<T: Summable> PrefixSum<T> { pub fn new(len: usize) -> PrefixSum<T> { ...
let mut negsum = T::zero(); negsum.sub_assign_ref(&vec[0]); for i in (1..vec.len()).rev() { let (a, b) = vec[i-1 ..= i].split_at_mut(1); let a = &a[0]; let b = &mut b[0]; Summable::sub_assign_ref(b, a); negsum.sub_assign_ref(&*b); ...
if vec.len() == 0 { vec.push(T::zero()); return PrefixSum { values: vec, }; }
if_condition
[ { "content": "/// Trait for types that can be used in a `PrefixSum`.\n\n///\n\n/// The distinction between `add_assign` and `add_assign_ref` exists to allow types such\n\n/// as [`BigInt`] to make proper use of memory allocations as appropriate.\n\n///\n\n/// See also the [`SummableSigned`] marker trait.\n\n///...
Rust
shared/rust/src/domain/badge.rs
jewish-interactive/ji-cloud
b6164bf1d15277115bcab1d8c9f91619e706231d
use serde::{Deserialize, Serialize}; use uuid::Uuid; use super::asset::UserOrMe; #[derive(Copy, Clone, Eq, PartialEq, Serialize, Deserialize, Debug)] #[cfg_attr(feature = "backend", derive(sqlx::Type))] #[cfg_attr(feature = "backend", sqlx(transparent))] pub struct BadgeId(pub Uuid); #[derive(Serialize, Deserializ...
use serde::{Deserialize, Serialize}; use uuid::Uuid; use super::asset::UserOrMe; #[derive(Copy,
2>, #[serde(default)] #[serde(skip_serializing_if = "Option::is_none")] pub page_limit: Option<u32>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct BadgeBrowseResponse { pub badges: Vec<Badge>, pub pages: u32, pub total_bad...
Clone, Eq, PartialEq, Serialize, Deserialize, Debug)] #[cfg_attr(feature = "backend", derive(sqlx::Type))] #[cfg_attr(feature = "backend", sqlx(transparent))] pub struct BadgeId(pub Uuid); #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct Badge { pub id: BadgeId, ...
random
[ { "content": "fn serialize_list<S, T>(list: &Vec<T>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n T: Serialize,\n\n{\n\n list.iter()\n\n .map(|v| serde_json::to_string(v).unwrap())\n\n .collect::<Vec<String>>()\n\n .join(\", \")\n\n .serialize(se...
Rust
tools/bindc/migration_tool/src/main.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
mod composite_bind; mod composite_device_desc; pub mod library; use regex::Regex; use std::collections::HashSet; use std::fmt::Write as FmtWrite; use std::fs::File; use std::fs::OpenOptions; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] str...
mod composite_bind; mod composite_device_desc; pub mod library; use regex::Regex; use std::collections::HashSet; use std::fmt::Write as FmtWrite; use std::fs::File; use std::fs::OpenOptions; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] str...
for file in migrate_success { println!(" {}", file); } println!("\nUnable to migrate: "); for file in migrate_failure { println!(" {}", file); } Ok(()) }
function_block-function_prefix_line
[]
Rust
protocols/relay/src/protocol/listen.rs
alerdenisov/rust-libp2p
ae89137f479004b4d6854adbabf29845a0c69313
use crate::message::{CircuitRelay, CircuitRelay_Type}; use crate::protocol::{ dest_request::RelayDestinationRequest, hop_request::RelayHopRequest, Peer, PeerParseError, MAX_ACCEPTED_MESSAGE_LEN, }; use futures::{prelude::*, try_ready}; use libp2p_core::upgrade; use protobuf::ProtobufError; use std::{convert::...
use crate::message::{CircuitRelay, CircuitRelay_Type}; use crate::protocol::{ dest_request::RelayDestinationRequest, hop_request::RelayHopRequest, Peer, PeerParseError, MAX_ACCEPTED_MESSAGE_LEN, }; use futures::{prelude::*, try_ready}; use libp2p_core::upgrade; use protobuf::ProtobufError; use std::{convert::...
uest::HopRequest(rq))) } CircuitRelay_Type::STOP => { let peer = Peer::try_from(msg.take_srcPeer())?; let rq = RelayDestinationRequest::new(substream, peer); Ok(Async::Ready(RelayRemoteRequest::DestinationRequest(rq))) } _ =...
Future { let f: fn(_, _, _) -> _ = |sock, msg, ()| Ok((sock, msg)); let fut = upgrade::read_respond(substream, MAX_ACCEPTED_MESSAGE_LEN, (), f); RelayListenFuture { inner: fut } } } #[must_use = "futures do nothing unless polled"] pub struct RelayListenFuture<TSubstream> { inner: u...
random
[ { "content": "/// Generates a new key pair as part of the exchange.\n\n///\n\n/// Returns the opaque private key and the corresponding public key.\n\npub fn generate_agreement(algorithm: KeyAgreement) -> impl Future<Output = Result<(AgreementPrivateKey, Vec<u8>), SecioError>> {\n\n let rng = ring_rand::Syste...
Rust
src/serde_types.rs
jpastuszek/varnishslog
e384e0dc127be8f7207b705b0dbb8ed5de2a5dcf
use serde::{Serialize, Serializer}; use serde::ser::{SerializeSeq, SerializeMap}; use crate::access_log::record::LogEntry as VslLogEntry; use crate::access_log::record::AclResult as VslAclResult; use linked_hash_map::LinkedHashMap; pub trait EntryType: Serialize { fn type_name(&self) -> &str; fn remote_ip(&se...
use serde::{Serialize, Serializer}; use serde::ser::{SerializeSeq, SerializeMap}; use crate::access_log::record::LogEntry as VslLogEntry; use crate::access_log::record::AclResult as VslAclResult; use linked_hash_map::LinkedHashMap; pub trait EntryType: Serialize { fn type_name(&self) -> &str; fn remote_ip(&se...
} #[derive(Debug)] pub struct LogVarsIndex<'a, 'i>(pub &'i LinkedHashMap<&'a str, &'a str>); impl<'a: 'i, 'i> Serialize for LogVarsIndex<'a, 'i> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { let mut state = serializer.serialize_map(Some(self.0.len()))?; ...
f values) in self.0 { state.serialize_key(key)?; state.serialize_value(values)?; } state.end() }
function_block-function_prefixed
[ { "content": "pub fn exit_with_error(msg: &str, code: i32) -> ! {\n\n error!(\"Exiting: {}\", msg);\n\n std::process::exit(code);\n\n}\n", "file_path": "src/program.rs", "rank": 0, "score": 225334.8873204857 }, { "content": "fn session_state(bench: &mut Bencher) {\n\n let mut cursor...
Rust
src/maths/matrix.rs
yggie/mach
b1c15026e0f31117d0d54ee6eeaeadd3e94a3d92
#[cfg(test)] #[path="../../tests/maths/matrix_test.rs"] mod matrix_test; use std::fmt; use std::ops::{ Add, Div, Index, IndexMut, Mul, Neg, Sub }; use { Scalar, TOLERANCE }; use maths::Vec3D; #[derive(Clone, Copy, Debug)] pub struct Matrix { elements: [Scalar; 9] } impl Matrix { #[inline(always)] p...
#[cfg(test)] #[path="../../tests/maths/matrix_test.rs"] mod matrix_test; use std::fmt; use std::ops::{ Add, Div, Index, IndexMut, Mul, Neg, Sub }; use { Scalar, TOLERANCE }; use maths::Vec3D; #[derive(Clone, Copy, Debug)] pub struct Matrix { elements: [Scalar; 9] } impl Matrix { #[inline(always)] p...
return Matrix { elements: elems }; } }
let elems: [Scalar; 9] = [ self[0]*other[0] + self[1]*other[3] + self[2]*other[6], self[0]*other[1] + self[1]*other[4] + self[2]*other[7], self[0]*other[2] + self[1]*other[5] + self[2]*other[8], self[3]*other[0] + self[4]*other[3] + self[5]*other[6], self[3]*o...
assignment_statement
[ { "content": "pub fn is_coplanar(points: &[Vec3D]) -> bool {\n\n let mut remaining_points = points.iter();\n\n let first = remaining_points.next().unwrap();\n\n let second = remaining_points.next().unwrap();\n\n let third = remaining_points.next().unwrap();\n\n\n\n let normal = (second - first).c...
Rust
jdwp-macros/src/lib.rs
necauqua/jdwp
51144b74d57d5194d1966e02c1727166f02b4eac
use proc_macro::TokenStream; use quote::quote; use syn::{ parse::{Parse, ParseStream}, Data, Fields, Index, LitInt, Token, Type, }; #[proc_macro_derive(JdwpReadable)] pub fn jdwp_readable(item: TokenStream) -> TokenStream { let derive_input = syn::parse_macro_input!(item as syn::DeriveInput); if let D...
use proc_macro::TokenStream; use quote::quote; use syn::{ parse::{Parse, ParseStream}, Data, Fields, Index, LitInt, Token, Type, }; #[proc_macro_derive(JdwpReadable)] pub fn jdwp_readable(item: TokenStream) -> TokenStream { let derive_input = syn::parse_macro_input!(item as syn::DeriveInput); if let D...
ttr { fn parse(input: ParseStream) -> syn::Result<Self> { let command_set = input.parse()?; let _ = input.parse::<Token![,]>()?; let command_id = input.parse()?; Ok(ShortCommandAttr { command_set, command_id, }) } } #[proc_macro_attribute] pub fn ...
syn::Result<Self> { let reply_type = input.parse()?; let _ = input.parse::<Token![,]>()?; Ok(CommandAttr { reply_type, command: input.parse()?, }) } } struct ShortCommandAttr { command_set: LitInt, command_id: LitInt, } impl ShortCommandAttr { f...
random
[ { "content": "pub trait Command: JdwpWritable {\n\n const ID: CommandId;\n\n type Output: JdwpReadable;\n\n}\n\n\n\n// VirtualMachine is done, pfew\n\n\n\n#[repr(u8)]\n\n#[derive(Copy, Clone)]\n\npub enum ReferenceType {\n\n Signature = 1,\n\n ClassLoader = 2,\n\n Modifiers = 3,\n\n Fields = 4...
Rust
synthesize/src/lib.rs
andir/bootspec
5ebf8c571d5500516fae0bb01303b1948e158cd4
use std::collections::HashMap; use std::error::Error; use std::fs; use std::path::Path; use bootspec::{ BootJson, BootSpecPath, SpecialisationDescription, SpecialisationName, SystemConfigurationRoot, JSON_FILENAME, SCHEMA_VERSION, }; #[doc(hidden)] pub type Result<T, E = Box<dyn Error + Send + Sync + 'static>...
use std::collections::HashMap; use std::error::Error; use std::fs; use std::path::Path; use bootspec::{ BootJson, Boo
let initrd = fs::canonicalize(generation.join("initrd")) .map_err(|e| format!("Failed to canonicalize the initrd:\n{}", e))?; let initrd_secrets = generation.join("append-initrd-secrets"); let mut specialisation: HashMap<SpecialisationName, SpecialisationDescription> = HashMap::new(); for spec in ...
tSpecPath, SpecialisationDescription, SpecialisationName, SystemConfigurationRoot, JSON_FILENAME, SCHEMA_VERSION, }; #[doc(hidden)] pub type Result<T, E = Box<dyn Error + Send + Sync + 'static>> = core::result::Result<T, E>; pub fn synthesize_schema_from_generation(generation: &Path) -> Result<BootJson> { let...
random
[ { "content": "use std::collections::HashMap;\n\nuse std::path::PathBuf;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::{SpecialisationDescription, SpecialisationName, SystemConfigurationRoot};\n\n\n\n/// The V1 bootspec schema version.\n\npub const SCHEMA_VERSION: u32 = 1;\n\n/// The V1 bootspec ...
Rust
src/rt/thread.rs
Ekleog/loom
ddcbdec6523a790cf158bc26e511fa2fb4d70cbc
use crate::rt::execution; use crate::rt::object::Operation; use crate::rt::vv::VersionVec; use std::{fmt, ops}; #[derive(Debug)] pub struct Thread { pub id: Id, pub state: State, pub critical: bool, pub operation: Option<Operation>, pub causality: VersionVec, pub ...
use crate::rt::execution; use crate::rt::object::Operation; use crate::rt::vv::VersionVec; use std::{fmt, ops}; #[derive(Debug)] pub struct Thread { pub id: Id, pub state: State, pub critical: bool, pub operation: Option<Operation>, pub causality: VersionVec, pub ...
} } pub fn set_runnable(&mut self) { self.state = State::Runnable; } pub fn set_blocked(&mut self) { self.state = State::Blocked; } pub fn is_blocked(&self) -> bool { match self.state { State::Blocked => true, _ => false, } } ...
pub fn is_runnable(&self) -> bool { match self.state { State::Runnable => true, _ => false,
function_block-random_span
[ { "content": "fn active(threads: &[Thread]) -> Option<usize> {\n\n // Get the index of the currently active thread\n\n threads\n\n .iter()\n\n .enumerate()\n\n .find(|(_, th)| th.is_active())\n\n .map(|(index, _)| index)\n\n}\n", "file_path": "src/rt/path.rs", "rank": 0...
Rust
src/tests/mod.rs
wmanley/rustysd
89e0c450253c6fdf73e44573bb87b607932ffeb7
#[test] fn test_service_parsing() { let descr = "This is a description"; let unit_before1 = "unit_before2"; let unit_before2 = "unit_before1"; let unit_after1 = "unit_after1"; let unit_after2 = "unit_after2,unit_after3"; let install_required_by = "install_req_by"; let install_wanted_by = "i...
#[test] fn test_service_parsing() { let descr = "This is a description"; let unit_before1 = "unit_before2"; let unit_before2 = "unit_before1"; let unit_after1 = "unit_after1"; let unit_after2 = "unit_after2,unit_after3"; let install_required_by = "install_req_by"; let install_wanted_by = "i...
#[test] fn test_socket_parsing() { let descr = "This is a description"; let unit_before1 = "unit_before2"; let unit_before2 = "unit_before1"; let unit_after1 = "unit_after1"; let unit_after2 = "unit_after2,unit_after3"; let install_required_by = "install_req_by"; let install_wanted_by = "...
lized { if let Some(conf) = srvc.service_config { assert_eq!(conf.exec, service_exec); assert_eq!(conf.stop, service_stop); assert_eq!( conf.sockets, vec!["socket_name1".to_owned(), "socket_name2".to_owned()] ); } else { ...
function_block-function_prefixed
[ { "content": "pub fn format_socket(socket_unit: &Unit) -> Value {\n\n let mut map = serde_json::Map::new();\n\n map.insert(\"Name\".into(), Value::String(socket_unit.conf.name()));\n\n\n\n if let UnitSpecialized::Socket(sock) = &socket_unit.specialized {\n\n map.insert(\n\n \"FileDesc...
Rust
server/blindai_sgx/src/identity.rs
mithril-security/blindai
48739da059d30ab28429ca5106d7f07f8d5d3f66
use anyhow::{anyhow, Result}; use der_parser::oid; use pkix::pem::{PEM_CERTIFICATE, PEM_PRIVATE_KEY}; use rand::{rngs::OsRng, RngCore}; use rcgen::{Certificate, CertificateParams, CustomExtension, SanType}; use ring_compat::signature::ed25519::SigningKey; use rsa::{ pkcs1::{ToRsaPrivateKey, ToRsaPublicKey}, R...
use anyhow::{anyhow, Result}; use der_parser::oid; use pkix::pem::{PEM_CERTIFICATE, PEM_PRIVATE_KEY}; use rand::{rngs::OsRng, RngCore}; use rcgen::{Certificate, CertificateParams, CustomExtension, SanType}; use ring_compat::signature::ed25519::SigningKey; use rsa::{ pkcs1::{ToRsaPrivateKey, ToRsaPublicKey}, R...
} impl From<&TlsIdentity> for Identity { fn from(identity: &TlsIdentity) -> Self { let cert_pem = pkix::pem::der_to_pem(&identity.cert_der, PEM_CERTIFICATE); let private_key_pem = pkix::pem::der_to_pem(&identity.private_key_der, PEM_PRIVATE_KEY); Identity::from_pem(cert_pem, priva...
borrow(); let cert_der = cert.serialize_der().unwrap(); let private_key_der = cert.serialize_private_key_der(); TlsIdentity { cert_der, private_key_der, } }
function_block-function_prefixed
[ { "content": "fn uri_to_socket(uri: &Uri) -> Result<SocketAddr> {\n\n uri.authority()\n\n .context(\"No authority\")?\n\n .as_str()\n\n .to_socket_addrs()?\n\n .next()\n\n .context(\"Uri could not be converted to socket\")\n\n}\n\n\n\nimpl NetworkConfig {\n\n pub fn inte...
Rust
src/main.rs
johannst/llvm-kaleidoscope-rs
a3dee93989b9fdd99b8a22a2da7f72bcd2ba50c2
use llvm_kaleidoscope_rs::{ codegen::Codegen, lexer::{Lexer, Token}, llvm, parser::{Parser, PrototypeAST}, Either, }; use std::collections::HashMap; use std::io::Read; fn main_loop<I>(mut parser: Parser<I>) where I: Iterator<Item = char>, { let mut module = llvm::Module::new(); ...
use llvm_kaleidoscope_rs::{ codegen::Codegen, lexer::{Lexer, Token}, llvm, parser::{Parser, PrototypeAST}, Either, }; use std::collections::HashMap; use std::io::Read; fn main_loop<I>(mut parser: Parser<I>) where I: Iterator<Item = char>, { let mut module = llvm::Module::new(); ...
} Err(err) => { eprintln!("Error: {:?}", err); parser.get_next_token(); } }, Token::Extern => match parser.parse_extern() { Ok(proto) => { println!("Parse 'extern'"); ...
if let Ok(func_ir) = Codegen::compile(&module, &mut fn_protos, Either::B(&func)) { func_ir.dump(); let rt = jit.add_module(module); fn_jit_rt.insert(func_name.to_string(), rt);...
if_condition
[ { "content": "struct Error<'llvm>(&'llvm mut libc::c_char);\n\n\n\nimpl<'llvm> Error<'llvm> {\n\n fn from(err: LLVMErrorRef) -> Option<Error<'llvm>> {\n\n (!err.is_null()).then(|| Error(unsafe { &mut *LLVMGetErrorMessage(err) }))\n\n }\n\n\n\n fn as_str(&self) -> &str {\n\n unsafe { CStr:...
Rust
nalgebra-sparse/src/proptest.rs
ThatGeoGuy/nalgebra
10deb03b71793c5d98de04267a99d7af69a715d5
mod proptest_patched; use crate::{ coo::CooMatrix, cs::{CscMatrix, CsrMatrix}, }; use nalgebra::{ proptest::{matrix, DimRange}, DMatrix, Dim, Scalar, }; use proptest::{ collection::{btree_set, hash_map, vec}, prelude::*, sample::Index, }; use std::{cmp::min, convert::TryFrom, fmt::Debug, ...
mod proptest_patched; use crate::{ coo::CooMatrix, cs::{CscMatrix, CsrMatrix}, }; use nalgebra::{ proptest::{matrix, DimRange}, DMatrix, Dim, Scalar, }; use proptest::{ collection::{btree_set, hash_map, vec}, prelude::*, sample::Index, }; use std::{cmp::min, convert::TryFrom, fmt::Debug, ...
triplets.extend(duplicates_iter); } let shuffled = Just(triplets).prop_shuffle(); (Just(coo.nrows()), Just(coo.ncols()), shuffled) }) .prop_map(move |(nrows, ncols, triplets)| { let mut coo = CooMatrix::new(nrows, ncols); ...
let duplicates_iter: Vec<_> = duplicates .into_iter() .map(|(idx, val)| { let (i, j, _) = idx.get(&triplets); (*i, *j, val) }) .collect();
assignment_statement
[ { "content": "pub fn dmatrix() -> impl Strategy<Value = DMatrix<f64>> {\n\n matrix(PROPTEST_F64, PROPTEST_MATRIX_DIM, PROPTEST_MATRIX_DIM)\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 0, "score": 563284.7893481092 }, { "content": "pub fn complex_f64() -> impl Strategy<Value ...
Rust
lib/src/crypto/public_encrypted_secure_data.rs
john-sharratt/ate
f9982e4d2b210942e6aa39aa03c1f3e72acb55e9
use crate::spec::SerializationFormat; use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use fxhash::FxHashMap; use serde::{Deserialize, Serialize}; use std::result::Result; use std::{io::ErrorKind, marker::PhantomData}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace...
use crate::spec::SerializationFormat; use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use fxhash::FxHashMap; use serde::{Deserialize, Serialize}; use std::result::Result; use std::{io::ErrorKind, marker::PhantomData}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace...
} pub fn add( &mut self, encrypt_key: &PublicEncryptKey, meta: String, referrer: &PrivateEncryptKey, ) -> Result<bool, std::io::Error> { match self.members.get(&referrer.hash().to_hex_string()) { Some(a) => { let shared_key = a.unwrap(ref...
Ok(match self.format.deserialize::<T>(&data[..]) { Ok(a) => Some(a), Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } })
call_expression
[ { "content": "pub fn decode_request<T>(format: SerializationFormat, request: &[u8]) -> Result<T, CallError>\n\nwhere\n\n T: de::DeserializeOwned,\n\n{\n\n let req: T = match format {\n\n SerializationFormat::Bincode => match bincode::deserialize(request) {\n\n Ok(a) => a,\n\n ...
Rust
entab/src/readers/xml.rs
bovee/entab
8b8228d65bde0a4b1ec21fd3685c3f5a1041b71f
use core::marker::Copy; use alloc::borrow::ToOwned; use alloc::format; use alloc::str::from_utf8; use alloc::string::String; use alloc::vec::Vec; use memchr::{memchr, memchr3_iter}; use crate::buffer::ReadBuffer; use crate::parsers::FromBuffer; use crate::record::StateMetadata; use crate::EtError; use crate::{impl_r...
use core::marker::Copy; use alloc::borrow::ToOwned; use alloc::format; use alloc::str::from_utf8; use alloc::string::String; use alloc::vec::Vec; use memchr::{memchr, memchr3_iter}; use crate::buffer::ReadBuffer; use crate::parsers::FromBuffer; use crate::record::StateMetadata; use crate::EtError; use crate::{impl_r...
found, but {} was open.", tag.id, open_tag), &rb, )); } } else { return Err(EtError::new( format!( "Closing tag {} found, but no tag...
&rb, )); } else { return Ok(false); } } let text = if rb[0] == b'<' { let tag = rb.extract::<XmlTag>(())?; match tag.tag_type { XmlTagType::Open => { state.stack.push(t...
random
[ { "content": "#[derive(Clone, Debug, Default, PartialEq)]\n\nstruct FcsHeaderKeyValue<'a>(String, Cow<'a, str>);\n\n\n\nimpl<'r> FromBuffer<'r> for FcsHeaderKeyValue<'r> {\n\n type State = (u8, u64);\n\n\n\n fn from_buffer(\n\n &mut self,\n\n rb: &'r mut ReadBuffer,\n\n (delim, text_e...
Rust
src/middleware/latency.rs
dmrolfs/egress-proxy
fd3b3e6e4c30dd4ce9f827ccba1bdf3a5d96739b
#![feature(duration_float)] use std::time::Duration; use std::rc::Rc; use log::info; use lazy_static::*; use futures::future::{ok, FutureResult}; use futures::{Future, Poll}; use actix_service::{Service, Transform}; use actix_web::{Error, dev::{ServiceRequest, ServiceResponse}, http::header}; use header::HeaderValue; ...
#![feature(duration_float)] use std::time::Duration; use std::rc::Rc; use log::info; use lazy_static::*; use futures::future::{ok, FutureResult}; use futures::{Future, Poll}; use actix_service::{Service, Transform}; use actix_web::{Error, dev::{ServiceRequest, ServiceResponse}, http::header}; use header::HeaderValue; ...
}
w( self.service .call( svc_req ) .and_then( move |resp| { let total_dur = total_timer.elapsed(); total_histogram.observe( total_dur.as_secs_f64() ); if let Some(req) = resp.response().extensions().get::<Duration>() { eg...
function_block-function_prefixed
[ { "content": "pub fn gather( _req: HttpRequest ) -> impl IntoFuture<Item = String, Error = Error> {\n\n let mut buffer = Vec::new();\n\n let encoder = prometheus::TextEncoder::new();\n\n let metric_families = prometheus::gather();\n\n encoder.encode( &metric_families, &mut buffer ).unwrap();\n\n\n\n...
Rust
endpoint-common/src/sender/process/external.rs
ctron/drogue-cloud
5337643fe98ae8f50b45509988da61e2944d54a4
use cloudevents::{ binding::reqwest::{RequestBuilderExt, RequestSerializer}, message::StructuredDeserializer, Event, }; use drogue_client::registry::v1::{ Authentication, ContentMode, ExternalEndpoint, RequestType, TlsOptions, }; use drogue_cloud_service_common::reqwest::to_method; use http::{header::He...
use cloudevents::{ binding::reqwest::{RequestBuilderExt, RequestSerializer}, message::StructuredDeserializer, Event, }; use drogue_client::registry::v1::{ Authentication, ContentMode, ExternalEndpoint, RequestType, TlsOptions, }; use drogue_cloud_service_common::reqwest::to_method; use http::{header::He...
pub async fn process( &self, payload: RequestPayload, endpoint: &ExternalEndpoint, ) -> Result<reqwest::Response, ExternalError> { let method = to_method(endpoint.method.as_deref().unwrap_or("")) .map_err(ExternalError::InvalidConfiguration)? .unwrap_or(...
pub fn new(tls: Option<&TlsOptions>) -> Result<Self, reqwest::Error> { let mut client = reqwest::Client::builder(); if let Some(tls) = tls { if tls.insecure { client = client .danger_accept_invalid_certs(true) .danger_accept_invalid_ho...
function_block-full_function
[ { "content": "#[inline]\n\npub fn authentication_url() -> Url {\n\n Url::parse(\"http://authentication-service\").unwrap()\n\n}\n\n\n", "file_path": "service-common/src/defaults.rs", "rank": 0, "score": 320251.15895207966 }, { "content": "#[async_trait]\n\npub trait EndpointSource: Debug ...
Rust
rsp2/src/io/lammps/low_level/mod.rs
colin-daniels/agnr-ml
fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8
/* ********************************************************************** ** ** This file is part of rsp2. ** ** ** ** rsp2 is free software: you can redistribute it and/or modify it under ** ** the term...
/* ********************************************************************** ** ** This file is part of rsp2. ** ** ** ** rsp2 is free software: you can redistribute it and/or modify it under ** ** the term...
} #[macro_use] mod c_enum_macros; pub(crate) use self::plain::LammpsOwner; mod plain; #[cfg(feature = "mpi")] pub(crate) mod mpi; #[cfg(feature = "mpi")] pub(crate) mod mpi_helper; c_enums!{ [pub(crate)] enum ComputeStyle { Global = 0, PerAtom = 1, Local = 2, } [] enum ComputeT...
write!( f, "LAMMPS threw {}: {}", match self.severity { Severity::Recoverable => "an exception", Severity::Fatal => "a fatal exception", }, self.message, ) }
function_block-function_prefix_line
[ { "content": "pub fn load(mut file: impl Read) -> FailResult<Assemble>\n\n{ _load(&mut file) }\n\n\n", "file_path": "rsp2/src/io/structure/layers_yaml.rs", "rank": 0, "score": 381229.27417752333 }, { "content": "// FIXME this really doesn't belong here, but it's the easiest reuse of code\n\n...
Rust
src/runtime/interpreter.rs
paavohuhtala/MiniPL-RS
3d0da289686424b56da1889b0cb9b51123de50e3
use std::collections::HashMap; use common::types::{TypeName, Value}; use diagnostics::file_context::FileContextSource; use parsing::ast::*; use runtime::io::Io; struct Variable { type_of: TypeName, value: Value, } pub struct Interpreter<'a, T: Io + 'a> { variables: HashMap<String, Variable>, ctx: &'a File...
use std::collections::HashMap; use common::types::{TypeName, Value}; use diagnostics::file_context::FileContextSource; use parsing::ast::*; use runtime::io::Io; struct Variable { type_of: TypeName, value: Value, } pub struct Interpreter<'a, T: Io + 'a> { variables: HashMap<String, Variable>, ctx: &'a File...
fn execute_statement(&mut self, statement: &StatementWithCtx) { match statement.statement { Statement::Declare { ref name, ref type_of, ref initial, .. } => { let initial_value = initial .as_ref() .map(|expr| self.evaluate_expression...
event this."), } } UnaryOp(ref op, ref param) => { let inner = self.evaluate_expression(param); match (*op, inner) { (Not, BoolV(x)) => BoolV(!x), _ => panic!("Type checker will prevent this."), } } } }
function_block-function_prefixed
[ { "content": "pub fn mul(a: Expression, b: Expression) -> Expression {\n\n BinaryOp(Mul, Box::new((a, b)))\n\n}\n\n\n", "file_path": "src/parsing/ast_test_util.rs", "rank": 0, "score": 154473.29274059128 }, { "content": "pub fn div(a: Expression, b: Expression) -> Expression {\n\n BinaryOp...
Rust
sdk/src/lobby/search.rs
Ewpratten/discord-sdk
2af8089eb1021fe99cfde9d7a00731203388ab4e
use super::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize_repr, Deserialize_repr)] #[repr(i8)] pub enum LobbySearchComparison { LessThanOrEqual = -2, LessThan = -1, Equal = 0, GreaterThan = 1, GreaterThanOrEqual = 2, NotEqual = 3, } #[derive(Copy, Clone, Debug, PartialEq, Eq, Seriali...
use super::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize_repr, Deserialize_repr)] #[repr(i8)] pub enum LobbySearchComparison { LessThanOrEqual = -2, LessThan = -1, Equal = 0, GreaterThan = 1, GreaterThanOrEqual = 2, NotEqual = 3, } #[derive(Copy, Clone, Debug, PartialEq, Eq, Seriali...
pub fn distance(mut self, distance: LobbySearchDistance) -> Self { self.distance = distance; self } } impl Default for SearchQuery { fn default() -> Self { Self { filter: Vec::new(), sort: Vec::new(), limit: 25, distance: D...
lue.into(), }); self } pub fn add_sort<'md>(mut self, key: impl Into<SearchKey<'md>>, value: SearchValue) -> Self { self.sort.push(SearchSort { key: key.into().to_string(), cast: value.cast(), near_value: value.into(), }); ...
random
[ { "content": "#[inline]\n\nfn truncate(text: Option<impl Into<String>>, name: &str) -> Option<String> {\n\n text.map(|text| {\n\n let mut text = text.into();\n\n if text.len() > 128 {\n\n tracing::warn!(\"{} '{}' is too long and will be truncated\", name, text);\n\n text.t...
Rust
src/http/messages.rs
phsym/rust-http
df8859839fe81907e1264dc86f5f7511b9f4d135
use std::collections::HashMap; use std::io::{BufReader, Error, ErrorKind}; use std::str; use std::str::FromStr; use std::collections::hash_map::{Iter, Keys}; use std::fmt; use std::io::prelude::*; use super::constants::properties; pub struct HttpReply<T: Read> { version: String, code: u32, status: S...
use std::collections::HashMap; use std::io::{BufReader, Error, ErrorKind}; use std::str; use std::str::FromStr; use std::collections::hash_map::{Iter, Keys}; use std::fmt; use std::io::prelude::*; use super::constants::properties; pub struct HttpReply<T: Read> { version: String, code: u32, status: S...
ut splt = line.split(": "); header.insert( option!(splt.next(), "Cannot parse header").to_string(), option!(splt.next(), "Cannot parse header").to_string() ); } line.clear(); } } let reply = HttpReply{version: version, code: code, status: status, header: header, reader...
o_string(); let mut splt = line.split(" "); version = option!(splt.next(), "HTTP version not found").to_string(); code = match u32::from_str(option!(splt.next(), "HTTP code not found")) { Ok(n) => n, Err(e) => return Err(Error::new(ErrorKind::Other, format!("Cannot parse HTTP code : {}", e))) ...
function_block-random_span
[ { "content": "/// Create a new client. The implementation which may differ according to the `protocol` is hidden\n\n/// behind a boxed `Http` trait\n\n///\n\n/// # Example :\n\n/// ```no_run\n\n/// use http::{open, Protocol};\n\n///\n\n/// let mut http = open(Protocol::HTTP, \"www.google.com:80\").unwrap();\n\n...
Rust
src/auth/Crypto.rs
grollrs/grollrs
51803bfbc4d7409e4435d75387bc390d913f0312
#![allow(non_snake_case)] /* extern crate bytes; extern crate num; extern crate sha1; extern crate itertools; extern crate crypto; */ use num::bigint::{BigInt, Sign, ToBigInt}; use num::One; use num::Signed; use itertools::Itertools; use crypto::rc4; use crypto::hmac::Hmac; use crypto::sha1::Sha1; use crypto::buffer...
#![allow(non_snake_case)] /* extern crate bytes; extern crate num; extern crate sha1; extern crate itertools; extern crate crypto; */ use num::bigint::{BigInt, Sign, ToBigInt}; use num::One; use num::Signed; use itertools::Itertools; use crypto::rc4; use crypto::hmac::Hmac; use crypto::sha1::Sha1; use crypto::buffer...
pub fn encrypt(&mut self, data: &mut Vec<u8>){ let mut buffer = vec![0; data.len()]; { let mut read_buffer = RefReadBuffer::new(data); let mut write_buffer = RefWriteBuffer::new(&mut buffer); let res = self.enc.encrypt(&mut read_buffer,&mut write_buffer,false).u...
pub fn new(key: &Vec<u8>)->WorldCrypt{ let sessionKey = (*key).clone().to_vec(); let srv_enc_key_seed : Vec<u8> = vec![ 0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE ]; let srv_dec_key_seed : Vec<u8> = vec![ 0xCC, 0x98, 0xAE, 0x04, 0xE8, 0x97, 0...
function_block-full_function
[ { "content": "pub fn to_hex_string(bytes: Vec<u8>) -> String {\n\n let strs: Vec<String> = bytes.iter().map(|b| format!(\"{:02X}\", b)).collect();\n\n strs.join(\" \")\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use auth::Crypto::SRP;\n\n use num::bigint::{BigInt, Sign, ToBigInt};\n\n use aut...
Rust
src/types.rs
puripuri2100/satysfi-parser
71d98f7ba1a4dd5cd39312bcf78adf2450f4e6dc
use std::fmt::Display; use itertools::{assert_equal, Itertools}; use crate::{grammar, Mode}; use self::rule::Rule; pub trait Vectorize<T> { fn vectorize(self) -> Vec<T>; } impl<T> Vectorize<T> for Vec<T> { fn vectorize(self) -> Vec<T> { self } } impl<T> Vectorize<T> for T {...
use std::fmt::Display; use itertools::{assert_equal, Itertools}; use crate::{grammar, Mode}; use self::rule::Rule; pub trait Vectorize<T> { fn vectorize(self) -> Vec<T>; } impl<T> Vectorize<T> for Vec<T> { fn vectorize(self) -> Vec<T> { self } } impl<T> Vectorize<T> for T {...
vec.push(cst) } let v = cst.pickup(rule); vec.extend(v); } vec } pub fn choose(&self, pos: usize) -> Option<&Cst> { for cst in &self.inner { if cst.span.includes(pos) { return Some(cst); } } ...
ickup(&self, rule: Rule) -> Vec<&Cst> { let mut vec = vec![]; for cst in &self.inner { if cst.rule == rule {
function_block-random_span
[ { "content": "pub fn nested_let_in_stmt(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"nested_let_in_stmt\");\n\n group.significance_level(0.1).sample_size(100);\n\n\n\n fn task(nest: usize) {\n\n let init = \"1\";\n\n // nest = 0: 1\n\n // nest = 1: let x = 1 in 1\n\...
Rust
src/authenticator.rs
incker2/github_auth
1234bd5b91642e355c594c5a5efedc7fe3b9e24a
use crate::auth_response::AuthResponse; use dialoguer::{Input, PasswordInput}; use directories::ProjectDirs; use failure::Error; use mkdirp::mkdirp; use reqwest::blocking::Client; use serde_json; use std::fs::{remove_file, File}; use std::io::prelude::*; use std::path::PathBuf; use super::Builder; use super::Scope; u...
use crate::auth_response::AuthResponse; use dialoguer::{Input, PasswordInput}; use directories::ProjectDirs; use failure::Error; use mkdirp::mkdirp; use reqwest::blocking::Client; use serde_json; use std::fs::{remove_file, File}; use std::io::prelude::*; use std::path::PathBuf; use super::Builder; use super::Scope; u...
d = serde_json::to_string(&json)?; let mut file = File::create(&filename)?; file.write_all(&serialized.as_bytes())?; Ok(Token::new(json.token)) } } impl Default for Authenticator { fn default() -> Self { Builder::new("GitHub Auth".into()) .note("A token created with the github_auth Rust c...
let res = Client::new() .post(crate::GITHUB_AUTH_URL) .header("X-GitHub-OTP", otp) .header("User-Agent", "github_auth") .header("Content-Type", "json") .json(&body) .basic_auth(username, Some(password)) .send()?; let status = res.status(); ensure!( sta...
random
[ { "content": "# github_auth\n\n[![crates.io version][1]][2] [![build status][3]][4]\n\n[![downloads][5]][6] [![docs.rs docs][7]][8]\n\n\n\nAuthenticate with GitHub from the command line. Caches the authentication token\n\nso that future interactions just work.\n\n\n\n- [Documentation][8]\n\n- [Crates.io][2]\n\n...
Rust
src/middleware/basic_auth.rs
ikanago/qz
3e59c25af2107d72e1cbe776c15c0aadd42525fc
use crate::{ header::HeaderName, middleware::Middleware, request::Request, response::Response, status::StatusCode, Uri, }; use async_trait::async_trait; use super::MiddlewareChain; #[derive(Debug)] pub struct BasicAuth { credential_hash: Vec<u8>, auth_root: Uri, } impl BasicAuth { pub fn new...
use crate::{ header::HeaderName, middleware::Middleware, request::Request, response::Response, status::StatusCode, Uri, }; use async_trait::async_trait; use super::MiddlewareChain; #[derive(Debug)] pub struct BasicAuth { credential_hash: Vec<u8>, auth_root: Uri, } impl BasicAuth { pub fn new...
}
let server = server().with(BasicAuth::new("user", "pass", "/")).build(); let request = Request::builder() .set_header(HeaderName::Authorization, "Basic wrong_hash") .build(); let response = server.respond(request).await; assert_eq!(StatusCode::Unauthorized, response.statu...
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait Handler<State>: Send + Sync + 'static\n\nwhere\n\n State: Clone + Send + Sync + 'static,\n\n{\n\n async fn call(&self, request: Request, state: State) -> crate::Result<Response>;\n\n}\n\n\n\n#[async_trait]\n\nimpl<State, F, Fut> Handler<State> for F\n\nwhere\n\n ...
Rust
src/lib.rs
bluejekyll/hyper-proxy
9e14a8bb6673af1de6f6af0d6b0331c61103c940
#![deny(missing_docs)] extern crate bytes; #[macro_use] extern crate futures; extern crate hyper; #[cfg(test)] extern crate hyper_tls; #[cfg(feature = "tls")] extern crate native_tls; extern crate tokio_core; extern crate tokio_io; #[cfg(feature = "tls")] extern crate tokio_tls; mod tunnel; mod stream; use std::an...
#![deny(missing_docs)] extern crate bytes; #[macro_use] extern crate futures; extern crate hyper; #[cfg(test)] extern crate hyper_tls; #[cfg(feature = "tls")] extern crate native_tls; extern crate tokio_core; extern crate tokio_io; #[cfg(feature = "tls")] extern crate tokio_tls; mod tunnel; mod stream; use std::an...
#[cfg(feature = "tls")] pub fn set_tls(&mut self, tls: Option<TlsConnector>) { self.tls = tls; } pub fn proxies(&self) -> &[Proxy] { &self.proxies } pub fn add_proxy(&mut self, proxy: Proxy) { self.proxies.push(proxy); } pub fn extend_prox...
ProxyConnector { connector: connector, proxies: self.proxies, tls: self.tls, } }
function_block-function_prefix_line
[ { "content": "#[derive(Debug)]\n\nenum TunnelState {\n\n Writing,\n\n Reading,\n\n}\n\n\n\nimpl<S> Tunnel<S> {\n\n /// Creates a new tunnel through proxy\n\n pub fn new(host: &str, port: u16, headers: &Headers) -> Tunnel<S> {\n\n let buf = format!(\n\n \"CONNECT {0}:{1} HTTP/1.1\\r...
Rust
src/command.rs
Selyatin/ephosh
fa8bae1a48b6b50718c9d18b57ae00ecda872ba0
use std::{ thread, time::Duration, io::{ Read, Write }, sync::{ mpsc::{ channel, Sender, Receiver }, Arc, Mutex, atomic::{AtomicBool, Ordering} } }; use portable_pty::{ PtySystem, PtyPair, Pty...
use std::{ thread, time::Duration, io::{ Read, Write }, sync::{ mpsc::{ channel, Sender, Receiver }, Arc, Mutex, atomic::{AtomicBool, Ordering} } }; use portable_pty::{ PtySystem, PtyPair, Pty...
} pub fn resize(&mut self, terminal_size: (u16, u16)) -> Result<(), String>{ if let Err(err) = self.pair.master.resize(PtySize{ cols: terminal_size.0, rows: terminal_size.1, pixel_width: 0, pixel_height: 0 }){ return Err(err.to_string...
Ok(Self { pair, kill, reader, stdin_channel: sender, bytes: [0 as u8; BUFFER_SIZE] })
call_expression
[ { "content": "fn main(){\n\n let mut shell = Shell::new();\n\n \n\n shell.run().expect(\"Couldn't run shell properly\"); \n\n}\n", "file_path": "src/main.rs", "rank": 0, "score": 19199.242470978028 }, { "content": " Ok(())\n\n }\n\n\n\n fn draw_horizontal_line(&mut self...
Rust
src/generator/c.rs
garritfra/antimony
6e897b3a0690b477c49154e7a74893dee28d9515
/** * Copyright 2020 Garrit Franke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
/** * Copyright 2020 Garrit Franke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
fn generate_block(block: Vec<Statement>, _scope: Vec<Variable>) -> String { let mut generated = String::from("{\n"); for statement in block { generated += &generate_statement(statement); } generated += "}\n"; generated } fn generate_statement(statement: Statement) -> String { let s...
let arguments: String = func .arguments .into_iter() .map(|var| format!("{} {}", generate_type(Either::Left(var.clone())), var.name)) .collect::<Vec<String>>() .join(", "); let t = generate_type(Either::Right(func.ret_type)); format!("{T} {N}({A})", T = t, N = func.name, ...
function_block-function_prefix_line
[ { "content": "fn generate_function(func: Function) -> String {\n\n let arguments: String = generate_arguments(func.arguments);\n\n\n\n let mut raw = format!(\"function {N}({A})\", N = func.name, A = arguments);\n\n\n\n raw += &generate_block(func.body, None);\n\n raw += \"\\n\";\n\n raw\n\n}\n\n\...
Rust
src/interactable.rs
Nickan/bevy_mod_picking
a6c32978fbd297af3715e5fe5833c83ff36e9aaf
use super::{highlight::*, select::*, *}; use bevy::prelude::*; use std::collections::HashSet; pub struct InteractablePickingPlugin; impl Plugin for InteractablePickingPlugin { fn build(&self, app: &mut AppBuilder) { app.add_system(generate_hover_events) .add_system(generate_click_events) ...
use super::{highlight::*, select::*, *}; use bevy::prelude::*; use std::collections::HashSet; pub struct InteractablePickingPlugin; impl Plugin for InteractablePickingPlugin { fn build(&self, app: &mut AppBuilder) { app.add_system(generate_hover_events) .add_system(generate_click_events) ...
pub fn generate_click_events( mouse_inputs: Res<Input<MouseButton>>, mut interactable_query: Query<(&mut InteractableMesh, &PickableMesh)>, ) { for (mut interactable, pickable) in interactable_query.iter_mut() { for group in &pickable.groups { match interactable.hover(&group)...
g"); let new_event = if was_hovered { HoverEvents::JustExited } else { HoverEvents::None }; interactable.hover_events.insert(*group, new_event); } } } }...
function_block-function_prefixed
[ { "content": "/// Update all entities with the groups they are selected in.\n\npub fn select_mesh(\n\n // Resources\n\n mouse_button_inputs: Res<Input<MouseButton>>,\n\n // Queries\n\n mut query: Query<(&mut SelectablePickMesh, &InteractableMesh)>,\n\n) {\n\n if mouse_button_inputs.just_pressed(M...
Rust
src/utils.rs
louisdevie/textflow
baab863ca5e5cd6004b3dd8fb9fab4be655f191c
pub fn split_evenly(number: usize, into: usize) -> Vec<usize> { let mut steps: Vec<usize> = Vec::new(); for i in 0..(into + 1) { steps.push((i as f32 * (number as f32 / into as f32)).round() as usize); } let mut deltas = Vec::new(); for i in 0..into { deltas.push(st...
pub fn split_evenly(number: usize, into: usize) -> Vec<usize> { let mut steps: Vec<usize> = Vec::new(); for i in 0..(into + 1) { steps.push((i as f32 * (number as f32 / into as f32)).round() as usize); } let mut deltas = Vec::new(); for i in 0..into { deltas.push(st...
ent("* ") .subsequent_indent("| ") .break_words(true); let output: textwrap::Options< '_, textwrap::wrap_algorithms::OptimalFit, textwrap::word_separators::AsciiSpace, textwrap::word_splitters::NoHyphenation, > = copy_textwrap_options(&input, 20); asser...
splitter(textwrap::word_splitters::NoHyphenation); let expected_output = textwrap::Options::new(20) .initial_ind
random
[ { "content": "/// Wraps and aligns text.\n\n///\n\n/// `width_or_options` can either be an integer or [textwrap::Options],\n\n/// see the documentation of `textwrap` for more information.\n\n///\n\n/// There are four alignment modes :\n\n/// * `LEFT` doesn't modifiy the text, so it ends up left-aligned\n\n/// ...
Rust
crates/modor/src/system_params/entity.rs
modor-engine/modor
447ae453030de44ed93a2ab03a66261080304ce4
use crate::entity::internal::{EntityGuard, EntityGuardBorrow, EntityIter}; use crate::storages::archetypes::EntityLocation; use crate::storages::components::ComponentTypeIdx; use crate::storages::core::CoreStorage; use crate::storages::entities::EntityIdx; use crate::storages::systems::SystemProperties; use crate::syst...
use crate::entity::internal::{EntityGuard, EntityGuardBorrow, EntityIter}; use crate::storages::archetypes::EntityLocation; use crate::storages::components::ComponentTypeIdx; use crate::storages::core::CoreStorage; use crate::storages::entities::EntityIdx; use crate::storages::systems::SystemProperties; use crate::syst...
#[inline] fn get_mut<'a, 'b>( guard: &'a mut <Self as SystemParamWithLifetime<'b>>::GuardBorrow, location: EntityLocation, ) -> Option<<Self as SystemParamWithLifetime<'a>>::Param> where 'b: 'a, { Self::get(guard, location) } #[inline] fn get_both_mut<'...
w, location: EntityLocation, ) -> Option<<Self as QuerySystemParamWithLifetime<'a>>::ConstParam> where 'b: 'a, { guard .data .archetypes .entity_idxs(location.idx) .get(location.pos) .map(|&e| Entity { entity...
function_block-function_prefixed
[ { "content": "struct StreamCollector(Vec<usize>);\n\n\n\n#[singleton]\n\nimpl StreamCollector {\n\n fn build() -> impl Built<Self> {\n\n EntityBuilder::new(Self(vec![]))\n\n }\n\n}\n\n\n", "file_path": "crates/modor/tests/integration/system_params/entity.rs", "rank": 0, "score": 307694....
Rust
validatron/src/error.rs
nsat/validatron
4d8e1c60baedfb019482b65993ecf945e87eb4b1
use std::borrow::Cow; use std::collections::HashMap; use thiserror::Error; use crate::Result; #[cfg(feature = "use-serde")] use serde::Serialize; #[derive(Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "use-serde", derive(Serialize), serde(untagged))] pub enum Location { Named(Cow<'static, str>), ...
use std::borrow::Cow; use std::collections::HashMap; use thiserror::Error; use crate::Result; #[cfg(feature = "use-serde")] use serde::Serialize; #[derive(Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "use-serde", derive(Serialize), serde(untagged))] pub enum Location { Named(Cow<'static, str>), ...
eb.try_at_named(k.to_string(), v.validate()); } eb.build() } fn validate_foo(x: &Foo) -> Result<()> { Error::build() .try_at_named("a", crate::validators::min(&x.a, 5)) .try_at_named("b", validate_a_vector(&x.b)) .try...
"cannot comprehend the meaning of life the universe and everything.", )) } else { Ok(()) } } } struct Foo { a: u64, b: Vec<i64>, c: HashMap<String, Bar>, } ...
random
[ { "content": "fn build_named(name: &str, error: TokenStream) -> TokenStream {\n\n quote! {\n\n eb.try_at_named(#name, #error);\n\n }\n\n}\n\n\n", "file_path": "validatron_derive/src/lib.rs", "rank": 1, "score": 150628.87681840552 }, { "content": "#[derive(PartialOrd, Ord, Partia...
Rust
crates/lib/kajiya/src/renderers/ssgi.rs
Mu-L/kajiya
66875dc96180d5c7a700fc3054dd685c12fc962c
use super::{GbufferDepth, PingPongTemporalResource}; use kajiya_backend::{ash::vk, vulkan::image::*}; use kajiya_rg::{self as rg, SimpleRenderPass, TemporalRenderGraph}; use rust_shaders_shared::ssgi::SsgiConstants; const USE_RUST_SHADERS: bool = false; pub struct SsgiRenderer { ssgi_tex: PingPongTemporalResource...
use super::{GbufferDepth, PingPongTemporalResource}; use kajiya_backend::{ash::vk, vulkan::image::*}; use kajiya_rg::{self as rg, SimpleRenderPass, TemporalRenderGraph}; use rust_shaders_shared::ssgi::SsgiConstants; const USE_RUST_SHADERS: bool = false; pub struct SsgiRenderer { ssgi_tex: PingPongTemporalResource...
fn temporal_tex_desc(extent: [u32; 2]) -> ImageDesc { ImageDesc::new_2d(INTERNAL_TEX_FMT, extent) .usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::STORAGE) } fn upsample_ssgi( rg: &mut rg::RenderGraph, ssgi: &rg::Handle<Image>, depth: &rg::Handle<Imag...
if USE_RUST_SHADERS { SimpleRenderPass::new_compute_rust( rg.add_pass("ssao spatial"), "ssgi::spatial_filter_cs", ) } else { SimpleRenderPass::new_compute( rg.add_pass("ssao spatial"), ...
function_block-function_prefix_line
[ { "content": "pub fn convolve_cube(rg: &mut rg::RenderGraph, input: &rg::Handle<Image>) -> rg::Handle<Image> {\n\n let width = 16u32;\n\n let mut sky_tex = rg.create(ImageDesc::new_cube(vk::Format::R16G16B16A16_SFLOAT, width));\n\n\n\n SimpleRenderPass::new_compute(rg.add_pass(\"convolve sky\"), \"/sha...
Rust
kernel/displayable/text_display/src/lib.rs
ravindra-csu/Theseus
a0f3949dad6190403017b45a284e6148b06222a7
#![no_std] extern crate alloc; extern crate displayable; extern crate font; extern crate framebuffer; extern crate framebuffer_printer; extern crate shapes; extern crate color; use alloc::string::String; use displayable::{Displayable}; use font::{CHARACTER_HEIGHT, CHARACTER_WIDTH}; use framebuffer::{Pixel, Framebuf...
#![no_std] extern crate alloc; extern crate displayable; extern crate font; extern crate framebuffer; extern crate framebuffer_printer; extern crate shapes; extern crate color; use alloc::string::String; use displayable::{Displayable}; use font::{CHARACTER_HEIGHT, CHARACTER_WIDTH}; use framebuffer::{Pixel, Framebuf...
ol; self.next_line = next_line; self.cache = self.text.clone(); return Ok(bounding_box + coordinate); } fn set_size(&mut self, width: usize, height: usize) { self.width = width; self.height = height; } fn get_size(&self) -> (usize, usize) { (self.width,...
( &self.text.as_str()[self.cache.len()..self.text.len()], self.next_col, self.next_line, ) } else { (self.text.as_str(), 0, 0) }; let (next_col, next_line, mut bounding_box) = framebuffer_printer::print_string( ...
function_block-random_span
[ { "content": "/// Draw a circle in the framebuffer. `coordinate` is the position of the center of the circle relative to the top-left corner of the framebuffer and `r` is the radius\n\npub fn draw_circle<P: Pixel>(framebuffer: &mut Framebuffer<P>, center: Coord, r: usize, pixel: P) {\n\n let r2 = (r * r) as ...
Rust
libeuler/src/traits.rs
zmbush/euler
91a29ee25f13993f3c6282930dd4b36d4facfb9a
use std::collections::HashSet; use num::bigint::{BigInt, ToBigInt}; use num::traits::{Zero, ToPrimitive}; pub trait PalindromeHelper { fn is_palindrome(&self) -> bool; } impl PalindromeHelper for String { fn is_palindrome(&self) -> bool { let forward = self.chars().take(self.len() / 2); let re...
use std::collections::HashSet; use num::bigint::{BigInt, ToBigInt}; use num::traits::{Zero, ToPrimitive}; pub trait PalindromeHelper { fn is_palindrome(&self) -> bool; } impl PalindromeHelper for String { fn is_palindrome(&self) -> bool { let forward = self.ch
rs = HashSet::new(); while num > 0 { let n = (num % 10) as u8; rv.push(n); rs.insert(n); num /= 10; } rv.reverse(); (rv, rs) } fn from_digits(digits...
ars().take(self.len() / 2); let reverse = self.chars().rev().take(self.len() / 2); forward.zip(reverse).all(|(a, b)| { a == b }) } } macro_rules! palindrome_helper_impl { ($($T:ty)+) => ($( impl PalindromeHelper for $T { fn is_palindrome(&self) -> bool { for...
random
[ { "content": "pub fn is_prime<T: ToPrimitive>(i: T) -> bool {\n\n let num = i.to_i64().unwrap();\n\n\n\n for i in 2..(num.to_f64().unwrap().sqrt().floor() as i64 + 1) {\n\n if num % i == 0 {\n\n return false;\n\n }\n\n }\n\n\n\n true\n\n}\n", "file_path": "libeuler/src/p...
Rust
ajars_web/src/lib.rs
ufoscout/AjaRS
5081d2e1d43c6934196fadf1c1c5178f04098436
use std::collections::HashMap; use std::fmt::Display; use std::marker::PhantomData; use std::rc::Rc; use ajars_core::HttpMethod; use ajars_core::RestType; use serde::de::DeserializeOwned; use serde::Serialize; use wasm_bindgen::JsCast as _; use wasm_bindgen_futures::JsFuture; use web_sys::window; use web_sys::Header...
use std::collections::HashMap; use std::fmt::Display; use std::marker::PhantomData; use std::rc::Rc; use ajars_core::HttpMethod; use ajars_core::RestType; use serde::de::DeserializeOwned; use serde::Serialize; use wasm_bindgen::JsCast as _; use wasm_bindgen_futures::JsFuture; use web_sys::window; use web_sys::Header...
async fn into_http_response<O: Serialize + DeserializeOwned>(response: WebResponse) -> Result<O, Error> { let status = HttpStatus::from(response.status()); if status.is_client_error() || status.is_server_error() { Err(Error::Response { status, context: format!("Error HTTP s...
function_block-full_function
[ { "content": "/// spanws an actix server and returns the server port\n\npub fn spawn_axum<REST: 'static + Clone + Send + RestType<Simple<String>, Simple<String>>>(echo_rest: REST) -> u16 {\n\n let free_port = port_check::free_local_port().unwrap();\n\n //let address = format!(\"127.0.0.1:{}\", free_port);...
Rust
tezos/context-tool/src/main.rs
simplestaking/tezos-rs
d859dff0a8db4f5adb4885e4885217d5284f7861
use std::{path::PathBuf, sync::Arc}; use crate::log::print; use clap::{Parser, Subcommand}; use crypto::hash::{ContextHash, HashTrait}; use parking_lot::RwLock; use tezos_context::{ kv_store::persistent::{FileSizes, PersistentConfiguration}, persistent::file::{File, TAG_SIZES}, snapshot, working_tree...
use std::{path::PathBuf, sync::Arc}; use crate::log::print; use clap::{Parser, Subcommand}; use crypto::hash::{ContextHash, HashTrait}; use parking_lot::RwLock; use tezos_context::{ kv_store::persistent::{FileSizes, PersistentConfiguration}, persistent::file::{File, TAG_SIZES}, snapshot, working_tree...
fn log_snapshot(s: &str) { log!("{}", s) }
fn main() { let args = Args::parse(); match args.command { Commands::DumpChecksums { context_path } => { let sizes_file = File::<{ TAG_SIZES }>::try_new(&context_path, true).unwrap(); let sizes = FileSizes::make_list_from_file(&sizes_file).unwrap_or_default(); log!("...
function_block-full_function
[ { "content": "pub fn reload_context_readonly(context_path: String) -> Result<Persistent, Error> {\n\n let sizes_file = File::<{ TAG_SIZES }>::try_new(&context_path, true)?;\n\n let sizes = FileSizes::make_list_from_file(&sizes_file).unwrap_or_default();\n\n assert!(!sizes.is_empty(), \"sizes.db is inva...
Rust
src/tasks/npm.rs
jokeyrhyme/dotfiles-rs
8e723ee271675ba783e15e608164813a4a136efb
use std::collections::HashMap; use std::path::Path; use std::{fs, io, str}; use serde_derive::Deserialize; use crate::lib::{ self, task::{self, Status, Task}, }; use crate::utils; const ERROR_MSG: &str = "error: nodejs"; #[derive(Debug, Deserialize)] struct Globals { #[serde(default)] dependencies: ...
use std::collections::HashMap; use std::path::Path; use std::{fs, io, str}; use serde_derive::Deserialize
&["config", "set", "python", exe.to_str().unwrap_or_default()], )?; } None => { utils::process::command_spawn_wait("npm", &["config", "delete", "python"])?; } }; utils::process::command_spawn_wait("npm", &["config", "set", "send-metric", "true"])?; O...
; use crate::lib::{ self, task::{self, Status, Task}, }; use crate::utils; const ERROR_MSG: &str = "error: nodejs"; #[derive(Debug, Deserialize)] struct Globals { #[serde(default)] dependencies: HashMap<String, HashMap<String, String>>, } #[derive(Debug, Deserialize)] struct Config { install: Ve...
random
[ { "content": "pub fn arch() -> &'static str {\n\n if ARCH == \"x86_64\" {\n\n \"amd64\"\n\n } else {\n\n ARCH\n\n }\n\n}\n\n\n", "file_path": "src/utils/golang.rs", "rank": 1, "score": 72897.6932699129 }, { "content": "pub fn os() -> &'static str {\n\n match OS {\n\...
Rust
src/item/key.rs
Kruemmelspalter/rpg-cli
9aa01ae89c7529b49578a5ae4c62b4fe2e87b036
use super::ring::Ring; use anyhow::{bail, Result}; use serde::{Deserialize, Serialize}; use std::convert::From; use std::fmt; use strum_macros::EnumIter; #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash, Debug, EnumIter)] #[serde(try_from = "String", into = "String")] pub enum Key { Potion, Escape, ...
use super::ring::Ring; use anyhow::{bail, Result}; use serde::{Deserialize, Serialize}; use std::convert::From; use std::fmt; use strum_macros::EnumIter; #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash, Debug, EnumIter)] #[serde(try_from = "String", into = "String")] pub enum Key { Potion, Escape, ...
} impl From<String> for Key { fn from(key: String) -> Self { Key::from(&key).unwrap() } } impl From<Key> for String { fn from(key_str: Key) -> Self { key_str.to_string() } } impl Default for Ring { fn default() -> Self { Ring::Void } } #[cfg(test)] mod tests { us...
Key::Ring(Ring::Protect) => "protect-rng", Key::Ring(Ring::Fire) => "fire-rng", Key::Ring(Ring::Poison) => "poison-rng", Key::Ring(Ring::Double) => "double-rng", Key::Ring(Ring::Counter) => "counter-rng", Key::Ring(Ring::Revive) => "revive-rng", Ke...
function_block-function_prefix_line
[]
Rust
libearthquake/src/resources/config.rs
csnover/earthquake-rust
c954298c3c085615615ab86209510d34e1baa019
use anyhow::{Context, Result as AResult}; use bitflags::bitflags; use byteordered::{Endianness, ByteOrdered}; use crate::{ensure_sample, player::score::Tempo}; use libcommon::{Reader, Resource, resource::Input}; use libmactoolbox::Rect; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::convert::Try...
use anyhow::{Context, Result as AResult}; use bitflags::bitflags; use byteordered::{Endianness, ByteOrdered}; use crate::{ensure_sample, player::score::Tempo}; use libcommon::{Reader, Resource, resource::Input}; use libmactoolbox::Rect; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::convert::Try...
fn load_1025(this: &mut Self, input: &mut ByteOrdered<impl Reader, Endianness>) -> AResult<()> { this.stage_color_index = input.read_i16().context("Can’t read stage color")?; this.default_color_depth = input.read_i16().context("Can’t read default color depth")?; this.field_1e = input.read_...
ate / 127_773 * 2836); if state < 0 { state += 0x7fff_ffff; } (state, ((state >> 14) as i16).abs()) }
function_block-function_prefixed
[ { "content": "fn get_projector_rsrc(input: &mut impl Reader, offset: u32, version: Version) -> AResult<Option<Vec<u8>>> {\n\n let (rsrc_offset, rsrc_size) = match version {\n\n Version::D3 => unreachable!(\"D3 does not include a system resource file\"),\n\n Version::D4 => {\n\n input...
Rust
src/main.rs
CredibleOpossum/crustle
7224122af74a8cc13526c6ce4b3934d888b06ce2
use ansi_term::Colour; use itertools::Itertools; use rand::seq::SliceRandom; use std::collections::{HashMap, HashSet}; use text_io::read; #[derive(Debug, Copy, Clone, PartialEq)] enum KeyResult { CorrectPosition, IncorrectPosition, NotInWord, } fn compare(guess: &str, answer: &str) -> [KeyResult; 5] ...
use ansi_term::Colour; use itertools::Itertools; use rand::seq::SliceRandom; use std::collections::{HashMap, HashSet}; use text_io::read; #[derive(Debug, Copy, Clone, PartialEq)] enum KeyResult { CorrectPosition, IncorrectPosition, NotInWord, }
fn print_guess(guess: &str, result: [KeyResult; 5]) { for (index, character) in guess.chars().enumerate() { print!( "{}", match result[index] { KeyResult::CorrectPosition => Colour::Green.paint(character.to_string()), KeyResult::IncorrectPosition => ...
fn compare(guess: &str, answer: &str) -> [KeyResult; 5] { let guess_chars: Vec<char> = guess.chars().collect(); let mut answer_chars: Vec<char> = answer.chars().collect(); let mut result = [KeyResult::NotInWord; 5]; for index in 0..answer.len() { if guess_chars[index] == answer_chars[index] { ...
function_block-full_function
[]
Rust
cli/src/interactive/helper.rs
sandhose/z33-emulator
c4f7496f9c973f9defe3e15d909843d29db11fb0
use std::borrow::Cow; use std::collections::HashSet; use std::marker::PhantomData; use ansi_term::Style; use clap::{App, IntoApp}; use rustyline::{ completion::Completer, highlight::Highlighter, hint::Hinter, validate::{ValidationContext, ValidationResult, Validator}, Context, }; use rustyline_deri...
use std::borrow::Cow; use std::collections::HashSet; use std::marker::PhantomData; use ansi_term::Style; use clap::{App, IntoApp}; use rustyline::{ completion::Completer, highlight::Highlighter, hint::Hinter, validate::{ValidationContext, ValidationResult, Validator}, Context, }; use rustyline_deri...
} impl<T: IntoApp> Hinter for RunHelper<T> { type Hint = String; fn hint(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<String> { let line = &line[..pos]; let complete = line .bytes() .last() .filter(|&c| c == b' ' || c == b'\t') .i...
f, prompt: &'p str, _default: bool, ) -> Cow<'b, str> { let style = Style::new().bold(); let prompt = style.paint(prompt).to_string(); Cow::Owned(prompt) }
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn display_error_offset(input: &str, offset: usize, message: &str) {\n\n let mut lines = input.lines().enumerate().peekable();\n\n\n\n let mut previous = VecDeque::new();\n\n let mut current = lines.next().expect(\"empty program\");\n\n loop {\n\n let ...
Rust
sm64gs2pc/src/typ.rs
sm64gs2pc/sm64gs2pc
620af782e91454a4a269bf6acdc3a24fae501e14
use serde::Deserialize; use serde::Serialize; pub type SizeInt = u32; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum Type { AnonStruct(Struct), Struct { name: String, }, Array { element_type: Box<Type>, num_el...
use serde::Deserialize; use serde::Serialize; pub type SizeInt = u32; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum Type { AnonStruct(Struct), Struct { name: String, }, Array { element_type: Box<Type>, num_el...
} _ => unimplemented!("clang type: {:?}, decl: {:?}", typ, typ.get_declaration()), } } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct StructField { pub offset: SizeInt, pub name: String, pub typ: Type, } #[derive(Debug, Clone...
match name { Some(name) => Type::Struct { name }, None => Type::Ignored, }
if_condition
[ { "content": "/// Helper for creating patches with minimal boilerplate\n\nfn gs_to_patch(decomp_data: &DecompData, name: &str, code: &str) -> String {\n\n let code = code.parse::<sm64gs2pc::gameshark::Code>().unwrap();\n\n let patch = decomp_data.gs_code_to_patch(name, code).unwrap();\n\n println!(\"{}...
Rust
examples/detector.rs
Christopher22/apriltag-rust
17ac1adcc77b37f96013311c4e511fd43e78d2cd
use anyhow::Result; #[cfg(feature = "full")] mod simple_detector { use anyhow::{ensure, Context, Error, Result}; use apriltag::{DetectorBuilder, Family, TagParams}; use std::{path::PathBuf, str::FromStr}; use structopt::StructOpt; #[derive(Debug, Clone, StructOpt)] struct Opts { #...
use anyhow::Result; #[cfg(feature = "full")] mod simple_detector { use anyhow::{ensure, Context, Error, Result}; use apriltag::{DetectorBuilder, Family, TagParams}; use std::{path::PathBuf, str::FromStr}; use structopt::StructOpt; #[derive(Debug, Clone, StructOpt)] struct Opts { #...
} } pub fn _main() -> Result<()> { let Opts { family: family_name, tag_params, input_files, } = Opts::from_args(); if input_files.is_empty() { eprintln!("no input files"); return Ok(()); } let family:...
Ok(Self { tagsize: values[0], fx: values[1], fy: values[2], cx: values[3], cy: values[4], })
call_expression
[ { "content": "#[test]\n\n#[cfg(feature = \"image\")]\n\nfn test_detection() {\n\n let grayscale_image = {\n\n let path: std::path::PathBuf = [\n\n env!(\"CARGO_MANIFEST_DIR\"),\n\n \"test_data\",\n\n \"DICT_APRILTAG_16h5-2x2-500-10-0.8-29,12,22,2.jpg\",\n\n ]\n\...
Rust
util/app-config/src/app_config.rs
ray-learn/ckb
dfafa773c5514fab988cbf8c7fb9673575fa250d
use std::fs; use std::path::{Path, PathBuf}; use serde_derive::{Deserialize, Serialize}; use ckb_chain_spec::ChainSpec; use ckb_db::DBConfig; use ckb_miner::BlockAssemblerConfig; use ckb_miner::MinerConfig; use ckb_network::NetworkConfig; use ckb_resource::{Resource, ResourceLocator}; use ckb_rpc::Config as RpcConf...
use std::fs; use std::path::{Path, PathBuf}; use serde_derive::{Deserialize, Serialize}; use ckb_chain_spec::ChainSpec; use ckb_db::DBConfig; use ckb_miner::BlockAssemblerConfig; use ckb_miner::MinerConfig; use ckb_network::NetworkConfig; use ckb_resource::{Resource, ResourceLocator}; use ckb_rpc::Config as RpcConf...
} _ => { let resource = locator.ckb(); let config: CKBAppConfig = toml::from_slice(&resource.get()?)?; Ok(AppConfig { resource, content: AppConfigContent::with_ckb( config.derive_opti...
Ok(AppConfig { resource, content: AppConfigContent::with_miner( config.derive_options(locator.root_dir())?, ), })
call_expression
[ { "content": "pub fn enum_name_sync_payload(e: SyncPayload) -> &'static str {\n\n let index: usize = e as usize;\n\n ENUM_NAMES_SYNC_PAYLOAD[index]\n\n}\n\n\n\npub struct SyncPayloadUnionTableOffset {}\n\n#[allow(non_camel_case_types)]\n\n#[repr(u8)]\n\n#[derive(Clone, Copy, PartialEq, Debug)]\n\npub enum Rel...
Rust
widgets/src/chip.rs
noogen-projects/yew-mdc-widgets
31017f101966058c89e62883f5dec8bf21c3979e
use std::{ ops::{Deref, DerefMut}, rc::Rc, }; use const_format::concatcp; use yew::{classes, html, html::onclick, Callback, Html, MouseEvent}; use crate::{utils::VTagExt, CustomEvent, MdcWidget, AUTO_INIT_ATTR}; pub mod mdc { pub const TYPE_NAME: &str = "MDCChip"; } pub mod set { pub mod mdc { ...
use std::{ ops::{Deref, DerefMut}, rc::Rc, }; use const_format::concatcp; use yew::{classes, html, html::onclick, Callback, Html, MouseEvent}; use crate::{utils::VTagExt, CustomEvent, MdcWidget, AUTO_INIT_ATTR}; pub mod mdc { pub const TYPE_NAME: &str = "MDCChip"; } pub mod set { pub mod mdc { ...
pub fn ripple(mut self, enabled: bool) -> Self { let root = self.root_tag_mut(); if enabled { root.set_attr(AUTO_INIT_ATTR, mdc::TYPE_NAME); } else { root.remove_attr(AUTO_INIT_ATTR); } self } pub fn icon(mut self, name: impl Into<String>) ...
pub fn select(mut self, selected: bool) -> Self { let root = self.root_tag_mut(); if let Some(icon) = root .find_child_contains_class_idx(Self::CHECKMARK_CLASS) .and_then(|_| root.find_child_contains_class_mut(Self::ICON_LEADING_CLASS)) { if selected { ...
function_block-full_function
[ { "content": "fn is_some_child_contains_class<'a>(children: impl IntoIterator<Item = &'a Html>, class: &str) -> bool {\n\n for child in children {\n\n if child.is_contains_class(class) {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "widgets/src/utils/ext...
Rust
libs/d7net/src/tcp/segment.rs
Dentosal/rust_os
ddfbefabf4e928859b57fd2dc44fa6e38545f6d5
use alloc::prelude::v1::*; use serde::{Deserialize, Serialize}; const INITIAL_WINDOW_SIZE: u16 = 8760; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct Segment { header: SegmentHeader, payload: Vec<u8>, } impl Segment { pub fn from_bytes(input: &[u8]) -> Self { let header ...
use alloc::prelude::v1::*; use serde::{Deserialize, Serialize}; const INITIAL_WINDOW_SIZE: u16 = 8760; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct Segment { header: SegmentHeader, payload: Vec<u8>, } impl Segment { pub fn from_bytes(input: &[u8]) -> Self { let header ...
} #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)] pub struct SegmentOptions { segemnt_max_size: Option<u16>, } impl SegmentOptions { pub fn empty() -> Self { Self { ..Default::default() } } pub fn from_bytes(mut input: &[u8]) -> Self { ...
pub fn reply_to_synack(self, next_sequence: u32) -> Self { Self { src_port: self.dst_port, dst_port: self.src_port, sequence: next_sequence, ack_number: self.sequence.wrapping_add(1), flags: SegmentFlags::ACK, window_size: INITIAL_WINDOW_SI...
function_block-full_function
[ { "content": "/// Read (and clear) kernel log buffer. Nonblocking.\n\npub fn kernel_log_read(buffer: &mut [u8]) -> SyscallResult<usize> {\n\n if buffer.is_empty() {\n\n panic!(\"Cannot ipc_select from an empty list\");\n\n }\n\n\n\n unsafe {\n\n Ok(syscall!(\n\n SyscallNumber::...
Rust
src/preconditioner.rs
aujxn/amg_match
08ee787f76b5fa6cd6bab66aa1324514e95df536
use crate::{ partitioner::Hierarchy, solver::{lsolve, usolve}, }; use nalgebra::base::DVector; use nalgebra_sparse::CsrMatrix; pub fn l1(mat: &CsrMatrix<f64>) -> Box<dyn Fn(&mut DVector<f64>)> { let l1_inverse: Vec<f64> = mat .row_iter() .map(|row_vec| { let row_sum_abs: f64 = r...
use crate::{ partitioner::Hierarchy, solver::{lsolve, usolve}, }; use nalgebra::base::DVector; use nalgebra_sparse::CsrMatrix; pub fn l1(mat: &CsrMatrix<f64>) -> Box<dyn Fn(&mut DVector<f64>)> { let l1_inverse: Vec<f64> = mat .row_iter() .map(|row_vec| { let row_sum_abs: f64 = r...
#[test_resources("test_matrices/*")] fn test_symmetry_ml1(mat_path: &str) { let (hierarchy, dim) = multilevel_loader(mat_path); let preconditioner = multilevell1(hierarchy); test_symmetry(&preconditioner, dim); } #[test_resources("test_matrices/*")] fn test_positive_defini...
r) { let mat = CsrMatrix::from( &nalgebra_sparse::io::load_coo_from_matrix_market_file(mat_path).unwrap(), ); let dim = mat.nrows(); let preconditioner = sgs(&mat); test_positive_definiteness(&preconditioner, dim); }
function_block-function_prefixed
[ { "content": "/// Upper triangular solve for sparse matrices and dense rhs\n\npub fn usolve(mat: &CsrMatrix<f64>, rhs: &mut DVector<f64>) {\n\n for i in (0..mat.nrows()).rev() {\n\n let row = mat.row(i);\n\n for (&j, val) in row\n\n .col_indices()\n\n .iter()\n\n ...
Rust
src/graphql/variable.rs
notarize/qlc
238e7ee37fdfdd04ee2cecb0c10646e049cd8636
use super::ParsedTextType; use crate::cli::PrintableMessage; use crate::graphql::ir::CompileContext; use crate::graphql::schema::field as schema_field; use graphql_parser::query as parsed_query; use graphql_parser::Pos; use std::convert::TryFrom; use std::path::Path; #[derive(Debug)] pub enum Error { UnknownCustom...
use super::ParsedTextType; use crate::cli::PrintableMessage; use crate::graphql::ir::CompileContext; use crate::graphql::schema::field as schema_field; use graphql_parser::query as parsed_query; use graphql_parser::Pos; use std::convert::TryFrom; use std::path::Path; #[derive(Debug)] pub enum Error { UnknownCustom...
} impl From<(&str, &Path, Error)> for PrintableMessage { fn from((contents, file_path, error): (&str, &Path, Error)) -> Self { match error { Error::UnknownCustomeVariableType(name, position) => { PrintableMessage::new_compile_error( &format!("unknown type fo...
String" => VariableType::String, "Float" => VariableType::Float, "Int" => VariableType::Int, "Boolean" => VariableType::Boolean, custom_type_name => match from.0.schema.get_type_for_name(custom_type_name) { None => { return Err(Error::U...
function_block-function_prefix_line
[ { "content": "/// Alias and field name\n\ntype FieldId<'a> = (&'a str, &'a str);\n\n\n", "file_path": "src/graphql/ir.rs", "rank": 0, "score": 138841.81972673224 }, { "content": "pub fn compile_scalar(config: &CompileConfig, scalar: &ScalarType) -> String {\n\n match scalar {\n\n S...
Rust
src/sys/component_manager/src/elf_runner/component.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { super::{error::ElfRunnerError, runtime_dir::RuntimeDirectory}, async_trait::async_trait, fidl::endpoints::Proxy, fidl_fuchsia_process_lifecycle::LifecycleProxy, fuchsia_async as fasync, fuchsia_zircon::{self as zx, AsHandleRef, Job, Process, Task}, futures::future::{BoxFuture, Future...
use { super::{error::ElfRunnerError, runtime_dir::RuntimeDirectory}, async_trait::async_trait, fidl::endpoints::Proxy, fidl_fuchsia_process_lifecycle::LifecycleProxy, fuchsia_async as fasync, fuchsia_zircon::{self as zx, AsHandleRef, Job, Process, Task}, futures::future::{BoxFuture, Future...
ss_critical, _tasks: tasks, component_url, } } pub fn copy_process(&self) -> Option<Arc<Process>> { self.process.clone() } pub fn copy_job_for_diagnostics(&self) -> Result<Job, ElfRunnerError> { self.job.as_handle_ref()...
roxy>, main_process_critical: bool, tasks: Vec<fasync::Task<()>>, component_url: String, ) -> Self { Self { _runtime_dir, job: Arc::new(job), process: Some(Arc::new(process)), lifecycle_channel, main_proce
random
[]
Rust
crates/rlsf/src/int.rs
yvt/rlsf
77b0c40715b08628e2da186e29eff8bc32e659db
#![allow(unstable_name_collisions)] use core::{fmt, marker, ops}; pub trait BinInteger: Clone + Copy + PartialEq + Eq + Ord + PartialOrd + marker::Unpin + ops::Add<Output = Self> + ops::Sub<Output = Self> + ops::Mul<Output = Self> + ops::Div<Output = Self> + ops::Rem<O...
#![allow(unstable_name_collisions)] use core::{fmt, marker, ops}; pub trait BinInteger: Clone + Copy + PartialEq + Eq + Ord + PartialOrd + marker::Unpin + ops::Add<Output = Self> + ops::Sub<Output = Self> + ops::Mul<Output = Self> + ops::Div<Output = Self> + ops::Rem<O...
of::<$type>() as u32 * 8; #[inline] fn ones(range: ops::Range<u32>) -> Self { assert!(range.end <= Self::BITS); Self::ones_truncated(range) } #[inline] fn ones_truncated(range: ops::Range<u32>) -> Self { assert!...
fn extract_u32(&self, range: ops::Range<u32>) -> u32; fn get_bit(&self, i: u32) -> bool; fn set_bit(&mut self, i: u32); fn clear_bit(&mut self, i: u32); fn checked_ceil_fix(self, fp: u32) -> Option<Self>; } macro_rules! impl_binary_integer { ($type:ty) => { ...
random
[ { "content": "/// Provides a constant default value.\n\npub trait Init {\n\n /// `Self`'s default value.\n\n const INIT: Self;\n\n}\n\n\n\n#[cfg(any(test, feature = \"std\"))]\n\n#[cfg_attr(feature = \"doc_cfg\", doc(cfg(feature = \"std\")))]\n\nimpl Init for std::alloc::System {\n\n const INIT: Self =...
Rust
continue_notation_macro/src/lib.rs
edmundsmith/continuation_notation
d3b533038a226c3788c26090c7db1f190c66060f
extern crate proc_macro; extern crate proc_macro2; extern crate syn; extern crate quote; use core::iter::*; use syn::*; use syn::fold::Fold; use syn::punctuated::{Punctuated, Pair}; use proc_macro2::*; use quote::*; const INVOCATION_NAME : &'static str = "cont"; type SEP = Token![,]; #[proc_macro_attribute] pub fn ...
extern crate proc_macro; extern crate proc_macro2; extern crate syn; extern crate quote; use core::iter::*; use syn::*; use syn::fold::Fold; use syn::punctuated::{Punctuated, Pair}; use proc_macro2::*; use quote::*; const INVOCATION_NAME : &'static str = "cont"; type SEP = Token![,]; #[proc_macro_attribute] pub fn ...
let parsed_invocation: ParsedInvocation = parse2(makro.tokens.clone()).unwrap(); let asyncness: Option<Token![async]> = parsed_invocation.asyncness; let staticness: Option<Token![static]> = None; let captures: Option<Token![move]> = parsed_invocation.moves; let remaining_stmts : Vec<_> = stmts[i+1....
function_block-function_prefix_line
[ { "content": "fn main() {\n\n \n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn it_works() {\n\n println!(\"It works!\");\n\n }\n\n\n\n \n\n}\n\n\n\n #[use_cps]\n\n #[test]\n\n fn cps_test() {\n\n println!(\"Initial\");\n\n fn cps<F,R>(x:i32,mut f:F) -> R w...
Rust
03-textured-cube/src/lib.rs
sognefej/learning_rust_webgl
5f5a098a71369ac30150a43ef9acaa8e89498f04
use std::rc::Rc; use std::cell::RefCell; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{WebGlProgram, WebGlRenderingContext as GL, WebGlShader}; use gl_matrix; fn window() -> web_sys::Window { web_sys::window().expect("no global `window` exists") } fn request_animation_frame(f: &Closure<d...
use std::rc::Rc; use std::cell::RefCell; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{WebGlProgram, WebGlRenderingContext as GL, WebGlShader}; use gl_matrix; fn window() -> web_sys::Window { web_sys::window().expect("no global `window` exists") } fn request_animation_frame(f: &Closure<d...
pub fn compile_shader( context: &GL, shader_type: u32, source: &str, ) -> Result<WebGlShader, String> { let shader = context .create_shader(shader_type) .ok_or_else(|| String::from("Unable to create shader object"))?; context.shader_source(&shader, source); context.compile_shad...
context.enable(GL::CULL_FACE); context.front_face(GL::CCW); context.cull_face(GL::BACK); let vert_shader = compile_shader( &context, GL::VERTEX_SHADER, r#" precision mediump float; attribute vec3 vertPosition; attribute vec2 vertTexCoord; vary...
function_block-function_prefix_line
[ { "content": "#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n // Grabing the whole web document \n\n let document = web_sys::window().unwrap().document().unwrap();\n\n // Get the canvas \n\n let canvas = document.get_element_by_id(\"canvas\").unwrap();\n\n // Shadow canvas (...
Rust
examples/write_traceroute.rs
dioptra-io/warts
590f5276bb771b0446229bbeeb26332f84e1da1e
use chrono::Utc; use deku::DekuContainerWrite; use std::ffi::CString; use std::io; use std::io::Write; use std::net::Ipv4Addr; use warts::{ Address, CycleStart, CycleStop, Flags, List, Object, Timeval, TraceGapAction, TraceProbe, TraceStopReason, TraceType, Traceroute, }; fn main() { let list_name = CStrin...
use chrono::Utc; use deku::DekuContainerWrite; use std::ffi::CString; use std::io; use std::io::Write; use std::net::Ipv4Addr; use warts::{ Address, CycleStart, CycleStop, Flags, List, Object, Timeval, TraceGapAction, TraceProbe, TraceStopReason, TraceType, Traceroute, }; fn main() { let list_name = CStrin...
trace_flags: None, attempts: Some(2), hop_limit: Some(0), trace_type: Some(TraceType::UDPParis), probe_size: Some(44), src_port: Some(57352), dst_port: Some(33435), first_ttl: Some(1), ip_tos: Some(0), timeout_sec: Some(5), allowed_loops: S...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n for path in &args[1..] {\n\n let data = fs::read(path).unwrap();\n\n let objects = Object::all_from_bytes(&data);\n\n for mut object in objects {\n\n // Resolve IP addresses references.\n\n ...
Rust
src/parser.rs
thegedge/fittle
350feef2faaac7d66985ab5eb2274c9d039ce22f
use std::{ convert::From, io::{ Cursor, Read, Seek, SeekFrom, }, result, }; use byteorder::{ BigEndian, LittleEndian, ReadBytesExt, }; use crate::{ fields::{ FieldContent, FieldDefinition, }, profile::{ enums::MesgNum, ...
use std::{ convert::From, io::{ Cursor, Read, Seek, SeekFrom, }, result, }; use byteorder::{ BigEndian, LittleEndian, ReadBytesExt, }; use crate::{ fields::{ FieldContent, FieldDefinition, }, profile::{ enums::MesgNum, ...
fn parse<'i>(&mut self) -> Result<Vec<Message>> { let mut results = Vec::new(); let mut local_types = vec![None; 255]; let file_header = self.file_header()?; let end_position = self.reader.seek(SeekFrom::Current(0))? + file_header.data_size as u64; while self.reader.seek(S...
fn file_header(&mut self) -> Result<FileHeader> { let size = self.reader.read_u8()?; let protocol_version = self.reader.read_u8()?; let profile_version = self.reader.read_u16::<LittleEndian>()?; let data_size = self.reader.read_u32::<LittleEndian>()? as usize; let data_type = [ ...
function_block-function_prefix_line
[ { "content": "fn enums<D: Seek + Read>(workbook: &mut Xlsx<D>) -> Result<Vec<FittleEnum>, Error> {\n\n let range = workbook.worksheet_range(\"Types\")??;\n\n let mut enums = Vec::new();\n\n\n\n // Skip the header row. We need it to be peekable because sometimes there's no empty row\n\n // between me...
Rust
attic/rust/c04/src/main.rs
gonzus/AdventOfCode
fe33871b9babe1c93663d468b6c135096c29c4f4
extern crate regex; use std::io::{self, BufRead}; use std::collections::HashMap; use regex::Regex; fn main() { let lines = read_lines(); let shifts = process_lines(&lines); shifts.analize(); } fn read_lines() -> Vec<String> { let mut lines = Vec::new(); let stdin = io::stdin(); for line in st...
extern crate regex; use std::io::{self, BufRead}; use std::collections::HashMap; use regex::Regex; fn main() { let lines = read_lines(); let shifts = process_lines(&lines); shifts.analize(); } fn read_lines() -> Vec<String> { let mut lines = Vec::new(); let stdin = io::stdin(); for line in st...
} struct Summary { guard: i32, minutes: i32, aslept: [i32; 60], max_pos: i32, max_aslept: i32, } impl Summary { fn new(guard: i32) -> Summary { Summary{ guard, minutes: 0, aslept: [0; 60], max_pos: -1, max_aslept: -1 } } fn consider(&mut self, pos: usize) { if self.max_...
ate::new_from_julian(self.day); let (_, m, d) = date.get_ymd(); print!("{:02}-{:02} #{:5} ", m, d, self.guard); for s in 0..60 { print!("{}", if self.asleep[s] { "#" } else { "." }); } println!(""); }
function_block-function_prefixed
[ { "content": "fn get_capture_as_i32(caps: &regex::Captures, name: String) -> i32 {\n\n match caps.name(&name) {\n\n Some(cap) => cap.as_str().parse::<i32>().unwrap(),\n\n None => -1,\n\n }\n\n}\n", "file_path": "attic/rust/c06/src/main.rs", "rank": 1, "score": 373248.1622336322 ...
Rust
src/main.rs
crate-ci/cargo-tarball
3725bfb9086c9c0f5b8a76fac08a4b66b7241777
#![warn(warnings)] extern crate cargo_metadata; extern crate env_logger; extern crate exitcode; extern crate globwalk; extern crate liquid; extern crate stager; extern crate tempfile; #[macro_use] extern crate clap; #[macro_use] extern crate failure; #[macro_use] extern crate log; #[macro_use] extern crate serde; #[m...
#![warn(warnings)] extern crate cargo_metadata; extern crate env_logger; extern crate exitcode; extern crate globwalk; extern crate liquid; extern crate stager; extern crate tempfile; #[macro_use] extern crate clap; #[macro_use] extern crate failure; #[macro_use] extern crate log; #[macro_use] extern crate serde; #[m...
fn load_data( roots: &[path::PathBuf], manifest_path: Option<&path::Path>, target: &str, ) -> Result<liquid::Object, failure::Error> { let mut data = load_data_dirs(roots)?; let cargo_meta = cargo_metadata::metadata(manifest_path).map_err(failure::SyncFailure::new)?; if cargo_meta.packages.le...
warn!("Invalid data file path: {:?}", rel_source); continue; } }; object::insert(&mut object, &path, key, data)?; } } Ok(object) }
function_block-function_prefix_line
[ { "content": "#[cfg(not(feature = \"tar\"))]\n\nfn compress_tar(root: &path::Path, output: &path::Path) -> Result<(), failure::Error> {\n\n bail!(\"tar is not supported\");\n\n}\n\n\n", "file_path": "src/compress.rs", "rank": 3, "score": 130080.11830360074 }, { "content": "#[cfg(feature =...
Rust
day23/src/main.rs
jgoz/aoc-2021
08d184344c192fce94f30d9897a3d0847165ece9
use core::fmt; use pathfinding::directed::astar::astar; use std::{ collections::{HashMap, HashSet, VecDeque}, env, fmt::{Debug, Display, Formatter}, io, io::prelude::*, }; fn main() { let args: Vec<String> = env::args().collect(); let part = args.get(1).cloned().unwrap_or(String::from("1"))...
use core::fmt; use pathfinding::directed::astar::astar; use std::{ collections::{HashMap, HashSet, VecDeque}, env, fmt::{Debug, D
g>) -> Board<SIZE> { let mut board = Board { spaces: HashMap::new(), amphipods: HashMap::new(), }; for (y, line) in v.skip(1).enumerate() { for (x, char) in line.chars().skip(1).enumerate() { if let Some(amph) = Amphipod::from(char) { ...
isplay, Formatter}, io, io::prelude::*, }; fn main() { let args: Vec<String> = env::args().collect(); let part = args.get(1).cloned().unwrap_or(String::from("1")); let reader = io::stdin(); let lines = reader.lock().lines(); let values = lines.map(|x| x.unwrap()); match part.as_str() ...
random
[ { "content": "type Flashed = HashSet<(usize, usize)>;\n\n\n", "file_path": "day11/src/main.rs", "rank": 0, "score": 31719.546183324484 }, { "content": "use std::collections::HashMap;\n\nuse std::{env, io, io::prelude::*};\n\n\n", "file_path": "day05/src/main.rs", "rank": 1, "scor...
Rust
src/tests.rs
gunvirranu/block-grid
cf5f56d002e351122cdce35b98de360ab4b69120
use std::vec::Vec; use crate::*; #[allow(clippy::upper_case_acronyms)] type BG<T, B> = BlockGrid<T, B>; fn gen_from_raw_vec<B: BlockDim>() { let (rows, cols) = (2 * B::WIDTH, 3 * B::WIDTH); let data: Vec<_> = (0..(rows * cols)).collect(); let grid = BG::<_, B>::from_raw_vec(rows, cols, data.clone()).unwr...
use std::vec::Vec; use crate::*; #[allow(clippy::upper_case_acronyms)] type BG<T, B> = BlockGrid<T, B>; fn gen_from_raw_vec<B: BlockDim>() { let (rows, cols) = (2 * B::WIDTH, 3 * B::WIDTH); let data: Vec<_> = (0..(rows * cols)).collect(); let grid = BG::<_, B>::from_raw_vec(rows, cols, data.clone()).unwr...
fn gen_from_row_major<B: BlockDim>() { let (rows, cols) = (5 * B::WIDTH, 3 * B::WIDTH); let data: Vec<_> = (0..(rows * cols)).collect(); let grid = BG::<_, B>::from_row_major(rows, cols, &data).unwrap(); assert_eq!((grid.rows(), grid.cols()), (rows, cols)); assert_eq!(grid.size(), rows * cols); ...
fn gen_filled<B: BlockDim>() { let (rows, cols) = (2 * B::WIDTH, 3 * B::WIDTH); let grid = BG::<_, B>::filled(rows, cols, 7).unwrap(); assert_eq!((grid.rows(), grid.cols()), (rows, cols)); assert_eq!(grid.size(), rows * cols); for &x in grid.each_iter() { assert_eq!(x, 7); } }
function_block-full_function
[ { "content": "fn gen_test_idiomatic<B: BlockDim>(rows: usize, cols: usize) {\n\n let mut in_bg = BlockGrid::<u8, B>::new(rows, cols).unwrap();\n\n let mut out_bg = in_bg.clone();\n\n let mut out_index = in_bg.clone();\n\n\n\n let mut in_ar = Array2D::filled_with(0u8, rows, cols);\n\n let mut out_...
Rust
macaron-impl/src/trans.rs
irrustible/macaron
3a0350735d3e12012a86f5686b79f5990e6d570c
use proc_macro2::{Literal, Punct, TokenTree, TokenStream}; use syn::{token, ext::IdentExt, parse::{Parse, ParseStream}, MacroDelimiter, Result, Token}; use crate::{*, parsing::*}; use quote::{TokenStreamExt, ToTokens}; use std::borrow::Cow; #[derive(Clone)] pub struct Splice { dollar: Token![$], brace: token::...
use proc_macro2::{Literal, Punct, TokenTree, TokenStream}; use syn::{token, ext::IdentExt, parse::{Parse, ParseStream}, MacroDelimiter, Result, Token}; use crate::{*, parsing::*}; use quote::{TokenStreamExt, ToTokens}; use std::borrow::Cow; #[derive(Clone)] pub struct Splice { dollar: Token![$], brace: token::...
fn transcribe_group( &self, stream: &mut TokenStream, scope: &mut Scope, group: &Group<Transcription> ) -> Result<()> { let mut inner_stream = TokenStream::new(); for t in group.values.iter() { t.transcribe(&mut inner_stream, scope)?; } let inner = ...
fn transcribe_metavar( &self, stream: &mut TokenStream, scope: &mut Scope, var: &FragmentTrans ) -> Result<()> { match scope.fragment(&var.name) { Some(f) => { f.to_tokens(stream); Ok(()) }, None => Err(syn::Error::new(var.name.iden...
function_block-full_function
[ { "content": "pub fn brace_many<T: Parse>(input: ParseStream) -> Result<(token::Brace, Vec<T>)> {\n\n let content;\n\n let brace = braced!(content in input);\n\n let mut values = Vec::new();\n\n while !input.is_empty() {\n\n values.push(content.parse()?);\n\n }\n\n Ok((brace, values))\n...
Rust
src/lib.rs
Robbepop/bucket_vec
d39ac8c3e793263793f1bedce6ee6ddd1697b2eb
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] extern crate alloc; #[cfg(not(feature = "std"))] use alloc::vec::Vec; mod bucket; mod config; mod iter; mod math; mod scale; #[cfg(test)] mod tests; use self::bucket::Bucket; use self::math::FloatExt; pub use self::{ config::{BucketVecCo...
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] extern crate alloc; #[cfg(not(feature = "std"))] use alloc::vec::Vec; mod bucket; mod config; mod iter; mod math; mod scale; #[cfg(test)] mod tests; use self::bucket::Bucket; use self::math::FloatExt; pub use self::{ config::{BucketVecCo...
pub fn first_mut(&mut self) -> Option<&mut T> { if self.is_empty() { return None } Some(&mut self.buckets[0][0]) } pub fn last(&self) -> Option<&T> { if self.is_empty() { return None } let len_buckets = self.buckets.len(); ...
pub fn first(&self) -> Option<&T> { if self.is_empty() { return None } Some(&self.buckets[0][0]) }
function_block-full_function
[ { "content": "/// Returns the capacity of the indexed bucket.\n\npub fn bucket_capacity<C>(index: usize) -> usize\n\nwhere\n\n C: BucketVecConfig,\n\n{\n\n let start_capacity = <C as BucketVecConfig>::STARTING_CAPACITY;\n\n let growth_rate = <C as BucketVecConfig>::GROWTH_RATE;\n\n if (growth_rate -...
Rust
src/os/macos/window.rs
yoanlcq/dmc
cf9b0b64e1f9fe2272007013fab21fcc56cbf65d
use error::Result; use window::{Window, WindowSettings, WindowHandle, WindowStyleHint, WindowTypeHint}; use super::OsContext; use {Vec2, Extent2, Rect, Rgba}; #[derive(Debug)] pub struct OsWindow; impl OsContext { pub fn create_window(&self, settings: &WindowSettings) -> Result<OsWindow> { unimplemented!(...
use error::Result; use window::{Window, WindowSettings, WindowHandle, WindowStyleHint, WindowTypeHint}; use super::OsContext; use {Vec2, Extent2, Rect, Rgba}; #[derive(Debug)] pub struct OsWindow; impl OsContext { pub fn create_window(&self, settings: &WindowSettings) -> Result<OsWindow> { unimplemented!(...
implemented!() } pub fn set_desktop(&self, i: usize) -> Result<()> { unimplemented!() } pub fn recenter_in_desktop(&self) -> Result<()> { unimplemented!() } pub fn recenter_in_work_area(&self) -> Result<()> { unimplemented!() } pub fn set_mouse_position(&self, pos...
&self) -> Result<Rect<i32, u32>> { unimplemented!() } pub fn set_position_and_size(&self, r: Rect<i32, u32>) -> Result<()> { unimplemented!() } pub fn set_opacity(&self, alpha: f64) -> Result<()> { un
random
[ { "content": "/// Sets a global hint for this crate.\n\n/// \n\n/// Such global hints should hopefully be rare, but sometimes they\n\n/// are the proper way to deal with some platform-specific details\n\n/// (usually, they are global in the first place because of quirky lower-level APIs).\n\n/// \n\n/// The app...
Rust
src/command/subgraph/delete.rs
jesusprubio/rover
0849daa95480c9b407a87b74b7bba74ded0735a4
use ansi_term::Colour::{Cyan, Red, Yellow}; use serde::Serialize; use structopt::StructOpt; use crate::command::RoverStdout; use crate::utils::client::StudioClientConfig; use crate::utils::parsers::{parse_graph_ref, GraphRef}; use crate::Result; use rover_client::query::subgraph::delete::{self, DeleteServiceResponse}...
use ansi_term::Colour::{Cyan, Red, Yellow}; use serde::Serialize; use structopt::StructOpt; use crate::command::RoverStdout; use crate::utils::client::StudioClientConfig; use crate::utils::parsers::{parse_graph_ref, GraphRef}; use crate::Result; use rover_client::query::subgraph::delete::{self, DeleteServiceResponse}...
fn confirm_delete() -> Result<bool> { eprintln!("Would you like to continue [y/n]"); let term = console::Term::stdout(); let confirm = term.read_line()?; if confirm.to_lowercase() == *"y" { Ok(true) } else { Ok(false) } } fn handle_response(response: DeleteServiceResponse, sub...
else { eprintln!("{} At the time of checking, there would be no composition errors resulting from the deletion of this subgraph.", warn_prefix); eprintln!("{} This is only a prediction. If the graph changes before confirming, there could be composition errors.", warn_prefix) } }
function_block-function_prefix_line
[]
Rust
src/users/user_update.rs
use-cubed/auth0-management
db310d6f592e306d0d80a0a4a229d62051df3304
use reqwest::Method; use serde::de::DeserializeOwned; use serde::Serialize; use crate::users::User; use crate::{Auth0Client, Auth0Result}; #[derive(Serialize)] pub struct UserUpdate<'a, A, U> { #[serde(skip_serializing)] client: &'a Auth0Client, #[serde(skip_serializing)] user_id: String, #[serde(skip_ser...
use reqwest::Method; use serde::de::DeserializeOwned; use serde::Serialize; use crate::users::User; use crate::{Auth0Client, Auth0Result}; #[derive(Serialize)] pub struct UserUpdate<'a, A, U> { #[serde(skip_serializing)] client: &'a Auth0Client, #[serde(skip_serializing)] user_id: String, #[serde(skip_ser...
pub fn user_metadata<UserMetadata>( &mut self, user_metadata: UserMetadata, ) -> UserUpdate<'a, A, UserMetadata> { UserUpdate { client: self.client, user_id: self.user_id.clone(), blocked: self.blocked, email: self.email.clone(), email_verified: self.email_verified, ...
t, user_id: self.user_id.clone(), blocked: self.blocked, email: self.email.clone(), email_verified: self.email_verified, phone_number: self.phone_number.clone(), phone_verified: self.phone_verified, given_name: self.given_name.clone(), family_name: self.family_name.clone(...
function_block-function_prefixed
[ { "content": "pub fn get_client() -> Auth0 {\n\n Auth0::builder()\n\n .domain(&env!(\"AUTH0_DOMAIN\"))\n\n .audience(&env!(\"AUTH0_AUDIENCE\"))\n\n .client_id(&env!(\"AUTH0_CLIENT_ID\"))\n\n .client_secret(env!(\"AUTH0_CLIENT_SECRET\"))\n\n .build()\n\n .unwrap()\n\n}\n", "file_path": "te...
Rust
examples/chat/client/src/addresses.rs
dapla-project/dapla
2378997db752215977d1f229d9fa8764b15c8fe0
use std::time::Duration; use web_sys::HtmlInputElement; use yew::{ html, services::{ console::ConsoleService, timeout::{TimeoutService, TimeoutTask}, Task, }, Component, ComponentLink, Html, MouseEvent, Properties, ShouldRender, }; use yew_mdc_widgets::{ utils::dom::{self, J...
use std::time::Duration; use web_sys::HtmlInputElement; use yew::{ html, services::{ console::ConsoleService, timeout::{TimeoutService, TimeoutTask}, Task, }, Component, ComponentLink, Html, MouseEvent, Properties, ShouldRender, }; use yew_mdc_widgets::{ utils::dom::{self, J...
"), ) .action( Button::new() .label("Add") .class(Dialog::BUTTON_CLASS) .on_click(self.this_link.callback(move |_| { let address = dom::select_exist_element::<HtmlInputElement>("#new-address > inp...
}))) .on_click(|event: MouseEvent| { if let Ok(range) = dom::document().create_range() { if let Some(element) = event .target() .and_then(|target| JsCast::dyn_into::<Element>(target).ok()) ...
function_block-random_span
[ { "content": "pub fn set_element_style(element: impl AsRef<HtmlElement>, property: &str, value: &str) {\n\n element\n\n .as_ref()\n\n .style()\n\n .set_property(property, value)\n\n .unwrap_or_else(|err| panic!(\"Can't set style \\\"{}:{}\\\": {:?}\", property, value, err));\n\n}\...
Rust
src/blocksdata.rs
TheNoswad/OpenSC
19c5c7a3d2aa260e8f672d3aae1bcc4f2a6149a1
use serde::Deserialize; #[derive(Debug, Deserialize)] #[allow(dead_code, non_snake_case)] pub struct BlocksDataCSV { #[serde(rename = "Class Name")] pub ClassName: Option<String>, pub DefaultDisplayName: Option<String>, pub DefaultCategory: Option<String>, pub Behaviors: Option<String>, pub Dis...
use serde::Deserialize; #[derive(Debug, Deserialize)] #[allow(dead_code, non_snake_case)] pub struct BlocksDataCSV { #[serde(rename = "Class Name")] pub ClassName: Option<String>, pub DefaultDisplayName: Option<String>, pub DefaultCategory: Option<String>, pub Behaviors: Option<String>, pub Dis...
pub ShovelPower: f32, pub HackPower: f32, pub DigResilience: f32, pub IsAimable: bool, pub WeaponPower: f32, pub NutritionalValue: f32, #[serde(deserialize_with = "tags_deserialize")] pub TextureLocation: Vec<f32>, pub AverageToolLongevity: i32 } pub fn load_blocksdata_xml() -> Block...
match record.ClassName { Some(_) => { blocksdata.push(record); }, None => { println!("Empty csv class name") }, } }, ...
random
[ { "content": "pub fn generate_chunk_mesh(chunk: &Chunk, blocksdata: &BlocksData) -> Mesh {\n\n let mut vertices: Vec<Vec3> = vec![];\n\n let mut indices: Vec<u32> = vec![];\n\n let mut uvs: Vec<Vec2> = vec![];\n\n\n\n let mut count = 0;\n\n let mut indices_count = 0;\n\n\n\n for z in 0..16 {\n...
Rust
kernel/src/asm.rs
stmobo/epiphyllum
66f7e35966b20fcf02db446c124ca40e44dbde79
pub mod cpuid; use crate::structures::Bitmask64; fn get_flags() -> u64 { let flags: u64; unsafe { llvm_asm!("pushfq; popq $0" : "=r"(flags) ::: "volatile"); } flags } pub fn get_cr0() -> Bitmask64 { let reg: u64; unsafe { llvm_asm!("mov %cr0, $0" : "=r"(reg) ::: "volatile"); ...
pub mod cpuid; use crate::structures::Bitmask64; fn get_flags() -> u64 { let flags: u64; unsafe { llvm_asm!("pushfq; popq $0" : "=r"(flags) ::: "volatile"); } flags } pub fn get_cr0() -> Bitmask64 { let reg: u64; unsafe { llvm_asm!("mov %cr0, $0" : "=r"(reg) ::: "volatile"); ...
llvm_asm!("outb %al, %dx" :: "{dx}"(addr), "{al}"(data) :: "volatile"); } pub unsafe fn outw(addr: u16, data: u16) { llvm_asm!("outw %ax, %dx" :: "{dx}"(addr), "{ax}"(data) :: "volatile"); } pub unsafe fn outd(addr: u16, data: u32) { llvm_...
eg) :: "volatile"); }; } pub fn get_cr4() -> Bitmask64 { let reg: u64; unsafe { llvm_asm!("mov %cr4, $0" : "=r"(reg) ::: "volatile"); } Bitmask64(reg) } pub unsafe fn set_cr4(flags: Bitmask64) { llvm_asm!("mov $0, %cr4" :: "r"(flags.0) :: "volatile"); } pub fn invlpg(page: usize) { ...
random
[ { "content": "/// Allocate a block of physical memory pages at a specific address.\n\n///\n\n/// The order is a buddy allocator order; the number of memory pages actually\n\n/// allocated is (1 << order).\n\npub fn allocate_at(addr: usize, order: u64) -> Result<usize, AllocationError> {\n\n if order > 8 {\n\...
Rust
src/router.rs
ikanago/qz
3e59c25af2107d72e1cbe776c15c0aadd42525fc
use crate::{ handler::Handler, method::Method, request::Request, response::Response, status::StatusCode, }; use std::collections::HashMap; #[derive(Debug)] pub struct Router<State> where State: Clone + Send + Sync + 'static, { path: Vec<u8>, handlers: HashMap<Method, Box<dyn Handler<State>>>, child...
use crate::{ handler::Handler, method::Method, request::Request, response::Response, status::StatusCode, }; use std::collections::HashMap; #[derive(Debug)] pub struct Router<State> where State: Clone + Send + Sync + 'static, { path: Vec<u8>, handlers: HashMap<Method, Box<dyn Handler<State>>>, child...
fn longest_common_prefix(&self, other: &[u8]) -> usize { let mut pos = 0; for (char_self, char_other) in self.path.iter().zip(other.iter()) { if char_self == char_other { pos += 1; } else { break; } } pos ...
assert!(self.path.len() >= 2); let (_, path) = self.path.split_last().unwrap(); self.path = path.to_vec(); let mut handlers: HashMap<Method, Box<dyn Handler<State> + 'static>> = HashMap::new(); handlers.insert(method, Box::new(handler)); self.children.push(Self { path...
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait Handler<State>: Send + Sync + 'static\n\nwhere\n\n State: Clone + Send + Sync + 'static,\n\n{\n\n async fn call(&self, request: Request, state: State) -> crate::Result<Response>;\n\n}\n\n\n\n#[async_trait]\n\nimpl<State, F, Fut> Handler<State> for F\n\nwhere\n\n ...
Rust
src/material.rs
sebas642/the-ray-tracer-challenge-rust
a2c87b95927c7339bbb1cbc88c53a365098ed396
use super::color::{Color, BLACK, WHITE}; use super::tuple::Tuple; use super::light::PointLight; use super::pattern; use super::shape::BoxShape; #[derive(Debug, Copy, Clone, PartialEq)] pub struct Material { pub color: Color, pub pattern: Option<pattern::StripePattern>, pub ambient: f64, pub diffuse: f6...
use super::color::{Color, BLACK, WHITE}; use super::tuple::Tuple; use super::light::PointLight; use super::pattern; use super::shape::BoxShape; #[derive(Debug, Copy, Clone, PartialEq)] pub struct Material { pub color: Color, pub pattern: Option<pattern::StripePattern>, pub ambient: f64, pub diffuse: f6...
normalv = Tuple::vector(0., 0., -1.); let light = PointLight::new(&Tuple::point(0., 10., -10.), &WHITE); let result = Color::new(1.6364, 1.6364, 1.6364); assert_eq!(result, m.lighting(&Sphere::default_boxed(), &light, &position, &eyev, &normalv, false)); } #[test] fn lighting_with_...
e_in_the_path_of_the_reflection_vector() { let m = Material::default(); let position = Tuple::point(0., 0., 0.); let eyev = Tuple::vector(0., -2f64.sqrt()/2., -2f64.sqrt()/2.); let
function_block-random_span
[ { "content": "pub fn stripe_at_object(pattern: &StripePattern, object: &BoxShape, &world_point: &Tuple) -> Color {\n\n let object_point = object.transformation().inverse() * world_point;\n\n let pattern_point = pattern.transform.inverse() * object_point;\n\n\n\n stripe_at(pattern, &pattern_point)\n\n}\...
Rust
src/framebuffer.rs
acgaudette/voodoo
968bba208e05eb255e648ba9c4816af52bcca029
use std::sync::Arc; use std::marker::PhantomData; use smallvec::SmallVec; use vks; use ::{VdResult, Device, RenderPass, ImageView, Handle, FramebufferCreateInfo, FramebufferCreateFlags}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub struct FramebufferHandle(pub(crate) vks::VkFramebuffer); impl Frame...
use std::sync::Arc; use std::marker::PhantomData; use smallvec::SmallVec; use vks; use ::{VdResult, Device, RenderPass, ImageView, Handle, FramebufferCreateInfo, FramebufferCreateFlags}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub struct FramebufferHandle(pub(crate) vks::VkFramebuffer); impl Frame...
pub fn flags<'s>(&'s mut self, flags: FramebufferCreateFlags) -> &'s mut FramebufferBuilder<'b> { self.create_info.set_flags(flags); self } pub fn render_pass<'s, 'p>(&'s mut self, render_pass: &'p RenderPass) -> &'s mut FramebufferBuilder<'b> ...
pub fn new() -> FramebufferBuilder<'b> { FramebufferBuilder { create_info: FramebufferCreateInfo::default(), render_pass: None, attachments: None, _p: PhantomData, } }
function_block-full_function
[ { "content": "pub fn create_framebuffers(device: &Device, render_pass: &RenderPass,\n\n swapchain_image_views: &[ImageView], depth_image_view: &ImageView,\n\n swapchain_extent: Extent2d) -> VdResult<Vec<Framebuffer>> {\n\n swapchain_image_views.iter().map(|image_view| {\n\n let attachmen...
Rust
my-little-robots/src/bin/mlr/application.rs
baszalmstra/my-little-robots
22a3698302a2a23371a5846ba988d7e31ec3a02f
use bracket_lib::prelude::*; use mlr::bracket_lib::{draw_map, draw_ui, player_color, unit_glyph}; use mlr::World; use mlr_api::{Coord, UnitId}; use std::collections::{HashMap, HashSet}; use std::ops::Deref; #[derive(Clone)] struct AnimatedWorld { world: World, unit_locations: HashMap<UnitId, Coord>, visibl...
use bracket_lib::prelude::*; use mlr::bracket_lib::{draw_map, draw_ui, player_color, unit_glyph}; use mlr::World; use mlr_api::{Coord, UnitId}; use std::collections::{HashMap, HashSet}; use std::ops::Deref; #[derive(Clone)] struct AnimatedWorld { world: World, unit_locations: HashMap<UnitId, Coord>, visibl...
; was_contained + (currently_contained - was_contained) * self.animation_time }; ctx.set_active_console(0); draw_map(&self.world.world.map, is_visible, ctx); ctx.set_active_console(1); for unit in self.world.world.units.iter() { let cur...
if self.world.visible_tiles.contains(&coord) { 1.0 } else { 0.0 }
if_condition
[ { "content": "/// Draw the UI\n\npub fn draw_ui(world: &World, _units: &HashMap<UnitId, Coord>, ctx: &mut BTerm) {\n\n let map = &world.map;\n\n let mut ui_string = format!(\"Turn {}\", world.turn);\n\n\n\n // TODO: change this to not happen each frame\n\n // Get unique players and sort them\n\n ...
Rust
src/camera.rs
SokichiFujita/raytracer
c60e05c7bf873dc1e8363de71b11bfce5f98edd0
use na::{Matrix4, Vector4}; use crate::canvas::Canvas; use crate::color::Color; use crate::ray::Ray; use crate::world::World; use crate::tuple::TupleOperation; #[derive(Clone, Debug)] pub struct Camera { horizontal_size: f32, vertical_size: f32, field_of_view: f32, transform: Matrix4<f32>, half_w...
use na::{Matrix4, Vector4}; use crate::canvas::Canvas; use crate::color::Color; use crate::ray::Ray; use crate::world::World; use crate::tuple::TupleOperation; #[derive(Clone, Debug)] pub struct Camera { horizontal_size: f32, vertical_size: f32, field_of_view: f32, transform: Matrix4<f32>, half_w...
pub fn render(&self, world: &World) -> Canvas { let mut pixels = vec![] as Vec<Color>; for y in 0..(self.vertical_size as usize) { for x in 0..(self.horizontal_size as usize) { let ray = self.ray_for_pixel(x as f32, y as f32); let color = world.color_at(...
pub fn ray_for_pixel(&self, px: f32, py: f32) -> Ray { let x_offset = (px + 0.5) * self.pixel_size; let y_offset = (py + 0.5) * self.pixel_size; let world_x = self.half_width - x_offset; let world_y = self.half_height - y_offset; let inv = self.transform.try_inverse().unwrap(); ...
function_block-full_function
[ { "content": "fn ch12() {\n\n let floor_material = Material::new(\n\n Some(Color::rgb(1.0, 0.9, 0.9)),\n\n None,\n\n None,\n\n Some(0.0),\n\n Some(0.0),\n\n Some(0.7),\n\n Some(0.0),\n\n Some(0.0),\n\n Some(Pattern::Checker(Checker::new(\n\n ...
Rust
src/diagnostics.rs
M0n0xy2/ELang
33ddbe100314d22389fb6dbac948e8f0d6c11a85
use std; use std::io::Write; use lexer::{LexicalError, Token}; use lalrpop_util::ParseError; use span::Span; use ir::builder::SemanticError; use source_manager::SourceManager; #[derive(Debug)] pub struct Error { source_index: usize, msg: String, lines: Vec<Line>, } #[derive(Debug)] struct Line { n: ...
use std; use std::io::Write; use lexer::{LexicalError, Token}; use lalrpop_util::ParseError; use span::Span; use ir::builder::SemanticError; use source_manager::SourceManager; #[derive(Debug)] pub struct Error { source_index: usize, msg: String, lines: Vec<Line>, } #[derive(Debug)] struct Line { n: ...
, } } } } } impl ToError for SemanticError { fn convert(self, source_manager: &SourceManager, source_index: usize) -> Error { Error { source_index: source_index, msg: self.kind.to_string(), lines: get_lines(source_manager, self.spa...
get_lines(source_manager, Span { source_index: source_index, lo: pos, hi: pos + 1 })
call_expression
[ { "content": "pub fn process_imports(tu: &mut ast::TranslationUnit,\n\n options: &CompileOptions,\n\n source_manager: &mut SourceManager,\n\n globals_table: &mut GlobalTable)\n\n -> Result<Vec<ir::Declaration>, diagnostics::...
Rust
modules/web/server/src/api/notes.rs
dowlandaiello/mypad
82b548faa1f294048658fd082aa3ec7659fe631f
use super::{ super::{ models::{NewNote, Note, Permission, UpdateNote, User}, schema::{self, notes::dsl::*, users::dsl::*}, }, users::{extract_bearer, hash_token, Error}, }; use actix_web::{ error, web::{Data, HttpRequest, Json, Path}, Scope as ActixScope, }; use diesel::{ dsl...
use super::{ super::{ models::{NewNote, Note, Permission, UpdateNote, User}, schema::{self, notes::dsl::*, users::dsl::*}, }, users::{extract_bearer, hash_token, Error}, }; use actix_web::{ error, web::{Data, HttpRequest, Json, Path}, Scope as ActixScope, }; use diesel::{ dsl...
if matching_note.user_id != matching_user.id { return Err(Error(error::ErrorUnauthorized("The provided access token does not match a user with sufficient privileges to update this note."))); } let final_note: Note = updated_note.new_note(matching_note); Ok(Json(update(notes).s...
let matching_user: User = users .filter(schema::users::oauth_token.eq(hash_token(extract_bearer(&req)?))) .first(&conn)?;
assignment_statement
[ { "content": "/// Constructs an actix service group for the users endpoint.\n\npub fn build_service_group() -> ActixScope {\n\n ActixScope::new(\"/users\")\n\n .service(all_user_ids)\n\n .service(user)\n\n .service(user_with_id)\n\n .service(boards_from_user_with_id)\n\n .s...
Rust
meilisearch-http/src/analytics.rs
mdubus/MeiliSearch
553e7d8aaa73325be11d4d161610d7f58b485fe2
use std::hash::{Hash, Hasher}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use log::debug; use serde::Serialize; use siphasher::sip::SipHasher; use crate::Data; use crate::Opt; const AMPLITUDE_API_KEY: &str = "f7fba398780e06d8fe6666a9be7e3d47"; #[derive(Debug, Serialize)] struct EventProperties { ...
use std::hash::{Hash, Hasher}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use log::debug; use serde::Serialize; use siphasher::sip::SipHasher; use crate::Data; use crate::Opt; const AMPLITUDE_API_KEY: &str = "f7fba398780e06d8fe6666a9be7e3d47"; #[derive(Debug, Serialize)] struct EventProperties { ...
device_id, time, app_version, user_properties, event_properties, }; let request = AmplitudeRequest { api_key: AMPLITUDE_API_KEY, events: vec![event], }; let response = reqwest::Client::new() .post("http...
function_block-function_prefix_line
[ { "content": "pub fn print_launch_resume(opt: &Opt, data: &Data) {\n\n let commit_sha = match option_env!(\"COMMIT_SHA\") {\n\n Some(\"\") | None => env!(\"VERGEN_GIT_SHA\"),\n\n Some(commit_sha) => commit_sha,\n\n };\n\n let commit_date = match dbg!(option_env!(\"COMMIT_DATE\")) {\n\n ...
Rust
core/src/ipld.rs
Stebalien/libipld
92586bc1708fb69463ef865f81f9986b3cf31524
use alloc::{ borrow::ToOwned, boxed::Box, collections::BTreeMap, string::{String, ToString}, vec, vec::Vec, }; use core::fmt; use crate::cid::Cid; use crate::error::TypeError; #[derive(Clone, PartialEq)] pub enum Ipld { Null, Bool(bool), Integer(i128), Floa...
use alloc::{ borrow::ToOwned, boxed::Box, collections::BTreeMap, string::{String, ToString}, vec, vec::Vec, }; use core::fmt; use crate::cid::Cid; use crate::error::TypeError; #[derive(Clone, PartialEq)] pub enum Ipld { Null, Bool(bool), Integer(i128), Floa...
}
fn test_get() { let ipld = Ipld::List(vec![Ipld::Integer(0), Ipld::Integer(1), Ipld::Integer(2)]); assert_eq!(ipld.get(0).unwrap(), &Ipld::Integer(0)); assert_eq!(ipld.get(1).unwrap(), &Ipld::Integer(1)); assert_eq!(ipld.get(2).unwrap(), &Ipld::Integer(2)); let mut map = BTreeMa...
function_block-full_function
[ { "content": "/// Reads a cid from a stream of cbor encoded bytes.\n\npub fn read_link<R: Read + Seek>(r: &mut R) -> Result<Cid> {\n\n let major = read_major(r)?;\n\n if major.kind() != MajorKind::ByteString {\n\n return Err(UnexpectedCode::new::<Cid>(major.into()).into());\n\n }\n\n let len ...
Rust
src/qsv/statistics.rs
hderms/qsv
c93a3247cd9648698c1edcb7cb3a0f9e6c8af19d
use crate::csv::csv_data::{reset_stream, CsvStream, CsvType}; use crate::csv::inference::ColumnInference; use crate::qsv::{csv_stream_from_mime_type, Options}; use log::debug; use stats::{Frequencies, MinMax, OnlineStats}; use std::error::Error; use std::fmt::{Display, Formatter}; use std::fs::File; use std::hash::Hash...
use crate::csv::csv_data::{reset_stream, CsvStream, CsvType}; use crate::csv::inference::ColumnInference; use crate::qsv::{csv_stream_from_mime_type, Options}; use log::debug; use stats::{Frequencies, MinMax, OnlineStats}; use std::error::Error; use std::fmt::{Display, Formatter}; use std::fs::File; use std::hash::Hash...
} fn print_statistics(stats: &OnlineStats, f: &mut Formatter) -> std::fmt::Result { writeln!(f, "\tMean: {:.5}", stats.mean())?; writeln!(f, "\tStddev: {:.5}", stats.stddev()) } fn print_frequencies(top_10: &[String], f: &mut Formatter) -> std::fmt::Result { writeln!(f, "\tTop ten most common occurrences...
if let Some(ref cardinality) = self.cardinality { writeln!(f, "\tUnique: {}", cardinality)?; } if let Some(ref top_10) = self.top_10 { print_frequencies(top_10, f)?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn sanitize(str: Option<String>) -> Option<String> {\n\n str.map(|s| s.replace(\" \", \"_\"))\n\n}\n", "file_path": "src/qsv/util.rs", "rank": 0, "score": 148119.86026843777 }, { "content": "pub fn remove_extension(p0: &Path) -> Option<String> {\n\n let file_name = p0...
Rust
src/lcg_utilities/lcg.rs
hube12/end_gen_rs
458aba3d7c10af63b900afba968918c117b29ffc
pub const JAVA_LCG: LCG = LCG { multiplier: 0x5DEECE66D, addend: 0xB }; pub const END_LCG: LCG = LCG { multiplier: 257489430523441, addend: 184379205320524 }; #[derive(Copy, Clone, Debug)] pub struct LCG { multiplier: u64, addend: u64, } pub mod lcg_const_extra { pub const INV_A: u64 = 0xdfe05bcb1365; ...
pub const JAVA_LCG: LCG = LCG { multiplier: 0x5DEECE66D, addend: 0xB }; pub const END_LCG: LCG = LCG { multiplier: 257489430523441, addend: 184379205320524 }; #[derive(Copy, Clone, Debug)] pub struct LCG { multiplier: u64, addend: u64, } pub mod lcg_const_extra { pub const INV_A: u64 = 0xdfe05bcb1365; ...
pub fn previous(&mut self) { self.seed = Self::previous_state(self.seed); } pub fn previous_state(s: u64) -> u64 { (s.wrapping_sub(JAVA_LCG.addend)).wrapping_mul(lcg_const_extra::INV_A) & mask(48) } }
ut self) -> f64 { let hi = (self.next(26) as i64) << 27; let lo = self.next(27) as i64; (hi + lo) as f64 / ((1u64 << 53) as f64) }
function_block-function_prefixed
[ { "content": "pub fn next(world_seed:i64,salt:i64)->i64{\n\n return world_seed*( world_seed * 6364136223846793005i64 + 1442695040888963407i64) + salt;\n\n}", "file_path": "src/lcg_utilities/biome_lcg.rs", "rank": 0, "score": 117233.2055361724 }, { "content": "pub fn get_fuzzy_positions(wo...
Rust
bin/amphora/src/amphora/server/reboot.rs
menmos/menmos
9e71569eb1ad93e73476092eb9d63f89c39d2c1e
use std::path::Path; use std::sync::Arc; use std::time::Duration; use anyhow::Result; use interface::{CertificateInfo, StorageNode}; use tokio::{sync::mpsc, task::JoinHandle}; use crate::{constants, make_node, CertPath, Config}; use super::server_impl::NodeServer; fn load_certificates<P: AsRef<Path>>(cert_directo...
use std::path::Path; use std::sync::Arc; use std::time::Duration; use anyhow::Result; use interface::{CertificateInfo, StorageNode}; use tokio::{sync::mpsc, task::JoinHandle}; use crate::{constants, make_node, CertPath, Config}; use super::server_impl::NodeServer; fn load_certificates<P: AsRef<Path>>(cert_directo...
} else { None }; let s = NodeServer::new(storage_node.clone(), cfg.clone(), cert_paths); let cert_change_validator = block_until_cert_change(storage_node.clone(), certs); let stop_signal = stop_rx.recv(); let should_terminate = tokio::select! { ...
Some(CertPath { certificate: cfg .server .certificate_storage_path .join(constants::CERTIFICATE_FILE_NAME), private_key: cfg .server .certificate_storage_path .join(con...
call_expression
[ { "content": "/// Converts a struct implementing [`AsyncRead`] into a stream of `Result<`[`Bytes`]`, `[`io::Error`]`>`.\n\n///\n\n/// [`AsyncRead`]: tokio::io::AsyncRead\n\n/// [`Bytes`]: bytes::Bytes\n\n/// [`io::Error`]: std::io::Error\n\n///\n\npub fn reader_to_iostream<R: AsyncRead>(reader: R) -> impl Strea...
Rust
core/src/subgraph/provider.rs
llogiq/graph-node
94f7941f4cae2e0c7c7ed4b9e3df6fd94662a994
use std::collections::BTreeMap; use std::sync::Mutex; use futures::sync::mpsc::{channel, Receiver, Sender}; use graph::prelude::{SubgraphProvider as SubgraphProviderTrait, *}; use graph_graphql::prelude::validate_schema; pub struct SubgraphProvider<L> { _logger: slog::Logger, event_stream: Option<Receiver<Su...
use std::collections::BTreeMap; use std::sync::Mutex; use futures::sync::mpsc::{channel, Receiver, Sender}; use graph::prelude::{SubgraphProvider as SubgraphProviderTrait, *}; use graph_graphql::prelude::validate_schema; pub struct SubgraphProvider<L> { _logger: slog::Logger, event_stream: Option<Receiver<Su...
, ).and_then(move |mut subgraph| { subgraph .schema .add_subgraph_id_directives(subgraph.id.clone()); let old_id = self_clone .subgraphs .lock() ...
match validate_schema(&subgraph.schema.document) { Err(e) => Err(SubgraphProviderError::SchemaValidationError(e)), _ => Ok(subgraph), }
if_condition
[ { "content": "pub fn subgraph_deploy_request(name: String, ipfs_hash: String, id: String) -> MethodCall {\n\n let params = serde_json::to_value(SubgraphDeployParams { name, ipfs_hash })\n\n .unwrap()\n\n .as_object()\n\n .cloned()\n\n .unwrap();\n\n\n\n MethodCall {\n\n ...
Rust
contracts/state-validator/src/verifications/revert.rs
zeroqn/godwoken-scripts
984dcd67dd42ff8ae55935cad16074a694beffac
use gw_common::{ h256_ext::H256Ext, smt::{Blake2bHasher, CompiledMerkleProof}, H256, }; use gw_types::{ core::Status, packed::{BlockMerkleState, Byte32, GlobalState, RawL2Block, RollupConfig, RollupRevert}, prelude::*, }; use validator_utils::gw_common; use validator_utils::gw_types; use validat...
use gw_common::{ h256_ext::H256Ext, smt::{Blake2bHasher, CompiledMerkleProof}, H256, }; use gw_types::{ core::Status, packed::{BlockMerkleState, Byte32, GlobalState, RawL2Block, RollupConfig, RollupRevert}, prelude::*, }; use validator_utils::gw_common; use validator_utils::gw_types; use validat...
block_merkle_proof .verify::<Blake2bHasher>(&prev_global_state.block().merkle_root().unpack(), leaves)? }; if !is_main_chain_block { return Err(Error::InvalidRevertedBlocks); } let reverted_block_merkle_proof = CompiledMerkleProof(revert_args.reverted_block_proo...
llections::BTreeSet, vec::Vec}; use validator_utils::error::Error; fn check_challenge_maturity( config: &RollupConfig, challenge_cell: &ChallengeCell, ) -> Result<(), Error> { let challenge_maturity_blocks: u64 = config.challenge_maturity_blocks().unpack(); let since = Since::new(load_input_since(chall...
random
[ { "content": "pub fn collect_burn_cells(config: &RollupConfig, source: Source) -> Result<Vec<BurnCell>, Error> {\n\n QueryIter::new(load_cell_lock_hash, source)\n\n .enumerate()\n\n .filter_map(|(index, lock_hash)| {\n\n let is_lock = lock_hash == config.burn_lock_hash().as_slice();\...
Rust
src/engine/board/piece/sliding/mod.rs
nagyf/rs-chess
b5a83c291d16f0ec13ec66b66bbb3fe8167f16d0
use crate::engine::board::bitboard::BitBoard; use crate::engine::board::piece::Piece; use crate::engine::board::square::{constants, Square}; #[cfg(test)] mod tests; pub fn get_piece_attacks(piece: Piece, square: Square, occupied: BitBoard) -> BitBoard { match piece { Piece::Rook => rook_attacks(square, ...
use crate::engine::board::bitboard::BitBoard; use crate::engine::board::piece::Piece; use crate::engine::board::square::{constants, Square}; #[cfg(test)] mod tests; pub fn get_piece_attacks(piece: Piece, square: Square, occupied: BitBoard) -> BitBoard { match piece { Piece::Rook => rook_attacks(square, ...
occ: BitBoard) -> BitBoard { let file = sq.get_file().to_index() - 1; let rankx8 = ((sq.get_rank().to_index() - 1) * 8) as usize; let rank_occurences = (occ.0 >> rankx8) as u8; let attacks = FIRST_RANK_ATTACKS[file as usize][rank_occurences as usize] as u64; BitBoard(attacks << rankx8 ...
fn rook_attacks(square: Square, occupied: BitBoard) -> BitBoard { rank_attacks(square, occupied) | file_attacks(square, occupied) } pub fn queen_attacks(square: Square, occupied: BitBoard) -> BitBoard { rook_attacks(square, occupied) | bishop_attacks(square, occupied) } pub fn bishop_attacks(square: Square, ...
random
[ { "content": "/// This function checks whether there are pieces attacking a particular square.\n\n///\n\n/// It will return a bitboard with every attackers in it.\n\npub fn square_attacked_by(square: Square, board: &Board) -> BitBoard {\n\n square_attacked_by_helper(square, board.pieces, board.colors, board....