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
benches/src/renderer.rs
jdahlstrom/retrofire
1564fb7f3cb220045f269ae3c0e0c05365b4a5cf
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::path::PathBuf; use std::time::Instant; use criterion::*; use geom::solids; use math::Angle::Rad; use math::transform::*; use math::vec::{dir, Y, Z}; use render::{Raster, Render, Renderer}; use render::raster::Fragment; use render::...
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::path::PathBuf; use std::time::Instant; use criterion::*; use geom::solids; use math::Angle::Rad; use math::transform::*; use math::vec::{dir, Y, Z}; use render::{Raster, Render, Renderer}; use render::raster::Fragment; use render::...
fn check_hash(buf: &[Color], expected: u64) { let h = &mut DefaultHasher::new(); buf.hash(h); let actual = h.finish(); if actual != expected { eprintln!("Hashes differ: actual={} vs expected={}", actual, expected); } } fn save_screenshot(name: &str, buf: &mut [Color]) { let path = Pat...
fn renderer() -> Renderer { let mut rdr = Renderer::new(); rdr.projection = perspective(1.0, 10.0, 1.0, Rad(1.0)); rdr.viewport = viewport(0.0, 0.0, W as f32, W as f32); rdr }
function_block-full_function
[ { "content": "fn render_scene<VA, FA>(scene: Scene<Mesh<VA, FA>>) -> Stats\n\nwhere VA: Copy + Linear<f32>, FA: Copy\n\n{\n\n const W: usize = 50;\n\n const H: usize = 20;\n\n let mut rdr = Renderer::new();\n\n rdr.projection = perspective(1.0, 100.0, 1.0, Deg(90.0));\n\n rdr.viewport = viewport(...
Rust
src/game/lib.rs
kvark/claymore
708c820ed0841c091c53245df3853d2b4a2839de
extern crate rustc_serialize; #[macro_use] extern crate log; extern crate grid; extern crate cgmath; #[macro_use] extern crate gfx; extern crate gfx_pipeline; extern crate claymore_scene as scene; extern crate claymore_load as load; use std::fs::File; use rustc_serialize::json; use gfx_pipeline::forward::Pipeline; mo...
extern crate rustc_serialize; #[macro_use] extern crate log; extern crate grid; extern crate cgmath; #[macro_use] extern crate gfx; extern crate gfx_pipeline; extern crate claymore_scene as scene; extern crate claymore_load as load; use std::fs::File; use rustc_serialize::json; use gfx_pipeline::forward::Pipeline; mo...
node: nid, }); }, None => { error!("Unable to find character: {}", name); }, } } }; let mut pipeline = Pipeline::new(factory).unwrap();...
let mut characters = Vec::new(); { let mut context = load::Context::new(factory, root); context.extend_scene(&mut scene, &config.level.scene).unwrap(); for (name, ch) in config.level.characters.iter() { let coord = [ch.cell.0 as i32, ch.cell.1 as i32]; ...
random
[ { "content": "pub fn load<R: gfx::Resources, F: gfx::Factory<R>>(name: &str, factory: &mut F)\n\n -> Result<gfx::handle::Program<R>, Error> {\n\n use std::io::Read;\n\n // vertex\n\n let mut src_vert = Vec::new();\n\n let path = format!(\"shader/{}.glslv\", name);\n\n match File::open(...
Rust
src/string_gen/cpp.rs
kondrak/codespawn
0bdbd98bba77552ee6b553c42bc62d0de24616ee
use raw_code::{CodeItem}; use string_gen::{AUTOGEN_HEADER, AUTOGEN_FOOTER}; use string_gen::keywords::*; pub fn convert(code_items: &Vec<CodeItem>, num_tabs: u8, tab_char: char) -> String { let mut code_str = format!("// {}", AUTOGEN_HEADER); for i in code_items.iter() { code_str = format!("{}{}", code...
use raw_code::{CodeItem}; use string_gen::{AUTOGEN_HEADER, AUTOGEN_FOOTER}; use string_gen::keywords::*; pub fn convert(code_items: &Vec<CodeItem>, num_tabs: u8, tab_char: char) -> String { let mut code_str = format!("// {}", AUTOGEN_HEADER); for i in code_items.iter() { code_str = format!("{}{}", code...
}, ATTRIBUTE => {}, _ => panic!("Illegal enum child: {}", c.name), } } enum_str.push_str(format!("{}{}", start_indent, "};\n\n").as_str()); enum_str } fn make_variable(e: &CodeItem, depth: u8, num_tabs: u8, tab_char: char) -> String { let mut s...
if v.is_empty() { enum_str.push_str(format!("{}{},\n", spaces_str, n).as_str()); } else { enum_str.push_str(format!("{}{} = {},\n", spaces_str, n, v).as_str()); }
if_condition
[ { "content": "fn make_function(e: &CodeItem, depth: u8, num_tabs: u8, tab_char: char, struct_func: bool, fptr: bool, is_arg: bool) -> String {\n\n let mut start_indent = String::from(\"\");\n\n\n\n if !is_arg {\n\n for _ in 0..num_tabs*depth {\n\n start_indent.push(tab_char);\n\n ...
Rust
src/monotone/mono_poly.rs
rmanoka/geo-crossings
b1bfa2ab10735ed23ac6c4213662fc1d109cb066
use geo::{ Coordinate, GeoFloat, GeoNum, LineString, Polygon, prelude::BoundingRect, Rect, }; use std::{cmp::Ordering, iter::from_fn}; use crate::SweepPoint; use super::{Trapz, Trip}; #[derive(Clone)] pub struct MonoPoly<T: GeoNum> { top: LineString<T>, bot: LineString<T>, } impl<T: GeoNum> Bounding...
use geo::{ Coordinate, GeoFloat, GeoNum, LineString, Polygon, prelude::BoundingRect, Rect, }; use std::{cmp::Ordering, iter::from_fn}; use crate::SweepPoint; use super::{Trapz, Trip}; #[derive(Clone)] pub struct MonoPoly<T: GeoNum> { top: LineString<T>, bot: LineString<T>, } impl<T: GeoNum> Bounding...
pub fn advance_upto<F: FnMut(Trapz<T>)>(&mut self, until: T, mut proc: F) { while self.curr.x < until { if let Some(result) = self.advance_next(until) { if let Some(result) = result { proc(result); } } else { retur...
e { std::mem::transmute(self) }; from_fn(move || { while this.curr.x < until { match this.advance_next(until) { Some(Some(t)) => return Some(t), None => return None, _ => {}, } } None ...
function_block-function_prefixed
[ { "content": "/// Partition a valid polygon into monotone pieces.\n\n///\n\n/// Uses the [`Sweep`] algorithm to parition a polygon into\n\n/// sub-polygons, each of which is monotone. The\n\n/// sub-polygons are returns as a pair of the top and bottom\n\n/// line-string.\n\n///\n\n/// # Validity\n\n///\n\n/// O...
Rust
src/apu/channel/dmc.rs
ltriant/nes
0abdb6a0175f5b0670333634fd6d5f81e933cef2
use std::cell::RefCell; use std::io; use std::fs::File; use std::rc::Rc; use crate::cpu::CPU; use crate::apu::channel::Voice; use crate::mem::Memory; const TIMER_TABLE: [u16; 16] = [ 0x01AC, 0x017C, 0x0154, 0x0140, 0x011E, 0x00FE, 0x00E2, 0x00D6, 0x00BE, 0x00A0, 0x008E, 0x0080, 0x006A, 0x0054, 0x0048,...
use std::cell::RefCell; use std::io; use std::fs::File; use std::rc::Rc; use crate::cpu::CPU; use crate::apu::channel::Voice; use crate::mem::Memory; const TIMER_TABLE: [u16; 16] = [ 0x01AC, 0x017C, 0x0154, 0x0140, 0x011E, 0x00FE, 0x00E2, 0x00D6, 0x00BE, 0x00A0, 0x008E, 0x0080, 0x006A, 0x0054, 0x0048,...
pub fn write_dac(&mut self, val: u8) { self.buffer = val & 0b0111_1111 } pub fn write_address(&mut self, val: u8) { debug!("write_address: addr={:02X}", val); self.sample_address = 0xC000 | ((val as u16) << 6); } pub fn write_length(&mut self, val:...
pub fn write_control(&mut self, val: u8) { let irq = (val & 0b1000_0000) != 0; let dmc_loop = (val & 0b0100_0000) != 0; let f_index = val & 0b0000_1111; self.irq_enabled = irq; if !irq { self.irq_flag = false; } self.dmc_loop = dmc_loop; ...
function_block-full_function
[ { "content": "pub fn load_file_into_memory(fh: &mut File)\n\n -> Result<Rc<RefCell<Box<dyn Mapper>>>, CartridgeError>\n\n{\n\n let mut header = [0; 16];\n\n let _ = fh.read(&mut header).map_err(CartridgeError::IO)?;\n\n\n\n // NES^Z\n\n let magic = &header[0 .. 4];\n\n if magic != INES_MAGIC {...
Rust
src/main.rs
rofrol/rust-shopping-bot
1245cbac87706d66e6bce5a0cf1c47894d7a5e3a
extern crate actix_web; extern crate env_logger; use std::env; extern crate serde; use serde::{Deserialize, Serialize}; extern crate serde_json; extern crate bytes; extern crate futures; use futures::{Future, Stream}; use actix_web::{ middleware, middleware::cors::Cors, web, App, HttpRequest, HttpResponse, HttpS...
extern crate actix_web; extern crate env_logger; use std::env; extern crate serde; use serde::{Deserialize, Serialize}; extern crate serde_json; extern crate bytes; extern crate futures; use futures::{Future, Stream}; use actix_web::{ middleware, middleware::cors::Cors, web, App, HttpRequest, HttpResponse, HttpS...
fn webhook_get(hub: web::Query<Hub>) -> impl Responder { let f = std::fs::read_to_string("veirify_token").unwrap(); let verify_token = f.trim(); match (&hub.mode, &hub.token) { (Some(mode), Some(token)) => { if mode == "subscribe" && token == verify_token { ...
function_block-full_function
[ { "content": "# rust shopping bot\n\n\n\nPort of https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup to Rust\n\n\n\n- https://messenger.com/platform\n\n- https://developers.facebook.com/docs/messenger-platform/getting-started/quick-start\n\n- https://developers.facebook.com/doc...
Rust
src/sieve.rs
calvinyong/pseg-sieve
7aa0c90dc0527c637e1e29a9d30667ba269e65a5
use rayon::prelude::*; pub fn sequential_sieve(upper_bound: usize) -> Vec<usize> { if upper_bound == 0 { return vec![]; } let mut sieve: Vec<bool> = vec![true; upper_bound + 1]; sieve[0] = false; sieve[1] = false; for i in 2..((upper_bound as f64).sqrt().ceil() as usize...
use rayon::prelude::*; pub fn sequential_sieve(upper_bound: usize) -> Vec<usize> { if upper_bound == 0 { return vec![]; } let mut sieve: Vec<bool> = vec![true; upper_bound + 1]; sieve[0] = false; sieve[1] = false; for i in 2..((upper_bound as f64).sqrt().ceil() as usize...
#[test] fn test_sequential_sieve() { assert_eq!(PRIMES, &sequential_sieve(230)[..]); let primes = sequential_sieve(100_000_000); assert_eq!(279209790387276usize, primes.iter().sum()); } #[test] fn test_seq_segmented_sieve() { assert_eq!(PRIMES, &sequentia...
let indices = get_partition_indices(31623, 1_000_000_000, 10000); assert_eq!(10001, indices.len()); let windows: Vec<&[usize]> = indices.windows(2).collect(); assert_eq!(10000, windows.len()); }
function_block-function_prefix_line
[ { "content": "pub fn sequential_primality(limit: usize) -> Vec<usize> {\n\n (2..limit).filter(|&n| is_prime(n)).collect()\n\n}\n\n\n", "file_path": "src/primality.rs", "rank": 5, "score": 96528.65490351005 }, { "content": "pub fn rayon_primality(limit: usize) -> Vec<usize> {\n\n (2..li...
Rust
src/glue/webgl/buffer.rs
blm768/gravity-wars
ca50482f3bf981cac9f610ebc39d096dba315539
use std::fmt; use std::fmt::{Debug, Formatter}; use std::rc::Rc; use std::slice; use web_sys::{WebGlBuffer, WebGlRenderingContext}; use crate::glue::webgl::WebGlContext; use crate::rendering; use crate::rendering::buffer::{AttributeType, VertexAttributeBinding}; fn to_gl_attr_type(attr_type: AttributeType) -> u32 { ...
use std::fmt; use std::fmt::{Debug, Formatter}; use std::rc::Rc; use std::slice; use web_sys::{WebGlBuffer, WebGlRenderingContext}; use crate::glue::webgl::WebGlContext; use crate::rendering; use crate::rendering::buffer::{AttributeType, VertexAttributeBinding}; fn to_gl_attr_type(attr_type: AttributeType) -> u32 { ...
} #[derive(Debug)] pub struct AttributeBuffer { buffer: Buffer, } impl AttributeBuffer { pub fn new(context: Rc<WebGlRenderingContext>) -> Option<Self> { Some(AttributeBuffer { buffer: Buffer::new(context, BufferBinding::ArrayBuffer)?, }) } } impl rendering::buffer::Buffer fo...
fn set_data(&self, data: &[u8]) { self.bind(); let bytes = unsafe { slice::from_raw_parts_mut(data.as_ptr() as *mut u8, data.len()) }; self.context.buffer_data_with_u8_array( self.binding as u32, bytes, WebGlRenderingContext::STATIC_...
function_block-full_function
[ { "content": "pub trait Buffer: Debug {\n\n type RenderingContext: context::RenderingContext + ?Sized;\n\n\n\n fn set_data(&self, data: &[u8]);\n\n}\n\n\n", "file_path": "src/rendering/buffer.rs", "rank": 0, "score": 156973.91457889226 }, { "content": "pub fn gen_sphere<Context>(\n\n ...
Rust
client/src/ui/mod.rs
EternalMC/voxel-rs-1
afecfaaa60d05fc5ec9e8b7eda4ead7f61b47c5a
use self::widgets::{Text, WithStyle}; use crate::ui::widgets::Button; use crate::window::WindowData; use anyhow::Result; use quint::{wt, Size, Style, WidgetTree}; use std::collections::BTreeMap; use voxel_rs_common::debug::DebugInfo; use wgpu_glyph::Scale; use winit::dpi::LogicalPosition; pub mod widgets; #[derive(De...
use self::widgets::{Text, WithStyle}; use crate::ui::widgets::Button; use crate::window::WindowData; use anyhow::Result; use quint::{wt, Size, Style, WidgetTree}; use std::collections::BTreeMap; use voxel_rs_common::debug::DebugInfo; use wgpu_glyph::Scale; use winit::dpi::LogicalPosition; pub mod widgets; #[derive(De...
pub fn handle_mouse_state_changes( &mut self, changes: Vec<(winit::event::MouseButton, winit::event::ElementState)>, ) { let changes = changes .into_iter() .map(|(button, state)| quint::Event::MouseInput { button: quint_mouse_button(button), ...
sage::ExitMenu), menu_button("EXIT", Message::ExitGame), ], ); buttons_container }
function_block-function_prefixed
[]
Rust
src/serialize.rs
blaggacao/nickel
c2ebd94ed615d53419018d620fa76f4047444836
use crate::error::SerializationError; use crate::identifier::Ident; use crate::term::{MetaValue, RichTerm, Term}; use serde::ser::{Error, Serialize, SerializeMap, Serializer}; use std::collections::HashMap; pub fn serialize_meta_value<S>(meta: &MetaValue, serializer: S) -> Result<S::Ok, S::Error> where S: Seriali...
use crate::error::SerializationError; use crate::identifier::Ident; use crate::term::{MetaValue, RichTerm, Term}; use serde::ser::{Error, Serialize, SerializeMap, Serializer}; use std::collections::HashMap; pub fn serialize_meta_value<S>(meta: &MetaValue, serializer: S) -> Result<S::Ok, S::Error> where S: Seriali...
at!("IO error: {}", io_err), None)) }) } macro_rules! assert_json_eq { ( $term:expr, $result:expr ) => { assert_eq!( serde_json::to_string(&mk_program($term).and_then(|mut p| p.eval_full()).unwrap()) .unwrap(), serde_json::to_strin...
t src = Cursor::new(s); Program::new_from_source(src, "<test>").map_err(|io_err| { Error::EvalError(EvalError::Other(form
function_block-random_span
[ { "content": "fn parse(s: &str) -> Result<RichTerm, ParseError> {\n\n let id = Files::new().add(\"<test>\", String::from(s));\n\n\n\n super::grammar::TermParser::new()\n\n .parse(id, Lexer::new(&s))\n\n .map_err(|err| ParseError::from_lalrpop(err, id))\n\n}\n\n\n", "file_path": "src/pars...
Rust
07-rust/stm32f0x1/stm32f0x1_pac/src/usb/istr.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register ISTR"] pub type R = crate::R<u32, super::ISTR>; #[doc = "Writer for register ISTR"] pub type W = crate::W<u32, super::ISTR>; #[doc = "Register ISTR `reset()`'s with value 0"] impl crate::ResetValue for super::ISTR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register ISTR"] pub type R = crate::R<u32, super::ISTR>; #[doc = "Writer for register ISTR"] pub type W = crate::W<u32, super::ISTR>; #[doc = "Register ISTR `reset()`'s with value 0"] i
e RESET_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RESET`"] pub struct RESET_W<'a> { w: &'a mut W, } impl<'a> RESET_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(a...
mpl crate::ResetValue for super::ISTR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `EP_ID`"] pub type EP_ID_R = crate::R<u8, u8>; #[doc = "Reader of field `DIR`"] pub type DIR_R = crate::R<bool, bool>; #[doc = "Reader of field `L1REQ`"] pub...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/actors/mod.rs
xudesheng/actix-mqtt-client
dd4e18a8ae1cd798687a61d40cfa7b9d8ab05a4b
use std::io; #[macro_use] pub mod macros; pub mod actions; pub mod packets; mod utils; use std::io::ErrorKind; use actix::dev::ToEnvelope; use actix::prelude::SendError; use actix::{Actor, Addr, Arbiter, Handler, MailboxError, Message, Recipient}; use log::trace; use tokio::time::{delay_until, Instant}; use crate::...
use std::io; #[macro_use] pub mod macros; pub mod actions; pub mod packets; mod utils; use std::io::ErrorKind; use actix::dev::ToEnvelope; use actix::prelude::SendError; use actix::{Actor, Addr, Arbiter, Handler, MailboxError, Message, Recipient}; use log::trace; use tokio::time::{delay_until, Instant}; use crate::...
} fn handle_mailbox_error_with_resend<TActor, TMessage>( tag: &str, e: MailboxError, error_recipient: &Recipient<ErrorMessage>, stop_recipient: &Recipient<StopMessage>, addr: Addr<TActor>, msg: TMessage, ) where TMessage: Message + Send + 'static, TActor: Actor + Handler<TMessage>, ...
match e { SendError::Closed(_) => { send_error( tag, error_recipient, ErrorKind::Interrupted, format!("[{}] Target mailbox is closed", tag), ); let _ = stop_recipient.do_send(StopMessage); } SendE...
if_condition
[ { "content": "fn send_packet<TActor, TMessage>(\n\n tag: &str,\n\n ctx: &Context<TActor>,\n\n send_recipient: &Recipient<VariablePacketMessage>,\n\n error_recipient: &Recipient<ErrorMessage>,\n\n stop_recipient: &Recipient<StopMessage>,\n\n packet: VariablePacket,\n\n resend_msg: TMessage,\...
Rust
src/grammar_parser.rs
Shiroy/lalr_gen
d486acb309c72c53d660534cc3af83db95ba08bb
use grammar::{Grammar, ProductionRule, LexicalUnit, RuleComponent}; struct ParserContext { src: String, row: u32, col: u32, str_pos: usize, } impl ParserContext { fn new(src : String) -> ParserContext { ParserContext { src: src, row: 1, col: 0, ...
use grammar::{Grammar, ProductionRule, LexicalUnit, RuleComponent}; struct ParserContext { src: String, row: u32, col: u32, str_pos: usize, } impl ParserContext { fn new(src : String) -> ParserContext { ParserContext { src: src, row: 1, col: 0, ...
pub fn read_line(&mut self) -> Option<String> { let mut iter = self.src.chars(); let mut ch = iter.nth(self.str_pos); let mut c : char; let mut read_word = String::new(); match ch { None => { return None }, Some(chr) => { c = chr} } ...
while (c == ' ') || (c == '\n') || (c == '\t') { next_char! { return None } } while !((c == ' ') || (c == '\n') || (c == '\t')) { read_word.push(c); next_char! { return Some(read_word) } } Some(read_word) }
function_block-function_prefix_line
[ { "content": "fn load_grammar(filename : &String) -> Result<String, String> {\n\n let mut f = match File::open(filename) {\n\n Err(io_error) => {\n\n return Err(io_error.to_string());\n\n },\n\n Ok(f) => f,\n\n };\n\n\n\n let mut grammar_content = String::new();\n\n m...
Rust
client/src/stream.rs
Frando/hyperspace-rs
ae49bdadc806469eb6e659d81c94eb058f0e9393
use futures::io::{AsyncRead, AsyncSeek, SeekFrom}; use futures::stream::Stream; use futures::stream::StreamExt; use std::future::Future; use std::io::Result; use std::pin::Pin; use std::task::{Context, Poll}; use crate::{HypercoreEvent, RemoteHypercore}; type GetOutput = Result<Option<Vec<u8>>>; type GetFuture = Pin<...
use futures::io::{AsyncRead, AsyncSeek, SeekFrom}; use futures::stream::Stream; use futures::stream::StreamExt; use std::future::Future; use std::io::Result; use std::pin::Pin; use std::task::{Context, Poll}; use crate::{HypercoreEvent, RemoteHypercore}; type GetOutput = Result<Option<Vec<u8>>>; type GetFuture = Pin<...
} impl Stream for ReadStream { type Item = Result<Vec<u8>>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { if self.finished { return Poll::Ready(None); } let poll_result = Pin::as_mut(&mut self.future).poll(cx); let (core...
Self { future: get_future(core, start), index: start, end, live, finished: false, } }
function_block-function_prefix_line
[ { "content": "fn main() -> Result<()> {\n\n env_logger::from_env(env_logger::Env::default().default_filter_or(\"info\")).init();\n\n task::block_on(async_main())\n\n}\n\n\n", "file_path": "corestore/examples/demo.rs", "rank": 7, "score": 80681.24810650668 }, { "content": "fn main() -> ...
Rust
sync/adonais_core/src/lib.rs
tommilligan/adonais
c7b05ebcb69e61f7580dee16051397ce505e7e03
#[cfg(feature = "parser_pest")] #[macro_use] extern crate pest_derive; #[macro_use] extern crate serde_derive; #[cfg(test)] #[macro_use] extern crate lazy_static; #[cfg(test)] #[macro_use] extern crate pretty_assertions; pub mod google; pub mod keats; use std::collections::{HashMap, HashSet}; use std::convert::TryFr...
#[cfg(feature = "parser_pest")] #[macro_use] extern crate pest_derive; #[macro_use] extern crate serde_derive; #[cfg(test)] #[macro_use] extern crate lazy_static; #[cfg(test)] #[macro_use] extern crate pretty_assertions; pub mod google; pub mod keats; use std::collections::{HashMap, HashSet}; use std::convert::TryFr...
} #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct CalendarUpdateRequest { pub existing: Vec<String>, pub new: Vec<keats::Event>, pub group: u32, pub time_min: DateTime<FixedOffset>, } #[derive(Clone, Debug, PartialEq, Serialize)] pub struct CalendarUpdate...
let description = join_some_strings( vec![Some(inner.code.clone()), inner.staff, inner.type_], "\n", ); google::Event { id, summary, start: google::Time { datetime: inner.start.to_rfc3339(), }, ...
function_block-function_prefix_line
[ { "content": "/// Parse a collection of ints of the form `1-3, 5`.\n\n/// If invalid syntax, default to 200 - 299.\n\npub fn parse_group_range(range: &str) -> Vec<u32> {\n\n if range.len() == 0 {\n\n return (200..300).collect();\n\n }\n\n\n\n let mut items: Vec<u32> = vec![];\n\n for part in ...
Rust
src/bin/backend.rs
PatriotRossii/gmod-panel-api
63c9d756950bc236f1ecd5ff22f8a3da0deb09ac
use actix_web::{error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer}; use diesel::{SqliteConnection, r2d2::{self, ConnectionManager}, sqlite::Sqlite}; use serde::{Deserialize, Serialize}; use gmod_panel_api::db::{establish_connection, models::{BillingInfo, NewBillingInfo, NewCardInfo, CardInfo, ...
use actix_web::{error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer}; use diesel::{SqliteConnection, r2d2::{self, ConnectionManager}, sqlite::Sqlite}; use serde::{Deserialize, Serialize}; use gmod_panel_api::db::{establish_connection, models::{BillingInfo, NewBillingInfo, NewCardInfo, CardInfo, ...
#[derive(Deserialize)] struct GetCardInfoQuery { pub id: i32, } async fn get_card_info(pool: web::Data<DbPool>, path: web::Query<GetCardInfoQuery>) -> Result<HttpResponse, Error> { let connection = pool.get().expect("couldn't get db connection from pool"); let id = path.into_inner().id; let info = w...
pub fn insert_card_info(pool: web::Data<DbPool>, path: web::Query<NewCardInfo>) -> HttpResponse { let connection = pool.get().expect("couldn't get db connection from pool"); CardInfo::insert( &connection, path.into_inner() ); HttpResponse::Ok().body("success") }
function_block-full_function
[ { "content": "pub fn establish_connection() -> SqliteConnection {\n\n let db: &str = \"./database.sqlite\";\n\n SqliteConnection::establish(db)\n\n .unwrap_or_else(|_| panic!(\"Error connecting to {}\", db))\n\n}\n\n\n\nimpl BillingInfo {\n\n pub fn insert(conn: &SqliteConnection, billing_info: ...
Rust
src/api/baseline.rs
provideplatform/provide-rust
b9cc7bebe258986e9f2ae1cc7b2addc30e948581
use crate::api::client::{ApiClient, Params, Response}; pub use crate::models::baseline::*; use async_trait::async_trait; const DEFAULT_SCHEME: &str = "https"; const DEFAULT_HOST: &str = "baseline.provide.network"; const DEFAULT_PATH: &str = "api/v1"; #[async_trait] pub trait Baseline { fn factory(token: &str) -> ...
use crate::api::client::{ApiClient, Params, Response}; pub use crate::models::baseline::*; use async_trait::async_trait; const DEFAULT_SCHEME: &str = "https"; const DEFAULT_HOST: &str = "baseline.provide.network"; const DEFAULT_PATH: &str = "api/v1"; #[async_trait] pub trait Baseline { fn factory(token: &str) -> ...
async fn delete_workstep_participant( &self, workflow_id: &str, workstep_id: &str, participant_address: &str, ) -> Response { let uri = format!( "workflows/{}/worksteps/{}/participants/{}", workflow_id, workstep_id, participant_address );...
async fn create_workstep_participant( &self, workflow_id: &str, workstep_id: &str, params: Params, ) -> Response { let uri = format!( "workflows/{}/worksteps/{}/participants", workflow_id, workstep_id ); return self.post(&uri, params, N...
function_block-function_prefixed
[ { "content": "#[async_trait]\n\npub trait Privacy {\n\n fn factory(token: &str) -> Self;\n\n\n\n async fn list_provers(&self) -> Response;\n\n\n\n async fn create_prover(&self, params: Params) -> Response;\n\n\n\n async fn get_prover(&self, prover_id: &str) -> Response;\n\n\n\n async fn generate_...
Rust
src/regular_dynamic.rs
dystonse/dystonse-curves
6aa6f7c9bab8bf64f29846328b7d3c579e1275d6
use crate::conversion::LikeANumber; use crate::{Curve, TypedCurve}; use gnuplot::{Figure, Caption, Color}; use serde::{Serialize, Deserialize}; use crate::tree::{LeafData, SerdeFormat}; use std::fmt::{Debug, Display, Formatter}; /** * A curve that has a dynamic length and data points at regular distances. */ #[deriv...
use crate::conversion::LikeANumber; use crate::{Curve, TypedCurve}; use gnuplot::{Figure, Caption, Color}; use serde::{Serialize, Deserialize}; use crate::tree::{LeafData, SerdeFormat}; use std::fmt::{Debug, Display, Formatter}; /** * A curve that has a dynamic length and data points at regular distances. */ #[deriv...
== i_min { return self.y[i_min]; } let a = i.fract(); return Y::make_from_f32(self.y[i_min].make_into_f32() * (1.0 - a) + self.y[i_max].make_into_f32() * a); } /** * TODO when multiple consecutive points have the given Y value, the firs...
} let i = X::make_into_f32(x - self.x0) / X::make_into_f32(self.s); let i_min = i.floor() as usize; let i_max = i.ceil() as usize; if i_max
function_block-random_span
[ { "content": "// calculate a weighted average between several curves\n\npub fn weighted_average(curves: Vec<&dyn Curve>, weights: Vec<f32>) -> IrregularDynamicCurve<f32, f32> {\n\n \n\n // make sure the number of weights and curves match:\n\n assert_eq!(curves.len(), weights.len(), \"invalid arguments:...
Rust
src/nix/hwinfo.rs
marirs/systeminfo-rs
8abda54f1fe322ef8531a7e6caee11c88f2d76ee
#![allow(clippy::needless_collect)] use crate::{ common::utils::{exec_command_with_args, to_hashmap, ToVecString}, consts::SystemHardware, }; use humanize::Humanize; use std::collections::HashMap; fn get_mem_info() -> Option<HashMap<String, String>> { let command = "grep"; let args = ["-i", "memtotal:"...
#![allow(clippy::needless_collect)] use crate::{ common::utils::{exec_command_with_args, to_hashmap, ToVecString}, consts::SystemHardware, }; use humanize::Humanize; use std::collections::HashMap; fn get_mem_info() -> Option<HashMap<String, String>> { let command = "grep"; let args = ["-i", "memtotal:"...
} } pub fn from_system_hardware() -> SystemHardware { let v = vec![ std::thread::spawn(get_mem_info), std::thread::spawn(move || from_dmidecode().or_else(from_lshw)), std::thread::spawn(from_lscpu), ]; let mut it = v.into_iter().filter_map(|x|...
let command = "lscpu"; let args = []; let output = exec_command_with_args(command, &args).unwrap_or_default(); if output.is_empty() { None } else { Some(to_hashmap(output))
function_block-random_span
[ { "content": "pub fn exec_command_with_args(command: &str, args: &[&str]) -> Result<String, Error> {\n\n //! Executes a command with arguments and returns\n\n //! the output in Vector of line strings.\n\n //!\n\n //! ## Example usage:\n\n //! ```ignore\n\n //!\n\n //! fn main() {\n\n //!...
Rust
src/bin/server.rs
pmengelbert/ennui
6a0c9f0ebaf2bb5c33bde7c2c374da9e69e38bc1
use std::io::{Read, Write}; use std::net::TcpListener; use std::sync::{Arc, Mutex}; use std::thread::{spawn, JoinHandle}; use ennui::error::EnnuiError; use ennui::game::{Game, GameResult, NpcInit}; use ennui::player::npc::YamlPlayer; use ennui::player::{Player, PlayerType, Uuid}; use ennui::text::message::{Broadcast,...
use std::io::{Read, Write}; use std::net::TcpListener; use std::sync::{Arc, Mutex}; use std::thread::{spawn, JoinHandle}; use ennui::error::EnnuiError; use ennui::game::{Game, GameResult, NpcInit}; use ennui::player::npc::YamlPlayer; use ennui::player::{Player, PlayerType, Uuid}; use ennui::text::message::{Broadcast,...
; rcv.start(shared_game.clone()); let (discrete_sender, discrete_receiver) = channel::<DiscreteMessage>(); let rcv = GameActor(discrete_receiver); rcv.start(shared_game.clone()); shared_game.lock().unwrap().set_fight_sender(fight_sender); shared_game .lock() .unwrap() ....
:new($wrapped)) }; ); trait ReadLine { fn read_line(&mut self) -> std::io::Result<String>; } impl<T> ReadLine for T where T: Read, { fn read_line(&mut self) -> std::io::Result<String> { let mut buf = [0u8; 256]; let n = match self.read(&mut buf) { Ok(n) => n, Er...
random
[ { "content": "pub trait Uuid {\n\n fn uuid(&self) -> u128;\n\n fn others(&self) -> Vec<u128> {\n\n vec![]\n\n }\n\n}\n\n\n\nimpl Read for PlayerType {\n\n fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {\n\n self.safe_unwrap_mut()\n\n .stream\n\n .as...
Rust
src/geometry_boolean/mod.rs
Scripta-Qumranica-Electronica/geometry-tools
2a652551501f0a045cb3b1ef92a00707b4f2dc38
extern crate geo_booleanop; extern crate geo_types; extern crate wkt; use self::geo_types::Polygon; use crate::information::type_of; use crate::json_errors; use geo_booleanop::boolean::BooleanOp; use geo_repair_polygon::join::Join; use geo_types::Geometry; use geo_validator::Validate; use geo_wkt_writer::ToWkt; use wa...
extern crate geo_booleanop; extern crate geo_types; extern crate wkt; use self::geo_types::Polygon; use crate::information::type_of; use crate::json_errors; use geo_booleanop::boolean::BooleanOp; use geo_repair_polygon::join::Join; use geo_types::Geometry; use geo_validator::Validate; use geo_wkt_writer::ToWkt; use wa...
pub fn geometry_boolean( geo_geom1: &Geometry<f64>, geo_geom2: &Geometry<f64>, operation: geo_booleanop::boolean::Operation, ) -> Result<Polygon<f64>, JsValue> { match geo_geom1 { Geometry::MultiPolygon { .. } => { let g1 = geo_geom1.clone().into_multi_polygon().unwrap(); ...
son_errors::geometry_processing_error::invalid_geom( &err.to_string(), )) } }; let geo_geom2 = match wkt::conversion::try_into_geometry(&wkt_geom2.items[0]) { Ok(g2) => g2, Err(err) => { return Err(json_errors::geometry_processing_error::invalid_ge...
function_block-function_prefixed
[ { "content": "#[wasm_bindgen(js_name = wktPolygonDifference)]\n\npub fn wkt_polygon_difference(geom1: String, geom2: String) -> Result<String, JsValue> {\n\n wkt_polygon_boolean(geom1, geom2, geo_booleanop::boolean::Operation::Difference)\n\n}\n\n\n\n/// Generates an intersection from two WKT geometries.\n\n...
Rust
jakescript/src/interpreter/stack.rs
jakemarsden/JakeScript
7ac9bd6f2e1c822d139bdaab2950736da387fa88
use crate::ast::{Identifier, VariableDeclarationKind}; use crate::interpreter::error::{ AssignToConstVariableError, VariableAlreadyDefinedError, VariableNotDefinedError, }; use crate::interpreter::value::Value; use std::cell::{Ref, RefCell}; use std::mem; use std::rc::Rc; #[derive(Default, Debug)] pub struct CallS...
use crate::ast::{Identifier, VariableDeclarationKind}; use crate::interpreter::error::{ AssignToConstVariableError, VariableAlreadyDefinedError, VariableNotDefinedError, }; use crate::interpreter::value::Value; use std::cell::{Ref, RefCell}; use std::mem; use std::rc::Rc; #[derive(Default, Debug)] pub struct CallS...
} } #[derive(Debug)] struct VariableInner { kind: VariableDeclarationKind, name: Identifier, value: Value, }
match inner.kind { VariableDeclarationKind::Let | VariableDeclarationKind::Var => { (*inner).value = value; Ok(()) } VariableDeclarationKind::Const => Err(AssignToConstVariableError), }
if_condition
[ { "content": "pub trait Node: Clone + fmt::Debug {}\n\n\n\n#[derive(Clone, Default, Debug, Serialize, Deserialize)]\n\npub struct Program {\n\n body: Block,\n\n}\n\n\n\nimpl Program {\n\n pub fn new(body: Block) -> Self {\n\n Self { body }\n\n }\n\n\n\n pub fn body(&self) -> &Block {\n\n ...
Rust
src/main.rs
ckampfe/jindex
1f44c1982f8ed9654fb6cdef5f2219a9ba6f60b7
#[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: jemalloc::Jemalloc = jemalloc::Jemalloc; use anyhow::{anyhow, Result}; use std::convert::TryInto; use std::fs::File; use std::io::{BufWriter, Read, Write}; use std::mem::ManuallyDrop; use std::path::PathBuf; use structopt::StructOpt; const NEWLINE: &str =...
#[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: jemalloc::Jemalloc = jemalloc::Jemalloc; use anyhow::{anyhow, Result}; use std::convert::TryInto; use std::fs::File; use std::io::{BufWriter, Read, Write}; use std::mem::ManuallyDrop; use std::path::PathBuf; use structopt::StructOpt; const NEWLINE: &str =...
= if let Some(json_location) = &options.json_location { let mut f = File::open(json_location)?; let len = f.metadata()?.len(); let mut buf = Vec::with_capacity(len.try_into()?); f.read_to_end(&mut buf)?; serde_json::from_slice(&buf)? } else { serde_json::from_reader(...
d_path.push_str(path_addition); PathValue::new(value, child_path) } fn write_path_as_bytes<W: Write>( writer: &mut W, pathvalue: &PathValue, separator: &str, ) -> std::io::Result<()> { writer.write_all(pathvalue.path.as_bytes())?; writer.write_all(separator.as_bytes())?; serde_json::to_writ...
random
[ { "content": "# Changelog\n\n\n\n## Unreleased\n\n\n\n## 0.7.0 - 2021-03-28\n\n\n\n- Speedup by using `ManuallyDrop` to have the OS clean up rather than running destructors\n\n- Bump deps\n\n\n\n## 0.6.0 - 2021-03-14\n\n\n\n- Fix performance regression introduced in 0.5.0.\n\n- Bump deps\n\n\n\n## 0.5.0 - 2021-...
Rust
contrib/uservices/badge/src/kafka.rs
jqueguiner/cds
b629b7e18108142440dcc06fafca420001384511
use actix::{Actor, Addr, Context, Running}; use futures::{Future, Stream}; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer::stream_consumer::StreamConsumer; use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, Rebalance}; use rdkafka::error::Kafk...
use actix::{Actor, Addr, Context, Running}; use futures::{Future, Stream}; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer::stream_consumer::StreamConsumer; use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, Rebalance}; use rdkafka::error::Kafk...
ity,broker") .set("session.timeout.ms", "6000") .set("auto.offset.reset", "latest") .set("enable.auto.commit", "true"); if group != "" { client_config.set("group.id", &group); } else { client_config.set("group.id", &(user.clone() + ".cds-badge")); } if user != "...
g::new(); client_config .set_log_level(RDKafkaLogLevel::Debug) .set("metadata.broker.list", &brokers.join(",")) .set("enable.partition.eof", "false") .set("api.version.request", "true") .set("debug", "protocol,secur
function_block-random_span
[]
Rust
src/launcher.rs
cdong1012/Crab-Runner
3f99b1c9cb781e190769fae5f55fdc57ac9cd3a7
#[cfg(windows)] extern crate winapi; use std::ffi::CString; use std::io::Read; use std::ptr::null_mut; use winapi::shared::minwindef::{DWORD, LPVOID}; use winapi::um::fileapi::{CreateFileA, GetFileSize, ReadFile, OPEN_EXISTING}; use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE}; use winapi::um::memoryapi::...
#[cfg(windows)] extern crate winapi; use std::ffi::CString; use std::io::Read; use std::ptr::null_mut; use winapi::shared::minwindef::{DWORD, LPVOID}; use winapi::um::fileapi::{CreateFileA, GetFileSize, ReadFile, OPEN_EXISTING}; use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE}; use winapi::um::memoryapi::...
pub unsafe fn run_shellcode_dump(file_name: CString, offset: u64) -> (LPVOID, u32) { let mut dump_file_name: String = file_name.clone().into_string().unwrap(); dump_file_name.push_str("_dump.out"); let dump_file_name: CString = CString::new(dump_file_name).unwrap(); CopyFileA( file_name.as_ptr...
0, Some(code_entry), null_mut(), CREATE_SUSPENDED, &mut thread_id, ); if thread == null_mut() { VirtualFree(code_base, file_size, MEM_RELEASE); println!("[!!] Error while creating thread..."); return 1; } println!("[x] Started thread {} in suspen...
function_block-function_prefix_line
[ { "content": "pub fn print_banner() {\n\n\tprint!(\"\\x1B[2J\\x1B[1;1H\");\n\n\tprintln!(\n\n\t\t\"\n\n ____ ____ _ ____ ____ _ _ _ _ _ _ _____ ____ \n\n / ___| _ \\\\ / \\\\ | __ )| _ \\\\| | | | \\\\ | | \\\\ | | ____| _ \\\\ \n\n | | | |_) | / _ \\\\ | _ \\\\| |_) | | | | \\\\...
Rust
src/value.rs
ALinuxPerson/build_script
3bb8716df4ee06e5d31c1e1a33056274724d9aac
use std::fmt; #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] pub enum Value { Singular(String), Mapping(String, String), OptionalKey(Option<String>, String), UnquotedOptionalKey(Option<String>, String), OptionalValue(String, Option<String>), ...
use std::fmt; #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] pub enum Value { Singular(String), Mapping(String, String), OptionalKey(Option<String>, String), UnquotedOptionalKey(Option<String>, String), OptionalValue(String, Option<String>), ...
} #[cfg(test)] mod tests { use crate::Value; macro_rules! new_display_test { ($name:ident, $value:expr, $expected:literal) => { #[test] fn $name() { let value = $value; let output = format!("{}", value); let expected = $expected;...
else { write!(f, "{}", value) } } Self::UnquotedOptionalKey(key, value) => { if let Some(key) = key { write!(f, "{}={}", key, value) } else { write!(f, "{}", value) } ...
function_block-function_prefix_line
[ { "content": "/// Wrapper for `cargo:KEY=VALUE`. This is metadata, used by `links` scripts.\n\npub fn cargo_mapping(key: impl Into<String>, value: impl Into<String>) {\n\n build_script().cargo_mapping(&key.into(), &value.into());\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use gag::BufferRedirect;\n\n ...
Rust
src/static_fs.rs
biluohc/hyper-fs
5c6694d90f3ec3853ea9034f7182a62256bdfb4f
use url::percent_encoding::percent_decode; use tokio_core::reactor::Handle; use hyper::server::{Request}; use hyper::{header, Method}; use futures_cpupool::CpuPool; use futures::{future}; use super::{Config, Error, FutureObject}; use super::{StaticFile, StaticIndex}; #[cfg(feature = "default")] use super::content_typ...
use url::percent_encoding::percent_decode; use tokio_core::reactor::Handle; use hyper::server::{Request}; use hyper::{header, Method}; use futures_cpupool::CpuPool; use futures::{future}; use super::{Config, Error, FutureObject}; use super::{StaticFile, StaticIndex}; #[cfg(feature = "default")] use super::content_typ...
assert!(Path::new("tests/index").exists()); test( vec!( (("/", "/", "tests"),Ok(("/", "tests"))), (("/../", "/", "tests"),Ok(("/", "tests"))), (("/../../", "/", "tests"),Ok(("/", "tests"))), (("/index", "/", "tests"),Ok(("/index", "tests/index"))), (("/index/", "/", "te...
ist: Vec<((&str, &str ,&str), Result<(&str, &str), Error>)>) { for (idx, (args, res)) in list.into_iter().enumerate() { let (req, base, path) = args; let res = res.map(|(u, p)|(u.to_string(), PathBuf::from(p))); let res2 = router(req, base, &PathBuf::from(path)); ...
function_block-function_prefixed
[ { "content": "fn render_html(title: &str, index: &PathBuf, path: &str, config: &Config) -> io::Result<String> {\n\n let mut html = format!(\n\n \"\n\n<!DOCTYPE HTML>\n\n<html><head><meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=utf-8\\\">\n\n<title>Index listing for {}</title>\n\...
Rust
src/testing/sl4f/src/wpan/types.rs
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
use fidl_fuchsia_lowpan_test::{ MacAddressFilterItem, MacAddressFilterMode, MacAddressFilterSettings, }; use serde::{Deserialize, Serialize}; pub enum WpanMethod { GetIsCommissioned, GetMacAddressFilterSettings, GetNcpChannel, GetNcpMacAddress, GetNcpRssi, GetNcpState, GetNetworkName,...
use fidl_fuchsia_lowpan_test::{ MacAddressFilterItem, MacAddressFilterMode, MacAddressFilterSettings, }; use serde::{Deserialize, Serialize}; pub enum WpanMethod { GetIsCommissioned, GetMacAddressFilterSettings, GetNcpChannel, GetNcpMacAddress, GetNcpRssi, GetNcpState, GetNetworkName,...
} #[derive(Serialize)] pub enum ConnectivityState { Inactive, Ready, Offline, Attaching, Attached, Isolated, Commissioning, } #[derive(Serialize, Deserialize)] pub struct MacAddressFilterItemDto { pub mac_address: Option<Vec<u8>>, pub rssi: Option<i8>, } #[derive(Serialize, Deser...
GetNcpMacAddress" => Ok(WpanMethod::GetNcpMacAddress), "GetNcpRssi" => Ok(WpanMethod::GetNcpRssi), "GetNcpState" => Ok(WpanMethod::GetNcpState), "GetNetworkName" => Ok(WpanMethod::GetNetworkName), "GetPanId" => Ok(WpanMethod::GetPanId), "GetPartitionId" => Ok(...
function_block-function_prefix_line
[]
Rust
src/daemon/rpc.rs
asymmetric/lorri
8a73505666b80821c146143af92b547c68eab6b2
use super::IndicateActivity; use super::LoopHandlerEvent; use crate::build_loop::Event; use crate::error; use crate::ops::error::ExitError; use crate::rpc; use crate::socket::{BindLock, SocketPath}; use crate::watch; use crate::NixFile; use crossbeam_channel as chan; use slog_scope::debug; use std::convert::TryFrom; ...
use super::IndicateActivity; use super::LoopHandlerEvent; use crate::build_loop::Event; use crate::error; use crate::ops::error::ExitError; use crate::rpc; use crate::socket::{BindLock, SocketPath}; use crate::watch; use crate::NixFile; use crossbeam_channel as chan; use slog_scope::debug; use std::convert::TryFrom; ...
?; } Ok(()) } } use std::convert::TryInto; impl TryFrom<&Event> for rpc::Event { type Error = &'static str; fn try_from(ev: &Event) -> Result<Self, Self::Error> { use rpc::Event_kind as kind; Ok(match ev { Event::SectionEnd => rpc::Event { kind:...
match event.try_into() { Ok(ev) => call.reply(ev), Err(e) => call.reply_invalid_parameter(e.to_string()), }
if_condition
[ { "content": "#[allow(dead_code)]\n\npub fn new(inner: Box<dyn VarlinkInterface + Send + Sync>) -> VarlinkInterfaceProxy {\n\n VarlinkInterfaceProxy { inner }\n\n}\n\nimpl varlink::Interface for VarlinkInterfaceProxy {\n\n fn get_description(&self) -> &'static str {\n\n \"# The interface `lorri dae...
Rust
src/entities/loader.rs
tomaka/declmagic
df3abdcd89cd1515f93c369401ac93581c3d4382
use resources::ResourcesLoader; use serialize::json; use std::ascii::StrAsciiExt; use std::collections::{ HashSet, HashMap }; use super::EntitiesState; use super::EntitiesHelper; use super::EntityID; use super::ComponentID; pub fn load(loader: &ResourcesLoader, resourceName: &str, output: &mut EntitiesState) -> Re...
use resources::ResourcesLoader; use serialize::json; use std::ascii::StrAsciiExt; use std::collections::{ HashSet, HashMap }; use super::EntitiesState; use super::EntitiesHelper; use super::EntityID; use super::ComponentID; pub fn load(loader: &ResourcesLoader, resourceName: &str, output: &mut EntitiesState) -> Re...
} fn load_entity(context: &mut LoadContext, resourceName: &str, entity: &json::Json) -> Result<EntityID, LoaderError> { match entity { &json::Object(ref entityData) => { let name = entityData .find(&"name".to_string()) .and_then(|e| e.as_string()) ...
match doc { &json::List(ref entities) => { let mut result = Vec::new(); for elem in entities.iter() { match load_entity(context, resourceName, elem) { Ok(e) => result.push(e), Err(err) => { for e in result.i...
if_condition
[ { "content": "pub fn exec_game<RL: resources::ResourcesLoader+Send+Share>(resources: RL) {\n\n let game = Game::new(resources);\n\n game.exec();\n\n}\n", "file_path": "src/declmagic.rs", "rank": 10, "score": 136527.9311297769 }, { "content": "pub fn execute_mut<E: EntitiesHelper, S: ::...
Rust
src/main.rs
jix/minimal_models_example
28573917cfd0af8ce8c0a115f172668dbdbb14c5
use std::{ collections::BTreeSet, io::{self, BufRead}, }; use cryptominisat::{Lbool, Lit, Solver}; use indexmap::IndexSet; use Lbool::{False, True, Undef}; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] enum VarName { UserVar(isize), Clause(usize), Chain(usize), } fn user_var_name(var_map: &I...
use std::{ collections::BTreeSet, io::{self, BufRead}, }; use cryptominisat::{Lbool, Lit, Solver}; use indexmap::IndexSet; use Lbool::{False, True, Undef}; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] enum VarName { UserVar(isize), Clause(usize), Chain(usize), } fn user_var_name(var_map: &I...
solver.add_clause(&clause); clause_counter += 1; let (index, _) = var_map.insert_full(VarName::Clause(clause_counter)); let clause_indicator = Lit::new(index as u32, false).unwrap(); if let Some(prev_chain) = chain { let (index, _) = var_map.inser...
ses"); } } False => { println!("unsat"); break; } Undef => { unreachable!() } } } for solver in &mut [&mut pos_solver, &mut neg_sol...
function_block-random_span
[ { "content": "# Minimal models\n\n\n\nUses a SAT solver to find minimal partial assignments that are model of a CNF\n\nformula. Supports incremental clause additions. Quick and dirty implementation\n\nto illustrate the technique.\n\n\n\nThis works by maintaining two SAT solver instances, one for the CNF formula...
Rust
nbody/src/main.rs
tisma/rust
608c6d282e66cabaf30d447f5d15417ae355b0a8
const PI: f64 = 3.141592653589793; const SOLAR_MASS: f64 = 4.0 * PI * PI; const YEAR: f64 = 365.24; const N_BODIES: usize = 5; use std::arch::x86_64::*; type F64x3 = [f64; 3]; #[repr(C)] #[derive(Clone, Copy)] struct Planet { x: F64x3, fill: f64, v: F64x3, mass: f64, } static BODIES: [Planet; N_BO...
const PI: f64 = 3.141592653589793; const SOLAR_MASS: f64 = 4.0 * PI * PI; const YEAR: f64 = 365.24; const N_BODIES: usize = 5; use std::arch::x86_64::*; type F64x3 = [f64; 3]; #[repr(C)] #[derive(Clone, Copy)] struct Planet { x: F64x3, fill: f64, v: F64x3, mass: f64, } static BODIES: [Planet; N_BO...
unwrap_or(1000); let mut bodies = BODIES; let mut sim = NBodySim::new(); offset_momentum(&mut bodies); println!("{:.9}", bodies_energy(&bodies)); sim.bodies_advance(&mut bodies, 0.01, ncycles); println!("{:.9}", bodies_energy(&bodies)); }
function_block-function_prefix_line
[ { "content": "pub fn find_matches(content: &str, pattern: &str, mut writter: impl std::io::Write) {\n\n for line in content.lines() {\n\n if line.contains(pattern) {\n\n writeln!(writter, \"{}\", line);\n\n }\n\n }\n\n}\n", "file_path": "cli_grep/src/lib.rs", "rank": 6, ...
Rust
src/test_utils.rs
jblondin/agnes
22f94409fc20da218a35b9161a9f170280c7481f
/*! Functions for generating sample data tables for tests. */ use cons::Nil; use field::FieldData; use store::DataStore; use view::ViewMerge; tablespace![ pub table emp_table { EmpId: u64, DeptId: u64, EmpName: String } pub table extra_emp { SalaryOffset: i64, DidTra...
/*! Functions for generating sample data tables for tests. */ use cons::Nil; use field::FieldData; use store::DataStore; use view::ViewMerge; tablespace![ pub table emp_table { EmpId: u64, DeptId: u64, EmpName: String } pub table extra_emp { SalaryOffset: i64, DidTra...
.push_back_cloned_from_iter(&[false, false, true, true, true, false, true]) .push_back_cloned_from_iter(&[47.3, 54.1, 98.3, 12.2, -1.2, 5.4, 22.5]) } pub fn sample_emp_table_full() -> full_emp_table::Store { DataStore::<Nil>::empty() .push_back_cloned_from_iter(&[0u64, 2, 5, 6, 8, 9, 10]) ...
$deptids.into(), $names .iter() .map(|s| s.to_string()) .collect::<Vec<_>>() .into() ] }}; } macro_rules! sample_emp_table { () => {{ emp_table![ vec![0u64, 2, 5, 6, 8, 9, 10], vec![1u64, ...
random
[ { "content": "/// Helper sorting method for floating-point (f32) values\n\npub fn sort_f32(left: &f32, right: &f32) -> Ordering {\n\n left.partial_cmp(&right).unwrap_or_else(|| {\n\n if left.is_nan() && !right.is_nan() {\n\n Ordering::Less\n\n } else {\n\n // since partial...
Rust
src/protocol_handle_stream.rs
jjyr/p2p
dee026bf28f30b066d16ac4fa784eeb736e9058f
use futures::{prelude::*, sync::mpsc}; use log::warn; use multiaddr::Multiaddr; use std::collections::HashMap; use crate::{ context::{ServiceContext, SessionContext}, traits::{ServiceProtocol, SessionProtocol}, ProtocolId, SessionId, }; pub enum ServiceProtocolEvent { Init, Connected { ses...
use futures::{prelude::*, sync::mpsc}; use log::warn; use multiaddr::Multiaddr; use std::collections::HashMap; use crate::{ context::{ServiceContext, SessionContext}, traits::{ServiceProtocol, SessionProtocol}, ProtocolId, SessionId, }; pub enum ServiceProtocolEvent { Init, Connected { ses...
} impl Stream for ServiceProtocolStream { type Item = (); type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { loop { match self.receiver.poll() { Ok(Async::Ready(Some(event))) => self.handle_event(event), Ok(Async::Ready(None)...
fn handle_event(&mut self, event: ServiceProtocolEvent) { use self::ServiceProtocolEvent::*; match event { Init => self.handle.init(&mut self.service_context), Connected { session, version } => { self.handle .connected(&mut self.service_context...
function_block-full_function
[ { "content": "pub fn init() {\n\n // init secio two peers\n\n START_SECIO.call_once(|| {\n\n let (meta, _receiver) = create_meta(1);\n\n let mut service = create(true, meta, ());\n\n let listen_addr = service\n\n .listen(\"/ip4/127.0.0.1/tcp/0\".parse().unwrap())\n\n ...
Rust
src/simple/evaluate.rs
yodalee/simplelang
0680fa0ad77427b90327bf8c6ade2280a090f242
use super::syntax::{Node}; use super::environment::{Environment}; use std::collections::HashSet; pub trait Evaluate { fn evaluate(&self, environment: &mut Environment) -> Box<Node>; } fn get_free_vars_helper(node: &Box<Node>, varlist: &mut HashSet<String>, free_vars: &mut HashSet<String>) { match **node { ...
use super::syntax::{Node}; use super::environment::{Environment}; use std::collections::HashSet; pub trait Evaluate { fn evaluate(&self, environment: &mut Environment) -> Box<Node>; } fn get_free_vars_helper(node: &Box<Node>, varlist: &mut HashSet<String>, free_vars: &mut HashSet<String>) { match **node { ...
#[test] fn test_simple_big_function_twoarg() { let x_add_y = Node::fun("addx", "x", Node::fun("addy", "y", Node::add(Node::variable("x"), Node::variable("y")))); let statement = Node::assign("result", Node::call(Node::call(x_add_y, Node::number(17)), Node::number(31))); let mut env = E...
fn test_simple_big_function_env() { let x_add_y = Node::fun("add1", "y", Node::add(Node::variable("x"), Node::variable("y"))); let statement = Node::sequence( Node::assign("x", Node::number(3)), Node::sequence( Node::assign("add3", x_add_y), Node:...
function_block-full_function
[ { "content": "fn build_while(pair: Pair<Rule>) -> Box<Node> {\n\n let mut inner = pair.into_inner();\n\n let cond = climb(inner.next().unwrap());\n\n let stmt = build_stats(inner.next().unwrap());\n\n Node::while_node(cond, stmt)\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 2, "score...
Rust
src/calculation.rs
pauljxtan/toitoi
bcce8ce2605782f95353fe33cba45395f6c18829
use crate::{ division::{divide, Division}, fu::fu_for_division, meld::no_open_calls, tile::Tile, types::{Call, FuReason, HanReason, HandContext, Yaku, Yakuman}, yaku::{yaku_in_hand, yakuman_in_hand, Checkable}, }; use itertools::{repeat_n, Itertools}; #[derive(Debug, Default, Eq, PartialEq, O...
use crate::{ division::{divide, Division}, fu::fu_for_division, meld::no_open_calls, tile::Tile, types::{Call, FuReason, HanReason, HandContext, Yaku, Yakuman}, yaku::{yaku_in_hand, yakuman_in_hand, Checkable}, }; use itertools::{repeat_n, Itertools}; #[derive(Debug, Default, Eq, PartialEq, O...
heck_kokushi( tiles: &Vec<Tile>, calls: &Vec<Call>, context: &HandContext, ) -> Option<CalcResult> { let mut remaining = tiles.clone(); remaining.push(context.winning_tile.clone()); let division = Division { pair: vec![], melds: vec![], remaining }; if Yakuman::KokushiMusou.check(&division, ca...
r_division(&division, calls, context); Some(CalcResult { winning_tile: context.winning_tile.clone(), pair: division.pair, melds: division.melds, remaining: division.remaining, fu_reasons: vec![(FuReason::Chiitoitsu, 25)], han_reasons, ...
random
[ { "content": "fn has_wind(wind: Tile, division: &Division, calls: &Vec<Call>, context: &HandContext) -> bool {\n\n (wind == context.round_wind || wind == context.player_wind)\n\n && combine_melds(division, calls).iter().any(|m| m[0] == wind)\n\n}\n\n\n", "file_path": "src/yaku.rs", "rank": 0, ...
Rust
2021/src/day19.rs
ajitnilakantan/advent-of-code
9015ed5065a4d094387172cb4319ee80274b1138
use regex::Regex; use std::collections::HashSet; use std::fs; use std::fs::File; use std::io::{self, BufRead, Error}; use std::iter::FromIterator; use std::path::Path; #[allow(dead_code)] fn read_lines<P>(filename: P) -> Result<Vec<String>, Error> where P: AsRef<Path>, { let file = File::open(filename)?; l...
use regex::Regex; use std::collections::HashSet; use std::fs; use std::fs::File; use std::io::{self, BufRead, Error}; use std::iter::FromIterator; use std::path::Path; #[allow(dead_code)] fn read_lines<P>(filename: P) -> Result<Vec<String>, Error> where P: AsRef<Path>, { let file = File::open(filename)?; l...
struct Match { index1: usize, index2: usize, pos2: Vec<isize>, mapping: Vec<isize>, } fn count_beacons(beacons: &Vec<Vec<(isize, isize, isize)>>, matches: &Vec<Match>) -> usize { let mut all_beacons: HashSet<(isize, isize, isize)> = HashSet::new(); for scanner in 0..beacons.len() { ...
fn match_up( vec1: &Vec<(isize, isize, isize)>, vec2: &Vec<(isize, isize, isize)>, ) -> Option<(Vec<isize>, Vec<isize>)> { for i in 0..vec1.len() { let vec_rel1 = vec_wrt(&vec1, i); for j in 0..vec2.len() { let vec_rel2 = vec_wrt(&vec2, j); if let Some(intersection) =...
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\nfn read_chunks<P>(filename: P) -> Result<Vec<String>, Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let text = fs::read_to_string(filename)?;\n\n let chunks: Vec<String> = Regex::new(r\"\\r\\n\\r\\n\")\n\n .unwrap()\n\n .split(&text)\n\n .map(|x|...
Rust
src/http.rs
Aleph-Alpha/aleph-alpha-client-rs
950b89591030e9579491d479fbda4cc6b002e48f
use std::borrow::Cow; use reqwest::{header, ClientBuilder, StatusCode}; use serde::{Deserialize, Serialize}; use thiserror::Error as ThisError; use crate::{Prompt, TaskCompletion}; #[derive(ThisError, Debug)] pub enum Error { #[error( "You are trying to calculate more tasks in parallel, than you cur...
use std::borrow::Cow; use reqwest::{header, ClientBuilder, StatusCode}; use serde::{Deserialize, Serialize}; use thiserror::Error as ThisError; use crate::{Prompt, TaskCompletion}; #[derive(ThisError, Debug)] pub enum Error { #[error( "You are trying to calculate more tasks in parallel, than you cur...
} #[derive(Deserialize, Debug, PartialEq, Eq)] pub struct ResponseCompletion { pub model_version: String, pub completions: Vec<Completion>, } impl ResponseCompletion { pub fn best(&self) -> &Completion { self.completions .first() .expect("Response is assumed to always...
Self { model, prompt: task.prompt, maximum_tokens: task.maximum_tokens, temperature: task.sampling.temperature(), top_k: task.sampling.top_k(), top_p: task.sampling.top_p(), } }
function_block-function_prefix_line
[ { "content": "# Aleph Alpha API client for Rust\n\n\n\nInteract with large language models provided by the Aleph Alpha API in Rust code.\n\n\n\n## Usage\n\n\n\n```rust\n\nuse aleph_alpha_client::{Client, Authentication};\n\n\n\n#[tokio::main]\n\nfn main() {\n\n // Authenticate against API. Fetches token.\n\n...
Rust
src/string_collection.rs
temporal-lens-team/temporal-lens-server
6a054c2b09d5ec1d906690405d87fd069c262862
use std::mem::MaybeUninit; use std::sync::{RwLock, Arc}; use std::ops::Index; use std::cell::UnsafeCell; use fxhash::FxHashMap; const POOL_SIZE: usize = 8192; #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub enum Key { StaticString(usize), ThreadName(usize) } #[derive(Copy, Clone)] struct Entry { ...
use std::mem::MaybeUninit; use std::sync::{RwLock, Arc}; use std::ops::Index; use std::cell::UnsafeCell; use fxhash::FxHashMap; const POOL_SIZE: usize = 8192; #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub enum Key { StaticString(usize), ThreadName(usize) } #[derive(Copy, Clone)] struct Entry { ...
or StringCollection {} impl Accessor { pub fn get<'a>(&'a self, k: Key) -> Option<&'a str> { let opt_entry = self.0.map.read().unwrap().get(&k).copied(); opt_entry.map(|entry| { unsafe { let s = std::slice::from_raw_parts(entry.ptr, entry.len); ...
pools: UnsafeCell<Vec<Pool>> } pub struct Accessor(Arc<Internal>); pub struct StringCollection(Arc<Internal>); impl StringCollection { pub fn new() -> Self { let ret = Internal { map: RwLock::new(Default::default()), pools: UnsafeCell::new(Vec::new()) }; Self(Arc...
random
[ { "content": "struct Managed {\n\n frame_db: MDBAccessor<FrameData>,\n\n zone_db: MDBAccessor<LiteZoneData>,\n\n plot_db: MDBAccessor<LitePlotData>,\n\n str_collection: SCAccessor,\n\n start: Instant\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 3, "score": 57002.36193800092 }, ...
Rust
crates/nsi-core/src/dynamic/mod.rs
virtualritz/nei
adc72920b5158e7924cd2fc13ef73874ffd85746
use crate::Api; extern crate dlopen; use dlopen::wrapper::{Container, WrapperApi}; use std::{env, path::Path}; pub type ApiImpl = DynamicApi; use crate::*; #[derive(WrapperApi)] struct CApi { NSIBegin: extern "C" fn(nparams: ::std::os::raw::c_int, params: *const NSIParam_t) -> NSIContext_t, NSIEnd: e...
use crate::Api; extern crate dlopen; use dlopen::wrapper::{Container, WrapperApi}; use std::{env, path::Path}; pub type ApiImpl = DynamicApi; use crate::*; #[derive(WrapperApi)] struct CApi { NSIBegin: extern "C" fn(nparams: ::std::os::raw::c_int, params: *const NSIParam_t) -> NSIContext_t, NSIEnd: e...
nparams, params); } #[inline] fn NSIRenderControl( &self, ctx: NSIContext_t, nparams: ::std::os::raw::c_int, params: *const NSIParam_t, ) { self.api.NSIRenderControl(ctx, nparams, params); } #[cfg(feature = "output")] #[inline] fn DspyRegisterDr...
SIEvaluate( &self, ctx: NSIContext_t, nparams: ::std::os::raw::c_int, params: *const NSIParam_t, ) { self.api.NSIEvaluate(ctx,
function_block-random_span
[ { "content": "/// Create a traslation transform node.\n\n///\n\n/// If `handle` is [`None`] a random handle is generated.\n\n///\n\n/// The `angle` is specified in degrees.\n\n///\n\n/// Returns `handle` for convenience.\n\npub fn rotation(ctx: &nsi::Context, handle: Option<&str>, angle: f64, axis: &[f64; 3]) -...
Rust
rust-webvr/src/api/oculusvr/gamepad.rs
Manishearth/rust-webvr
c860c10cb8626db07d3bd384dd293e22cde12be9
#![cfg(target_os="android")] #![cfg(feature = "oculusvr")] use {VRGamepad, VRGamepadButton, VRGamepadData, VRGamepadHand, VRGamepadState}; use ovr_mobile_sys as ovr; use ovr_mobile_sys::ovrButton::*; use ovr_mobile_sys::ovrControllerCapabilties::*; use ovr_mobile_sys::ovrControllerType::*; use std::cell::{Cell, RefCel...
#![cfg(target_os="android")] #![cfg(feature = "oculusvr")] use {VRGamepad, VRGamepadButton, VRGamepadData, VRGamepadHand, VRGamepadState}; use ovr_mobile_sys as ovr; use ovr_mobile_sys::ovrButton::*; use ovr_mobile_sys::ovrControllerCapabilties::*; use ovr_mobile_sys::ovrControllerType::*; use std::cell::{Cell, RefCel...
-> Arc<RefCell<OculusVRGamepad>> { let capabilities = InputCapabilities::from_ovr(ovr, ovr_type, ovr_id); let gamepad = Self { ovr: ovr, ovr_id: ovr_id, ovr_type: ovr_type, connected: true, capabilities: capabilities.unwrap_o...
display_id: u32, predicted_display_time: Cell<f64>, } unsafe impl Send for OculusVRGamepad {} unsafe impl Sync for OculusVRGamepad {} impl OculusVRGamepad { pub fn new(ovr: *mut ovr::ovrMobile, ovr_id: ovr::ovrDeviceID, ovr_type: ovr::ovrControllerType, display_id:...
random
[ { "content": "#[inline]\n\npub fn ovr_vec3_to_array(v: &ovr::ovrVector3f) -> [f32; 3] {\n\n [v.x, v.y, v.z]\n\n}\n", "file_path": "rust-webvr/src/api/oculusvr/display.rs", "rank": 0, "score": 143171.31150796934 }, { "content": "#[inline]\n\npub fn ovr_quat_to_array(q: &ovr::ovrQuatf) -> [...
Rust
src/lib.rs
shinmili/texture
d23df7eea791db2db6215d918a3da16087747995
#![deny(missing_docs)] pub mod ops; pub trait ImageSize { fn get_size(&self) -> (u32, u32); #[inline(always)] fn get_width(&self) -> u32 { let (w, _) = self.get_size(); w } #[inline(always)] fn get_height(&self) -> u32 { let (_, h) = self.get_size(); ...
#![deny(missing_docs)] pub mod ops; pub trait ImageSize { fn get_size(&self) -> (u32, u32); #[inline(always)] fn get_width(&self) -> u32 { let (w, _) = self.get_size(); w } #[inline(always)] fn get_height(&self) -> u32 { let (_, h) = self.get_size(); ...
pub fn get_convert_gamma(&self) -> bool { self.convert_gamma } pub fn set_convert_gamma(&mut self, val: bool) { self.convert_gamma = val; } pub fn convert_gamma(mut self, val: bool) -> Self { self.set_convert_gamma(val); self } pub fn get_compress(&self) -> boo...
pub fn new() -> TextureSettings { TextureSettings { convert_gamma: false, compress: false, generate_mipmap: false, min: Filter::Linear, mag: Filter::Linear, mipmap: Filter::Linear, wrap_u: Wrap::ClampToEdge, wrap_v: ...
function_block-full_function
[ { "content": "/// Converts from alpha to rgba8.\n\npub fn alpha_to_rgba8(memory: &[u8], size: [u32; 2]) -> Vec<u8> {\n\n let (width, height) = (size[0] as usize, size[1] as usize);\n\n let capacity = width * height * 4;\n\n let stride = width;\n\n let mut res = Vec::with_capacity(capacity);\n\n f...
Rust
garnet/public/rust/carnelian/src/view.rs
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
use crate::{ app::App, geometry::Size, message::{make_message, Message}, scenic_utils::PresentationTime, }; use failure::Error; use fidl_fuchsia_ui_gfx::{self as gfx, Metrics, ViewProperties}; use fidl_fuchsia_ui_input::{ FocusEvent, InputEvent, KeyboardEvent, PointerEvent, SetHardKeyboardDelivery...
use crate::{ app::App, geometry::Size, message::{make_message, Message}, scenic_utils::PresentationTime, }; use failure::Error; use fidl_fuchsia_ui_gfx::{self as gfx, Metrics, ViewProperties}; use fidl_fuchsia_ui_input::{ FocusEvent, InputEvent, KeyboardEvent, PointerEvent, SetHardKeyboardDelivery...
view_assistant.setup(&context)?; let initial_animation_mode = view_assistant.initial_animation_mode(); let view_controller = ViewController { key, view, root_node, session, metrics: Size::zero(), physical_size: Size::zero...
let context = ViewAssistantContext { key, view: &view, root_node: &root_node, session: &session, logical_size: Size::zero(), size: Size::zero(), metrics: Size::zero(), presentation_time: Time::get(ClockId::Monotonic), ...
assignment_statement
[]
Rust
crates/bevy_atelier/src/assets.rs
kabergstrom/bevy
c078c8b194f099e8d2b5c07048b8994c1161028c
use crate::{ update_asset_storage_system, AssetChannel, AssetLoader, AssetServer, AssetTypeRegistry, ChannelAssetHandler, Handle, HandleId, HandleUntyped, }; use atelier_importer::BoxedImporter; use atelier_loader::TypeUuid; use bevy_app::{prelude::Events, AppBuilder}; use bevy_ecs::{FromResources, IntoQuerySys...
use crate::{ update_asset_storage_system, AssetChannel, AssetLoader, AssetServer, AssetTypeRegistry, ChannelA
ader::LoadHandle, load_op: atelier_loader::AssetLoadOp, version: u32, ) -> Result<(), Box<dyn std::error::Error>> { todo!() } fn commit_asset_version( &self, asset_type: &atelier_core::AssetTypeId, load_handle: atelier_loader::LoadHandle, version: u32,...
ssetHandler, Handle, HandleId, HandleUntyped, }; use atelier_importer::BoxedImporter; use atelier_loader::TypeUuid; use bevy_app::{prelude::Events, AppBuilder}; use bevy_ecs::{FromResources, IntoQuerySystem, ResMut, Resource}; use bevy_type_registry::RegisterType; use std::cell::RefCell; use std::collections::HashMap; ...
random
[ { "content": "fn use_meta() -> bool {\n\n crate_name(\"bevy\").is_ok()\n\n}\n\n\n\nconst AS_CRATE_ATTRIBUTE_NAME: &str = \"as_crate\";\n\n\n", "file_path": "crates/bevy_derive/src/modules.rs", "rank": 0, "score": 85264.52834855841 }, { "content": "fn use_meta() -> bool {\n\n crate_name...
Rust
query-engine/connectors/mongodb-query-connector/src/query_builder/group_by_builder.rs
prisma-korea/prisma-engines
99ac5a5c95ba2f5308d84fc30a7110f606182d92
use connector_interface::{AggregationSelection, Filter, ScalarProjection}; use mongodb::bson::{doc, Bson, Document}; use prisma_models::ScalarFieldRef; use std::collections::HashSet; #[derive(Debug, Default)] pub struct GroupByBuilder { aggregations: HashSet<(ScalarFieldRef, AggregationType)>, count_...
use connector_interface::{AggregationSelection, Filter, ScalarProjection}; use mongodb::bson::{doc, Bson, Document}; use prisma_models::ScalarFieldRef; use std::collections::HashSet; #[derive(Debug, Default)] pub struct GroupByBuilder { aggregations: HashSet<(ScalarFieldRef, AggregationType)>, count_...
fn insert_groupings(&mut self, fields: &[ScalarFieldRef], aggregation_type: AggregationType) { for field in fields { self.insert_grouping(field, &aggregation_type) } } fn insert_grouping(&mut self, field: &ScalarFieldRef, aggregation_type: &AggregationType) { self.aggr...
fn insert_from_filter(&mut self, filter: &Filter, aggregation_type: AggregationType) { let scalar_filter = filter.as_scalar().unwrap(); let field = match &scalar_filter.projection { ScalarProjection::Single(sf) => sf, _ => unreachable!(), }; self.insert_grouping(...
function_block-full_function
[ { "content": "/// Convert a PrismaValue into Bson, with a special case for `_count` aggregation filter.\n\n///\n\n/// When converting the value of a `_count` aggregation filter for a field that's _not_ numerical,\n\n/// we force the `TypeIdentifier` to be `Int` to prevent panics.\n\nfn into_bson_coerce_count(sf...
Rust
cargo-apk/src/apk.rs
selaux/android-ndk-rs
41cb81dc5fd383f89c22f6756e14640102a892a8
use crate::error::Error; use crate::manifest::Manifest; use cargo_subcommand::{Artifact, CrateType, Profile, Subcommand}; use ndk_build::apk::{Apk, ApkConfig}; use ndk_build::cargo::{cargo_apk, VersionCode}; use ndk_build::config::Config; use ndk_build::dylibs::get_libs_search_paths; use ndk_build::error::NdkError; use...
use crate::error::Error; use crate::manifest::Manifest; use cargo_subcommand::{Artifact, CrateType, Profile, Subcommand}; use ndk_build::apk::{Apk, ApkConfig}; use ndk_build::cargo::{cargo_apk, VersionCode}; use ndk_build::config::Config; use ndk_build::dylibs::get_libs_search_paths; use ndk_build::error::NdkError; use...
}
pub fn default(&self) -> Result<(), Error> { let ndk = Ndk::from_env()?; let target_sdk_version = self .manifest .metadata .target_sdk_version .unwrap_or_else(|| ndk.default_platform()); for target in &self.build_targets { let mut cargo...
function_block-full_function
[ { "content": "fn run_cargo(cmd: &Subcommand) -> Result<(), Error> {\n\n Command::new(\"cargo\")\n\n .arg(cmd.cmd())\n\n .args(cmd.args())\n\n .status()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "cargo-apk/src/main.rs", "rank": 0, "score": 291469.1544794627 }, { "conte...
Rust
src/service_provider.rs
mineichen/minfac
0eed6cc293af0e0384908901961f4d145ad4b6b8
use crate::{ binary_search, lifetime::{ DanglingCheckerResult, DanglingCheckerResults, LifetimeError, OutlivedLifetimeErrorVariants, }, strategy::{Identifyable, Strategy}, untyped::{ArcAutoFreePointer, AutoFreePointer, UntypedFn}, AllRegistered, AnyStrategy, InternalBuildResult, Register...
use crate::{ binary_search, lifetime::{ DanglingCheckerResult, DanglingCheckerResults, LifetimeError, OutlivedLifetimeErrorVariants, }, strategy::{Identifyable, Strategy}, untyped::{ArcAutoFreePointer, AutoFreePointer, UntypedFn}, AllRegistered, AnyStrategy, InternalBuildResult, Register...
fn count(self) -> usize where Self: Sized, { self.next_pos .map(|i| { let pos = binary_search::binary_search_last_by_key( &self.provider.0.immutable_state.producers[i..], &T::get_id(), UntypedFn::get_res...
fn last(self) -> Option<Self::Item> where Self: Sized, { self.next_pos.map(|i| { let pos = binary_search::binary_search_last_by_key( &self.provider.0.immutable_state.producers[i..], &T::get_id(), UntypedFn::<TS>::get_result_type_id, ...
function_block-full_function
[ { "content": "type UntypedFnFactoryCreator<TS> = extern \"C\" fn(\n\n outer_context: AutoFreePointer,\n\n inner_context: &mut UntypedFnFactoryContext<TS>,\n\n) -> InternalBuildResult<TS>;\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 257167.35429198953 }, { "content": "struct ...
Rust
src/pages/user_detail.rs
putchom/yew-todo
21988654e952899b7deda918c4bd85050ad23eff
mod product_grid_view; mod skeleton_user_info_view; mod user_info_view; use crate::models::user::User; use nachiguro::Container; use product_grid_view::ProductGridView; use serde::Deserialize; use skeleton_user_info_view::SkeletonUserInfoView; use user_info_view::UserInfoView; use yew::{ format::Json, prelude:...
mod product_grid_view; mod skeleton_user_info_view; mod user_info_view; use crate::models::user::User; use nachiguro::Container; use product_grid_view::ProductGridView; use serde::Deserialize; use skeleton_user_info_view::SkeletonUserInfoView; use user_info_view::UserInfoView; use yew::{ format::Json, prelude:...
ml { match self.data { Some(ref res) => { html! { <> <UserInfoView user=res.user.clone() /> <Container class=classes!("UserDetail-container")> <ProductGridView user=res.user.clone() /> ...
} (_, _, _) => { self.fail() } } } </div> } } } impl UserDetail { fn success(&self) -> Ht
random
[ { "content": "pub fn get(uri: String) -> Request<Nothing> {\n\n Request::get(uri)\n\n .header(\"Authorization\", format!(\"{} {}\", \"Bearer\", API_KEY))\n\n .body(Nothing)\n\n .expect(\"Could not build request.\")\n\n}\n", "file_path": "src/api.rs", "rank": 0, "score": 10725...
Rust
src/main_x86.rs
centowen/wasmduck
1d598b73664e16ec8c2f6f4cdc373b64d26c70c3
#![feature(duration_as_u128)] extern crate image; extern crate rayon; extern crate termion; use std::env; use std::fs; use std::io::{stdout, Write}; use std::{thread, time}; use termion::raw::IntoRawMode; mod grid; mod kernels; mod math; mod sph; const DT: f64 = 0.0005; const WIDTH: u16 = 100; const HEIGHT: u16 = 30...
#![feature(duration_as_u128)] extern crate image; extern crate rayon; extern crate termion; use std::env; use std::fs; use std::io::{stdout, Write}; use std::{thread, time}; use termion::raw::IntoRawMode; mod grid; mod kernels; mod math; mod sph; const DT: f64 = 0.0005; const WIDTH: u16 = 100; const HEIGHT: u16 = 30...
fn main() { let mut stdout = stdout(); let mut state = sph::create_initial_state(); let mut frame = 0; let mode = handle_args(); while true { let t1 = time::Instant::now(); let (grid, debug) = sph::update_state(&mut state, DT, sph::SPHDebug::new());...
ollect(); let mut mode = Mode::Terminal; if args.len() == 3 { if args[1] == "image" { mode = Mode::Image { size: args[2].parse().unwrap(), }; } } return mode; }
function_block-function_prefixed
[ { "content": "pub fn update_state(state: &mut State, dt: f64, debug: SPHDebug) -> (grid::Grid, SPHDebug) {\n\n let mut grid = grid::create_grid(H, MIN_X, MAX_X, MIN_Y, MAX_Y);\n\n\n\n let duck = &mut state.duck;\n\n\n\n duck.x += duck.vx * dt;\n\n duck.y += duck.vy * dt;\n\n\n\n if duck.y > MAX_Y...
Rust
chips/nrf52/src/uart.rs
dcellucci/tock
c26454249981da4bd564c188d1b182ea953177f4
use core::cell::Cell; use kernel; use kernel::common::regs::{ReadOnly, ReadWrite, WriteOnly}; use nrf5x::pinmux; const UARTE_BASE: u32 = 0x40002000; static mut BYTE: u8 = 0; #[repr(C)] struct UarteRegisters { pub task_startrx: WriteOnly<u32, Task::Register>, pub task_stoprx: WriteOnly<u32, Task::Register>,...
use core::cell::Cell; use kernel; use kernel::common::regs::{ReadOnly, ReadWrite, WriteOnly}; use nrf5x::pinmux; const UARTE_BASE: u32 = 0x40002000; static mut BYTE: u8 = 0; #[repr(C)] struct UarteRegisters { pub task_startrx: WriteOnly<u32, Task::Register>, pub task_stoprx: WriteOnly<u32, Task::Register>,...
fn enable_uart(&self) { let regs = unsafe { &*self.regs }; regs.enable.write(Uart::ENABLE::ON); } #[allow(dead_code)] fn disable_uart(&self) { let regs = unsafe { &*self.regs }; regs.enable.write(Uart::ENABLE::OFF); } #[allow(dead_code)] fn enable_rx_...
57600 => regs.baudrate.set(0x00EB0000), 76800 => regs.baudrate.set(0x013A9000), 115200 => regs.baudrate.set(0x01D60000), 230400 => regs.baudrate.set(0x03B00000), 250000 => regs.baudrate.set(0x04000000), 460800 => regs.baudrate.set(0x07400000), 9216...
function_block-function_prefix_line
[ { "content": "// get closest power of two greater than the given number\n\npub fn closest_power_of_two(mut num: u32) -> u32 {\n\n num -= 1;\n\n num |= num >> 1;\n\n num |= num >> 2;\n\n num |= num >> 4;\n\n num |= num >> 8;\n\n num |= num >> 16;\n\n num += 1;\n\n num\n\n}\n\n\n\n#[derive...
Rust
source-kafka/src/state.rs
estuary/connectors
e0dd46c891cad7fce6553439a37b3c42d5e31248
use std::collections::BTreeMap; use rdkafka::message::BorrowedMessage; use rdkafka::metadata::Metadata; use serde::{Deserialize, Serialize}; use tracing::info; use crate::{airbyte, catalog, connector, kafka}; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("failed to read the state file")] File(#...
use std::collections::BTreeMap; use rdkafka::message::BorrowedMessage; use rdkafka::metadata::Metadata; use serde::{Deserialize, Serialize}; use tracing::info; use crate::{airbyte, catalog, connector, kafka}; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("failed to read the state file")] File(#...
} } impl PartialOrd for Offset { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { use std::cmp::Ordering; match (self, other) { (Offset::Start, Offset::Start) => Some(Ordering::Equal), (Offset::Start, Offset::End) => Some(Ordering::Less), ...
match self { Self::Start => Self::Start, Self::End => Self::End, Self::UpThrough(n) => Self::UpThrough(*n + 1), }
if_condition
[ { "content": "fn open_file(path: impl AsRef<Path>) -> eyre::Result<File> {\n\n File::open(&path).wrap_err(format!(\"failed to read {:?}\", path.as_ref()))\n\n}\n\n\n", "file_path": "source-kafka/src/connector.rs", "rank": 0, "score": 250420.41390469385 }, { "content": "pub fn consumer_fro...
Rust
src/cli_opts.rs
psFried/pgen
008a4c680cd3651da5442780076523df1e8df86e
use dgen::interpreter::UnreadSource; use dgen::verbosity::Verbosity; use std::path::PathBuf; #[derive(Debug, StructOpt)] #[structopt( name = "dgen", about = "A language and interpreter for generating pseudo-random data", after_help = "Run `dgen` without any arguments to enter the interactive shell\nRun `dg...
use dgen::interpreter::UnreadSource; use dgen::verbosity::Verbosity; use std::path::PathBuf; #[derive(Debug, StructOpt)] #[structopt( name = "dgen", about = "A language and interpreter for generating pseudo-random data", after_help = "Run `dgen` without any arguments to enter the interactive shell\nRun `dg...
} #[derive(Debug, StructOpt)] pub struct HelpOptions { #[structopt(short = "F", long = "function")] pub function_name: Option<String>, #[structopt(short = "m", long = "module")] pub module_name: Option<String>, } #[derive(Debug, StructOpt)] pub enum SubCommand { #[structopt(name =...
r file in self.files[0..(num_files - 1)].iter() { let src = UnreadSource::file(file.clone()); libs.push(src); } } libs }
function_block-function_prefixed
[ { "content": "pub fn run_program(iterations: u64, program: &str) -> Result<Vec<u8>, Error> {\n\n let mut out = Vec::new();\n\n {\n\n let mut output = DataGenOutput::new(&mut out);\n\n let mut prog = Runner::new(\n\n iterations,\n\n program.to_owned(),\n\n cre...
Rust
proto/src/model.rs
adacta-io/adacta-backend
9bcf261abb3a05dbf8e120053d432e04f9b4355a
use std::borrow::Borrow; use std::collections::{HashMap, HashSet}; use std::ffi::OsString; use std::str::FromStr; use anyhow::{anyhow, Error}; use base58::{FromBase58, ToBase58}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize, Serializer}; use uuid::Uuid; #[derive(Debug, Clone, Copy, Hash, Eq, Partia...
use std::borrow::Borrow; use std::collections::{HashMap, HashSet}; use std::ffi::OsString; use std::str::FromStr; use anyhow::{anyhow, Error}; use base58::{FromBase58, ToBase58}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize, Serializer}; use uuid::Uuid; #[derive(Debug, Clone, Copy, Hash, Eq, Partia...
} impl std::fmt::Display for DocId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.to_base58()) } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum Kind { Document, Preview, Plaintext, Metadata, Other { name: OsString }, } impl Kind { ...
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::de::Deserializer<'de> { struct DocIdVisitor; impl<'de> serde::de::Visitor<'de> for DocIdVisitor { type Value = DocId; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::R...
function_block-full_function
[ { "content": "pub trait StrExt: AsRef<str> {\n\n fn split2(&self, p: char) -> Option<(&str, &str)> {\n\n let s = self.as_ref();\n\n let i = s.find(p)?;\n\n\n\n Some((&s[..i], &s[i + 1..]))\n\n }\n\n}\n\n\n\nimpl<S: AsRef<str>> StrExt for S {}\n", "file_path": "backend/src/utils.rs...
Rust
crates/typed-store/src/rocks/mod.rs
huitseeker/mysten-infra
3a389449cfaf0e1bc5a0b39c28ce56aaa382ec2a
mod errors; mod iter; mod keys; mod values; use crate::traits::Map; use bincode::Options; use collectable::TryExtend; use rocksdb::{ColumnFamilyDescriptor, DBWithThreadMode, MultiThreaded, WriteBatch}; use serde::{de::DeserializeOwned, Serialize}; use std::{borrow::Borrow, marker::PhantomData, path::Path, sync::Arc}...
mod errors; mod iter; mod keys; mod values; use crate::traits::Map; use bincode::Options; use collectable::TryExtend; use rocksdb::{ColumnFamilyDescriptor, DBWithThreadMode, MultiThreaded, WriteBatch}; use serde::{de::DeserializeOwned, Serialize}; use std::{borrow::Borrow, marker::PhantomData, path::Path, sync::Arc}...
sdb::Options>, opt_cfs: &[(&str, &rocksdb::Options)], ) -> Result<Arc<rocksdb::DBWithThreadMode<MultiThreaded>>, TypedStoreError> { let mut options = db_options.unwrap_or_default(); let mut opt_cfs: std::collections::HashMap<_, _> = opt_cfs.iter().cloned().collect(); let cfs = rocksdb::DBWithThrea...
rror> { if !Arc::ptr_eq(&db.rocksdb, &self.rocksdb) { return Err(TypedStoreError::CrossDBBatch); } let from_buf = be_fix_int_ser(from)?; let to_buf = be_fix_int_ser(to)?; self.batch.delete_range_cf(&db.cf(), from_buf, to_buf); Ok(self) } pub fn...
random
[ { "content": "pub fn dalek_pubkey_strategy() -> impl Strategy<Value = ed25519_dalek::PublicKey> {\n\n dalek_keypair_strategy().prop_map(|v| v.public)\n\n}\n", "file_path": "crates/rccheck/src/tests/test_utils.rs", "rank": 2, "score": 166505.0612254201 }, { "content": "pub trait Map<'a, K,...
Rust
ergo-nipopow/src/nipopow_algos.rs
sahandzou/sigma-rust
a56bb4bc750feea2015dd2d39239b2109466c4e7
use ergo_chain_types::Header; use ergotree_ir::sigma_protocol::dlog_group::order; use num_bigint::BigInt; use num_traits::ToPrimitive; use std::convert::TryInto; use crate::{ autolykos_pow_scheme::{AutolykosPowScheme, AutolykosPowSchemeError}, nipopow_proof::PoPowHeader, NipopowProof, NipopowProofError, };...
use ergo_chain_types::Header; use ergotree_ir::sigma_protocol::dlog_group::order; use num_bigint::BigInt; use num_traits::ToPrimitive; use std::convert::TryInto; use crate::{ autolykos_pow_scheme::{AutolykosPowScheme, AutolykosPowSchemeError}, nipopow_proof::PoPowHeader, NipopowProof, NipopowProofError, };...
EFIX) .collect(); if interlinks.is_empty() { Some(ergo_merkle_tree::BatchMerkleProof::new(vec![], vec![])) } else { NipopowAlgos::extension_batch_proof_for(ext, &interlinks) } } pub fn extension_proof_for( ext: &ExtensionCandidate, ...
t interlinks: Vec<[u8; 2]> = ext .fields() .iter() .map(|(key, _)| *key) .filter(|key| key[0] == INTERLINK_VECTOR_PR
function_block-random_span
[ { "content": "/// Blake2b256 hash (256 bit)\n\npub fn blake2b256_hash(bytes: &[u8]) -> Digest32 {\n\n Digest(sigma_util::hash::blake2b256_hash(bytes))\n\n}\n\n\n\nimpl<const N: usize> From<[u8; N]> for Digest<N> {\n\n fn from(bytes: [u8; N]) -> Self {\n\n Digest(Box::new(bytes))\n\n }\n\n}\n\n\n...
Rust
examples/gear/src/main.rs
Overpeek/gears
68746cf5dc7d14799b159d46d6872cebdd546f06
use gears::{ glam::{Mat4, Vec3}, load_obj, Buffer, ContextGPUPick, ContextValidation, EventLoopTarget, Frame, FrameLoop, FrameLoopTarget, FramePerfReport, ImmediateFrameInfo, InputState, KeyboardInput, MultiWriteBuffer, RenderRecordInfo, Renderer, RendererRecord, SyncMode, UpdateRecordInfo, VertexBu...
use gears::{ glam::{Mat4, Vec3}, load_obj, Buffer, ContextGPUPick, ContextValidation, EventLoopTarget, Frame, FrameLoop, FrameLoopTarget, FramePerfReport, ImmediateFrameInfo, InputState, KeyboardInput, MultiWriteBuffer, RenderRecordInfo, Renderer, RendererRecord, SyncMode, UpdateRecordInfo, VertexBu...
fn vertex_data() -> Vec<shader::VertexData> { load_obj(include_str!("../res/gear.obj"), None, |position, normal| { shader::VertexData { pos: position, norm: normal, } }) } fn reload_mesh(&self) { let vertices = Self::vertex_d...
fn init(frame: Frame, renderer: Renderer) -> Arc<RwLock<Self>> { let input = InputState::new(); let shader = shader::DefaultPipeline::build(&renderer).unwrap(); let vb = RwLock::new( shader .create_vbo_with(Self::vertex_data().as_slice()) .unwrap(), ...
function_block-full_function
[ { "content": "pub trait Uniform: PartialEq + Default {\n\n type Fields;\n\n type HasFields;\n\n}\n\n\n\nimpl Input for () {\n\n type Fields = ();\n\n const BINDING_DESCRIPTION: &'static [vk::VertexInputBindingDescription] = &[];\n\n const ATTRIBUTE_DESCRIPTION: &'static [vk::VertexInputAttributeD...
Rust
src/lib.rs
flodiebold/headers
417ddfeb42dcdd3275096d29de59ed67cd94e3fc
extern crate headers_core; #[allow(unused_imports)] #[macro_use] extern crate headers_derive; extern crate headers_ext; pub use headers_core::*; pub use headers_derive::*; pub use headers_ext::*; /* #[cfg(test)] mod tests { use std::fmt; use super::{Headers, Header, Raw, ContentLength, ContentType, Host, Se...
extern crate headers_core; #[allow(unused_imports)] #[macro_use] extern crate headers_derive; extern crate headers_ext; pub use headers_core::*; pub use headers_derive::*; pub use headers_ext::*; /* #[cfg(test)] mod tests { use std::fmt; use super::{Headers, Header, Raw, ContentLength, ContentType, Host, Se...
, headers2); headers1 = Headers::new(); headers2 = Headers::new(); headers1.set(Host::new("foo.bar", None)); headers1.set(ContentLength(11)); headers2.set(ContentLength(11)); assert_ne!(headers1, headers2); } #[test] #[cfg(feature = "compat")] fn test_c...
|&x| x == b':').unwrap(); make_header!(&bytes[..colon], &bytes[colon + 2..]) }) } #[test] fn test_from_raw() { let headers = make_header!(b"Content-Length", b"10"); assert_eq!(headers.get(), Some(&ContentLength(10))); } #[derive(Clone, PartialEq, Debug)] stru...
random
[ { "content": "/// Percent encode a sequence of bytes with a character set defined in\n\n/// [https://tools.ietf.org/html/rfc5987#section-3.2][url]\n\n///\n\n/// [url]: https://tools.ietf.org/html/rfc5987#section-3.2\n\npub fn http_percent_encode(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result {\n\n let ...
Rust
server/src/service/routes/audit_event/get.rs
gematik/ref-eRp-FD-Server
94d6245829a08d03c8d872ba71c5d8cae0d9dccf
/* * Copyright (c) 2021 gematik GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
/* * Copyright (c) 2021 gematik GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
) }); } if events.len() > MAX_COUNT { query.count = match query.count { Some(c) if c < MAX_COUNT => Some(c), _ => Some(MAX_COUNT), } } let page_id = query.page_id.unwrap_or_default(); let (skip, take) = if let Some(count) = query.count { ...
match arg { SortArgs::Date => { let a = &a.recorded; let b = &b.recorded; a.cmp(&b) } SortArgs::Agent => { let a = &a.agent.who; let b = &b.agent.who; ...
if_condition
[ { "content": "pub fn parse_key_value_list<I, F>(mut it: I, mut f: F) -> Result<(), String>\n\nwhere\n\n I: Iterator<Item = TokenTree>,\n\n F: FnMut(&str, TokenStream) -> Result<(), String>,\n\n{\n\n while let Some(ident) = it.next() {\n\n let ident = match ident {\n\n TokenTree::Ident...
Rust
juniper/src/macros/union.rs
neoeinstein/juniper
28763a563902b07cba6fe487e5fd9e1c5ef566e7
/** Expose GraphQL unions Like interfaces, mapping unions can be tricky in idiomatic Rust. Because of their similarity, the helper macros are similar, too: you provide a set of expressions that resolve the union into the actual concrete type. ## Syntax See the documentation for [`graphql_object!`][1] on the general ...
/** Expose GraphQL unions Like interfaces, mapping unions can be tricky in idiomatic Rust. Because of their similarity, the helper macros are similar, too: you provide a set of expressions that resolve the union into the actual concrete type. ## Syntax See the documentation for [`graphql_object!`][1] on the general ...
| &$mainself | { $( $items )* }); }; ( $name:ty : $ctxt:ty | &$mainself:ident | { $( $items:tt )* } ) => { graphql_union!(() $name : $ctxt as (stringify!($name)) | &$mainself | { $( $items )* }); }; }
$($items)*); } }); }; ( <$($lifetime:tt),*> $name:ty : $ctxt:ty as $outname:tt | &$mainself:ident | { $( $items:tt )* } ) => { graphql_union!( ($($lifetime),*) $name : $ctxt as $outname | &$mainself | { $( $items )* }); }...
random
[ { "content": "fn field_error_message(field_name: &str, arg_name: &str, type_name: &str) -> String {\n\n format!(\n\n r#\"Field \"{}\" argument \"{}\" of type \"{}\" is required but not provided\"#,\n\n field_name, arg_name, type_name\n\n )\n\n}\n\n\n", "file_path": "juniper/src/validatio...
Rust
src/index/zonemap.rs
o0Ignition0o/lever
339ae8208ef6be7c4ea8a9a7ad375f153488fa53
use crate::stats::bitonics::CountingBitonic; use crate::table::lotable::LOTable; use anyhow::*; use itertools::Itertools; use slice_group_by::GroupBy; use std::any::Any; use std::borrow::{Borrow, Cow}; use std::ops::{Deref, Range, RangeBounds}; use std::sync::Arc; #[derive(Default, Clone, Debug)] pub struct Zone { ...
use crate::stats::bitonics::CountingBitonic; use crate::table::lotable::LOTable; use anyhow::*; use itertools::Itertools; use slice_group_by::GroupBy; use std::any::Any; use std::borrow::{Borrow, Cow}; use std::ops::{Deref, Range, RangeBounds}; use std::sync::Arc; #[derive(Default, Clone, Debug)] pub struct Zone { ...
, ) -> usize where C: Into<String>, R: PartialOrd + std::fmt::Debug, { self.col_zones .get(&column.into()) .map_or(0_usize, |c| c.selectivity_range(range_min, range_max, data)) } pub fn scan_range<C, R>( &self, column: C, ...
|mut acc, e| { acc.0 = acc.0.min(e.min); acc.1 = acc.1.max(e.max); acc }) } pub fn zone_hits(&self, zone_id: usize) -> usize { self.zones.get(&zone_id).map_or(0, |z| z.hits()) } } #[derive(Debug, Clone)] pub struct ZoneMap { col...
random
[ { "content": "///\n\n/// Instantiate lever instance\n\npub fn lever() -> Lever {\n\n Lever(TxnManager::manager())\n\n}\n\n\n\nimpl Lever {\n\n ///\n\n /// Builder method for transactional optimistic, repeatable read in-memory table.\n\n pub fn new_lotable<K, V>(&self) -> LOTable<K, V>\n\n where\n...
Rust
src/sanitize.rs
wezm/sanitize-html-rs
820be5375568945c9aaced58f905f6cf86ba402d
use std::mem; use std::cell::RefCell; use html5ever::rcdom::{RcDom, Handle, Node}; use html5ever::rcdom::NodeData; use html5ever::tree_builder::TreeSink; use html5ever::interface::tree_builder::NodeOrText; use html5ever::interface; use html5ever::tendril::StrTendril; use html5ever::{namespace_url, ns}; use super::rule...
use std::mem; use std::cell::RefCell; use html5ever::rcdom::{RcDom, Handle, Node}; use html5ever::rcdom::NodeData; use html5ever::tree_builder::TreeSink; use html5ever::interface::tree_builder::NodeOrText; use html5ever::interface; use html5ever::tendril::StrTendril; use html5ever::{namespace_url, ns}; use super::rule...
fn create_space_text() -> Handle { let contents = StrTendril::from(" "); Node::new( NodeData::Text { contents: RefCell::new(contents) } ) } enum ElementAction<'t> { Keep(&'t Element), Delete, Space, Elide, Rename(&'t str), } fn element_action<'t>(element_name: &interface::Qua...
fn simple_element(dom: &mut RcDom, name: interface::QualName, attrs: Vec<interface::Attribute>, children: Vec<Handle>) -> Handle { let element = dom.create_element(name, attrs, Default::default()); for child in children { dom.remove_from_parent(&child); dom.append(&element, NodeOrText::AppendNod...
function_block-full_function
[ { "content": "/// Sanitize HTML string\n\npub fn sanitize_str(rules: &Rules, input: &str) -> Result<String, SanitizeError> {\n\n let result_bytes = sanitize_bytes(rules, input.as_bytes())?;\n\n let result_string = String::from_utf8(result_bytes).map_err(SanitizeError::Utf8Error)?;\n\n Ok(result_string)...
Rust
src/upload/mod.rs
at-tran/twitch-youtube-sync
db6755fa6eb40939c8d8f7ca3e1ac7c140416f69
mod auth; use crate::video::Video; use auth::get_auth_token; use reqwest::blocking::{Client, Response}; use reqwest::header::{CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, LOCATION}; use serde_json::json; use std::fs::File; use std::io::{Seek, SeekFrom}; use std::path::Path; use std::time::Duration; pub struct UploadS...
mod auth; use crate::video::Video; use auth::get_auth_token; use reqwest::blocking::{Client, Response}; use reqwest::header::{CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, LOCATION}; use serde_json::json; use std::fs::File; use std::io::{Seek, SeekFrom}; use std::path::Path; use std::time::Duration; pub struct UploadS...
.timeout(Duration::from_secs(3600 * 15)) .body(file) .send(); println!("{:?}", res); } fn get_upload_session_uri(video: &Video, auth_token: &str) -> String { let client = Client::new(); let req_body = json!({ "snippet": { "title": &vide...
.bearer_auth(&self.auth_token) .header(CONTENT_LENGTH, self.video.size - start_index) .header( CONTENT_RANGE, &format!( "bytes {}-{}/{}", start_index, self.video.size - 1, ...
function_block-random_span
[ { "content": "pub fn download_twitch_video<P: AsRef<Path>>(video_id: &str, save_folder: P) -> Video {\n\n let path = save_folder.as_ref().join(video_id).with_extension(\"mp4\");\n\n\n\n if !path.exists() {\n\n let (token, sig) = get_access_token(&get_client_id(), video_id);\n\n let m3u8_url ...
Rust
src/day14.rs
kiwiscott/aoc-2020
e1dc6904f81482ef76508e528cc27eb359b16794
use aoc_runner_derive::{aoc, aoc_generator}; use regex::Regex; use std::collections::HashMap; #[derive(Debug)] enum Ops { Mask(String), Mem(usize, usize), } #[aoc_generator(day14)] fn parse_input(input: &str) -> Vec<Ops> { lazy_static! { static ref RE: Regex = Regex::new(r"^(?P<op>\w+)...
use aoc_runner_derive::{aoc, aoc_generator}; use regex::Regex; use std::collections::HashMap; #[derive(Debug)] enum Ops { Mask(String), Mem(usize, usize), } #[aoc_generator(day14)] fn parse_input(input: &str) -> Vec<Ops> { lazy_static! { static ref RE: Rege
#[aoc(day14, part1)] fn part1(ops: &[Ops]) -> usize { let mut mask = String::from("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); let mut memory = HashMap::<usize, usize>::new(); for o in ops { match o { Ops::Mask(n) => { mask = n.to_string(); } Ops::M...
x = Regex::new(r"^(?P<op>\w+)(\[(?P<addr>\d+)\])? = (?P<value>[\dX]+)$").unwrap(); } input .lines() .map(|l| { let captures = RE.captures(l).unwrap(); match captures.name("op").unwrap().as_str() { "mask" => Ops::Mask(captures.name("value").unw...
function_block-function_prefixed
[ { "content": "#[aoc_generator(day18)]\n\nfn parse_input(input: &str) -> Vec<Vec<Op>> {\n\n input.lines().map(|s| to_vec_char(s.to_string())).collect()\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 0, "score": 157835.19088746252 }, { "content": "#[derive(Debug, Copy, Clone, PartialEq, ...
Rust
src/torrent.rs
CrimsonVoid/tsunami
a0bb50c8191e47199fa83ec5120d233bd25de5e4
use std::{collections::HashMap, ffi::OsStr, iter::once, path::PathBuf}; use crate::bencode::Bencode; #[derive(Debug, PartialEq)] pub struct Torrent { pub trackers_list: Vec<Vec<String>>, pub info: Info, pub info_hash: [u8; 20], } #[derive(Debug, PartialEq)] pub struct Info { ...
use std::{collections::HashMap, ffi::OsStr, iter::once, path::PathBuf}; use crate::bencode::Bencode; #[derive(Debug, PartialEq)] pub struct Torrent { pub trackers_list: Vec<Vec<String>>, pub info: Info, pub info_hash: [u8; 20], } #[derive(Debug, PartialEq)] pub struct Info { ...
fn build_files(info: &InfoAST) -> Option<Vec<File>> { let valid_path = |p: &str| p != "." && p != ".."; let mut tmp = [FileAST { path: vec![info.name], length: 0, }]; let (base_dir, f...
t> { let torrent = TorrentAST::decode(torrent_file)?; if torrent.info.pieces.len() % 20 != 0 { return None; } let pieces = torrent .info .pieces .chunks(20) .map(|p| p.try_into().unwrap()) .collect(); let ...
function_block-function_prefixed
[]
Rust
parallel-processor-rs/src/memory_data_size.rs
Guilucand/biloki
7c1d710bd03e797584e7f4db151d7b4c7b4433d7
#[macro_export] macro_rules! implement_display { ($($t:ty)*) => ($( impl ::std::fmt::Display for $t { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let (unit, value) = self.get_appropriate_units(); value.fmt(f)?; wri...
#[macro_export] macro_rules! implement_display { ($($t:ty)*) => ($( impl ::std::fmt::Display for $t { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let (unit, value) = self.get_appropriate_units(); value.fmt(f)?; wri...
#[test] fn kibioctet() { let i1 = MemoryDataSize::from_octets(100.0); let r1 = i1.as_kibioctets(); let i2 = MemoryDataSize::from_kibioctets(100.0); let r2 = i2.as_octets(); assert_almost_eq(r1, 0.09765625); assert_almost_eq(r2, 102400.0); } #[tes...
fn teraoctet() { let i1 = MemoryDataSize::from_octets(100.0); let r1 = i1.as_teraoctets(); let i2 = MemoryDataSize::from_teraoctets(100.0); let r2 = i2.as_octets(); assert_almost_eq(r1, 1e-10); assert_almost_eq(r2, 1e14); }
function_block-function_prefix_line
[ { "content": "pub fn cast_static_mut<T: ?Sized>(val: &mut T) -> &'static mut T {\n\n unsafe { std::mem::transmute(val) }\n\n}\n", "file_path": "src/utils/mod.rs", "rank": 0, "score": 290358.3317538741 }, { "content": "pub trait HashFunctionFactory: Ord + Sized + Clone + Debug + 'static {\...
Rust
src/lib.rs
uptimeventures/gotham-cors-middleware
11ab10e0afe1cbf49e7929aa2ff9a9cb406e8ad2
#[macro_use] extern crate gotham_derive; extern crate futures; extern crate gotham; extern crate hyper; extern crate unicase; use futures::Future; use gotham::handler::HandlerFuture; use gotham::middleware::Middleware; use gotham::state::{FromState, State}; use hyper::header::{ AccessControlAllowCredentials, Ac...
#[macro_use] extern crate gotham_derive; extern crate futures; extern crate gotham; extern crate hyper; extern crate unicase; use futures::Future; use gotham::handler::HandlerFuture; use gotham::middleware::Middleware; use gotham::state::{FromState, State}; use hyper::header::{ AccessControlAllowCr
nse = create_response( &state, StatusCode::Ok, Some((body.into_bytes(), mime::TEXT_PLAIN)), ); Box::new(future::ok((state, response))) } fn default_router() -> Router { let (chain, pipeline) = single_pipeline(new_pipeline().add(CORSMiddle...
edentials, AccessControlAllowHeaders, AccessControlAllowMethods, AccessControlAllowOrigin, AccessControlMaxAge, Headers, Origin, }; use hyper::Method; use std::option::Option; use unicase::Ascii; #[derive(Clone, NewMiddleware, Debug, PartialEq)] pub struct CORSMiddleware { methods: Vec<Method>, origin: Opt...
random
[ { "content": "# Gotham CORS Middleware\n\n\n\nThis library is aimed to provide CORS functionality to [Gotham.rs](https://gotham.rs/) servers.\n\n\n\nCurrently this is a very simple implementation with limited customisability.\n\n\n\nRequires rust 1.26 or later.\n\n\n\nUsage:\n\n```rust\n\nextern crate gotham;\n...
Rust
src/utils.rs
alecchendev/runner-game
8b5778c646432611d77fe9c93f1f652152a03942
pub fn set_panic_hook() { #[cfg(feature = "console_error_panic_hook")] console_error_panic_hook::set_once(); } #[derive(Clone, Copy)] pub struct Vec3 { pub x: f32, pub y: f32, pub z: f32, } impl Vec3 { pub fn new(x: f32, y: f32, z: f32) -> Self { Self { ...
pub fn set_panic_hook() { #[cfg(feature = "console_error_panic_hook")] console_error_panic_hook::set_once(); } #[derive(C
) -> Self { Self { x: self.x - other.x, y: self.y - other.y, z: self.z - other.z, } } } impl std::ops::SubAssign for Vec3 { fn sub_assign(&mut self, other: Self) { *self = Self { x: self.x - other.x, y: self.y - other.y, ...
lone, Copy)] pub struct Vec3 { pub x: f32, pub y: f32, pub z: f32, } impl Vec3 { pub fn new(x: f32, y: f32, z: f32) -> Self { Self { x, y, z, } } pub fn length(&self) -> f32 { (self.x.powi(2) + self.y.powi(2) + self.z.powi(2)).sqrt() ...
random
[ { "content": " pub fn colors(&self) -> Vec<f32> {\n\n self.colors.clone()\n\n }\n\n pub fn indices(&self) -> Vec<u32> {\n\n self.indices.clone()\n\n }\n\n pub fn cam_pos(&self) -> Vec<f32> {\n\n self.cam_pos.clone()\n\n }\n\n pub fn cam_theta(&self) -> f32 {\n\n ...
Rust
storage/src/object_store/s3.rs
MrCroxx/RunKV
0770ce449363a98814c80e343a4e6e6a029e5f6b
use std::ops::Range; use async_trait::async_trait; use aws_sdk_s3::error::{GetObjectError, GetObjectErrorKind}; use aws_sdk_s3::types::SdkError; use aws_sdk_s3::{Client, Endpoint, Region}; use aws_smithy_http::body::SdkBody; use super::ObjectStore; use crate::{ObjectStoreError, Result}; pub struct S3ObjectStore { ...
use std::ops::Range; use async_trait::async_trait; use aws_sdk_s3::error::{GetObjectError, GetObjectErrorKind}; use aws_sdk_s3::types::SdkError; use aws_sdk_s3::{Client, Endpoint, Region}; use aws_smithy_http::body::SdkBody; use super::ObjectStore; use crate::{ObjectStoreError, Result}; pub struct S3ObjectStore { ...
async fn remove(&self, path: &str) -> Result<()> { self.client .delete_object() .bucket(&self.bucket) .key(path) .send() .await .map_err(err)?; Ok(()) } }
range(format!("bytes={}-{}", range.start, range.end - 1)); let rsp = match req.send().await { Ok(rsp) => rsp, Err(SdkError::ServiceError { err: GetObjectError { kind: GetObjectErrorKind::NoSuchKey(..), .....
function_block-function_prefix_line
[]
Rust
cavern-macroquad-naive/src/global_state.rs
saveriomiroddi/Code-the-Classics-dev
6543dfc6fe3f5d725351bade9601af16f3454cc3
use macroquad::prelude::{collections::storage, draw_texture, is_key_pressed, KeyCode, WHITE}; use crate::{ drawing::{draw_game_text, CHAR_WIDTH, IMAGE_WIDTH}, game::Game, game_playback::play_game_sound, player::Player, resources::Resources, state::State, WIDTH, }; pub struct GlobalState { ...
use macroquad::prelude::{collections::storage, draw_texture, is_key_pressed, KeyCode, WHITE}; use crate::{ drawing::{draw_game_text, CHAR_WIDTH, IMAGE_WIDTH}, game::Game, game_playback::play_game_sound, player::Player, resources::Resources, state::State, WIDTH, }; pub struct GlobalState { ...
fn draw_status(&self) { let player = self.game.player.as_ref().unwrap(); let number_width = CHAR_WIDTH[0]; let s = player.score.to_string(); draw_game_text(&s, 451, Some(WIDTH - 2 - (number_width * s.len() as i32))); draw_game_text(&format!("LEV...
rame = (((self.game.timer + 40) % 160) / 4).min(9) as usize; draw_texture(resources.space_textures[anim_frame], 130., 280., WHITE); } State::Play => { self.draw_status(); } State::GameOver => { self.draw_status(); ...
function_block-function_prefixed
[ { "content": "pub fn resource_path(resource_path: &str) -> PathBuf {\n\n let manifest_dir = env::var(\"CARGO_MANIFEST_DIR\").unwrap();\n\n\n\n PathBuf::from(manifest_dir)\n\n .join(RESOURCES_RELATIVE_PATH)\n\n .join(resource_path)\n\n}\n", "file_path": "bunner-tetra/src/resource_path.rs"...
Rust
http-client/src/client/chooser/subnet.rs
qiniu/rust-sdk
f44b802302739c4a9fd80639d741c17c1f15189a
use super::{ super::super::{ regions::{DomainWithPort, IpAddrWithPort}, spawn::spawn, }, ChooseOptions, Chooser, ChooserFeedback, ChosenResults, }; use dashmap::DashMap; pub use ipnet::PrefixLenError; use ipnet::{Ipv4Net, Ipv6Net}; use log::{info, warn}; use std::{ collections::HashMap, ...
use super::{ super::super::{ regions::{DomainWithPort, IpAddrWithPort}, spawn::spawn, }, ChooseOptions, Chooser, ChooserFeedback, ChosenResults, }; use dashmap::DashMap; pub use ipnet::PrefixLenError; use ipnet::{Ipv4Net, Ipv6Net}; use log::{info, warn}; use std::{ collections::HashMap, ...
} impl SubnetChooserBuilder { #[inline] pub fn block_duration(&mut self, block_duration: Duration) -> &mut Self { self.inner.block_duration = block_duration; self } #[inline] pub fn shrink_interval(&mut self, shrink_interval: Duration) -> &mut Self { self.inner.s...
N, shrink_interval: DEFAULT_SHRINK_INTERVAL, ipv4_netmask_prefix_length: DEFAULT_IPV4_NETMASK_PREFIX_LENGTH, ipv6_netmask_prefix_length: DEFAULT_IPV6_NETMASK_PREFIX_LENGTH, }, } }
function_block-function_prefixed
[ { "content": "fn do_some_work_async(inner: &Arc<IpChooserInner>, need_to_shrink: bool) {\n\n if need_to_shrink && is_time_to_shrink(inner) {\n\n let cloned = inner.to_owned();\n\n if let Err(err) = spawn(\"qiniu.rust-sdk.http-client.chooser.IpChooser\".into(), move || {\n\n if is_tim...
Rust
src/scalable_bloom_filter.rs
zaeleus/bloom
3b8773d90c0250133dc96178ea7ded2c7c968948
use std::hash::{BuildHasher, Hash}; use crate::{BloomFilter, DefaultHashBuilder}; const GROWTH_FACTOR: usize = 2; const TIGHTENING_RATIO: f64 = 0.85; pub struct ScalableBloomFilter<S = DefaultHashBuilder> { n: usize, total_capacity: usize, filters: Vec<BloomFilter<S>>, last_fpp: ...
use std::hash::{BuildHasher, Hash}; use crate::{BloomFilter, DefaultHashBuilder}; const GROWTH_FACTOR: usize = 2; const TIGHTENING_RATIO: f64 = 0.85; pub struct ScalableBloomFilter<S = DefaultHashBuilder> { n: usize, total_capacity: usize, filters: Vec<BloomFilter<S>>, last_fpp: ...
fn grow(&mut self) { let p = self.last_fpp * TIGHTENING_RATIO; let n = self.total_capacity * GROWTH_FACTOR; let filter = BloomFilter::from_fpp_with_hashers(p, n, S::default(), S::default()); self.filters.push(filter); self.total_capacity += n; self.last_fpp = p; ...
pub fn contains_or_insert<H: Hash + ?Sized>(&mut self, key: &H) -> bool { let n = if self.filters.len() == 1 { 1 } else { self.filters.len() - 1 }; if self.filters.iter().take(n).any(|f| f.contains(key)) { true } else { !self.inser...
function_block-full_function
[ { "content": "fn hash<H, B>(key: &H, builder: &B) -> u64\n\nwhere\n\n H: Hash + ?Sized,\n\n B: BuildHasher,\n\n{\n\n let mut hasher = builder.build_hasher();\n\n key.hash(&mut hasher);\n\n hasher.finish()\n\n}\n", "file_path": "src/double_hasher.rs", "rank": 0, "score": 80790.33863175...
Rust
src/elements/table.rs
smallstepman/orgize
ae185d2f65f0f0cd8a3f7220f15714881118dd75
use std::borrow::Cow; use nom::{ error::{make_error, ErrorKind}, Err, IResult, }; use crate::parse::combinators::{blank_lines_count, line, lines_while}; #[derive(Debug, PartialEq, Clone)] #[cfg_attr(feature = "ser", derive(serde::Serialize))] #[cfg_attr(feature = "ser", serde(tag = "table_type"))] pub enum T...
use std::borrow::Cow; use nom::{ error::{make_error, ErrorKind}, Err, IResult, }; use crate::parse::combinators::{blank_lines_count, line, lines_while}; #[derive(Debug, PartialEq, Clone)] #[cfg_attr(feature = "ser", derive(serde::Serialize))] #[cfg_attr(feature = "ser", serde(tag = "table_type"))] pub enum T...
} } #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "ser", derive(serde::Serialize))] #[cfg_attr(feature = "ser", serde(tag = "table_row_type"))] #[cfg_attr(feature = "ser", serde(rename_all = "kebab-case"))] pub enum TableRow { Header, Body, HeaderRule, BodyRule, } #[...
match self { Table::Org { tblfm, post_blank, has_header, } => Table::Org { tblfm: tblfm.map(Into::into).map(Cow::Owned), post_blank, has_header, }, Table::TableEl { value, post...
if_condition
[ { "content": "// read until the first line_ending, if line_ending is not present, return the input directly\n\npub fn line(input: &str) -> IResult<&str, &str, ()> {\n\n if let Some(i) = memchr(b'\\n', input.as_bytes()) {\n\n if i > 0 && input.as_bytes()[i - 1] == b'\\r' {\n\n Ok((&input[i +...
Rust
diem/vendor/cipher/src/stream.rs
LeeMaster/phala-blockchain
0cefd3da2ac6e4dc7e9d5e42f2eeaec384705c1c
#[cfg(feature = "dev")] mod dev; mod errors; pub use errors::{InvalidKeyNonceLength, LoopError, OverflowError}; pub use generic_array::{self, typenum::consts}; #[cfg(feature = "dev")] pub use blobby; use crate::block::{BlockCipher, BlockCipherMut, NewBlockCipher}; use core::convert::{TryFrom, TryInto}; use gener...
#[cfg(feature = "dev")] mod dev; mod errors; pub use errors::{InvalidKeyNonceLength, LoopError, OverflowError}; pub use generic_array::{self, typenum::consts}; #[cfg(feature = "dev")] pub use blobby; use crate::block::{BlockCipher, BlockCipherMut, NewBlockCipher}; use core::convert::{TryFrom, TryInto}; use gener...
} impl<C> NewStreamCipher for C where C: FromBlockCipherMut, C::BlockCipher: NewBlockCipher, { type KeySize = <<Self as FromBlockCipherMut>::BlockCipher as NewBlockCipher>::KeySize; type NonceSize = <Self as FromBlockCipherMut>::NonceSize; fn new(key: &Key<Self>, nonce: &Nonce<Self>) -> C { ...
cipher: Self::BlockCipher, nonce: &GenericArray<u8, Self::NonceSize>, ) -> C { C::from_block_cipher(cipher, nonce) }
function_block-function_prefix_line
[ { "content": "/// Calculates the HMAC of `data` using the signing key `key`, and verifies\n\n/// whether the resultant value equals `tag`, in one step.\n\n///\n\n/// This is logically equivalent to, but more efficient than, constructing a\n\n/// `Key` with the same value as `key` and then using `verify`.\n\n///...
Rust
src/transpile/mod.rs
hegza/serpent-rs
1c17ac0ffb5e0d8f56871164d19d1c0ee11b3f3f
pub mod ast_to_ast; mod codegen; mod context; mod parser_ext; pub mod python; mod rs_ast; pub mod rust; use crate::{ config::{self, TranspileConfig}, output::TranspiledFileKind, }; use crate::{ error::ApiError, output::ModPath, output::TranspiledFile, output::TranspiledModule, output::TranspiledString,...
pub mod ast_to_ast; mod codegen; mod context; mod parser_ext; pub mod python; mod rs_ast; pub mod rust; use crate::{ config::{self, TranspileConfig}, output::TranspiledFileKind, }; use crate::{ error::ApiError, output::ModPath, output::TranspiledFile, output::TranspiledModule, output::TranspiledString,...
fn ast_to_ast( py_ast: &PythonAst, relative_mod_symbols: &[String], cfg: &TranspileConfig, ) -> Result<RustAst, crate::error::TranspileNodeError> { let mut ast_ctx = AstContext::new(&relative_mod_symbols, &py_ast.0, cfg); for node in py_ast.0.iter() { node.transpile(&mut ast_ctx)?; } ...
pub fn transpile_module_dir( dir_path: impl AsRef<path::Path>, cfg: &TranspileConfig, ) -> Result<TranspiledModule, ApiError> { let dir_path = dir_path.as_ref(); info!( "Transpiling module from directory {:?} with config {:?}", dir_path, cfg ); let py_module = PyModule::from_dir...
function_block-full_function
[ { "content": "pub fn insert_crate_local_mods(rust_ast: &mut RustAst, mod_symbols: &[String]) {\n\n for sym in mod_symbols {\n\n if sym != \"__init__\" {\n\n // Create the mod definition\n\n let node = create_mod_node(sym);\n\n\n\n // Insert at start\n\n rust...
Rust
crates/sdk/src/internal/data_tree.rs
polyphene/holium-rs-sdk
859ccda53515a381eac956f9ad24dcc4fe41dd2c
use crate::internal::key_tree::Node as KeyNode; use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_cbor::Value as CborValue; use std::collections::BTreeMap; #[derive(thiserror::Error, Debug)] enum Error { #[error("float types are currently unhandled")] FloatUnhandled, } #[derive(Debug, Parti...
use crate::internal::key_tree::Node as KeyNode; use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_cbor::Value as CborValue; use std::collections::BTreeMap; #[derive(thiserror::Error, Debug)] enum Error { #[error("float types are currently unhandled")] FloatUnhandled, } #[derive(Debug, Parti...
} } } } #[cfg(test)] mod tests { use serde::Serialize; use serde_cbor::value::to_value; use std::collections::BTreeMap; use crate::internal::key_tree::GenerateNode; use super::*; #[test] fn can_represent_null_value() { assert_eq!( Node::new(Cb...
if &key_node.children.len() > &(0usize) { let mut map: BTreeMap<CborValue, CborValue> = BTreeMap::new(); for (i, child) in self.children.iter().enumerate() { let key = &key_node.children.get(i).unwrap(); ma...
if_condition
[ { "content": "#[holium_bindgen]\n\npub fn pass11(a: Vec<u32>) -> Vec<u32> {\n\n a\n\n}\n\n\n", "file_path": "crates/macro/tests/proc-macro-tests/export.rs", "rank": 0, "score": 108790.36481364275 }, { "content": "#[holium_bindgen]\n\npub fn pass6(a: &GoodStruct) -> GoodStruct {\n\n Goo...
Rust
crates/mani/fabled_render/src/mesh/primitive/cube.rs
KDahir247/Fabled-Engine
31db8f20f9364ab707786f052fe6e314a77e7a5a
use crate::mesh::{Mesh, Model, Vertex}; #[repr(C, align(16))] #[derive(Debug)] struct CubeData { pub normal: [glam::Vec3A; 6], pub tangent: [glam::Vec3A; 6], pub bi_tangent: [glam::Vec3A; 6], } const CUBE_FACE_DATA: CubeData = CubeData { normal: [ glam::const_vec3a!([0.0, 0.0, 1.0]), ...
use crate::mesh::{Mesh, Model, Vertex}; #[repr(C, align(16))] #[derive(Debug)] struct CubeData { pub normal: [glam::Vec3A; 6], pub tangent: [glam::Vec3A; 6], pub bi_tangent: [glam::Vec3A; 6], } const CUBE_FACE_DATA: CubeData = CubeData { normal: [ glam::const_vec3a!([0.0, 0.0, 1.0]), ...
let face_vertices = [ first_vertex_chunk, second_vertex_chunk, third_vertex_chunk, fourth_vertex_chunk, ]; { let offset = (index + chunk) * 4; let (t...
let fourth_vertex_chunk = Vertex { position: face[3].to_array(), tex_coord: [0.0, 0.0], normal: normal.to_array(), tangent: [0.0; 4], bi_tangent: [0.0; 4], };
assignment_statement
[ { "content": "pub fn transform(vector: [f32; 4], quaternion: Rotation) -> [f32; 3] {\n\n let [x_pos, y_pos, z_pos, scalar] = vector;\n\n\n\n let [quat_i, quat_j, quat_k, quat_w] = quaternion.value;\n\n\n\n let inv_scalar = 1.0 / scalar;\n\n\n\n\n\n let [norm_x_pos, norm_y_pos, norm_z_pos] =\n\n ...
Rust
src/server_info/raw.rs
trickybestia/scpsl-api
1b286adc6c10f8099407469fd58068a62f3c8b5b
use super::RequestParameters; #[cfg(feature = "raw")] use super::{Player, Response, ServerInfo}; use reqwest::Error; use serde::Deserialize; #[cfg(feature = "raw")] use serde::Serialize; #[cfg_attr(feature = "raw", derive(Serialize, Clone))] #[derive(Deserialize)] pub struct RawResponse { #[allow(missing_docs)] ...
use super::RequestParameters; #[cfg(feature = "raw")] use super::{Player, Response, ServerInfo}; use reqwest::Error; use serde::Deserialize; #[cfg(feature = "raw")] use serde::Serialize; #[cfg_attr(feature = "raw", derive(Serialize, Clone))] #[derive(Deserialize)] pub struct RawResponse { #[allow(missing_docs)] ...
} #[cfg_attr(feature = "raw", derive(Serialize, Clone))] #[derive(Deserialize)] pub struct RawServerInfo { #[allow(missing_docs)] #[serde(rename = "ID")] pub id: u64, #[allow(missing_docs)] #[serde(rename = "Port")] pub port: u16, #[allow(missing_docs)] #[serde( rename = "LastO...
fn from(response: Response) -> Self { match response { Response::Success(success) => RawResponse { success: true, error: None, servers: Some( success .servers .into_iter() ...
function_block-full_function
[ { "content": " cooldown: raw.cooldown.unwrap(),\n\n servers: raw\n\n .servers\n\n .unwrap()\n\n .into_iter()\n\n .map(ServerInfo::from)\n\n .collect(),\n\n })\n\n }\n\n ...
Rust
src/fallback.rs
pedrosland/url-decode-simd
15aa44ea3a61970a98cd00fb1abbe9fd98046125
use std::slice; use std::borrow::Cow; #[inline] fn percent_decode(input: &[u8]) -> PercentDecode { PercentDecode { bytes: input.iter(), } } fn replace_plus(input: &[u8]) -> Cow<[u8]> { match input.iter().position(|&b| b == b'+') { None => Cow::Borrowed(input), Some(first_position...
use std::slice; use std::borrow::Cow; #[inline] fn percent_decode(input: &[u8]) -> PercentDecode { PercentDecode { bytes: input.iter(), } } fn replace_plus(input: &[u8]) -> Cow<[u8]> { match input.iter().position(|&b| b == b'+') { None => Cow::Borrowed(input), Some(first_position...
let v = b"\xCF%%sA\x00`A%5%%6%6\xEF"; url_decode(v, &mut result); assert_eq!(b"\xCF%%sA\x00`A%5%%6%6\xEF", &result[..]); } }
url_decode(v, &mut result); assert_eq!(b"%1-2345678901234", &result[..]); } #[test] fn test_end_percent() { let mut result = Vec::new(); let v = b"aaaaaaaaaaaaaaa%"; url_decode(v, &mut result); assert_eq!(b"aaaaaaaaaaaaaaa%", &result[..]); ...
random
[ { "content": "#[inline]\n\n#[allow(unreachable_code)]\n\npub fn url_decode(src: &[u8], dst: &mut Vec<u8>) {\n\n #[cfg(all(target_feature = \"sse4.1\", target_feature = \"popcnt\"))]\n\n return unsafe { sse41::url_decode(src, dst) };\n\n\n\n fallback::url_decode(src, dst);\n\n}\n\n\n\n#[cfg(test)]\n\nmo...
Rust
day-04/src/main.rs
Walther/adventofcode18
4af32eb4d77ff7d8e99190d34b2e2525a8330486
use std::collections::HashMap; extern crate regex; use regex::Regex; struct Guard { id: i32, sleeps: Vec<Sleep>, } impl Guard { pub fn new(id: i32) -> Guard { Guard { id, sleeps: Vec::new(), } } pub fn sleep_total(&self) -> i32 { self.sleeps.iter()....
use std::collections::HashMap; extern crate regex; use regex::Regex; struct Guard { id: i32, sleeps: Vec<Sleep>, } impl Guard { pub fn new(id: i32) -> Guard { Guard { id, sleeps: Vec::new(), } } pub fn sleep_total(&self) -> i32 { self.sleeps.iter()....
fn times_slept_at_minute(&self, minute: i32) -> i32 { let sleep_stats = &self.minute_sleep_counts(); *sleep_stats.get(&minute).unwrap() } pub fn strategy2(&self) -> i32 { self.times_slept_at_minute(self.most_slept_minute()) } } struct Sleep { start: i32, end...
for (stat_minute, stat_count) in sleep_stats.iter() { if count < *stat_count { minute = *stat_minute; count = *stat_count; } } minute }
function_block-function_prefix_line
[ { "content": "fn parse(numbers: &Vec<i32>, mut position: usize) -> (Node, usize) {\n\n let mut node = Node::new();\n\n\n\n let num_children = numbers[position];\n\n position += 1;\n\n let num_metadata = numbers[position];\n\n position += 1;\n\n\n\n while node.children.len() < num_children as u...
Rust
src/engine/shader.rs
TomCrypto/equinox
915d40238f2b6d8258727b74a68ed2d4cd2702d4
#[allow(unused_imports)] use log::{debug, error, info, warn}; use crate::{shader::ShaderInfo, Framebuffer}; use js_sys::Error; use regex::Regex; use std::collections::HashMap; use web_sys::{ WebGl2RenderingContext as Context, WebGlBuffer, WebGlProgram, WebGlShader, WebGlTexture, WebGlVertexArrayObject, }; #[d...
#[allow(unused_imports)] use log::{debug, error, info, warn}; use crate::{shader::ShaderInfo, Framebuffer}; use js_sys::Error; use regex::Regex; use std::collections::HashMap; use web_sys::{ WebGl2RenderingContext as Context, WebGlBuffer, WebGlProgram, WebGlShader, WebGlTexture, WebGlVertexArrayObject, }; #[d...
fn determine_real_position(source: &str, line: u32) -> (String, u32) { let pattern = Regex::new(r#"^// __POS__ ([^:]+):([0-9]+)$"#).unwrap(); let lines: Vec<&str> = source.lines().collect(); for index in (0..line).rev() { if let Some(captures) = pattern.captures(lines[in...
for line in glsl_source.lines() { if let Some(captures) = pattern.captures(line) { let header = captures.get(1).unwrap().as_str(); if let Some(code) = headers.get(header) { source += code; source += "\n"; continue; ...
function_block-function_prefix_line
[ { "content": "fn vec_contains(vec: &[String], item: &str) -> bool {\n\n vec.iter().any(|x| x == item) // see issue #42671\n\n}\n", "file_path": "build.rs", "rank": 0, "score": 219623.87662177708 }, { "content": "fn preprocess_shaders(dir: &str, ext: &str, include_path: &str) -> Result<()>...
Rust
git-lock/src/backoff.rs
xmo-odoo/gitoxide
a77d14ce5e107a5e20ed7e66237254826ea9dab1
use std::time::Duration; pub fn randomize(backoff_ms: usize) -> usize { let new_value = (fastrand::usize(750..=1250) * backoff_ms) / 1000; if new_value == 0 { backoff_ms } else { new_value } } pub struct Exponential<Fn> { multiplier: usize, max_multiplier: usize, exponent: ...
use std::time::Duration; pub fn randomize(backoff_ms: usize) -> usize { let new_value = (fastrand::usize(750..=1250) * backoff_ms) / 1000; if new_value == 0 { backoff_ms } else { new_value } } pub struct Exponential<Fn> { multiplier: usize, max_multiplier: usize, exponent: ...
ollect::<Vec<_>>(), EXPECTED_TILL_SECOND .iter() .map(|n| Duration::from_millis(*n as u64)) .collect::<Vec<_>>() ); } }
random_exponential_produces_values_in_the_correct_range() { let mut num_identities = 0; for (actual, expected) in Exponential::default_with_random().zip(EXPECTED_TILL_SECOND) { let actual: usize = actual.as_millis().try_into().unwrap(); if actual == *expected { n...
random
[]
Rust
sos21-domain/src/model/registration_form_answer.rs
sohosai/sos21-backend
f1883844b0e5c68d6b3f9d159c9268142abc81b4
use crate::context::{ConfigContext, RegistrationFormAnswerRepository}; use crate::model::date_time::DateTime; use crate::model::form; use crate::model::form_answer::FormAnswerItems; use crate::model::pending_project::PendingProject; use crate::model::permissions::Permissions; use crate::model::project::Project; use cra...
use crate::context::{ConfigContext, RegistrationFormAnswerRepository}; use crate::model::date_time::DateTime; use crate::model::form; use crate::model::form_answer::FormAnswerItems; use crate::model::pending_project::PendingProject; use crate::model::permissions::Permissions; use crate::model::project::Project; use cra...
pub fn from_content(content: RegistrationFormAnswerContent) -> Self { RegistrationFormAnswer { content } } pub fn into_content(self) -> RegistrationFormAnswerContent { self.content } pub fn id(&self) -> RegistrationFormAnswerId { self.content...
pub async fn new<C>( ctx: C, author: &User, pending_project: &PendingProject, registration_form: &RegistrationForm, items: FormAnswerItems, ) -> DomainResult<Self, NewRegistrationFormAnswerError> where C: RegistrationFormAnswerRepository + ConfigContext, { ...
function_block-full_function
[ { "content": "pub fn new_registration_form_with_items(author_id: UserId, items: FormItems) -> RegistrationForm {\n\n RegistrationForm {\n\n id: new_registration_form_id(),\n\n created_at: DateTime::now(),\n\n author_id,\n\n name: mock_registration_form_name(),\n\n descripti...
Rust
src/byte_slice/mod.rs
ranging-rs/ranging
388225323797df104999116b19b598d6e212d82b
use crate::abstra::NewLike; use crate::slices::{ByteSlice, SliceBackedChoice, SliceDefault}; #[cfg(feature = "no_std_vec")] extern crate alloc; #[cfg(feature = "no_std_vec")] use alloc::vec::Vec; pub const fn num_bits_to_bytes(num_bits: usize) -> usize { let divided = num_bits / 8; if num_bits == divided * 8 {...
use crate::abstra::NewLike; use crate::slices::{ByteSlice, SliceBackedChoice, SliceDefault}; #[cfg(feature = "no_std_vec")] extern crate alloc; #[cfg(feature = "no_std_vec")] use alloc::vec::Vec; pub const fn num_bits_to_bytes(num_bits: usize) -> usize { let divided = num_bits / 8; if num_bits == divided * 8 {...
)), } } fn to_array_based(&self) -> Self { unimplemented!("Never") } #[cfg(any(not(feature = "no_std"), feature = "no_std_vec"))] fn to_vec_based(self) -> Self { unimplemented!("Never") } #[cfg(any(not(feature = "no_std"), feature = "no_std_vec"))] fn to_non_ar...
e.get(index / 8); get_bit(byte, index % 8) } fn set(&mut self, index: usize, value: &bool) { let (byte_index, _, new_byte) = self.dry_run_set(index, value); self.byte_slice.set(byte_index, &new_byte); } fn check_and_set(&mut self, index: usize, value: &bool) -> bool { let...
random
[ { "content": "fn clone_array<T: Clone, const N: usize>(from: &[T; N]) -> [T; N] {\n\n from.clone()\n\n}\n", "file_path": "src/slices/mod.rs", "rank": 1, "score": 125220.04821057899 }, { "content": "fn indexer_usize() -> RangeIndexer<usize> {\n\n RangeIndexer::new(&0)\n\n}\n\n\n", "...
Rust
src/connect4/board/test.rs
JulianCO/discord-c4
ec4645189bc5ab9dcef6706e7894871a8710ef08
use super::*; fn test_game(moves: &[u8], expected_result: GameResult) { let mut e = Board::empty_board(); for k in moves { assert!(e.is_move_legal(*k)); e.play_move(*k); } assert!(e.game_status() == GameStatus::GameOver(expected_result)); } #[test] fn empty_is_empty() { let e = Boa...
use super::*; fn test_game(moves: &[u8], expected_result: GameResult) { let mut e = Board::empty_board(); for k in moves { assert!(e.is_move_legal(*k)); e.play_move(*k); } assert!(e.game_status() == GameStatus::GameOver(expected_result)); } #[test] fn empty_is_empty() { let e = Boa...
#[test] fn test_game_3() { let game = vec![ 2, 3, 3, 3, 2, 2, 5, 5, 3, 5, 5, 2, 2, 6, 6, 3, 3, 5, 4, 0, 0, 0, 5, 6, 1, 1, 1, 6, 0, 4, ]; test_game(&game, GameResult::Winner(Player::Blue)); } #[test] fn test_game_4() { let game = vec![ 4, 3, 3, 3, 3, 4, 5, 4, 4, 0, 3, 0, 3, 4, 2, 4, 1,...
fn test_game_2() { let game = vec![ 3, 3, 3, 5, 5, 2, 3, 3, 2, 2, 2, 2, 6, 1, 4, 6, 6, 6, 1, 3, 1, 0, 1, 1, 4, 6, 4, ]; test_game(&game, GameResult::Winner(Player::Red)); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_sequencial_games_in_database() {\n\n let _ = fs::remove_file(\"test3.sqlite\");\n\n let mut conn = initialize(\"test3.sqlite\").expect(\"Failed to create database\");\n\n\n\n let game1 = vec![\n\n 3, 3, 2, 1, 3, 5, 2, 2, 4, 3, 1, 2, 5, 1, 1, 3, 5, 5, 5, 2, 1, 2,\...
Rust
day_3/src/main.rs
asaaki/advent-of-code-2019
7f3e166c13595e60cb3a08f1b1b90b4fa6a20430
use clap::{App, Arg}; use std::fs; use std::fs::File; use std::io::{BufRead, BufReader}; type Coord = isize; type Distance = isize; type Distances = Vec<Distance>; #[derive(Debug)] enum Orientation { Horizontal, Vertical, } type LineOp = (Coord, Orientation); type LineOps = Vec<LineOp>; #[derive(Debug, Cl...
use clap::{App, Arg}; use std::fs; use std::fs::File; use std::io::{BufRead, BufReader}; type Coord = isize; type Distance = isize; type Distances = Vec<Distance>; #[derive(Debug)] enum Orientation { Horizontal, Vertical, } type LineOp = (Coord, Orientation); type LineOps = Vec<LineOp>; #[derive(Debug, Cl...
} }) .collect() } fn calculate_line(start: Point, line_ops: LineOps) -> Line { use Orientation::*; let mut next_point = start; let mut last_steps = 0; let mut line = Line::default(); for (pos, (coord, orientation)) in line_ops.iter().enumerate() { let point = match ...
rap(); match direction { "L" => (-length_abs, Horizontal), "R" => (length_abs, Horizontal), "U" => (length_abs, Vertical), "D" => (-length_abs, Vertical), d => panic!("Invalid direction encountered: {}", d),
function_block-random_span
[ { "content": "fn string2vec(input: String) -> Vec<String> {\n\n input.chars().map(|c| c.to_string()).collect()\n\n}\n\n\n", "file_path": "day_4/src/main.rs", "rank": 8, "score": 135207.8445093508 }, { "content": "fn int2vec(input: Code) -> Vec<String> {\n\n string2vec(format!(\"{}\", i...
Rust
src/workflow/config.rs
capterqa/cli
386be95f868be8f7a4b823dfb7b0200d31d530bb
use crate::utils::exit_with_code; use path_clean::PathClean; use serde::{Deserialize, Serialize}; use std::{ collections::{BTreeMap, HashMap}, fs::{create_dir_all, read_to_string, OpenOptions}, io::Write, path::PathBuf, }; const EXAMPLE_WORKFLOW: &str = r#"name: example env: URL: https://fake-api.cap...
use crate::utils::exit_with_code; use path_clean::PathClean; use serde::{Deserialize, Serialize}; use std::{ collections::{BTreeMap, HashMap}, fs::{create_dir_all, read_to_string, OpenOptions}, io::Write, path::PathBuf, }; const EXAMPLE_WORKFLOW: &str = r#"name: example env: URL: https://fake-api.cap...
; let result = WorkflowConfig::from_yaml(yaml); match result { Ok(mut workflow_config) => { if workflow_config.file.is_none() { workflow_config.file = Some(path.to_owned()); } workflow_config ...
match read_to_string(&path) { Ok(val) => val, _ => exit_with_code(exitcode::CONFIG, Some(&format!("Failed to read {}", path))), }
if_condition
[ { "content": "pub fn to_be_true(a: &Value, _b: &Value, not: bool) -> Option<String> {\n\n if let Some(val) = a.as_bool() {\n\n let result = val == true;\n\n if utils::did_pass(result, not) {\n\n return None;\n\n }\n\n }\n\n\n\n Some(format!(\"expected {} {} be true\", a,...
Rust
src/al/play.rs
leod/webglee
7b9e27b5bea9ef260bd811b492836f7174bc7fb9
use nalgebra::{Point3, Vector3}; use thiserror::Error; use wasm_bindgen::JsValue; use web_sys::{AudioBufferSourceNode, AudioNode, DistanceModelType, PannerNode, PanningModelType}; use super::Sound; #[derive(Debug, Error)] pub enum PlayError { #[error("failed web audio call: {0:?}")] WebAudio(JsValue), } #[d...
use nalgebra::{Point3, Vector3}; use thiserror::Error; use wasm_bindgen::JsValue; use web_sys::{AudioBufferSourceNode, AudioNode, DistanceModelType, PannerNode, PanningModelType}; use super::Sound; #[derive(Debug, Error)] pub enum PlayError { #[error("failed web audio call: {0:?}")] WebAudio(JsValue), } #[d...
} pub type PlayNode = AudioBufferSourceNode; pub struct SpatialPlayNode { pub source: AudioBufferSourceNode, pub panner: PannerNode, } pub fn play_node(sound: &Sound) -> Result<PlayNode, PlayError> { let al = sound.al(); let source = al .context() .create_buffer_source() .map...
fn default() -> Self { Self { cone_inner_angle: 360.0, cone_outer_angle: 360.0, cone_outer_gain: 0.3, panning_model: PanningModelType::Hrtf, distance_model: DistanceModelType::Linear, max_distance: 1000.0, ref_distance: 30.0, ...
function_block-full_function
[ { "content": "/// Build a 3x3 matrix that applies transformations in this order: first\n\n/// scaling, then translation.\n\npub fn scale_translate3(scale: Vector2<f32>, offset: Vector3<f32>) -> Matrix3<f32> {\n\n #[rustfmt::skip]\n\n let transform = Matrix3::new(\n\n scale.x, 0.0, offset.x,\n\n...
Rust
src/main.rs
jsimmons/concurrency
0bddc198fbfc1f6fdd45249b8c2c65f3c99fe59b
use std::os::unix::thread::JoinHandleExt; use std::{ cell::UnsafeCell, sync::{ atomic::{AtomicU64, AtomicUsize, Ordering}, Arc, Barrier, RwLock, }, thread, time::Instant, }; use libc::{self, setpriority, PRIO_PROCESS}; trait Universe { fn name(&self) -> &'static str; fn ste...
use std::os::unix::thread::JoinHandleExt; use std::{ cell::UnsafeCell, sync::{ atomic::{AtomicU64, AtomicUsize, Ordering}, Arc, Barrier, RwLock, }, thread, time::Instant, }; use libc::{self, setpriority, PRIO_PROCESS}; trait Universe { fn name(&self) -> &'static str; fn ste...
} }); frame_times.clear(); println!( "took {:?} for {} steps over {} frames", duration, verse.step_count(), num_frames, ); println!( "min: {:.2}ms max: {:.2}ms avg: {:.2}ms", stats.min * 1000.0, ...
if use_prio { unsafe { setpriority( PRIO_PROCESS, thread.as_pthread_t() as u32, if world_type == WorldType::Slow { 10 } else { ...
random
[]
Rust
src/year2020/day12/mod.rs
haraldmaida/advent-of-code
1d1f0e1dfad6ecbef5fd9c2be37ad44ba6a183fa
use std::ops::{Add, AddAssign}; use std::str::FromStr; pub type Mile = i32; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Navigate { Forward(Mile), North(Mile), East(Mile), South(Mile), West(Mile), RotateLeft(Angle), RotateRight(Angle), } #[derive(Debug, Clone, Copy, PartialEq, ...
use std::ops::{Add, AddAssign}; use std::str::FromStr; pub type Mile = i32; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Navigate { Forward(Mile), North(Mile), East(Mile), South(Mile), West(Mile), RotateLeft(Angle), RotateRight(Angle), } #[derive(Debug, Clone, Copy, PartialEq, ...
} #[aoc(day12, part1)] pub fn part1_distance_to_final_position(instructions: &[Navigate]) -> Mile { let mut ship = Ship::default(); let start_position = ship.position; AutoPilot1::execute(instructions, &mut ship); ship.position.manhattan_distance(start_position) } #[derive(Debug, Clone, Copy)] pub st...
fn apply(instruction: Navigate, ship: &mut Ship) { match instruction { Navigate::Forward(miles) => ship.move_(miles, ship.facing), Navigate::North(miles) => ship.move_(miles, Direction::North), Navigate::East(miles) => ship.move_(miles, Direction::East), Navigate:...
function_block-full_function
[ { "content": "#[aoc(day2, part1)]\n\npub fn product_of_final_position(route: &[Move]) -> i32 {\n\n let final_position = simulate_navigation::<Position>(route);\n\n final_position.x * final_position.depth\n\n}\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\npub struct AimedPosition {\n\n x: i32,\...
Rust
bootloader/src/main.rs
srikwit/chocolate_milk
8270e5d2f03179c59c5c0dba65705ffbeb86c426
#![feature(panic_info_message, rustc_private, alloc_error_handler)] #![no_std] #![no_main] extern crate compiler_builtins; extern crate core_reqs; #[allow(unused_imports)] #[macro_use] extern crate alloc; #[macro_use] mod print; mod realmode; mod mm; mod panic; mod pxe; mod intrins; use core::sync::atomic::{Atomi...
#![feature(panic_info_message, rustc_private, alloc_error_handler)] #![no_std] #![no_main] extern crate compiler_builtins; extern crate core_reqs; #[allow(unused_imports)] #[macro_use] extern crate alloc; #[macro_use] mod print; mod realmode; mod mm; mod panic; mod pxe; mod intrins; use core::sync::atomic::{Atomi...
extern fn entry(bootloader_end: usize) -> ! { { let mut serial = BOOT_ARGS.serial.lock(); if serial.is_none() { *serial = Some(unsafe { SerialPort::new() }); core::mem::drop(serial); for _ in 0..100 { print...
function_block-full_function
[ { "content": "/// Initialize the physical memory manager. Here we get the memory map from the\n\n/// BIOS via E820 and put it into a `RangeSet` for tracking and allocation.\n\n/// We also subtract off the first 1 MiB of memory to prevent BIOS data\n\n/// structures from being overwritten.\n\npub fn init() {\n\n...
Rust
rlink-connectors/kafka-connector/src/source/consumer.rs
yorkart/rlink-rs
3bbbc049ac71c412f585d641328441bb830c898d
use std::collections::HashMap; use std::sync::Mutex; use std::time::Duration; use futures::StreamExt; use rdkafka::consumer::{Consumer, DefaultConsumerContext, StreamConsumer}; use rdkafka::{ClientConfig, Message, Offset, TopicPartitionList}; use rlink::channel::TrySendError; use rlink::utils; use rlink::utils::get_ru...
use std::collections::HashMap; use std::sync::Mutex; use std::time::Duration; use futures::StreamExt; use rdkafka::consumer::{Consumer, DefaultConsumerContext, StreamConsumer}; use rdkafka::{ClientConfig, Message, Offset, TopicPartitionList}; use rlink::channel::TrySendError; use rlink::utils; use rlink::utils::get_ru...
}
s += 1; tokio::time::delay_for(Duration::from_millis(100)).await; } Err(TrySendError::Disconnected(_r)) => { panic!("handover produce `Disconnected`"); } ...
function_block-function_prefixed
[ { "content": "pub fn create_mem_channel(chain_id: u32, task_number: u16) -> (ElementSender, ElementReceiver) {\n\n info!(\n\n \"Create memory channel `chain_id`={}, `task_number`={}\",\n\n chain_id, task_number\n\n );\n\n\n\n let key = format!(\"{}-{}\", chain_id, task_number);\n\n\n\n ...
Rust
src/sensors/ultrasonic_sensor.rs
MassiminoilTrace/ev3dev-lang-rust
728d86d25139b7d3d680a494fcb13ca9657e8cfa
use std::cell::Cell; use super::SensorPort; use crate::{Attribute, Device, Driver, Ev3Error, Ev3Result}; #[derive(Debug, Clone, Device)] pub struct UltrasonicSensor { driver: Driver, cm_scale: Cell<Option<f32>>, in_scale: Cell<Option<f32>>, } impl UltrasonicSensor { fn new(driver: Driver) -> Self {...
use std::cell::Cell; use super::SensorPort; use crate::{Attribute, Device, Driver, Ev3Error, Ev3Result}; #[derive(Debug, Clone, Device)] pub struct UltrasonicSensor { driver: Driver, cm_scale: Cell<Option<f32>>, in_scale: Cell<Option<f32>>, } impl UltrasonicSensor { fn new(driver: Driver) -> Self {...
f) -> Ev3Result<f32> { let scale_field = self.in_scale.get(); let scale = match scale_field { Some(s) => s, None => { let decimals = self.get_decimals()?; let s = 10f32.powi(-decimals); self.in_scale.set(Some(s)); s ...
pub const MODE_US_SI_CM: &'static str = "US-SI-CM"; pub const MODE_US_SI_IN: &'static str = "US-SI-IN"; pub const MODE_US_DC_CM: &'static str = "US-DC-CM"; pub const MODE_US_DC_IN: &'static str = "US-DC-IN"; sensor!(); pub fn set_mode_us_dist_cm(&self) -> Ev3R...
random
[ { "content": "/// Speak the given text aloud.\n\npub fn speak(text: &str) -> Ev3Result<Child> {\n\n let espeak = Command::new(\"/usr/bin/espeak\")\n\n .args(&[\"--stdout\", \"-a\", \"200\", \"-s\", \"130\", text])\n\n .stdout(Stdio::piped())\n\n .spawn()?;\n\n\n\n Ok(Command::new(\"/u...
Rust
src/day22/mod.rs
MikkelPaulson/advent-of-code-2019
2f0d672f4b7c5137e252c5a9257918d4967e726b
use std::collections::HashSet; use std::mem; use std::str::FromStr; use super::math; pub fn part1(input: &str) -> Result<u64, String> { let cards = deal_with_deck_size(&parse(input)?, 10007); cards .iter() .enumerate() .find_map(|(i, &card)| if card == 2019 { Some(i as u64) } else { N...
use std::collections::HashSet; use std::mem; use std::str::FromStr; use super::math; pub fn part1(input: &str) -> Result<u64, String> { let cards = deal_with_deck_size(&parse(input)?, 10007); cards .iter() .enumerate() .find_map(|(i, &card)| if card == 2019 { Some(i as u64) } else { N...
rive(Debug)] enum Instruction<T: FromStr> { CutLeft(T), CutRight(T), DealWithIncrement(T), DealIntoNewStack, } impl Instruction<u64> { fn get_period(&self, deck_size: u64) -> u64 { match self { Self::CutLeft(i) => deck_size / (math::gcd(deck_size as i64, *i as i64) as u64), ...
let cards: Vec<u64> = (0..10) .map(|i| card_at(&instructions, i, DECK_SIZE, shuffles).unwrap()) .collect(); println!("{} shuffles: {:?}", shuffles, cards); return Ok(shuffles); } } Err("Not found".to_string()) /* let instructions =...
random
[ { "content": "pub fn part1(input: &str) -> Result<u64, String> {\n\n let map = parse(input);\n\n\n\n let mut orbit_count = 0;\n\n\n\n let body_ids = map.keys().cloned().collect::<Vec<BodyID>>();\n\n for body_id in body_ids {\n\n orbit_count += get_orbit_count(&body_id, &map);\n\n }\n\n\n\n...
Rust
mc-server-wrapper/src/ui.rs
Zokalyx/mc-server-wrapper
387e3a48f157f6ca2c0c9d4c74d1d05098ca2a26
use std::{ collections::{BTreeMap, VecDeque}, fmt::Display, }; use chrono::{Duration, Local, TimeZone, Utc}; use crossterm::event::{Event, KeyCode}; use tui::{ backend::Backend, layout::{Constraint, Direction, Layout, Rect}, style::{Color, Style}, text::{Span, Spans}, widgets::{Block, Borde...
use std::{ collections::{BTreeMap, VecDeque}, fmt::Display, }; use chrono::{Duration, Local, TimeZone, Utc}; use crossterm::event::{Event, KeyCode}; use tui::{ backend::Backend, layout::{Constraint, Direction, Layout, Rect}, style::{Color, Style}, text::{Span, Spans}, widgets::{Block, Borde...
} #[derive(Debug)] pub struct PlayersState; impl PlayersState { fn draw<B: Backend>( &self, f: &mut Frame<B>, area: Rect, online_players: &BTreeMap<String, OnlinePlayerInfo>, ) { let now_utc = Utc::now(); let online_players = online_play...
bar.complete = percent; } } None => { self.progress_bar = Some(ProgressBarState { complete: percent, out_of: 100, }) } } }
function_block-function_prefix_line
[ { "content": "/// Helper to make a status for the bot\n\npub fn activity(name: String) -> Activity {\n\n Activity {\n\n application_id: None,\n\n assets: None,\n\n buttons: vec![],\n\n created_at: None,\n\n details: None,\n\n emoji: None,\n\n flags: None,\n\n ...
Rust
src/client_server/context.rs
wrott/conduit
cb9655c016e43dd0bee0d37176703bd3875db716
use crate::{database::DatabaseGuard, ConduitResult, Error, Ruma}; use ruma::{ api::client::{error::ErrorKind, r0::context::get_context}, events::EventType, }; use std::collections::HashSet; use std::convert::TryFrom; #[cfg(feature = "conduit_bin")] use rocket::get; #[cfg_attr( feature = "conduit_bin", ...
use crate::{database::DatabaseGuard, ConduitResult, Error, Ruma}; use ruma::{ api::client::{error::ErrorKind, r0::context::get_context}, events::EventType, }; use std::collections::HashSet; use std::convert::TryFrom; #[cfg(feature = "conduit_bin")] use rocket::get; #[cfg_attr( feature = "conduit_bin", ...
r::BadRequest(ErrorKind::InvalidParam, "Limit value is invalid.") })? as usize / 2, ) .filter_map(|r| r.ok()) .collect(); for (_, event) in &events_after { if !db.rooms.lazy_load_was_sent_before( &sender_user, &sender_device, ...
function_block-function_prefixed
[ { "content": "#[tracing::instrument(skip(db, body))]\n\npub fn get_room_state_ids_route(\n\n db: DatabaseGuard,\n\n body: Ruma<get_room_state_ids::v1::Request<'_>>,\n\n) -> ConduitResult<get_room_state_ids::v1::Response> {\n\n if !db.globals.allow_federation() {\n\n return Err(Error::bad_config(...
Rust
src/lib.rs
LukasKalbertodt/confique
cc1681bf5359f3cb599e37cca2af7eb344828878
#[cfg(any(feature = "toml", feature = "yaml"))] use std::path::PathBuf; use serde::Deserialize; #[doc(hidden)] pub mod internal; mod builder; mod env; mod error; pub mod meta; #[cfg(any(feature = "toml", feature = "yaml"))] mod format; #[cfg(any(feature = "toml", feature = "yaml"))] mod file; #[cfg(feature = "t...
#[cfg(any(feature = "toml", feature = "yaml"))] use std::path::PathBuf; use serde::Deserialize; #[doc(hidden)] pub mod internal; mod builder; mod env; mod error; pub mod meta; #[cfg(any(feature = "toml", feature = "yaml"))] mod format; #[cfg(any(feature = "toml", feature = "yaml"))] mod file; #[cfg(feature = "t...
} pub trait Partial: for<'de> Deserialize<'de> { fn empty() -> Self; fn default_values() -> Self; fn from_env() -> Result<Self, Error>; fn with_fallback(self, fallback: Self) -> Self; fn is_empty(&self) -> bool; ...
fn from_file(path: impl Into<PathBuf>) -> Result<Self, Error> { let default_values = Self::Partial::default_values(); let mut file = File::new(path)?; if !default_values.is_complete() { file = file.required(); } Self::from_partial(file.load::<Self::Partial>()?.with_f...
function_block-full_function
[ { "content": "/// Formats the configuration description as a YAML file.\n\n///\n\n/// This can be used to generate a template file that you can give to the users\n\n/// of your application. It usually is a convenient to start with a correctly\n\n/// formatted file with all possible options inside.\n\n///\n\n///...
Rust
src/latex/latex_obj.rs
loovjo/Ytesrev
fa8cd8bda4c7fd529d3f1dbf7d850b6d37d871ea
extern crate sdl2; use super::render::{read_image, register_equation, LatexIdx}; use drawable::{DrawSettings, Drawable, KnownSize, Position, State}; use image::{ImageContainer, PngImage}; use sdl2::{pixels::Color, render::Canvas, video::Window}; pub struct LatexObj { pub inner: Option<PngImage>, id: Op...
extern crate sdl2; use super::render::{read_image, register_equation, LatexIdx}; use drawable::{DrawSettings, Drawable, KnownSize, Position, State}; use image::{ImageContainer, PngImage}; use sdl2::{pixels::Color, render::Canvas, video::Window}; pub struct LatexObj { pub inner: Option<PngImage>, id: Op...
position, settings); } else { canvas.set_draw_color(Color::RGB(255, 0, 255)); let rect = position.into_rect_with_size(100, 100); canvas.fill_rect(rect).expect("Can't draw"); } } fn register(&mut self) { self.id = Some(register_equation(self.expr, sel...
ner] } else { vec![] } } fn draw(&self, canvas: &mut Canvas<Window>, position: &Position, settings: DrawSettings) { if let Some(ref img) = self.inner { img.draw(canvas,
random
[ { "content": "/// Register an equation to be rendered. To render, use the [`render_all_equations`] method.\n\n///\n\n/// ```\n\n/// use ytesrev::latex::render::*;\n\n/// # fn make_invalid_idx() -> LatexIdx {\n\n/// # use std::mem::transmute;\n\n/// # unsafe { transmute::<usize, LatexIdx>(0) }\n\n/// # }\n\n...
Rust
tests/defaults.rs
gibfahn/up-rs
d850f9579841db1f209eba5cce62d5134a589249
#![cfg(target_os = "macos")] use testutils::{assert, run_defaults}; #[test] fn defaults_read_global() { let temp_dir = testutils::temp_dir(file!(), testutils::function_name!()).unwrap(); let expected_value = run_defaults(&["read", "-g", "com.apple.sound.beep.sound"]); { let mut cmd = ...
#![cfg(target_os = "macos")] use testutils::{assert, run_defaults}; #[test] fn defaults_read_global() { let temp_dir = testutils::temp_dir(file!(), testutils::function_name!()).unwrap(); let expected_value = run_defaults(&["read", "-g", "com.apple.sound.beep.sound"]); { let mut cmd = ...
#[test] fn defaults_write_local() { let temp_dir = testutils::temp_dir(file!(), testutils::function_name!()).unwrap(); let domain = format!("co.fahn.up-rs.test-{}", testutils::function_name!()); let test_values = [ ("bool", "true", "true", "false", "0"), ("int", "5", "5", "10", "10"...
fn defaults_read_local() { let temp_dir = testutils::temp_dir(file!(), testutils::function_name!()).unwrap(); let expected_value = run_defaults(&["read", "com.apple.finder", "FXPreferredViewStyle"]); { let mut cmd = testutils::up_cmd(&temp_dir); cmd.args(&[ "defa...
function_block-full_function
[ { "content": "#[must_use]\n\npub fn run_cmd(cmd: &mut Command) -> Output {\n\n println!(\"Running command '{:?}'.\", cmd);\n\n let cmd_output = cmd.output().unwrap();\n\n println!(\" status: {}\", cmd_output.status);\n\n if !cmd_output.stdout.is_empty() {\n\n println!(\" stdout: {}\", Strin...
Rust
src/lib.rs
veer66/chamkho
0663ffe2fa3f62b18f949ec776458efcee85e1dd
pub extern crate wordcut_engine; use self::wordcut_engine::Dict; use std::io::Result; use std::path::Path; pub type Wordcut = self::wordcut_engine::Wordcut; #[allow(dead_code)] pub fn cargo_dir() -> &'static Path { Path::new(env!("CARGO_MANIFEST_DIR")) } pub fn default_path() -> &'static Path { Path::new(co...
pub extern crate wordcut_engine; use self::wordcut_engine::Dict; use std::io::Result; use std::path::Path; pub type Wordcut = self::wordcut_engine::Wordcut; #[allow(dead_code)] pub fn cargo_dir() -> &'static Path { Path::new(env!("CARGO_MANIFEST_DIR")) } pub fn default_path() -> &'static Path { Path::new(co...
#[test] fn test_from_law() { let dict = super::load_dict(Path::new("data/thai.txt")); let wordcut = Wordcut::new(dict.unwrap()); let words = wordcut.segment_into_strings("มาตรา 482 ผู้ขายไม่"); let expected = &vec!["มาตรา", " ", "482", " ", "ผู้", "ขาย", "ไม่"] .ite...
let dict = super::load_dict(Path::new("data/thai.txt")); let wordcut = Wordcut::new(dict.unwrap()); let words = wordcut.segment_into_strings("มาตรา"); let expected = &vec!["มาตรา"] .iter() .map(|&s| s.to_string()) .collect::<Vec<String>>()[..]; assert_...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let yaml = load_yaml!(\"cli.yaml\");\n\n let matches = App::from_yaml(yaml).get_matches();\n\n let lang = matches.value_of(\"lang\");\n\n let dict_path = match matches.value_of(\"dict_path\") {\n\n Some(_dict_path) => Path::new(_dict_path),\n\n None => mat...
Rust
src/update.rs
sourcebox/dfu-buddy
d9d2e550f075a394017f9c23c8243f30ba75c109
use crate::{dfudev, DeviceUpdateStep, Message, Result}; pub fn full_update( device_id: u64, file_path: std::path::PathBuf, message_sender: std::sync::mpsc::Sender<Message>, ) -> Result<()> { message_sender.send(Message::DeviceUpdateStarted)?; erase_device(device_id, &file_path, &message_sender)?;...
use crate::{dfudev, DeviceUpdateStep, Message, Result}; pub fn full_update( device_id: u64, file_path: std::path::PathBuf, message_sender: std::sync::mpsc::Sender<Message>, ) -> Result<()> { message_sender.send(Message::DeviceUpdateStarted)?; erase_device(device_id, &file_path, &message_sender)?;...
#[derive(Debug)] pub enum Error { TargetNotFound(u8), MemoryRegionNotFound(u32, u32), VerificationFailed(u32), PlainDfuNotSupported, } impl std::error::Error for Error {} impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { ...
nsfer_size ); let num_elements = image.image_elements.len(); for (element_no, element) in image.image_elements.iter().enumerate() { log::debug!( "Reading element at address 0x{:08X}, size {}", ...
function_block-function_prefixed
[ { "content": "/// High-level function to set the address for subsequent uploads or downloads\n\npub fn set_address(device: &DfuDevice, address: u32) -> Result<()> {\n\n // Device must be in idle state for this operation\n\n device.abort_request()?;\n\n\n\n // Issue the request\n\n set_address_reques...