lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/tcp/stock/kline.rs
zjp-CN/rustdx
3df31ad369f6329cb9008418e43552d1f3f8bc16
use crate::tcp::{helper::DateTime, Tdx}; #[derive(Debug, Clone)] pub struct Kline<'d> { pub send: Box<[u8]>, pub market: u16, pub code: &'d str, pub category: u16, pub start: u16, pub count: u16, pub response: Vec<u8>, pub data: Vec<KlineData<'d>>, } #[rustfmt::skip...
use crate::tcp::{helper::DateTime, Tdx}; #[derive(Debug, Clone)] pub struct Kline<'d> { pub send: Box<[u8]>, pub market: u16, pub code: &'d str, pub category: u16, pub start: u16, pub count: u16, pub response: Vec<u8>, pub data: Vec<KlineData<'d>>, } #[rustfmt::skip...
8, high: 18.32, low: 17.65, vol: 1379837.0, amount: 2465683712.0, }, KlineData { dt: DateTime { year: 2021, month: 9, ...
function_block-function_prefixed
[ { "content": "/// 解析价格 (open / close / high / low)\n\n///\n\n/// 注意:\n\n/// 1. 第二次之后计算的价格为浮动价格,基于第一次解析的实际价格而浮动;\n\n/// 2. 返回的 pos 是不定长的。\n\npub fn price(arr: &[u8], pos: &mut usize) -> i32 {\n\n let mut shl = 6;\n\n let mut bit = arr[*pos] as i32;\n\n let mut res = bit & 0x3f;\n\n let sign = (bit & ...
Rust
twili/src/main.rs
ramonbrugman/SunriseOS
91dd9c009da396deab09dfad5b1a2714becef3db
#![no_std] extern crate alloc; use core::cmp::min; use alloc::boxed::Box; use alloc::collections::BTreeMap; use alloc::collections::VecDeque; use alloc::sync::Arc; use spin::Mutex; use lazy_static::lazy_static; use sunrise_libuser::{kip_header, capabilities}; use sunrise_libuser::error::{Error, TwiliError, PmError}...
#![no_std] extern crate alloc; use core::cmp::min; use alloc::boxed::Box; use alloc::collections::BTreeMap; use alloc::collections::VecDeque; use alloc::sync::Arc; use spin::Mutex; use lazy_static::lazy_static; use sunrise_libuser::{kip_header, capabilities}; use sunrise_libuser::error::{Error, TwiliError, PmError}...
fn write<'a>(&'a mut self, _manager: WorkQueue<'static>, _buf: &'a [u8]) -> FutureObj<'a, Result<(), Error>> { FutureObj::new(Box::new(async move { Err(TwiliError::OperationUnsupported.into()) })) } } impl Drop for DumbPipeWrite { fn drop(&mut self) { log::info!("Write...
buf[..counts1].copy_from_slice(&s1[..counts1]); let counts2 = min(s2.len(), buf.len() - counts1); buf[counts1..counts1 + counts2].copy_from_slice(&s2[..counts2]); log::info!("Read {} bytes", counts1 + counts2); locked.queue.drain(..counts1 + counts2); Ok((c...
function_block-function_prefix_line
[ { "content": "/// Implement the Control ipc cmd types.\n\n///\n\n/// See [switchbrew](https://switchbrew.org/w/index.php?title=IPC_Marshalling#Control)\n\nfn control_dispatch<T, DISPATCH>(object: &mut T, dispatch: DISPATCH, manager: WorkQueue<'static>, cmdid: u32, buf: &mut [u8]) -> Result<(), Error>\n\nwhere\n...
Rust
src/cli/src/cluster/install/mod.rs
nacardin/fluvio
e0e3d6c7262499258587ee14eeb90d0addd76df9
use std::{fmt, str::FromStr}; use structopt::StructOpt; #[cfg(any(feature = "cluster_components", feature = "cluster_components_rustls"))] mod local; mod k8; mod tls; use crate::CliError; use tls::TlsOpt; #[cfg(target_os = "macos")] fn get_log_directory() -> &'static str { "/usr/local/var/log/fluvio" } #[cfg(no...
use std::{fmt, str::FromStr}; use structopt::StructOpt; #[cfg(any(feature = "cluster_components", feature = "cluster_components_rustls"))] mod local; mod k8; mod tls; use crate::CliError; use tls::TlsOpt; #[cfg(target_os = "macos")] fn get_log_directory() -> &'static str { "/usr/local/var/log/fluvio" } #[cfg(no...
= "cluster_components", feature = "cluster_components_rustls"))] use local::{install_local, run_local_setup}; if self.sys { install_sys(self)?; } else if self.local { if self.setup { run_local_setup(self).await?; } else { #[cf...
ructopt(long)] sys: bool, #[structopt(long)] local: bool, #[structopt(flatten)] tls: TlsOpt, #[structopt(long)] authorization_config_map: Option<String>, #[structopt(long)] pub skip_checks: bool, #[structopt(long)] pub setup: bool, } impl InstallOpt {...
random
[ { "content": "#[allow(unused)]\n\npub fn command_exec(binary: &str, prefix: &str, process: impl Fn(&mut Command)) {\n\n let mut cmd = get_binary(binary).unwrap_or_else(|_| panic!(\"unable to get binary: {}\", binary));\n\n\n\n let (output, error) = open_log(prefix);\n\n\n\n cmd.stdout(Stdio::from(outpu...
Rust
src/connectivity/lib/at-commands/src/serde_tests.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
#![cfg(test)] use crate::{ highlevel::Command, serde::{DeserializeBytes, DeserializeError, DeserializeErrorCause, DeserializeResult, SerDe}, }; use {matches::assert_matches, std::io::Cursor}; #[test] fn serialize() { let commands = vec![Command::Testex {}, Command::Testex {}]; let mut bytes = Vec::n...
#![cfg(test)] use crate::{ highlevel::Command, serde::{DeserializeBytes, DeserializeError, DeserializeErrorCause, DeserializeResult, SerDe}, }; use {matches::assert_matches, std::io::Cursor}; #[test] fn serialize() { let commands = vec![Command::Testex {}, Command::Testex {}]; let mut bytes = Vec::n...
#[test] fn multipart_command_deserialize() { let bytes1 = b"ATTES"; let bytes2 = b"TEX\r"; let result1 = Command::deserialize(&mut Cursor::new(bytes1), DeserializeBytes::new()); assert_eq!( result1, DeserializeResult { values: Vec::new(), error: None, ...
ommand_deserialize() { let bytes = b"ATTESTEX\rATTESTEX\r"; let result = Command::deserialize(&mut Cursor::new(bytes), DeserializeBytes::new()); assert_eq!( result, DeserializeResult { values: vec!(Command::Testex {}, Command::Testex {}), error: None, rema...
function_block-function_prefixed
[]
Rust
tests/utils/ignite_node.rs
isapego/ignite-rust
1a48d89a3c95da3e2232a29250abf99290eb312c
use std::env; use std::ffi::OsStr; use std::path::Path; use std::process::{Child, Command, Stdio}; use std::env::current_dir; use std::time::{Duration, Instant}; use tokio::time; use crate::IgniteResult; use crate::IgniteError; #[derive(Debug)] pub struct IgniteNode { process: Option<Child>, } impl IgniteNode {...
use std::env; use std::ffi::OsStr; use std::path::Path; use std::process::{Child, Command, Stdio}; use std::env::current_dir; use std::time::{Duration, Instant}; use tokio::time; use crate::IgniteResult; use crate::IgniteError; #[derive(Debug)] pub struct IgniteNode { process: Option<Child>, } impl IgniteNode {...
ing()))) } pub async fn start_test_node(cfg_name: &str) -> IgniteResult<IgniteNode> { let current_dir = current_dir().unwrap(); let cfg = current_dir.join("tests").join("cfg").join(cfg_name); println!("Starting node"); let node = IgniteNode::start(cfg)?; wait_till_available(10800u16, 20000u64).aw...
Err(IgniteError::new(format!("Error while killing process: {}", res.to_string()))) } #[cfg(target_family = "unix")] pub fn kill_process_tree(proc_id: u32) -> IgniteResult<()> { let res = Command::new("pkill") .arg("-9") .arg("-p") .arg(format!("{}", proc_id)) .stdout(Stdio::nul...
random
[ { "content": "/// Calculate the value fast which is the power of two and is greater or equals to the provided\n\n/// value. See https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 for details.\n\npub fn round_to_pow2_u32(val: u32) -> u32 {\n\n assert_ne!(val, 0, \"Value can not be zero\");\n...
Rust
src/lib.rs
ErichDonGubler/adhesion-rs
d9d9d2e27fe4e87f34fb44ff3c180f5a99d3a6a8
#![deny(missing_docs)] #![doc(html_root_url = "https://docs.rs/adhesion/0.4.0")] mod parse_generics_shim_util; #[macro_export] macro_rules! contract { ( @muncher, [double_check $double_check: tt], $(#[$attribute: meta])* $(pub$(($access_modifier: ident))*)* fn $fn_name: ident $($...
#![deny(missing_docs)] #![doc(html_root_url = "https://docs.rs/adhesion/0.4.0")] mod parse_generics_shim_util; #[macro_export] macro_rules! contract { ( @muncher, [double_check $double_check: tt], $(#[$attribute: meta])* $(pub$(($access_modifier: ident))*)* fn $fn_name: ident $($...
tt, global_double_check $global_double_check: tt $(, #![$inner_attribute: meta])*) ) => { { $(#![$inner_attribute])* $pre $global_double_check $double_check let $return_value = $body; $global_double_check $double_check...
ody $body: tt, post ($return_value: ident) {}, double_check $double_check: tt, global_double_check $global_double_check: tt $(, #![$inner_attribute: meta])*) post $post: tt $($tail: tt)* ) => { contract_body! { @processing_blocks (pre $pre, body $body, post ($return_v...
random
[ { "content": "#[test]\n\nfn attributes() {\n\n contract! {\n\n #[cold]\n\n fn before() {\n\n body {}\n\n }\n\n }\n\n\n\n before();\n\n\n\n contract! {\n\n fn after() {\n\n #![cold]\n\n body {}\n\n }\n\n }\n\n\n\n after();\n\n}...
Rust
examples/collaboration/shop/src/lib.rs
xueying4402/liquid
fb12fd0b5108d44132d5104376d2a65de58a27c7
#![cfg_attr(not(feature = "std"), no_std)] use liquid_lang as liquid; #[liquid::collaboration] mod shop { #[liquid(contract)] pub struct Iou { #[liquid(signers)] issuer: address, owner: address, amount: u64, currency: String, } #[liquid(rights)] impl Iou ...
#![cfg_attr(not(feature = "std"), no_std)] use liquid_lang as liquid; #[liquid::collaboration] mod shop { #[liquid(contract)] pub struct Iou { #[liquid(signers)] issuer: address, owner: address, amount: u64, currency: String, } #[liquid(rights)] impl Iou ...
} #[liquid(contract)] pub struct Offer { #[liquid(signers)] owner: address, #[liquid(signers)] vendor: address, item_id: ContractId<Item>, price: u64, currency: String, users: Vec<address>, } #[liquid(rights)] impl Offer { ...
pub fn disclose(self, users: Vec<address>) -> ContractId<Item> { sign! { Item => observers: users, ..self } }
function_block-full_function
[]
Rust
src/response.rs
infincia/reqwest
8633060eaf89711d25f0cf4e17dcac3762c930e7
use std::fmt; use std::io::{self, Read}; use hyper::header::{Headers, ContentEncoding, ContentLength, Encoding, TransferEncoding}; use hyper::status::StatusCode; use hyper::Url; use libflate::gzip; use serde::de::DeserializeOwned; use serde_json; pub struct Response { inner: Decoder, } pub fn new(res: ::hyper::c...
use std::fmt; use std::io::{self, Read}; use hyper::header::{Headers, ContentEncoding, ContentLength, Encoding, TransferEncoding}; use hyper::status::StatusCode; use hyper::Url; use libflate::gzip; use serde::de::DeserializeOwned; use serde_json; pub struct Response { inner: Decoder, } pub fn new(res: ::hyper::c...
struct Head { headers: ::hyper::header::Headers, url: ::hyper::Url, status: ::hyper::status::StatusCode, } struct Peeked { peeked: Option<u8>, inner: ::hyper::client::Response, } impl Read for Peeked { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if buf.is_...
fn new_gzip(mut res: ::hyper::client::Response) -> Decoder { let mut peek = [0]; match res.read(&mut peek) { Ok(0) => return Decoder::PlainText(res), Ok(n) => { debug_assert_eq!(n, 1); } Err(e) => return Decoder::Errored { err: Some(e), ...
function_block-full_function
[ { "content": "#[inline]\n\npub fn loop_detected(url: Url) -> Error {\n\n Error {\n\n kind: Kind::RedirectLoop,\n\n url: Some(url),\n\n }\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 0, "score": 154986.37549692835 }, { "content": "#[inline]\n\npub fn too_many_redirect...
Rust
src/client/mod.rs
jakalope/game_network
59651d70c1dff83e644bbce27f20018f4a9fb9d2
use control; use msg; use std; use bincode; use bitvec; use serde; use std::net::{TcpStream, SocketAddr, UdpSocket}; use std::sync::mpsc; use std::io::Read; use util; mod reliable; mod low_latency; pub struct Client { seq: control::ControllerSequence, chat_history: Vec<msg::reliable::ChatMessage>, ...
use control; use msg; use std; use bincode; use bitvec; use serde; use std::net::{TcpStream, SocketAddr, UdpSocket}; use std::sync::mpsc; use std::io::Read; use util; mod reliable; mod low_latency; pub struct Client { seq: control::ControllerSequence, chat_history: Vec<msg::reliable::ChatMessage>, ...
pub fn quit(mut self) { drop(self.from_reliable_servicer); drop(self.to_reliable_servicer); drop(self.from_low_latency_servicer); drop(self.to_low_latency_servicer); } pub fn send_controller_input( &mut...
port: local_udp_addr.port(), }; let tcp_stream = TcpStream::connect(&server_addr)?; let mut reliable_servicer = reliable::Servicer::connect( cred, server_addr.clone(), tcp_stream, re_to_application, re_from_application, ...
function_block-function_prefixed
[ { "content": "pub fn maybe_receive_udp(socket: &std::net::UdpSocket) -> Result<Vec<u8>, msg::CommError> {\n\n // Make a buffer of the maximum packet size.\n\n let mut buf = Vec::<u8>::with_capacity(MAX_PACKET_SIZE);\n\n buf.resize(MAX_PACKET_SIZE, 0);\n\n match socket.recv(&mut buf) {\n\n Ok(...
Rust
src/geom/line/join/miter.rs
rylev/nannou
3f802939dd286021497c9ff4ebc94d213d1dd29d
use crate::geom::{line, Line, Point2, Quad}; use crate::math::BaseFloat; #[derive(Clone, Debug)] pub struct VertexPairs<I, S> { half_thickness: S, points: I, point_a: Option<Point2<S>>, point_b: Option<Point2<S>>, } #[derive(Clone, Debug)] pub struct Vertices<I, S> { pairs: VertexPairs<I...
use crate::geom::{line, Line, Point2, Quad}; use crate::math::BaseFloat; #[derive(Clone, Debug)] pub struct VertexPairs<I, S> { half_thickness: S, points: I, point_a: Option<Point2<S>>, point_b: Option<Point2<S>>, } #[derive(Clone, Debug)] pub struct Vertices<I, S> { pairs: VertexPairs<I...
} impl<I, S> ExactSizeIterator for Vertices<I, S> where I: Iterator<Item = Point2<S>> + ExactSizeIterator, S: BaseFloat, { fn len(&self) -> usize { self.pairs.len() * 2 + if self.next.is_some() { 1 } else { 0 } } } impl Iterator for TriangleIndices { type Item = [usize; 3]; fn next(&m...
Option<Self::Item> { if let Some(next) = self.next.take() { return Some(next); } if let Some([this, next]) = self.pairs.next() { self.next = Some(next); return Some(this); } None }
function_block-function_prefixed
[ { "content": "///\n\n/// use nannou::prelude::*;\n\n/// use nannou::geom::line;\n\n///\n\n/// fn main() {\n\n/// let half_thickness = 1.0;\n\n/// let a = pt2(0.0, 0.0);\n\n/// let b = pt2(2.0, 0.0);\n\n///\n\n/// // ab\n\n/// let expected = [pt2(0.0, -1.0), pt2(0.0, 1.0), pt2(2.0, 1.0), pt2(...
Rust
src/server.rs
Dentosal/facts
f5c4ecb325520b864908489966d9b3ddfefa4a15
use crossbeam_channel::{bounded, unbounded}; use serde::{Deserialize, Serialize}; use std::fs; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::Ordering; use std::thread::{self, JoinHandle}; use crate::config::*; use crate::download; use crate...
use crossbeam_channel::{bounded, unbounded}; use serde::{Deserialize, Serialize}; use std::fs; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::Ordering; use std::thread::{self, JoinHandle}; use crate::config::*; use crate::download; use crate...
pub fn unlink_mod(&self, mod_info: &ModInfo) { let mut dest = self.dir.clone(); dest.push("factorio"); dest.push("mods"); dest.push(mod_info.file_name()); if dest.exists() { fs::remove_file(dest).expect("Could not remove mod symlink"); } } ...
o"); dest.push("mods"); dest.push(mod_info.file_name()); if !dest.exists() { symlink(mod_info.path(), dest).expect("Could not create mod symlink") } }
function_block-function_prefixed
[ { "content": "/// Returns directory `worlds/$name` if it exists\n\npub fn get_world(name: &str) -> Result<PathBuf, NoSuchWorld> {\n\n let mut pb = app_root();\n\n pb.push(\"worlds\");\n\n pb.push(app_dirs::sanitized(name));\n\n\n\n if pb.exists() {\n\n Ok(pb)\n\n } else {\n\n Err(No...
Rust
src/tests/fixtures.rs
typedruby/typedruby
0216fe987e1bfc55fce36f8c859d529aa9b8d870
use std::env; use std::fs::File; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; extern crate difference; use self::difference::{Changeset, Difference}; use glob::glob; use regex::{Regex, Captures}; use termcolor::NoColor; use typed_arena::Arena; use environment::Environment; use report::TerminalReporter...
use std::env; use std::fs::File; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; extern crate difference; use self::difference::{Changeset, Difference}; use glob::glob; use regex::{Regex, Captures}; use termcolor::NoColor; use typed_arena::Arena; use environment::Environment; use report::TerminalReporter...
#[test] fn test_fixtures() { env::set_var("TYPEDRUBY_LIB", env::current_dir().unwrap().join("definitions/lib")); let rewrite = match env::var("TYPEDRUBY_UPDATE_FIXTURES") { Ok(ref val) => val != "", Err(..) => false, }; let mut errors = Vec::new(); for entry in glob("tests/fixtur...
fn compare_fixture(path: PathBuf) -> Option<Mismatch> { let root_dir = env::current_dir().unwrap(); let mut error_buff = Vec::new(); { let mut errors = TerminalReporter::new(NoColor::new(&mut error_buff)); let project = project::load_fixture(&mut errors, &path); let arena = Arena...
function_block-full_function
[ { "content": "#[cfg(test)]\n\npub fn load_fixture(reporter: &mut Reporter, fixture_path: &Path) -> Project {\n\n let root = fixture_path\n\n .parent()\n\n .expect(\"fixture_path.parent()\")\n\n .to_owned();\n\n\n\n let mut config = ProjectConfig::default();\n\n\n\n config.typedruby...
Rust
src/lib.rs
mernen/sgmlish
26a75b0cacbc54bb16a10ba9b5487a2093d8979a
pub mod entities; pub mod error; mod fragment; pub mod marked_sections; pub mod parser; pub mod text; pub mod transforms; use std::borrow::Cow; use std::fmt::{self, Write}; pub use error::{Error, Result}; pub use fragment::*; pub use parser::{parse, Parser, ParserConfig}; #[cfg(feature = "serde")] pub mod de; #[c...
pub mod entities; pub mod error; mod fragment; pub mod marked_sections; pub mod parser; pub mod text; pub mod transforms; use std::borrow::Cow; use std::fmt::{self, Write}; pub use error::{Error, Result}; pub use fragment::*; pub use parser::{parse, Parser, ParserConfig}; #[cfg(feature = "serde")] pub mod de; #[c...
}
fn test_display_attribute() { assert_eq!( SgmlEvent::Attribute { name: "key".into(), value: None } .to_string(), "key" ); assert_eq!( SgmlEvent::Attribute { name: "key".into(), ...
function_block-full_function
[ { "content": "/// Expands entities (`&foo;`) in the text using the given closure as lookup.\n\n///\n\n/// Character references (`&#123;`) are also expanded, without going through the closure.\n\n/// Function names (`&#SPACE;`) as well as invalid character references\n\n/// (codes that go beyond Unicode, e.g. `&...
Rust
lsh-rs/src/hash.rs
pixelami/lsh-rs
64a5058db6ab1181a7451c02e491fb9ccf36d8cb
use crate::data::Integer; use crate::multi_probe::StepWiseProbe; use crate::{data::Numeric, dist::l2_norm, multi_probe::QueryDirectedProbe, utils::create_rng}; use ndarray::prelude::*; use ndarray_rand::rand_distr::{StandardNormal, Uniform}; use ndarray_rand::RandomExt; use num::{traits::NumCast, Float, Zero}; use std:...
use crate::data::Integer; use crate::multi_probe::StepWiseProbe; use crate::{data::Numeric, dist::l2_norm, multi_probe::QueryDirectedProbe, utils::create_rng}; use ndarray::prelude::*; use ndarray_rand::rand_distr::{StandardNormal, Uniform}; use ndarray_rand::RandomExt; use num::{traits::NumCast, Float, Zero}; use std:...
}) }); hash.to_vec() } } #[cfg(test)] mod test { use super::*; #[test] fn test_l2() { let l2 = <L2>::new(5, 2.2, 7, 1); let h1 = l2.hash_vec_query(&[1., 2., 3., 1., 3.]); let h2 = l2.hash_vec_query(&[1.1, 2., 3., 1., 3.1]); ...
if *v > Zero::zero() { let v = K::from(*v).expect("could not cast N to K"); if v < acc { v } else { acc } } else { acc }
if_condition
[ { "content": "/// L2 norm of a single vector.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use lsh_rs::dist::l2_norm;\n\n/// let a = vec![1., -1.];\n\n/// let norm_a = l2_norm(&a);\n\n///\n\n/// // norm between two vectors\n\n/// let b = vec![0.2, 1.2];\n\n/// let c: Vec<_> = a.iter().zip(b).map(|(ai, bi)|...
Rust
treblo_cli/src/main.rs
taskie/treblo
46062e19963b86a8263b6002eab1f17cc6de3245
use std::{env, ffi::OsStr, io::stdout, path::PathBuf}; use byteorder::{BigEndian, LittleEndian, WriteBytesExt}; use serde::{Deserialize, Serialize}; use sha1::Sha1; use sha2::Sha256; use std::io::{Error, Write}; use structopt::{clap, StructOpt}; use treblo::{hex::to_hex_string, walk, walk::Hasher}; use twox_hash::XxHa...
use std::{env, ffi::OsStr, io::stdout, path::PathBuf}; use byteorder::{BigEndian, LittleEndian, WriteBytesExt}; use serde::{Deserialize, Serialize}; use sha1::Sha1; use sha2::Sha256; use std::io::{Error, Write}; use structopt::{clap, StructOpt}; use treblo::{hex::to_hex_string, walk, walk::Hasher}; use twox_hash::XxHa...
return; } let object_type = if is_tree { "tree" } else { "blob" }; let path = if path_is_default { p.strip_prefix(&base_path).unwrap() } else { p }; let path = if path.to_str().map_or(false, |p| p.is_empty()) { base_path.as_ref() } else { path }; let depth ...
.ignore_vcs && opt.ignore_exclude); if opt.ignore_vcs { wb.filter_entry(|p| p.file_name() != OsStr::new(".git")); } if opt.ignore { wb.add_custom_ignore_filename(".trebloignore"); } wb.build() }; let tw = walk::T...
random
[ { "content": "fn tree_entry<W>(w: &mut W, file_mode: FileMode, name: &str, digest: &[u8]) -> Result<usize>\n\nwhere\n\n W: Write,\n\n{\n\n let mut n = 0;\n\n n += w.write(format!(\"{:o}\", file_mode.0).as_bytes())?;\n\n n += w.write(b\" \")?;\n\n n += w.write(name.as_bytes())?;\n\n n += w.writ...
Rust
packages/yewtil/src/ptr/irc.rs
higumachan/yew
bf3d97928a08b7454aa7637d70219310d3ce06a7
use crate::ptr::rc_box::{ clone_impl, clone_inner, decrement_and_possibly_deallocate, get_count, get_ref_boxed_content, is_exclusive, try_unwrap, unwrap_clone, RcBox, }; use std::borrow::Borrow; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use std::ptr::NonNull; pub...
use crate::ptr::rc_box::{ clone_impl, clone_inner, decrement_and_possibly_deallocate, get_count, get_ref_boxed_content, is_exclusive, try_unwrap, unwrap_clone, RcBox, }; use std::borrow::Borrow; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use std::ptr::NonNull; pub...
} #[cfg(test)] mod test { use super::*; #[test] fn create_new() { let _irc = Irc::new(0); } }
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let rc_box = get_ref_boxed_content(&self.ptr); f.debug_struct("Irc") .field("value", rc_box.value.as_ref()) .field("count", &rc_box.get_count()) .finish() }
function_block-full_function
[ { "content": "/// Hook for consuming context values in function components.\n\n/// The context of the type passed as `T` is returned. If there is no such context in scope, `None` is returned.\n\n/// A component which calls `use_context` will re-render when the data of the context changes.\n\n///\n\n/// More inf...
Rust
src/lib.rs
Dushistov/rust-property
2a6fb3d2d1d02efdc9420147d3edbca4f475d960
extern crate proc_macro; use quote::quote; mod generate; mod parse; use crate::{ generate::{FieldType, GetType}, parse::{FieldDef, GetTypeConf, PropertyDef, SetTypeConf}, }; #[proc_macro_derive(Property, attributes(property))] pub fn derive_property(input: proc_macro::TokenStream) -> proc_macro::TokenStre...
extern crate proc_macro; use quote::quote; mod generate; mod parse; use crate::{ generate::{FieldType, GetType}, parse::{FieldDef, GetTypeConf, PropertyDef, SetTypeConf}, }; #[proc_macro_derive(Property, attributes(property))] pub fn derive_property(input: proc_macro::TokenStream) -> proc_macro::TokenStre...
, _ => match field_conf.set.typ { SetTypeConf::Ref => quote!( #visibility fn #method_name<T: Into<#field_type>>( &mut self, val: T ) -> &mut Self { self.#field_name = val.into(); s...
match field_conf.set.typ { SetTypeConf::Ref => quote!( #visibility fn #method_name<T: Into<#inner_type>>( &mut self, val: impl IntoIterator<Item = T> ) -> &mut Self { self.#field_name = val.into...
if_condition
[ { "content": "fn parse_attrs(\n\n span: proc_macro2::Span,\n\n mut conf: FieldConf,\n\n attrs: &[syn::Attribute],\n\n) -> ParseResult<FieldConf> {\n\n for attr in attrs.iter() {\n\n if let syn::AttrStyle::Outer = attr.style {\n\n let meta = attr\n\n .parse_meta()\n\n...
Rust
day2/src/main.rs
jhungerford/adventofcode-2020
f9a803ad96e0acb5625a97d82ac5028fcf39e882
use std::ops::Range; use std::str::FromStr; use regex::Regex; use std::fs::File; use std::io::{BufReader, BufRead}; #[derive(Debug)] struct ParsePasswordErr {} #[derive(Debug, Eq, PartialEq)] struct PasswordPolicy { password: String, policy: Policy } impl PasswordPolicy { fn validate_range(&sel...
use std::ops::Range; use std::str::FromStr; use regex::Regex; use std::fs::File; use std::io::{BufReader, BufRead}; #[derive(Debug)] struct ParsePasswordErr {} #[derive(Debug, Eq, PartialEq)] struct PasswordPolicy { password: String, policy: Policy } impl PasswordPolicy { fn validate_range(&sel...
println!("Part 2: {}", count_valid_position(&passwords)); }
ange() { let a = PasswordPolicy { password: String::from("abcde"), policy: Policy { count: 1..3, letter: 'a' }, }; let b = PasswordPolicy { password: String::from("cdefg"), policy: Policy { count: 1..3, letter: 'b' }, }; assert!(a...
random
[ { "content": "/// Counts the number of bags inside the given bag, including the bag.\n\nfn count_bags(rules: &HashMap<String, Vec<Bag>>, color: &str) -> usize {\n\n let count = match rules.get(color) {\n\n None => 1,\n\n Some(bags) => {\n\n let mut count = 1;\n\n\n\n for b...
Rust
src/actions.rs
msizanoen1/lmaobgd
973fc840f1990a7181c2ddb40cf343def537cbeb
use crate::models::*; use crate::schema::*; use blake2::Blake2b; use diesel::pg::expression::dsl::any; use diesel::pg::upsert::excluded; use diesel::pg::PgConnection; use diesel::prelude::*; use diesel::QueryResult; use digest::Digest; use once_cell::sync::Lazy; use rand::prelude::*; use std::collections::HashMap; use ...
use crate::models::*; use crate::schema::*; use blake2::Blake2b; use diesel::pg::expression::dsl::any; use diesel::pg::upsert::excluded; use diesel::pg::PgConnection; use diesel::prelude::*; use diesel::QueryResult; use digest::Digest; use once_cell::sync::Lazy; use rand::prelude::*; use std::collections::HashMap; use ...
pub fn gen_api_key( conn: &PgConnection, note: Option<&str>, write_access: bool, ) -> QueryResult<String> { let key = generate_api_key(128); let hash = Blake2b::digest(key.as_bytes()); let new = NewApiKey { hash: &hash[..], note, write_access, }; diesel::insert_...
diesel::update(answers::table.filter(answers::question_id.eq(any(ids)))) .set(answers::reviewed.eq(true)) .execute(conn)?; Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn process_answer(s: &str) -> String {\n\n let mut iter = s.lines().map(|s| s.trim()).filter(|s| *s != \"\");\n\n format!(\n\n \"{} {}\",\n\n iter.next().unwrap_or(\"\"),\n\n iter.collect::<Vec<_>>().join(\"\\n\")\n\n )\n\n}\n\n\n", "file_path": "src/display.r...
Rust
src/handler/cache_update.rs
fakeshadow/pixel-social
7e2fff3acae5b9d8fa6ae711642de2dd83f037cd
use std::{collections::VecDeque, time::Duration}; use actix_send::prelude::*; use chrono::Utc; use redis::{aio::MultiplexedConnection, cmd, pipe}; use crate::handler::{ cache::MyRedisPool, db::MyPostgresPool, messenger::{ErrReportMsg, ErrReportServiceAddr}, }; use crate::model::{cache_schema::HashMapBrown...
use std::{collections::VecDeque, time::Duration}; use actix_send::prelude::*; use chrono::Utc; use redis::{aio::MultiplexedConnection, cmd, pipe}; use crate::handler::{ cache::MyRedisPool, db::MyPostgresPool, messenger::{ErrReportMsg, ErrReportServiceAddr}, }; use crate::model::{cache_schema::HashMapBrown...
let addr: Address<CacheService> = builder.start().await; addr.run_interval(LIST_INTERVAL, |service| { Box::pin(async move { if let Err(e) = service.cache_pool.handle_list_update().await { service.send_err_rep(e); } }) }) .await .expect("Fail...
let builder = CacheService::builder(move || { let rep_addr = rep_addr.clone(); let db_pool = db_pool.clone(); let cache_pool = cache_pool.clone(); async { CacheService { db_pool, cache_pool, rep_addr, message: De...
assignment_statement
[]
Rust
tss-esapi/src/abstraction/ak.rs
wiktor-k/rust-tss-esapi
cc9a08e22f4ae88eb66c96fe601d8b1d058d00b6
use crate::{ abstraction::{cipher::Cipher, IntoKeyCustomization, KeyCustomization}, attributes::{ObjectAttributesBuilder, SessionAttributesBuilder}, constants::{tss::*, SessionType}, handles::{AuthHandle, KeyHandle, SessionHandle}, interface_types::{ algorithm::{AsymmetricAlgorithm, Hashin...
use crate::{ abstraction::{cipher::Cipher, IntoKeyCustomization, KeyCustomization}, attributes::{ObjectAttributesBuilder, SessionAttributesBuilder}, constants::{tss::*, SessionType}, handles::{AuthHandle, KeyHandle, SessionHandle}, interface_types::{ algorithm::{AsymmetricAlgorithm, Hashin...
pub fn create_ak<IKC: IntoKeyCustomization>( context: &mut Context, parent: KeyHandle, hash_alg: HashingAlgorithm, sign_alg: SignatureScheme, ak_auth_value: Option<&Auth>, key_customization: IKC, ) -> Result<CreateKeyResult> { let key_alg = AsymmetricAlgorithm::try_from(sign_alg).map_err(|...
pub fn load_ak( context: &mut Context, parent: KeyHandle, ak_auth_value: Option<&Auth>, private: Private, public: TPM2B_PUBLIC, ) -> Result<KeyHandle> { let policy_auth_session = context .start_auth_session( None, None, None, SessionType::P...
function_block-full_function
[ { "content": "/// Retreive the Endorsement Key public certificate from the TPM\n\npub fn retrieve_ek_pubcert(context: &mut Context, alg: AsymmetricAlgorithm) -> Result<Vec<u8>> {\n\n let nv_idx = match alg {\n\n AsymmetricAlgorithm::Rsa => RSA_2048_EK_CERTIFICATE_NV_INDEX,\n\n AsymmetricAlgorit...
Rust
src/day18.rs
SanderHageman/AdventOfCode2020
2ec28609e28f4b4cc41fdc701c53061c27128745
type TParsed = Vec<TParsedSub>; type TParsedSub = Vec<Expr>; pub fn day(input: String) -> (i64, i64) { let parsed_input = parse(&input); (part_1(&parsed_input), part_2(&parsed_input)) } fn part_1(input: &TParsed) -> i64 { input.iter().map(|line| get_scope_value(&line)).sum() } fn part_2(input: &TParsed) ...
type TParsed = Vec<TParsedSub>; type TParsedSub = Vec<Expr>; pub fn day(input: String) -> (i64, i64) { let parsed_input = parse(&input); (part_1(&parsed_input), part_2(&parsed_input)) } fn part_1(input: &TParsed) -> i64 { input.iter().map(|line| get_scope_value(&line)).sum() } fn part_2(input: &TParsed) ...
red expression {:?}", expr), } } result } #[derive(Debug, Clone, PartialEq)] enum Expr { N(i64), Add, Mult, Scope(Vec<Expr>), StartScope, EndScope, } #[test] fn test_example_1() { assert_eq!(part_1(&parse(&EX)), 51); assert_eq!(part_1(&parse(&EX1)), 26); assert_eq!...
modifier = None; } Expr::Add => modifier = Some(Expr::Add), Expr::Mult => modifier = Some(Expr::Mult), Expr::Scope(other_scope) => { let scoped_result = fn_recurse(other_scope); apply_modifier(scoped_result, modifier); ...
function_block-random_span
[ { "content": "pub fn day(input: String) -> (i64, i64) {\n\n let parsed_input = parse(&input);\n\n (part_1(&parsed_input), part_2(&parsed_input))\n\n}\n\n\n", "file_path": "src/day08.rs", "rank": 3, "score": 242246.251744441 }, { "content": "pub fn day(input: String) -> (i64, i64) {\n\n...
Rust
zkcrypto/src/kzg_proofs.rs
sifraitech/kzg
9ef31f2f7baa87500f688db6cbaf823d3cfd4951
use core::borrow::Borrow; use std::ops::Mul; use crate::zkfr::blsScalar as Scalar; use crate::poly::ZPoly as Poly; use crate::fftsettings::ZkFFTSettings; use crate::kzg_types::{ZkG1Projective as G1, ZkG2Projective as G2, pairings_verify, G1_GENERATOR, G2_GENERATOR, }; use kzg::{G1 as _G1, G2...
use core::borrow::Borrow; use std::ops::Mul; use crate::zkfr::blsScalar as Scalar; use crate::poly::ZPoly as Poly; use crate::fftsettings::ZkFFTSettings; use crate::kzg_types::{ZkG1Projective as G1, ZkG2Projective as G2, pairings_verify, G1_GENERATOR, G2_GENERATOR, }; use kzg::{G1 as _G1, G2...
} pub fn default_kzg() -> KZGSettings { KZGSettings { fs: ZkFFTSettings::default(), secret_g1: Vec::new(), secret_g2: Vec::new(), length: 0, } } pub(crate) fn new_kzg_settings(_secret_g1: Vec<G1>, _secret_g2: Vec<G2>, secrets_len: u64, _fs: &ZkFFTSettings) ...
fn default() -> KZGSettings { KZGSettings { fs: ZkFFTSettings::default(), secret_g1: Vec::new(), secret_g2: Vec::new(), length: 0, } }
function_block-function_prefix_line
[ { "content": "pub fn pairings_work<TFr: Fr, TG1: G1 + G1Mul<TFr>, TG2: G2 + G2Mul<TFr>>(\n\n pairings_verify: &dyn Fn(&TG1, &TG2, &TG1, &TG2) -> bool,\n\n) {\n\n // // Verify that e([3]g1, [5]g2) = e([5]g1, [3]g2)\n\n\n\n let three = TFr::from_u64(3);\n\n let five = TFr::from_u64(5);\n\n\n\n let ...
Rust
core-contracts/staking-pool/tests/utils.rs
DaviRain-Su/learn-near
5c4e59585ae2b2b7a61dc8c102e98f7913d3d568
#![allow(dead_code)] extern crate staking_pool; use near_crypto::{InMemorySigner, KeyType, Signer}; use near_primitives::{ account::{AccessKey, Account}, errors::{RuntimeError, TxExecutionError}, hash::CryptoHash, transaction::{ExecutionOutcome, ExecutionStatus, Transaction}, types::{AccountId, Bal...
#![allow(dead_code)] extern crate staking_pool; use near_crypto::{InMemorySigner, KeyType, Signer}; use near_primitives::{ account::{AccessKey, Account}, errors::{RuntimeError, TxExecutionError}, hash::CryptoHash, transaction::{ExecutionOutcome, ExecutionStatus, Transaction}, types::{AccountId, Bal...
pub fn pool_stake(&self, runtime: &mut RuntimeStandalone, amount: u128) -> TxResult { let args = json!({ "amount": format!("{}", amount) }) .to_string() .as_bytes() .to_vec(); let tx = self .new_tx(runtime, POOL_ACCOUNT_ID.into()) .functi...
pub fn pool_ping(&self, runtime: &mut RuntimeStandalone) -> TxResult { let tx = self .new_tx(runtime, POOL_ACCOUNT_ID.into()) .function_call("ping".into(), vec![], MAX_GAS, 0) .sign(&self.signer); let res = runtime.resolve_tx(tx).unwrap(); runtime.process_all(...
function_block-full_function
[ { "content": "pub fn new_root(account_id: AccountId) -> (RuntimeStandalone, ExternalUser) {\n\n let (runtime, signer) = init_runtime_and_signer(&account_id);\n\n (runtime, ExternalUser { account_id, signer })\n\n}\n", "file_path": "core-contracts/staking-pool-factory/tests/utils.rs", "rank": 2, ...
Rust
chips/lpc43xx/src/ssp.rs
elsuizo/tock
45a70f5f794a6a2cbe2db26dc2c589dff7d5c654
use kernel::common::StaticRef; use kernel::common::registers::{self, ReadOnly, ReadWrite, WriteOnly, register_bitfields}; #[repr(C)] struct SspRegisters { cr0: ReadWrite<u32, CR0::Register>, cr1: ReadWrite<u32, CR1::Register>, dr: ReadWrite<u32>, sr: ReadOnly<u32, SR::Register>, cpsr: ReadWrite<u32>, imsc: ...
use kernel::common::StaticRef; use kernel::common::registers::{self, ReadOnly, ReadWrite, W
FIRST_CLOCK = 0, SECOND_CLOCK = 1 ], SCR OFFSET(8) NUMBITS(8) [] ], CR1 [ LBM OFFSET(0) NUMBITS(1) [ DuringNormalOperation = 0, OUPTU = 1 ], SSE OFFSET(1) NUMBITS(1) [ TheSSPControllerIsDisabled = 0, ...
riteOnly, register_bitfields}; #[repr(C)] struct SspRegisters { cr0: ReadWrite<u32, CR0::Register>, cr1: ReadWrite<u32, CR1::Register>, dr: ReadWrite<u32>, sr: ReadOnly<u32, SR::Register>, cpsr: ReadWrite<u32>, imsc: ReadWrite<u32, IMSC::Register>, ris: ReadOnly<u32, RIS::Register>, mis: ReadOnly<u32, MIS:...
random
[ { "content": "pub trait Counter<W = u32>: Time<W> {\n\n fn start(&self) -> ReturnCode;\n\n fn stop(&self) -> ReturnCode;\n\n fn is_running(&self) -> bool;\n\n}\n\n\n", "file_path": "kernel/src/hil/time.rs", "rank": 0, "score": 96042.25489904254 }, { "content": "/// The `Alarm` trait...
Rust
plugin/examples/gain/src/lib.rs
jaxter184/clack
53c66e41c16300122631cbd6326cfec32d03a533
use clack_common::events::event_types::NoteEvent; use clack_common::events::list::EventList; use clack_common::events::{Event, EventType}; use clack_common::process::ProcessStatus; use clack_extensions::params::info::ParamInfoFlags; use clack_extensions::params::{implementation::*, info::ParamInfo, PluginParams}; use c...
use clack_common::events::event_types::NoteEvent; use clack_common::events::list::EventList; use clack_common::events::{Event, EventType}; use clack_common::process::ProcessStatus; use clack_extensions::params::info::ParamInfoFlags; use clack_extensions::params::{implementation::*, info::ParamInfo, PluginParams}; use c...
fn process( &mut self, _process: &Process, mut audio: Audio, events: ProcessEvents, ) -> Result<ProcessStatus> { let io = audio.zip(0, 0).unwrap().into_f32().unwrap(); for (input, output) in io { output.set(input.get() * 2.0) ...
fn new( _host: HostHandle<'a>, _main_thread: &mut GainPluginMainThread, _shared: &(), _sample_config: SampleConfig, ) -> Result<Self> { Ok(Self) }
function_block-full_function
[ { "content": "pub trait ToShared<'a>: Extension<'a> {\n\n type Shared: Send + Sync + 'a;\n\n\n\n fn to_shared(&self) -> &Self::Shared;\n\n}\n", "file_path": "common/src/extensions.rs", "rank": 0, "score": 64347.84584669464 }, { "content": "pub trait PluginShared<'a>: Sized + Send + Syn...
Rust
common/datavalues/src/columns/struct_/mod.rs
zhyass/databend
e54bef9ef4f6cb8c4a9c0b7be177f738f0cb7330
use std::sync::Arc; use common_arrow::arrow::array::*; use crate::prelude::*; #[derive(Clone)] pub struct StructColumn { values: Vec<ColumnRef>, data_type: DataTypePtr, } impl From<StructArray> for StructColumn { fn from(array: StructArray) -> Self { Self::new(array) } } impl StructColumn...
use std::sync::Arc; use common_arrow::arrow::array::*; use crate::prelude::*; #[derive(Clone)] pub struct StructColumn { values: Vec<ColumnRef>, data_type: DataTypePtr, } impl From<StructArray> for StructColumn { fn from(array: StructArray) -> Self { Self::new(array) } } impl StructColumn...
ta = Vec::new(); for idx in 0..self.len() { let x = self.get(idx); data.push(format!("{:?}", x)); } let head = "StructColumn"; let iter = data.iter(); display_fmt(iter, head, self.len(), self.data_type_id(), f) } }
, data_type: DataTypePtr) -> Self { Self { values, data_type } } pub fn values(&self) -> &[ColumnRef] { &self.values } } impl Column for StructColumn { fn as_any(&self) -> &dyn std::any::Any { self } fn data_type(&self) -> DataTypePtr { self.data_type.clone() ...
random
[ { "content": "fn from_iter(values: &Buffer<i32>) -> Result<Box<dyn Array>> {\n\n let it = (0..values.len()).map(|i| i32::abs(i as i32) as u32);\n\n\n\n let arr = unsafe { PrimitiveArray::from_trusted_len_values_iter_unchecked(it) };\n\n Ok(Box::new(arr))\n\n}\n\n\n", "file_path": "common/datavalues...
Rust
benches/bench.rs
nsmryan/myopic
7f59bb4e40f4976de2d08f1b50c0b2769be08f84
#[macro_use]extern crate criterion; extern crate myopic; use criterion::Criterion; use criterion::black_box; use myopic::lens::*; use myopic::lens_box::*; use myopic::lens_fn::*; const ITER: usize = 1000; fn get_bit(d: &u8) -> u8 { return d & 0x01; } fn set_bit(d: &mut u8, a: u8) { *d = (*d & 0xFE) | a; }...
#[macro_use]extern crate criterion; extern crate myopic; use criterion::Criterion; use criterion::black_box; use myopic::lens::*; use myopic::lens_box::*; use myopic::lens_fn::*; const ITER: usize = 1000; fn get_bit(d: &u8) -> u8 { return d & 0x01; } fn set_bit(d: &mut u8, a: u8) { *d = (*d & 0xFE) | a; }...
val = composed.get(&mut d); composed.set(&mut d, !black_box(val)); } })); } criterion_group!(lens_benches, lens, lens_box, lens_fn, lens_no_black_box, lens_inline, lens_composed, lens_box_composed, lens_composed_no_black_box, lens_fn_composed); criterion_main!(lens_benches);
(|d: &u8| (d & 0x01) == 0x01), Box::new(|d: &mut u8, a: bool| *d = (*d & 0xFE) | a as u8)); let composed = lens_box::ComposedLens::new(Box::new(func1), Box::new(func2)); c.bench_function("lens_box_composed", move |b| b.iter(|| { let mut d: u32 = 0; for _ in 0..IT...
random
[ { "content": "# The Name\n\nThe joke in the name is that this is both my own optics library, and it is\n\nlikely a bad optics library. Myopic means having bad vision, and it sounds\n\nlike \"my optics\". Hopefully this is a little amusing.\n\n\n\n\n\n# Comparison\n\nThere are a number of Rust lense libraries, s...
Rust
src/day_10.rs
jacobguenther/advent_of_code_2019
b274d24840a2cd04572a474fed42a3e82e196e42
/* Copyright 2020 Jacob Guenther Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, su...
/* Copyright 2020 Jacob Guenther Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, su...
fn setup_ratios(map_size: &Vec2<usize>) -> StepRatios { let mut set = StepRatios::new(); set.insert(Vec2::new( 1, 0)); set.insert(Vec2::new( 0, 1)); set.insert(Vec2::new(-1, 0)); set.insert(Vec2::new( 0,-1)); for dy in 1..map_size.y { for dx in dy..map_size.x { if dx != 1 && dx == dy { continue; } ...
let mut count = 0; for ratio in ratios { let mut check_pos = step_ratio(&start.into(), &ratio); let map_size = map_size(map); while in_bounds(&check_pos, &map_size) { let c = map[check_pos.y as usize][check_pos.x as usize]; if c == '#' { count += 1; break; } else { check_pos = step_ratio(&ch...
function_block-function_prefix_line
[ { "content": "#[derive(Copy, Clone)]\n\nstruct Count {\n\n\tzeros: u32,\n\n\tones: u32,\n\n\ttwos: u32,\n\n}\n\nimpl Default for Count {\n\n\tfn default() -> Count {\n\n\t\tCount {\n\n\t\t\tzeros: 0,\n\n\t\t\tones: 0,\n\n\t\t\ttwos: 0,\n\n\t\t}\n\n\t}\n\n}\n", "file_path": "src/day_8.rs", "rank": 3, ...
Rust
examples/chat/module/rust/tests/integration_test.rs
jadephilipoom/oak
601875dfd1a642a8f2013a1201112bd581b84699
use assert_matches::assert_matches; use chat_grpc::proto::{ chat_client::ChatClient, CreateRoomRequest, DestroyRoomRequest, Message, SendMessageRequest, SubscribeRequest, }; use futures::executor::block_on; use log::info; use serial_test::serial; use std::sync::{Arc, Condvar, Mutex}; use tokio::sync::Semaphor...
use assert_matches::assert_matches; use chat_grpc::proto::{ chat_client::ChatClient, CreateRoomRequest, DestroyRoomRequest, Message, SendMessageRequest, SubscribeRequest, }; use futures::executor::block_on; use log::info; use serial_test::serial; use std::sync::{Arc, Condvar, Mutex}; use tokio::sync::Semaphor...
req); let result = client.destroy_room(req.clone()).await; assert_matches!(result, Ok(_)); info!("Sending request: {:?}", req); let result = client.destroy_room(req).await; assert_matches!(result, Err(_)); runtime.stop(); } #[tokio::test(core_threads = 4)] #[serial] async fn test_chat()...
::channel_and_interceptor().await; let mut client = ChatClient::with_interceptor(channel, interceptor); let req = CreateRoomRequest { room_id: b"dummy room id".to_vec(), admin_token: b"dummy admin token".to_vec(), }; info!("Sending request: {:?}", req); let result = client.create_ro...
random
[ { "content": "fn load_signature(signature_path: &str) -> Signature {\n\n let signature_file = read(&signature_path).expect(\"Couldn't read signature file\");\n\n let (_, signature) =\n\n crate::parse_pem_signature(&signature_file).expect(\"Couldn't parse signature\");\n\n signature\n\n}\n\n\n", ...
Rust
src/main.rs
roSievers/sogo
5f678a3706ed183d0a7b6a426632be8e9de5dded
#[cfg(test)] mod tests; mod game; mod ai; mod ui; mod game_view; mod constants; mod helpers; mod thread_synchronisation; mod replay; mod command_line; extern crate kiss3d; extern crate glfw; extern crate nalgebra as na; extern crate rand; extern crate clap; extern crate threadpool; use ai::StatelessAI; use std::sy...
#[cfg(test)] mod tests; mod game; mod ai; mod ui; mod game_view; mod constants; mod helpers; mod thread_synchronisation; mod replay; mod command_line; extern crate kiss3d; extern crate glfw; extern crate nalgebra as na; extern crate rand; extern crate clap; extern crate threadpool; use ai::StatelessAI; use std::sy...
} Arguments::Humans { structure } => humans(Arc::new(structure.into())), }; println!("{}", replay.notation()); } fn interactive(structure: Arc<game::Structure>, mut p2: ai::AIBox) -> replay::History { let ui_connector = ui::UiConnector::new(structure.clone()); let mut...
demo( Arc::new(structure.into()), ai::AIBox::new(ai_1), ai::AIBox::new(ai_2), )
call_expression
[ { "content": "fn ai_parser(mut values: clap::Values) -> Result<ai::Constructor, String> {\n\n let ai_name: &str = values.next().unwrap();\n\n match ai_name {\n\n \"random\" => Ok(ai::Constructor::Random),\n\n \"mc\" => {\n\n let endurance = values.next().unwrap_or(\"10000\").parse...
Rust
src/decimal/juniper_support.rs
jgarvin/fraction
2a0c284197c2ecd8bd86ba377c41857e4e80985e
use juniper::{ meta::MetaType, parser::ScalarToken, Executor, FromInputValue, GraphQLType, InputValue, ParseScalarResult, ParseScalarValue, Registry, ScalarRefValue, ScalarValue, Selection, ToInputValue, Value, }; use generic::GenericInteger; use num::Integer; use std::fmt; use super::GenericDecimal; imp...
use juniper::{ meta::MetaType, parser::ScalarToken, Executor, FromInputValue, GraphQLType, InputValue, ParseScalarResult, ParseScalarValue, Registry, ScalarRefValue, ScalarValue, Selection, ToInputValue, Value, }; use generic::GenericInteger; use num::Integer; use std::fmt; use super::GenericDecimal; imp...
Some(GenericDecimal::from_decimal_str(val).ok())? } } #[cfg(test)] mod tests { use super::*; use fraction::GenericFraction; type D = GenericDecimal<u64, u8>; type F = GenericFraction<u64>; fn get_tests() -> Vec<(&'static str, D)> { vec![ ("NaN", D::nan()), ...
let val = match value.as_scalar() { None => return None, Some(scalar) => { let s: Option<&String> = scalar.into(); match s { Some(v) => v, _ => return None, } } };
assignment_statement
[ { "content": "#[inline]\n\npub fn write_u16(mut buf: &mut [u8], value: u16) -> Result<(), Box<dyn Error + Sync + Send>> {\n\n match buf.write_u16::<BigEndian>(value) {\n\n Ok(()) => Ok(()),\n\n Err(e) => Err(e.into()),\n\n }\n\n}\n\n\n\nimpl<T> FromSql for GenericFraction<T>\n\nwhere\n\n ...
Rust
t1/src/main.rs
yutannihilation/learn-wgpu-0.7
9c33c0b6ed5078ce73b0244e1b42d967c95bd556
mod camera; mod texture; use std::f32::consts::PI; use camera::{CameraController, CameraUniform}; use wgpu::include_wgsl; use wgpu::util::{DeviceExt, RenderEncoder}; use winit::window::Window; use winit::{ event::*, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; use bytemuck::{Pod, Zeroa...
mod camera; mod texture; use std::f32::consts::PI; use camera::{CameraController, CameraUniform}; use wgpu::include_wgsl; use wgpu::util::{DeviceExt, RenderEncoder}; use winit::window::Window; use winit::{ event::*, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; use bytemuck::{Pod, Zeroa...
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Camera Bind Group Layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VER...
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Camera Buffer"), contents: bytemuck::cast_slice(&[camera_uniform]), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, });
assignment_statement
[ { "content": " pub fn from_image(\n\n device: &wgpu::Device,\n\n queue: &wgpu::Queue,\n\n img: &image::DynamicImage,\n\n label: Option<&str>,\n\n ) -> Result<Self> {\n\n let rgba = img.as_rgba8().unwrap();\n\n let dimensions = img.dimensions();\n\n\n\n let ...
Rust
crates/lib/kajiya-backend/src/vulkan/swapchain.rs
Horki/kajiya
b67eaea2272924eae053b5918afedf2a318b8bd9
use super::{device::Device, surface::Surface}; use anyhow::Result; use ash::{extensions::khr, vk}; #[allow(unused_imports)] use log::{debug, error, info, trace, warn}; use std::sync::Arc; #[derive(Clone, Copy, Default)] pub struct SwapchainDesc { pub format: vk::SurfaceFormatKHR, pub dims: vk::Extent2D, pu...
use super::{device::Device, surface::Surface}; use anyhow::Result; use ash::{extensions::khr, vk}; #[allow(unused_imports)] use log::{debug, error, info, trace, warn}; use std::sync::Arc; #[derive(Clone, Copy, Default)] pub struct SwapchainDesc { pub format: vk::SurfaceFormatKHR, pub dims: vk::Extent2D, pu...
dex as u32, acquire_semaphore, rendering_finished_semaphore, }) } Err(err) if err == vk::Result::ERROR_OUT_OF_DATE_KHR || err == vk::Result::SUBOPTIMAL_KHR => { Err(SwapchainAc...
pub(crate) raw: vk::SwapchainKHR, pub desc: SwapchainDesc, pub images: Vec<Arc<crate::Image>>, pub acquire_semaphores: Vec<vk::Semaphore>, pub rendering_finished_semaphores: Vec<vk::Semaphore>, pub next_semaphore: usize, #[allow(dead_code)] pub(crate) device: Arc<Device>, ...
random
[ { "content": "pub fn image_aspect_mask_from_format(format: vk::Format) -> vk::ImageAspectFlags {\n\n match format {\n\n vk::Format::D16_UNORM => vk::ImageAspectFlags::DEPTH,\n\n vk::Format::X8_D24_UNORM_PACK32 => vk::ImageAspectFlags::DEPTH,\n\n vk::Format::D32_SFLOAT => vk::ImageAspectF...
Rust
src/systems.rs
hfaulds/amethyst-test
5c60d96cc15843ce5f78613fef5c79e12142c59d
use amethyst::{ core::{ math::{Point3, Vector2}, Transform, SystemDesc, }, derive::SystemDesc, ecs::*, input::{InputHandler, StringBindings}, renderer::{ActiveCamera,Camera}, ui::UiText, window::ScreenDimensions, winit::MouseButton, }; use crate::components::C...
use amethyst::{ core::{ math::{Point3, Vector2}, Transform, SystemDesc, }, derive::SystemDesc, ecs::*, input::{InputHandler, StringBindings}, renderer::{ActiveCamera,Camera}, ui::UiText, window::ScreenDimensions, winit::MouseButton, }; use crate::components::C...
Transform>, ) -> Option<Point3<f32>> { let mouse_position = input.mouse_position()?; let mut camera_join = (&cameras, transforms).join(); if let Some((camera, camera_transform)) = active_camera .entity .and_then(|a| camera_join.get(a, &entities)) .or_else(|| camera_join.next(...
_pos_for_cursor(&input, &entities, active_camera, screen, cameras, &transforms) { Some(p) => p, None => return, }; if input.mouse_button_is_down(MouseButton::Left) { match &self.selection { Some(selection) => { let (_, transform) =...
random
[ { "content": "fn init_camera(world: &mut World, screen: &ScreenDimensions) {\n\n // Center the camera in the middle of the screen, and let it cover\n\n // the entire screen\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(screen.width() * 0.5, screen.height() * 0.5, 1....
Rust
tests/test_address.rs
planet-s/actix
2bb4e09a43aa7bccc804327e05509dae94c37244
extern crate actix; extern crate futures; extern crate tokio_core; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use futures::{future, Future}; use tokio_core::reactor::Timeout; use actix::prelude::*; #[derive(Debug)] struct Ping(usize); struct MyActor(Arc<AtomicUsize>)...
extern crate actix; extern crate futures; extern crate tokio_core; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use futures::{future, Future}; use tokio_core::reactor::Timeout; use actix::prelude::*; #[derive(Debug)] struct Ping(usize); struct MyActor(Arc<AtomicUsize>)...
ing::Relaxed), 3); } #[test] fn test_sync_address() { let sys = System::new("test"); let count = Arc::new(AtomicUsize::new(0)); let arbiter = Arbiter::new(None); let addr: SyncAddress<_> = MyActor(Arc::clone(&count)).start(); let addr2 = addr.clone(); let addr3 = addr.clone(); addr.send(Pi...
2 = addr.clone(); addr.send(Ping(0)); Arbiter::handle().spawn_fn(move || { addr2.send(Ping(1)); Timeout::new(Duration::new(0, 100), Arbiter::handle()).unwrap() .then(move |_| { addr2.send(Ping(2)); Arbiter::system().send(msgs::SystemExit(0)); ...
function_block-random_span
[ { "content": "type Item<A> = (SpawnHandle, Box<ActorFuture<Item=(), Error=(), Actor=A>>);\n\n\n\npub struct ActorItemsCell<A> where A: Actor, A::Context: AsyncContext<A> {\n\n index: SpawnHandle,\n\n items: Vec<Item<A>>,\n\n}\n\n\n\nimpl<A> Default for ActorItemsCell<A> where A: Actor, A::Context: AsyncCo...
Rust
src/gitko/main_window.rs
sula0/gitko
f30e3c9c4ba541b9ff6c7a5d7bbdc754c367789f
use std::fs::{metadata,read_dir,remove_file}; use std::path::{Path, PathBuf}; use std::process::Command; use crate::git; use crate::git::{parse_file_state, FileState}; use crate::ascii_table::*; use crate::render::{Bold, Colored, Line, Renderer, KeyHandlers, Component, ScreenSize, Underlined, Window, Position}; use cr...
use std::fs::{metadata,read_dir,remove_file}; use std::path::{Path, PathBuf}; use std::process::Command; use crate::git; use crate::git::{parse_file_state, FileState}; use crate::ascii_table::*; use crate::render::{Bold, Colored, Line, Renderer, KeyHandlers, Component, ScreenSize, Underlined, Window, Position}; use cr...
fn open_in_file_manager(&mut self, window: &mut Window) -> bool { let command = if cfg!(unix) { "xdg-open" } else if cfg!(windows) { "explorer" } else { panic!("Platform not supported."); }; let path_str = window.get_cursor_line()[3..].t...
Renderer::new( &mut CommandWindow{}, ScreenSize { lines: 2, cols: window.width() }, Position { x: 0, y: window.height() - 2 } ).render(); self.on_start(window); true }
function_block-function_prefixed
[ { "content": "pub fn unstage_file(path: &str) {\n\n run(vec![\"reset\", path]);\n\n}\n\n\n", "file_path": "src/git.rs", "rank": 0, "score": 107529.10379525935 }, { "content": "pub fn add_file(path: &str) {\n\n run(vec![\"add\", path]);\n\n}\n\n\n", "file_path": "src/git.rs", "r...
Rust
src/systems/varia/combat.rs
dwino/EngineRustLegionBracketLib
27a90cc5178cd19af61e950daa5402516de1bd35
use crate::prelude::*; #[system] #[read_component(WantsToAttack)] #[read_component(WantsToRangedAttack)] #[read_component(Player)] #[write_component(Health)] #[read_component(Damage)] #[read_component(RangedDamage)] #[read_component(Defense)] #[read_component(Carried)] #[read_component(Equiped)] #[write_co...
use crate::prelude::*; #[system] #[read_component(WantsToAttack)] #[read_component(WantsToRangedAttack)] #[read_component(Player)] #[write_component(Health)] #[read_component(Damage)] #[read_component(RangedDamage)] #[read_component(Defense)] #[read_component(Carried)] #[read_component(Equiped)] #[write_co...
m); } } commands.remove(*message); }); let mut melee_attackers = <(Entity, &WantsToAttack)>::query(); let melee_victims: Vec<(Entity, Entity, Entity)> = melee_attackers .iter(ecs) .map(|(entity, attack)| (*entity, attack.attacker, attack....
function_block-function_prefixed
[ { "content": "#[system]\n\n#[read_component(ActivateItem)]\n\n#[read_component(ProvidesHealing)]\n\n#[read_component(ProvidesSensing)]\n\n#[write_component(Health)]\n\n#[read_component(ProvidesDungeonMap)]\n\n#[read_component(Equipment)]\n\n#[read_component(Equiped)]\n\n#[read_component(Weapon)]\n\n#[read_compo...
Rust
drivers/rust/driver/src/metrics.rs
pact-foundation/pact-plugins
edd1530036c89c227f4c420fce745845b35b8c23
use std::env::consts::{ARCH, OS}; use std::env::var; use std::process::Command; use std::str; use anyhow::anyhow; use log::{debug, warn}; use maplit::hashmap; use reqwest::Client; use uuid::Uuid; use crate::plugin_models::PactPluginManifest; static CIS: &'static [&str] = &[ "CI", "CONTINUOUS_INTEGRATION", "BST...
use std::env::consts::{ARCH, OS}; use std::env::var; use std::process::Command; use std::str; use anyhow::anyhow; use log::{debug, warn}; use maplit::hashmap; use reqwest::Client; use uuid::Uuid; use crate::plugin_models::PactPluginManifest; static CIS: &'static [&str] = &[ "CI", "CONTINUOUS_INTEGRATION", "BST...
Ok(output) => if output.status.success() { Ok(str::from_utf8(&*output.stdout)?.to_string()) } else { Err(anyhow!("Failed to invoke hostname command: status {}", output.status)) } Err(err) => Err(anyhow!("Failed to invoke hostname command: {}", err)) } }
function_block-function_prefix_line
[ { "content": "fn load_manifest_from_disk(plugin_dep: &PluginDependency) -> anyhow::Result<PactPluginManifest> {\n\n let plugin_dir = pact_plugin_dir()?;\n\n debug!(\"Looking for plugin in {:?}\", plugin_dir);\n\n\n\n if plugin_dir.exists() {\n\n for entry in fs::read_dir(plugin_dir)? {\n\n let path =...
Rust
src/project/importers.rs
dmitmel/crosscode-localization-engine
b8c69c81feb203e28ba3b0761588efbb95ab0825
use crate::cc_ru_compat; use crate::gettext_po; use crate::impl_prelude::*; use crate::localize_me; use crate::rc_string::RcString; use crate::utils; use crate::utils::Timestamp; use once_cell::sync::Lazy; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::Path; #[derive(Debug)] pub struct Importe...
use crate::cc_ru_compat; use crate::gettext_po; use crate::impl_prelude::*; use crate::localize_me; use crate::rc_string::RcString; use crate::utils; use crate::utils::Timestamp; use once_cell::sync::Lazy; use std::collections::{HashMap, HashSet}; use std::fmt; use std::path::Path; #[derive(Debug)] pub struct Importe...
} #[derive(Debug)] pub struct GettextPoImporter; impl GettextPoImporter { pub const ID: &'static str = "po"; } impl Importer for GettextPoImporter { #[inline(always)] fn id_static() -> &'static str where Self: Sized, { Self::ID } #[inline(always)] fn new_boxed() -> Box<dyn Importer> where...
ragment { file_path: RcString::from(fragment.original.file), json_path: RcString::from(fragment.original.json_path), original_text: RcString::from(fragment.original.text), translations: fragment .translations .into_iter() .map(|t| ImportedTranslation { ...
function_block-function_prefixed
[ { "content": "// Rewritten from <https://github.com/dmitmel/crosscode-ru/blob/ea8ee6244d0c89e3118f2344440181f594d95783/tool/src/Notabenoid.ts#L499-L667>\n\n// LMT's tagging algorithm also looks interesting, maybe we can learn something from it as well:\n\n// <https://github.com/L-Sherry/Localize-Me-Tools/blob/c...
Rust
blockchain/src/escrow.rs
vldm/stegos
e0fd93a5da96d86ba03bfac94054abb37e3f98ce
use crate::error::BlockchainError; use crate::mvcc::MultiVersionedMap; use crate::output::Output; use log::*; use serde_derive::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::collections::HashMap; use stegos_crypto::hash::Hash; use stegos_crypto::pbc; use stegos_crypto::scc; #[derive(Debug, Clone...
use crate::error::BlockchainError; use crate::mvcc::MultiVersionedMap; use crate::output::Output; use log::*; use serde_derive::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::collections::HashMap; use stegos_crypto::hash::Hash; use stegos_crypto::pbc; use stegos_crypto::scc; #[derive(Debug, Clone...
pub fn info(&self, epoch: u64) -> EscrowInfo { let mut validators: HashMap<pbc::PublicKey, ValidatorInfo> = HashMap::new(); for (k, v) in self.escrow.iter() { let entry = validators .entry(k.validator_pkey.clone()) .or_insert(ValidatorInfo { ...
self, inputs: OutputIter, outputs: OutputIter, epoch: u64, ) -> Result<(), BlockchainError> where OutputIter: Iterator<Item = &'a Output>, { let mut staking_balance: HashMap<pbc::PublicKey, i64> = HashMap::new(); for input in inputs { match input {...
function_block-function_prefix_line
[ { "content": "#[inline(always)]\n\npub fn shrink_hash(hash: Hash) -> i64 {\n\n let slice = hash.base_vector();\n\n let mut result = 0;\n\n for i in 0..8 {\n\n result |= (slice[8 - i] as i64) << (i * 8);\n\n }\n\n result\n\n}\n\n\n", "file_path": "blockchain/src/election.rs", "rank"...
Rust
noodles-cram/src/reader/data_container/compression_header/data_series_encoding_map.rs
veldsla/noodles
ac2916c6c4c547a266da3313e391a2991e2a8642
use std::io; use bytes::{Buf, Bytes}; use super::get_encoding; use crate::{ data_container::compression_header::{ data_series_encoding_map::DataSeries, DataSeriesEncodingMap, }, reader::num::get_itf8, }; pub fn get_data_series_encoding_map(src: &mut Bytes) -> io::Result<DataSeriesEncodingMap> { ...
use std::io; use bytes::{Buf, Bytes}; use super::get_encoding; use crate::{ data_container::compression_header::{ data_series_encoding_map::DataSeries, DataSeriesEncodingMap, }, reader::num::get_itf8, }; pub fn get_data_series_encoding_map(src: &mut Bytes) -> io::Result<DataSeriesEncodingMap> { ...
es_of_quality_scores_encoding(encoding) } DataSeries::BaseSubstitutionCodes => { builder.set_base_substitution_codes_encoding(encoding) } DataSeries::Insertion => builder.set_insertion_encoding(encoding), DataSeries::ReferenceSkipLength => buil...
lder.set_stretches_of_bases_encoding(encoding), DataSeries::StretchesOfQualityScores => { builder.set_stretch
random
[ { "content": "pub fn read_container<R>(reader: &mut R, buf: &mut BytesMut) -> io::Result<Container>\n\nwhere\n\n R: Read,\n\n{\n\n let header = read_header(reader)?;\n\n\n\n buf.resize(header.len(), 0);\n\n reader.read_exact(buf)?;\n\n let mut buf = buf.split().freeze();\n\n\n\n let blocks_len...
Rust
generate_reflection/src/values.rs
Anaminus/rbx-dom
7d3a656a21124222c5955603fe385e60b1c604cb
use std::collections::BTreeMap; use rbx_dom_weak::types::{ Axes, BinaryString, BrickColor, CFrame, Color3, Color3uint8, ColorSequence, ColorSequenceKeypoint, Content, CustomPhysicalProperties, Enum, Faces, Matrix3, NumberRange, NumberSequence, NumberSequenceKeypoint, PhysicalProperties, Ray, Rect, Region...
use std::collections::BTreeMap; use rbx_dom_weak::types::{ Axes, BinaryString, BrickColor, CFrame, Color3, Color3uint8, ColorSequence, ColorSequenceKeypoint, Content, CustomPhysicalProperties, Enum, Faces, Matrix3, NumberRange, NumberSequence, NumberSequenceKeypoint, PhysicalProperties, Ray, Rect, Region...
TestEntry { ty: value.ty(), value, }, ) }) .collect(); Ok(serde_json::to_string_pretty(&entries)?) }
values.insert("Float64", 15123.0f64.into()); values.insert("Int32", 6014i32.into()); values.insert("Int64", 23491023i64.into()); values.insert("NumberRange", NumberRange::new(-36.0, 94.0).into()); values.insert( "NumberSequence", NumberSequence { keypoints: vec![ ...
function_block-random_span
[ { "content": "fn encode_packed_color3(source: Color3uint8) -> u32 {\n\n let Color3uint8 { r, g, b } = source;\n\n\n\n (b as u32) + ((g as u32) << 8) + ((r as u32) << 16)\n\n}\n\n\n", "file_path": "rbx_xml/src/types/colors.rs", "rank": 1, "score": 195745.55692902143 }, { "content": "pub...
Rust
src/registry.rs
canac/portman
c3e920da79d6d927f4b151ea1eeb2bb6397b77c6
use crate::allocator::PortAllocator; use crate::config::Config; use crate::error::ApplicationError; use crate::registry_store::RegistryStore; use regex::Regex; use serde::{Deserialize, Serialize}; use std::{ collections::BTreeMap, fs, path::PathBuf, process::{Command, Stdio}, }; #[derive(Clone, Default...
use crate::allocator::PortAllocator; use crate::config::Config; use crate::error::ApplicationError; use crate::registry_store::RegistryStore; use regex::Regex; use serde::{Deserialize, Serialize}; use std::{ collections::BTreeMap, fs, path::PathBuf, process::{Command, Stdio}, }; #[derive(Clone, Default...
pub fn save(&self) -> Result<(), ApplicationError> { self.store.save(&RegistryData { ports: self.ports.clone(), }) } pub fn get(&self, project: &str) -> Option<u16> { self.ports.get(project).cloned() } pub fn allocate(&mut self, project: &str) -...
pub fn new( registry_store: impl RegistryStore + 'static, config: &Config, ) -> Result<Self, ApplicationError> { let registry_data = registry_store.load()?; let mut changed = false; let mut allocator = PortAllocator::new(config.get_valid_ports()); l...
function_block-full_function
[ { "content": "#[entrait(pub ChoosePort, mock_api=ChoosePortMock)]\n\nfn choose_port(_deps: &impl std::any::Any, available_ports: &HashSet<u16>) -> Option<u16> {\n\n let mut rng = rand::thread_rng();\n\n available_ports.iter().choose(&mut rng).copied()\n\n}\n\n\n", "file_path": "src/dependencies.rs", ...
Rust
ledger/sync/src/reqwest_transactions_fetcher.rs
dvdplm/mobilecoin
b3ef5e64eb476c02867b48c7d0ac613a7f1d9a68
use crate::transactions_fetcher_trait::{TransactionFetcherError, TransactionsFetcher}; use failure::Fail; use mc_api::{blockchain, conversions::block_num_to_s3block_path}; use mc_common::{ logger::{log, Logger}, ResponderId, }; use mc_transaction_core::{Block, BlockContents, BlockSignature}; use reqwest::Erro...
use crate::transactions_fetcher_trait::{TransactionFetcherError, TransactionsFetcher}; use failure::Fail; use mc_api::{blockchain, conversions::block_num_to_s3block_path}; use mc_common::{ logger::{log, Logger}, ResponderId, }; use mc_transaction_core::{Block, BlockContents, BlockSignature}; use reqwest::Erro...
; } Ok(s3_block_data.block_contents) } }
Err(ReqwestTransactionsFetcherError::InvalidBlockReceived( url.to_string(), "block data mismatch".to_string(), ))
call_expression
[ { "content": "#[inline]\n\npub fn to_io_error(err: serde_json::error::Error) -> std::io::Error {\n\n std::io::Error::new(std::io::ErrorKind::Other, Box::new(err))\n\n}\n\n\n\n// Helper boilerplate mapping mc_util_serial error to io::Error\n", "file_path": "util/keyfile/src/lib.rs", "rank": 0, "sc...
Rust
src/renderer/sprite_overlay.rs
Joey9801/wgpu-test
dd999da7b66354a3e5e0854f449d151a59110da7
use std::collections::HashMap; use crate::shader_cache::ShaderCache; use super::{frame_packet::{FramePacket, SpriteInstanceData}, Renderer, AtlasId, GpuAtlas}; pub struct SpriteOverlayRenderStage { pipeline: wgpu::RenderPipeline, texture_bind_group_layout: wgpu::BindGroupLayout, texture_bind_groups: HashM...
use std::collections::HashMap; use crate::shader_cache::ShaderCache; use super::{frame_packet::{FramePacket, SpriteInstanceData}, Renderer, AtlasId, GpuAtlas}; pub struct SpriteOverlayRenderStage { pipeline: wgpu::RenderPipeline, texture_bind_group_layout: wgpu::BindGroupLayout, texture_bind_groups: HashM...
, primitive_topology: wgpu::PrimitiveTopology::TriangleStrip, color_states: &[wgpu::ColorStateDescriptor { format: wgpu::TextureFormat::Bgra8Unorm, alpha_blend: wgpu::BlendDescriptor::REPLACE, color_blend: wgpu::BlendDescriptor { ...
Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Ccw, cull_mode: wgpu::CullMode::Back, depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, })
call_expression
[ { "content": "/// Represents a render stage that renders instanced 3d geometry to a texture view\n\nstruct ForwardRenderStage {\n\n uniform_bind_group: wgpu::BindGroup,\n\n uniform_buff: wgpu::Buffer,\n\n texture_bind_group_layout: wgpu::BindGroupLayout,\n\n pipeline: wgpu::RenderPipeline,\n\n te...
Rust
src/addition.rs
UCL-ARC/householder
1b7160248b9a118acd35fbc63e8e4ce542e0d91e
use crate::matrix::*; use crate::traits::*; use cauchy::Scalar; use std::marker::PhantomData; pub struct Addition<'a, Item, Mat1, Mat2, Layout, RS, CS>( Mat1, Mat2, PhantomData<Item>, PhantomData<Layout>, PhantomData<RS>, PhantomData<CS>, PhantomData<&'a ()>, ) where Item: Scalar, ...
use crate::matrix::*; use crate::traits::*; use cauchy::Scalar; use std::marker::PhantomData; pub struct Addition<'a, Item, Mat1, Mat2, Layout, RS, CS>( Mat1, Mat2, PhantomData<Item>, PhantomData<Layout>, PhantomData<RS>, PhantomData<CS>, PhantomData<&'a ()>, ) where Item: Scalar, ...
} impl<'a, Item, Mat1, Mat2, Layout, RS, CS> Dimensions for Addition<'a, Item, Mat1, Mat2, Layout, RS, CS> where Item: Scalar, Mat1: MatrixTrait<'a, Item, Layout, RS, CS>, Mat2: MatrixTrait<'a, Item, Layout, RS, CS>, Layout: LayoutIdentifier, RS: SizeIdentifier, CS: SizeIdentifier, { f...
elf { assert_eq!( mat1.dim(), mat2.dim(), "Dimensions not identical in a + b with a.dim() = {:#?}, b.dim() = {:#?}", mat1.dim(), mat2.dim() ); Self( mat1, mat2, PhantomData, PhantomData, ...
function_block-function_prefixed
[ { "content": "/// Implement this trait to provide an iterator\n\npub trait Iterable<'a, Item: Scalar, Iter: Iterator<Item = Item>> {\n\n fn iter(&'a self) -> Iter;\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 0, "score": 101093.68908491242 }, { "content": "/// General trait specifyi...
Rust
src/interpreter/value/function/function_arena.rs
emirayka/nia_interpreter_core
8b212e44fdede3d49cd75eddb255091a1d67b0e5
use std::collections::HashMap; use crate::interpreter::environment::EnvironmentId; use crate::interpreter::error::Error; use crate::interpreter::value::Function; use crate::interpreter::value::FunctionId; use crate::interpreter::value::Value; #[derive(Clone)] pub struct FunctionArena { arena: HashMap<FunctionId, ...
use std::collections::HashMap; use crate::interpreter::environment::EnvironmentId; use crate::interpreter::error::Error; use crate::interpreter::value::Function; use crate::interpreter::value::FunctionId; use crate::interpreter::value::Value; #[derive(Clone)] pub struct FunctionArena { arena: HashMap<FunctionId, ...
n_id).is_err()); } #[test] fn returns_err_when_attempts_to_free_function_twice() { let mut function_arena = FunctionArena::new(); let function = Function::Builtin(BuiltinFunction::new(test_func)); let function_id = function_arena.register_function(function);...
ind_a_function() { let mut function_arena = FunctionArena::new(); let function_id = FunctionId::new(234234); nia_assert(function_arena.free_function(functio
function_block-random_span
[ { "content": "pub fn infect(interpreter: &mut Interpreter) -> Result<(), Error> {\n\n let pairs: Vec<(&str, BuiltinFunctionType)> = vec![\n\n (\"assert\", assert::assert),\n\n (\"string\", string::string),\n\n (\"flookup\", flookup::flookup),\n\n (\"gensym\", gensym::gensym),\n\n ...
Rust
src/descriptor/pegin/dynafed_pegin.rs
apoelstra/elements-miniscript
144b68eb90b997c590e024590ed592b38ab41cf3
use bitcoin::hashes::Hash; use bitcoin::Script as BtcScript; use bitcoin::{self, blockdata::script, hashes}; #[allow(deprecated)] use bitcoin::{blockdata::opcodes, util::contracthash}; use bitcoin::{hashes::hash160, Address as BtcAddress}; use elements::secp256k1_zkp; use expression::{self, FromTree}; use policy::{se...
use bitcoin::hashes::Hash; use bitcoin::Script as BtcScript; use bitcoin::{self, blockdata::script, hashes}; #[allow(deprecated)] use bitcoin::{blockdata::opcodes, util::contracthash}; use bitcoin::{hashes::hash160, Address as BtcAddress}; use elements::secp256k1_zkp; use expression::{self, FromTree}; use policy::{se...
isfier)?; Ok(res) } fn max_satisfaction_weight(&self) -> Result<usize, Error> { let w = self.fed_desc.max_satisfaction_weight()?; Ok(w) } fn script_code<C: secp256k1_zkp::Verification>( &self, secp: &secp256k1_zkp::Secp256k1<C>, ) -> BtcScript w...
let fed_desc = BtcDescriptor::<Pk>::from_tree(&ms_expr)?; let elem_desc = Descriptor::<Pk>::from_tree(&top.args[1])?; Ok(Pegin::new(fed_desc, elem_desc)) } else { Err(Error::Unexpected(format!( "{}({} args) while parsing legacy_pegin descriptor", ...
random
[ { "content": "/// Compute the checksum of a descriptor\n\n/// Note that this function does not check if the\n\n/// descriptor string is syntactically correct or not.\n\n/// This only computes the checksum\n\npub fn desc_checksum(desc: &str) -> Result<String, Error> {\n\n let mut c = 1;\n\n let mut cls = 0...
Rust
src/vtok_p11/src/api/sign.rs
andrewhop/aws-nitro-enclaves-acm
1b7d538da7ae1b470e2ce7d9464dabc3526c99fb
use super::util::copy_data_to_ck_out_slice; use crate::backend::Mechanism; use crate::crypto::OpCtxState; use crate::pkcs11; use crate::util::ckraw::CkRawMechanism; use crate::Error; pub extern "C" fn C_SignInit( hSession: pkcs11::CK_SESSION_HANDLE, pMechanism: *mut pkcs11::CK_MECHANISM, hKey: pkcs11::CK...
use super::util::copy_data_to_ck_out_slice; use crate::backend::Mechanism; use crate::crypto::OpCtxState; use crate::pkcs11; use crate::util::ckraw::CkRawMechanism; use crate::Error; pub extern "C" fn C_SignInit( hSession: pkcs11::CK_SESSION_HANDLE, pMechanism: *mut pkcs11::CK_MECHANISM, hKey: pkcs11::CK...
pub extern "C" fn C_Sign( hSession: pkcs11::CK_SESSION_HANDLE, pData: *mut pkcs11::CK_BYTE, ulDataLen: pkcs11::CK_ULONG, pSignature: *mut pkcs11::CK_BYTE, pulSignatureLen: *mut pkcs11::CK_ULONG, ) -> pkcs11::CK_RV { trace!("C_Sign() called"); lock_session_mut!(hSession, session, _sarc); ...
let raw_mech = unsafe { CkRawMechanism::from_raw_ptr_unchecked(pMechanism) }; let mech = match Mechanism::from_ckraw_mech(&raw_mech) { Ok(mech) => mech, Err(_) => return pkcs11::CKR_MECHANISM_INVALID, }; lock_session_mut!(hSession, session, _sarc); session .sign_init(&mech, hKey...
function_block-function_prefix_line
[ { "content": "/// Configure the current EVP PKEY prior to a signing or a verification operation.\n\n/// Depending on the RSA mechanism used, padding might differ.\n\n/// ECDSA does not require any special handling\n\nfn config_evp_pkey_ctx(pctx: *mut ffi::EVP_PKEY_CTX, mech: &Mechanism) -> Result<()> {\n\n l...
Rust
paddlers-game-master/src/api/attacks.rs
jakmeier/paddlers-browser-game
6c7afbb1ac13467ed94c418a5515fcf98224149e
use super::{check_owns_village0, internal_server_error}; use crate::game_master::attack_funnel::PlannedAttack; use crate::game_master::event::Event; use crate::game_master::town_worker::TownWorkerEventMsg; use crate::{authentication::Authentication, game_master::story_worker::StoryWorkerMessage}; use actix::prelude::*;...
use super::{check_owns_village0, internal_server_error}; use crate::game_master::attack_funnel::PlannedAttack; use crate::game_master::event::Event; use crate::game_master::town_worker::TownWorkerEventMsg; use crate::{authentication::Authentication, game_master::story_worker::StoryWorkerMessage}; use actix::prelude::*;...
ses>, ) -> impl Responder { let event = Event::CheckVisitorHp { hobo_id: body.0 }; addr.town_worker .try_send(TownWorkerEventMsg(event, chrono::Utc::now())) .map_err(|e| eprintln!("Send failed: {:?}", e)) } pub(crate) fn new_invitation( pool: web::Data<crate::db::Pool>, body: web::Json<...
(crate) fn welcome_visitor( pool: web::Data<crate::db::Pool>, body: web::Json<StartFightRequest>, mut auth: Authentication, addr: web::Data<crate::ActorAddresses>, ) -> HttpResponse { let db: crate::db::DB = pool.get_ref().into(); let destination_village = body.destination; let attack = body...
random
[]
Rust
ap-com/src/models/field/mod.rs
Devisa/dv-api
3ac4116364f74b6d3f0d8bb8de80dff8230ffec9
pub mod value; pub mod target; use uuid::Uuid; use actix::prelude::*; use crate::{Id, Status, now, private}; use serde::{Serialize, Deserialize}; use crate::models::Model; use sqlx::{ FromRow, Postgres, postgres::PgPool, types::chrono::{NaiveDateTime, Utc} }; #[derive(Debug, FromRow, Clone, Serialize, Deseria...
pub mod value; pub mod target; use uuid::Uuid; use actix::prelude::*; use crate::{Id, Status, now, private}; use serde::{Serialize, Deserialize}; use crate::models::Model; use sqlx::{ FromRow, Postgres, postgres::PgPool, types::chrono::{NaiveDateTime, Utc} }; #[derive(Debug, FromRow, Clone, Serialize, Deseria...
} impl Actor for Field { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { log::info!("FIELD ACTOR STARTED: {:?}", self.id); } fn stopped(&mut self, ctx: &mut Self::Context) { log::info!("FIELD ACTOR STOPPED: {:?}", self.id); } } #[derive(sqlx::Type, ...
Field { id: Id::gen(), user_id: Id::nil(), name: String::new(), private: true, kind: FieldKind::default(), status: Status::Active, description: None, created_at: Utc::now().naive_utc(), updated_at: Utc::now().nai...
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn private() -> bool {\n\n true\n\n}\n\n\n\n\n\n\n\nimpl ToString for Status {\n\n #[inline]\n\n fn to_string(&self) -> String {\n\n match self {\n\n &Status::Active => \"Active\".to_string(),\n\n &Status::Deferred => \"Deferred\".to_string(),...
Rust
src/models/mod.rs
bazaah/aureate
3d362ecf7791d4c5e3cd321ebac5412fd43cbd37
use { crate::{ cli::ProgramArgs, match_with_log, models::{ assets::{Headers, ReadFrom, Record}, error::ErrorKind, }, }, csv::ReaderBuilder, serde_json::{map::Map as JMap, value::Value as JsonValue}, serde_yaml::{Mapping as YMap, Value as YamlVa...
use { crate::{ cli::ProgramArgs, match_with_log, models::{ assets::{Headers, ReadFrom, Record}, error::ErrorKind, }, }, csv::ReaderBuilder, serde_json::{map::Map as JMap, value::Value as JsonValue}, serde_yaml::{Mapping as YMap, Value as YamlVa...
pub fn get_reader(r: Option<&str>) -> Option<ReadFrom> { match r { Some("-") => Some(ReadFrom::Stdin), Some(file_name) => { let path = PathBuf::from(file_name); if path.is_file() { Some(ReadFrom::File(path)) } else { None ...
e) ), }, info!("Attempting to append to {}...", file_name) ), (None, _) => match_with_log!( Box::new(cout()), info!("No file detected, defaulting to stdout...") ), } }
function_block-function_prefixed
[ { "content": "pub fn generate_cli<'a>() -> Matches<'a> {\n\n let matches = App::new(\"aureate\")\n\n .about(\"Utility for converting CSV to JSON/YAML\")\n\n .author(crate_authors!(\"\\n\"))\n\n .version(crate_version!())\n\n .arg(\n\n Arg::with_name(\"verbosity\")\n\n ...
Rust
src/neq_pair.rs
advancedresearch/discrete
ba95cba322c27f58fae9a973f8a5af75c8c5833b
use std::marker::PhantomData; use Construct; use Data; use Count; use Of; use ToIndex; use ToPos; use Zero; pub struct NeqPair<T = Data>(PhantomData<T>); impl<T> Construct for NeqPair<T> { fn new() -> NeqPair<T> { NeqPair(PhantomData) } } impl Count<usize> for NeqPair<Data> { fn count(&self, dim: &usize) ->...
use std::marker::PhantomData; use Construct; use Data; use Count; use Of; use ToIndex; use ToPos; use Zero; pub struct NeqPair<T = Data>(PhantomData<T>); impl<T> Construct for NeqPair<T> { fn new() -> NeqPair<T> { NeqPair(PhantomData) } } impl Count<usize> for NeqPair<Data> { fn count(&self, dim: &usize) ->...
} impl ToPos<usize, (usize, usize)> for NeqPair<Data> { fn to_pos(&self, dim: &usize, index: usize, pos: &mut (usize, usize)) { use Pair; let pair: Pair<Data> = Construct::new(); if index % 2 == 0 { pair.to_pos(dim, index / 2, pos); } else { pair.to_pos(dim...
x): &(V, V) ) -> usize { let of: T = Construct::new(); let data: NeqPair<Data> = Construct::new(); let min = of.to_index(dim, min); let max = of.to_index(dim, max); data.to_index(&self.count(dim), &(min, max)) }
function_block-function_prefixed
[ { "content": "#[cfg(test)]\n\npub fn does_zero<T, U, V>()\n\n where\n\n T: Zero<U, V>\n\n{}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 164921.60008708935 }, { "content": "#[cfg(test)]\n\npub fn does_to_index<T, U, V>()\n\n where\n\n T: ToIndex<U, V>\n\n{}\n\n\...
Rust
opam_file_format/src/lexer.rs
PhotonQuantum/opam-file-format-rs
d7423d42b33084307a18291d68bb1146cc883d6d
use std::{char, u32}; use logos::{Lexer, Logos}; use partial_application::partial; #[derive(Logos, Debug, PartialEq)] enum EscapeToken { #[regex(r"(\r?\n) *", | lex | lex.slice().len())] EOL(usize), #[regex(r#"["'\\n\r\t ]"#, | lex | lex.slice().parse())] #[regex(r"\d\d\d", char_from_dec)] #[regex...
use std::{char, u32}; use logos::{Lexer, Logos}; use partial_application::partial; #[derive(Logos, Debug, PartialEq)] enum EscapeToken { #[regex(r"(\r?\n) *", | lex | lex.slice().len())] EOL(usize), #[regex(r#"["'\\n\r\t ]"#, | lex | lex.slice().parse())] #[regex(r"\d\d\d", char_from_dec)] #[regex...
#[derive(Logos, Debug, PartialEq)] pub enum Token { #[token(":")] COLON, #[token("{")] LBRACE, #[token("}")] RBRACE, #[token("[")] LBRACKET, #[token("]")] RBRACKET, #[token("(")] LPAR, #[token(")")] RPAR, #[token("\"", parse_string)] #[token("\"\"\"", pa...
l = false; } else { break; }; if let Some(pos) = parse_id_lodash(&remainder[remaining_pos..]) { remaining_pos += pos; is_final = true; } else { break; } } if is_final { lex.bump(remaining_pos); } let mut re...
function_block-function_prefixed
[ { "content": "pub fn pretty_error(filename: &str, source: &str, span: &lexer::Span, message: &str) {\n\n let split_source: Vec<&str> = source.lines().collect();\n\n let lexer::Span { start, end } = span.clone();\n\n let (start_ln, end_ln) = get_line_range(source, start, end);\n\n let pad = (&end_ln....
Rust
src/ws2300.rs
sanpii/ws2300
bc10b18bbf76a7084f973943648ba4e54bda1482
use std::cell::RefCell; use std::thread::sleep; use std::time::Duration; pub struct Device { port: Box<RefCell<dyn serial::SerialPort>>, memory: MemoryMap, } #[derive(serde_derive::Serialize)] pub struct Data { temperature_indoor: f32, temperature_outdoor: f32, dewpoint: f32, humidity_indoor: ...
use std::cell::RefCell; use std::thread::sleep; use std::time::Duration; pub struct Device { port: Box<RefCell<dyn serial::SerialPort>>, memory: MemoryMap, } #[derive(serde_derive::Serialize)] pub struct Data { temperature_indoor: f32, temperature_outdoor: f32, dewpoint: f32, humidity_indoor: ...
pub fn wind_speed(&self) -> serial::Result<f32> { let value = self.try_read(&self.memory.wind_speed)?; Ok(((((value[1] & 0xF) as u16) << 8) as f32 + value[0] as f32) / 10.0) } pub fn wind_dir(&self) -> serial::Result<f32> { let value = self.try_read(&self.memory.wind_dir)?; ...
fn humidity(&self, memory: &Memory) -> serial::Result<u32> { let value = self.try_read(memory)?; let low = (value[0] >> 4) as u32 * 10 + (value[0] & 0xF) as u32; Ok(low) }
function_block-full_function
[ { "content": "#[derive(Parser)]\n\nstruct Opt {\n\n device: String,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 3, "score": 24874.938038397464 }, { "content": "fn main() {\n\n let opt = Opt::parse();\n\n\n\n let ws2300 = ws2300::Device::new(opt.device);\n\n\n\n let data = ma...
Rust
src/daemon/mod.rs
TheMindCompany/signedurl
c710b984ce9f7bb4074bcdff3821d279513e4fe4
mod response; use actix_web::middleware::Logger; use env_logger::Env; use response::{SignedUrlResponse, SignedUrlAttributes}; use crate::signed_url::SignedUrlRunner; use crate::command_control; use crate::command_control::CmdCtl; use actix_web::{HttpRequest, Responder, HttpResponse}; use structopt::StructOpt; use uuid:...
mod response; use actix_web::middleware::Logger; use env_logger::Env; use response::{SignedUrlResponse, SignedUrlAttributes}; use crate::signed_url::SignedUrlRunner; use crate::command_control; use crate::command_control::CmdCtl; use actix_web::{HttpRequest, Responder, HttpResponse}; use structopt::StructOpt; use uuid:...
pub async fn put_key() -> impl Responder { let mut options = command_control::CmdCtl::from_args(); options.method = "PUT".to_string(); match &options.prefix { Some(prefix) => { let mut new_key = prefix.clone(); new_key.push_str("/"); ...
attributes.set_method(method); attributes.set_ttl(ttl); attributes.set_engine("aws".to_string()); attributes.set_request(origin); json.set_attributes(attributes); json }
function_block-function_prefix_line
[ { "content": "fn create_pathbuf(string_path: String) -> PathBuf {\n\n Path::new(&string_path).to_path_buf()\n\n}\n", "file_path": "src/command_control/completion_handler/generator/build_filepath.rs", "rank": 0, "score": 66463.38484352485 }, { "content": "fn create_completion_mod(name: &'s...
Rust
src/shape.rs
MinusKelvin/game-util-rs
d9bc506342933188a9c2076733e1f89e7c13c407
use crate::prelude::*; pub struct ShapeRenderer { pub pixels_per_unit: f32, gl: Gl, vertices: Vec<ShapeVertex>, indices: Vec<u32>, vbo: glow::Buffer, ibo: glow::Buffer, shader: glow::Program, proj_loc: glow::UniformLocation, } impl ShapeRenderer { pub fn new(gl: &Gl, shader: glow::...
use crate::prelude::*; pub struct ShapeRenderer { pub pixels_per_unit: f32, gl: Gl, vertices: Vec<ShapeVertex>, indices: Vec<u32>, vbo: glow::Buffer, ibo: glow::Buffer, shader: glow::Program, proj_loc: glow::UniformLocation, } impl ShapeRenderer { pub fn new(gl: &Gl, shader: glow::...
pub fn shape_shader(gl: &Gl) -> glow::Program { glutil::compile_shader_program( gl, include_str!("shaders/shape.vert.glsl"), include_str!("shaders/shape.frag.glsl"), ) .unwrap() }
function_block-full_function
[ { "content": "pub fn compile_shader(gl: &Gl, shader_type: u32, code: &str) -> Result<glow::Shader, String> {\n\n let mut patched_code = String::new();\n\n #[cfg(not(target_arch = \"wasm32\"))]\n\n patched_code.push_str(\"#version 330 core\\n\");\n\n #[cfg(target_arch = \"wasm32\")]\n\n patched_co...
Rust
src/lib.rs
MrKonstantinT/min-binary-heap
80ccdeb22e7c971e756aebb98454c4767f263b34
pub struct MinBinaryHeap<T> { tree: Vec<T>, } impl<T> MinBinaryHeap<T> where T: Ord { pub fn extract_min(&mut self) -> Option<T> { if self.tree.len() < 1 { return None; } else if self....
pub struct MinBinaryHeap<T> { tree: Vec<T>, } impl<T> MinBinaryHeap<T> where T: Ord { pub fn extract_min(&mut self) -> Option<T> { if self.tree.len() < 1 { return None; } else if self....
assert_eq!(queue.child_index_min(3), Some(8)); assert_eq!(queue.child_index_min(2), Some(6)); assert_eq!(queue.child_index_min(1), Some(4)); assert_eq!(queue.child_index_min(0), Some(1)); } fn setup() -> MinBinaryHeap<u8> { let mut queue = MinBinaryHeap::new(); q...
ld_index_min(current_index) { Some(index) => index, None => break, } } } Some(minimum) } fn parent_index(&self, of_index: usize) -> usize { if of_index < 1 || of_index >= self.size...
random
[]
Rust
model/src/addressing_mode.rs
cdubz/mos6502
d88ad4deb8bc55ecba72d833ec05eafb76eb3807
use crate::address; use crate::machine::{Cpu, Memory}; use crate::operand; use crate::Address; pub trait Trait { type Operand: operand::Trait; fn instruction_bytes() -> u16 { <Self::Operand as operand::Trait>::instruction_bytes() } } pub trait ReadJumpTarget: Trait { fn read_jump_target<M: Mem...
use crate::address; use crate::machine::{Cpu, Memory}; use crate::operand; use crate::Address; pub trait Trait { type Operand: operand::Trait; fn instruction_bytes() -> u16 { <Self::Operand as operand::Trait>::instruction_bytes() } } pub trait ReadJumpTarget: Trait { fn read_jump_target<M: Mem...
} } pub struct IndirectYIndexed; impl Trait for IndirectYIndexed { type Operand = operand::Byte; } impl IndirectYIndexed { fn address<M: Memory>(cpu: &Cpu, memory: &mut M) -> Address { let base_address = memory.read_u8(cpu.pc.wrapping_add(1)); memory .read_u16_le_zero_page(base...
if address::lo(address) != 0xFF { memory.read_u16_le(address) } else { let lo = memory.read_u8(address); let hi = memory.read_u8(address & 0xFF00); address::from_u8_lo_hi(lo, hi) }
if_condition
[]
Rust
src/movement/crab_move.rs
sim82/game1
e4cd03c91421dea3234eaf7b4f9fabbae30312be
use crate::{ pointer::MouseGrabState, sprites, tilemap::{hex_neighbors, pixel_to_pointy_hex, pointy_hex_to_aabb}, tune, }; use bevy::{prelude::*, sprite::collide_aabb::collide}; use bevy_aseprite::AsepriteAnimation; use bevy_ecs_tilemap::{MapQuery, Tile, TilePos}; use super::zap::BeingZapped; #[derive...
use crate::{ pointer::MouseGrabState, sprites, tilemap::{hex_neighbors, pixel_to_pointy_hex, pointy_hex_to_aabb}, tune, }; use bevy::{prelude::*, sprite::collide_aabb::collide}; use bevy_aseprite::AsepriteAnimation; use bevy_ecs_tilemap::{MapQuery, Tile, TilePos}; use super::zap::BeingZapped; #[derive...
pub fn clip_movement( map_query: &mut MapQuery, tile_query: &Query<&Tile>, translation: Vec3, delta: Vec3, ) -> Vec3 { let p = translation + Vec3::new(256.0, 256.0, 0.0); let (x, y) = pixel_to_pointy_hex(p); let tile_pos = TilePos(x as u32, y as u32); let player_size = ...
function_block-full_function
[ { "content": "pub fn debug_draw_cross(debug_lines: &mut DebugLines, p: Vec3, duration: Option<f32>) {\n\n let duration = duration.unwrap_or(0.0);\n\n let s = 2.0;\n\n let c0 = Vec3::new(-s, s, 0.0);\n\n let c1 = Vec3::new(s, s, 0.0);\n\n\n\n let mut start = p + c0;\n\n let mut end = p - c0;\n\...
Rust
src/digging.rs
seurimas/LudumDare48
dd18cafcf46175d91ec936b08a7885e0a28c92ec
use crate::prelude::*; use amethyst::renderer::Camera; pub const SCOOPS_PER_BLOCK: u32 = 4; pub const SCOOPS_PER_METER: u32 = 28; pub const BLOCKS_PER_METER: u32 = SCOOPS_PER_METER / SCOOPS_PER_BLOCK; pub const DRILL_METER: u32 = 20; pub const DRILL_TIME: f32 = 60.; pub const DRILL_SPEED: f32 = 4.; pub const ROBOT_MET...
use crate::prelude::*; use amethyst::renderer::Camera; pub const SCOOPS_PER_BLOCK: u32 = 4; pub const SCOOPS_PER_METER: u32 = 28; pub const BLOCKS_PER_METER: u32 = SCOOPS_PER_METER / SCOOPS_PER_BLOCK; pub const DRILL_METER: u32 = 20; pub const DRILL_TIME: f32 = 60.; pub const DRILL_SPEED: f32 = 4.; pub const ROBOT_MET...
} pub struct DiggingBundle; impl SystemBundle<'_, '_> for DiggingBundle { fn build( self, world: &mut World, dispatcher: &mut DispatcherBuilder<'_, '_>, ) -> Result<(), Error> { world.insert(DiggingStatus::default()); dispatcher.add(DepthCameraSystem, "depth_camera", &...
let alert_entity = spawner.spawn_ui_widget( "prefabs/robot_alertable.ron", Position { x: -64., y: -224. }, ); alertables .insert( alert_entity, crate::cards::Alertable { ...
function_block-function_prefix_line
[ { "content": "pub fn update_texture(\n\n image: &mut UiImage,\n\n new_left: Option<f32>,\n\n new_right: Option<f32>,\n\n new_top: Option<f32>,\n\n new_bottom: Option<f32>,\n\n) {\n\n if let UiImage::PartialTexture {\n\n left,\n\n right,\n\n top,\n\n bottom,\n\n ...
Rust
src/split.rs
Zenithsiz/int-conv
627ec21edfa167c2d7a629e2e99e93f8339dc982
use super::{Truncate, ZeroExtend}; use core::{ mem, ops::{Shl, Shr}, }; pub trait Split: Sized { type Hi; type Lo; fn hi(self) -> Self::Hi; fn lo(self) -> Self::Lo; fn lo_hi(self) -> (Self::Lo, Self::Hi); } pub trait Join: Split { fn join(lo: <Self as Split>::Lo, hi: <Self as Split>::Lo) -> ...
use super::{Truncate, ZeroExtend}; use core::{ mem, ops::{Shl, Shr}, }; pub trait Split: Sized { type Hi; type Lo; fn hi(self) -> Self::Hi; fn lo(self) -> Self::Lo; fn lo_hi(self) -> (Self::Lo, Self::Hi); } pub trait Join: Split { fn join(lo: <Self as Split>::Lo, hi: <Self as Split>::Lo) -> ...
#[test] #[rustfmt::skip] fn split_lo_hi() { assert_eq!(u128::lo_hi(u128::MAX), (u128::lo(u128::MAX), u128::hi(u128::MAX))); assert_eq!( u64::lo_hi( u64::MAX), ( u64::lo( u64::MAX), u64::hi( u64::MAX))); assert_eq!( u32::lo_hi( u32::MAX), ( u32::lo( u32::MAX), u32::hi( u32::MAX))); assert_eq!( u16::lo_hi(...
fn split_hi_half() { assert_eq!(u128::hi(u128::from(u64::MAX)), 0); assert_eq!( u64::hi( u64::from(u32::MAX)), 0); assert_eq!( u32::hi( u32::from(u16::MAX)), 0); assert_eq!( u16::hi( u16::from( u8::MAX)), 0); }
function_block-full_function
[ { "content": "/// All types that are signed\n\npub trait IsSigned: Signed<Signed = Self> {}\n\nimpl<T: Signed<Signed = T>> IsSigned for T {}\n\n\n", "file_path": "src/sign.rs", "rank": 2, "score": 62218.968253502346 }, { "content": "/// All types that are unsigned\n\npub trait IsUnsigned: Si...
Rust
faux_macros/src/methods/morphed.rs
Wesmania/faux
639cbed330633b12b03696cdf9392c8cf08dab6a
use crate::{ methods::receiver::{self, Receiver}, self_type::SelfType, }; use quote::{quote, ToTokens}; use syn::spanned::Spanned; struct SpanMarker(proc_macro2::Span); impl Spanned for SpanMarker { fn span(&self) -> proc_macro2::Span { self.0.clone() } } pub struct Signature<'a> { name: ...
use crate::{ methods::receiver::{self, Receiver}, self_type::SelfType, }; use quote::{quote, ToTokens}; use syn::spanned::Spanned; struct SpanMarker(proc_macro2::Span); impl Spanned for SpanMarker { fn span(&self) -> proc_macro2::Span { self.0.clone() } } pub struct Signature<'a> { name: ...
} impl<'a> MethodData<'a> { pub fn create_when(&self, output: Option<&syn::Type>) -> syn::ImplItemMethod { let &MethodData { ref name_string, ref arg_types, .. } = self; let mock_ident = syn::Ident::new( &format!("_when_{}", name_string), ...
self.method_data .as_ref() .filter(|m| !m.is_private) .map(|m| m.create_when(self.output)) }
function_block-function_prefix_line
[ { "content": "// makes methods in this impl block be at least visible to super\n\nfn publicize_methods(impl_block: &mut syn::ItemImpl) {\n\n impl_block\n\n .items\n\n .iter_mut()\n\n .filter_map(|item| match item {\n\n syn::ImplItem::Method(m) => Some(m),\n\n _ => N...
Rust
curve-benches/src/macros/ec.rs
daira/curves
23e87bf224c23be5c5bccc6084aae31fff8bb83f
macro_rules! ec_bench { ($projective:ty, $affine:ty) => { #[bench] fn bench_rand(b: &mut ::test::Bencher) { let mut rng = XorShiftRng::seed_from_u64(1231275789u64); b.iter(|| <$projective>::rand(&mut rng)); } #[bench] fn bench_mul_assign(b: &mut ::tes...
macro_rules! ec_bench { ($projective:ty, $affine:ty) => { #[bench] fn bench_rand(b: &mut ::test::Bencher) { let mut rng = XorShiftRng::seed_from_u64(1231275789u64); b.iter(|| <$projective>::rand(&mut rng)); } #[bench] fn bench_mul_assign(b: &mut ::tes...
+ 1) % SAMPLES; let index = count * num_bytes; <$affine>::deserialize(&v[index..(index + num_bytes)]).unwrap() }); } #[bench] fn bench_ser(b: &mut ::test::Bencher) { use ark_ec::ProjectiveCurve; use ark_serialize::CanonicalSeri...
}); } #[bench] fn bench_add_assign(b: &mut ::test::Bencher) { const SAMPLES: usize = 1000; let mut rng = XorShiftRng::seed_from_u64(1231275789u64); let v: Vec<($projective, $projective)> = (0..SAMPLES) .map(|_| (<$projective>::rand(&mut...
random
[ { "content": "fn random_expansion_tests<F: Field, R: Rng>(rng: &mut R) {\n\n for _ in 0..ITERATIONS {\n\n // Compare (a + b)(c + d) and (a*c + b*c + a*d + b*d)\n\n\n\n let a = F::rand(rng);\n\n let b = F::rand(rng);\n\n let c = F::rand(rng);\n\n let d = F::rand(rng);\n\n\n\...
Rust
src/utils.rs
gurkeclub/wvr
a51883af6e4eab6335c88a1fb106cb0a57d72f7b
use std::collections::HashMap; use std::fs; use std::fs::File; use std::path::{Path, PathBuf}; use std::str::FromStr; use anyhow::{Context, Result}; use clap::{App, Arg}; use git2::Repository; use glium::glutin; use glium::glutin::event_loop::EventLoop; use glium::Display; use glutin::dpi::PhysicalSize; use glutin::...
use std::collections::HashMap; use std::fs; use std::fs::File; use std::path::{Path, PathBuf}; use std::str::FromStr; use anyhow::{Context, Result}; use clap::{App, Arg}; use git2::Repository; use glium::glutin; use glium::glutin::event_loop::EventLoop; use glium::Display; use glutin::dpi::PhysicalSize; use glutin::...
} else { None }; let config_path = config_path.unwrap(); let project_path = config_path.parent().unwrap().to_owned(); let config: ProjectConfig = if let Ok(file) = File::open(&config_path) { serde_json::from_reader::<File, ProjectConfig>(file).unwrap() } else { panic!(...
Some(wvr_shadertoy::create_project_from_shadertoy_url( data_path.as_path(), shadertoy_url, matches.value_of("shadertoy-key").unwrap(), )?)
call_expression
[ { "content": "pub fn start_wvr(\n\n display: Display,\n\n mut wvr: Wvr,\n\n event_loop: EventLoop<()>,\n\n order_receiver: Receiver<Message>,\n\n) {\n\n event_loop.run(move |event, _, control_flow| {\n\n if wvr.get_recording() {\n\n println!(\n\n \"{:} / {:}\",\n\...
Rust
runtime/Rust/src/parser.rs
3c1u/antlr4
61961d03310dcfcad3ba29a83a11a57942c2fe62
use std::any::Any; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::marker::{PhantomData, Unsize}; use std::mem; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use std::sync::Arc; use crate::atn::ATN; use crate::atn_simulator::IATNSimulator; use crate::common_token_factory::TokenFactory; use ...
use std::any::Any; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::marker::{PhantomData, Unsize}; use std::mem; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use std::sync::Arc; use crate::atn::ATN; use crate::atn_simulator::IATNSimulator; use crate::common_token_factory::TokenFactory; use ...
} impl<T, Ext> BaseParser<Ext, T> where T: ParseTreeListener + ?Sized + 'static, Ext: ParserRecog<Recog=Self> + 'static { pub fn new_base_parser( input: Box<dyn TokenStream>, interpreter: Arc<ParserATNSimulator>, ext: Ext, ) -> BaseParser<Ext, T> { BaseParser { ...
fn get_rule_invocation_stack(&self) -> Vec<String> { let mut vec = Vec::new(); let rule_names = self.get_rule_names(); let mut ctx = self.get_parser_rule_context().clone(); loop { let rule_index = ctx.get_rule_index(); vec.push(rule_names.get(rule_index).unwrap_or...
function_block-full_function
[ { "content": "/// **! Usually generated by ANTLR !**\n\n///\n\n/// This trait combines everything that can be used to extend Parser behavior\n\npub trait LexerRecog: Recognizer + Actions<Recog=BaseLexer<Self>> + Sized + 'static {\n\n /// Callback to extend emit behavior\n\n fn before_emit(_lexer: &mut Bas...
Rust
src/connectivity/network/netstack3/core/src/device/loopback.rs
sffc/fuchsia-clone
633553d647314c9032f75d430c9377b9f6cfc26e
use alloc::vec::Vec; use core::convert::Infallible as Never; use net_types::{ ip::{AddrSubnet, AddrSubnetEither, IpAddr, IpAddress}, SpecifiedAddr, Witness as _, }; use packet::{Buf, BufferMut, SerializeError, Serializer}; use crate::{ device::{DeviceIdInner, FrameDestination}, error::NotFoundError, ...
use alloc::vec::Vec; use core::convert::Infallible as Never; use net_types::{ ip::{AddrSubnet, AddrSubnetEither, IpAddr, IpAddress}, SpecifiedAddr, Witness as _, }; use packet::{Buf, BufferMut, SerializeError, Serializer}; use crate::{ device::{DeviceIdInner, FrameDestination}, error::NotFoundError, ...
}
fn test_loopback_methods() { const MTU: u32 = 66; let mut ctx = DummyEventDispatcherBuilder::default().build::<DummyEventDispatcher>(); let device = ctx.state.add_loopback_device(MTU).expect("error adding loopback device"); crate::device::initialize_device(&mut ctx, device); ass...
function_block-full_function
[]
Rust
cargo/binding/lib.rs
afinch7/deno_std
df57d71c3006ab896d2df84a9f54554083756eba
use deno::{PinnedBuf}; use deno::bindings::{BindingOpResult, BindingResult, new_binding_error}; use futures; use serde::{Deserialize, Serialize}; use serde_json; use std::path::{Path, PathBuf}; use cargo::ops::compile; use cargo::ops::CompileOptions; use cargo::util::homedir; use cargo::util::config::Config; use cargo:...
use deno::{PinnedBuf}; use deno::bindings::{BindingOpResult, BindingResult, new_binding_error}; use futures; use serde::{Deserialize, Serialize}; use serde_json; use std::path::{Path, PathBuf}; use cargo::ops::compile; use cargo::ops::CompileOptions; use cargo::util::homedir; use cargo::util::config::Config; use cargo:...
let data_str = std::str::from_utf8(&data[..]).unwrap(); let build_config = BuildConfig::from_json(data_str); let build_result = match run_cargo_build(build_config) { Ok(br) => br, Err(err) => return BindingOpResult::Sync(Err(err)), }; let result = serde_json::to_string(&build_result...
if !is_sync { return BindingOpResult::Async(Box::new(futures::future::err(new_binding_error(String::from("Async not supported!"))))); }
if_condition
[ { "content": " fn(): void {\n\n const actual = datetime.toIMF(new Date(0));\n\n const expected = \"Thus, 01 Jan 1970 00:00:00 GMT\";\n\n assertEquals(actual, expected);\n", "file_path": "datetime/test.ts", "rank": 1, "score": 92260.031243335 }, { "content": " fn(): void {\n\n a...
Rust
src/yubihsm.rs
jacksteroo/kms
77d32316025a6412bf53e0483f049ca6cf5ff982
use crate::{ config::{provider::yubihsm::YubihsmConfig, KmsConfig}, error::{KmsError, KmsErrorKind}, }; use abscissa::{Error, GlobalConfig}; use std::{ process, sync::{Mutex, MutexGuard}, }; use yubihsm::{Client, Connector}; #[cfg(not(feature = "yubihsm-mock"))] use { crate::config::provider::yubihs...
use crate::{ config::{provider::yubihsm::YubihsmConfig, KmsConfig}, error::{KmsError, KmsErrorKind}, }; use abscissa::{Error, GlobalConfig}; use std::{ process, sync::{Mutex, MutexGuard}, }; use yubihsm::{Client, Connector}; #[cfg(not(feature = "yubihsm-mock"))] use { crate::config::provider::yubihs...
} impl From<yubihsm::DeviceErrorKind> for KmsErrorKind { fn from(other: yubihsm::device::DeviceErrorKind) -> KmsErrorKind { use yubihsm::device::DeviceErrorKind; match other { DeviceErrorKind::AuthenticationFailed => KmsErrorKind::AccessError, DeviceErrorKind::Inv...
fn from(other: yubihsm::client::ClientErrorKind) -> KmsErrorKind { use yubihsm::client::ClientErrorKind; match other { ClientErrorKind::AuthenticationError => KmsErrorKind::AccessError, ClientErrorKind::ConnectionError { kind } => kind.into(), ClientErrorKind::Device...
function_block-full_function
[ { "content": "/// Initialize the chain registry from the configuration file\n\npub fn load_config(config: &KmsConfig) -> Result<(), KmsError> {\n\n for config in &config.chain {\n\n REGISTRY.register(Chain::from_config(config)?)?;\n\n }\n\n\n\n let mut registry = REGISTRY.0.write().unwrap();\n\n...
Rust
src/applications.rs
benashford/rs-transducers
73a63af59fa8cd73c59383d45603f37f35670bc7
/* * Copyright 2016 rs-transducers developers * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * exc...
/* * Copyright 2016 rs-transducers developers * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * exc...
Err(e) => Err(e) } } fn complete(&mut self) -> Result<(), SendError<O>> { Ok(()) } } impl<O, SR> TransducingSender<O, SR> where SR: Reducing<O, (), SendError<O>> { pub fn send(&mut self, f: O) -> Result<bool, SendError<O>> { ma...
ult<StepResult, SendError<O>> { match self.0.send(value) { Ok(_) => Ok(StepResult::Continue),
function_block-random_span
[ { "content": "/// Defines a reducing function from I to O with step errors of E\n\npub trait Reducing<I, O, E> {\n\n /// The type of each value after the reducing function\n\n type Item;\n\n\n\n /// Transducers must call the underlying `init`\n\n /// TODO: may not be required at all. Not currently u...
Rust
src/connection.rs
brennie/mizuno
88ccca58027e27de4c5d30635e7ecccd46664a92
use std::collections::HashSet; use std::fmt; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; use std::str::{self, Utf8Error}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use failure::Fail; use crate::capabilities::Capab...
use std::collections::HashSet; use std::fmt; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; use std::str::{self, Utf8Error}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use failure::Fail; use crate::capabilities::Capab...
pub fn capabilities(&self) -> &HashSet<Capability> { &self.capabilities } pub fn encoding(&self) -> &str { &self.encoding } pub fn read_chunk(&mut self) -> Result<Chunk, ReadChunkError> { Self::read_chunk_from(&mut self.stdout) } pub fn run_command(&'_ mut self, ...
pub(self) fn from_builder(builder: &ConnectionBuilder) -> Result<Self, ConnectionError> { let hg_cmd = builder .hg .as_ref() .map(AsRef::as_ref) .unwrap_or_else(|| Path::new("hg")); let mut command = Command::new(hg_cmd); command .arg...
function_block-full_function
[ { "content": "fn main() -> Result<(), Error> {\n\n let path = Path::new(&env::var(\"OUT_DIR\")?).join(\"capabilities.codegen.rs\");\n\n let mut file = BufWriter::new(File::create(&path)?);\n\n\n\n write!(&mut file, \"#[allow(clippy::all)]\\n\")?;\n\n write!(\n\n &mut file,\n\n \"static...
Rust
src/commands/config.rs
vincentserpoul/funicular
de89405b62187f35b48804c17bda63c069ced09d
use crate::config::apk_overlay::APKOverlay; use color_eyre::eyre::Result; use gumdrop::Options; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use thiserror::Error; #[derive(Debug, Options)] pub struct ConfigOpts { #[options(help = "config file related command, gen, list")] pub hel...
use crate::config::apk_overlay::APKOverlay; use color_eyre::eyre::Result; use gumdrop::Options; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use thiserror::Error; #[derive(Debug, Options)] pub struct ConfigOpts { #[options(help = "config file related command, gen, list")] pub hel...
} #[derive(Debug, Options)] pub struct LsOpts { #[options(help = "show this help message")] help: bool, #[options(help = "path of folder containing all your system configs")] system_config_path: Option<PathBuf>, } #[derive(Error, Debug)] pub enum LsError { #[error("`{0}` is not a directory")] ...
let mut file = File::create("config.toml")?; file.write_all(toml::to_string(&overlay).unwrap().as_bytes())?; Ok(()) }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn with_provisioners() {\n\n let overlay =\n\n APKOverlay::from_path(\"./tests/config/apk_overlay/configs/with_provisioners.toml\").unwrap();\n\n assert_eq!(overlay.base.hostname, String::from(\"with_provisioners\"));\n\n assert_eq!(overlay.base.arch, Arch::AARCH64);\n\n...
Rust
misskey-api/src/model/id/aid.rs
bunnegirl/misskey-rs
43ccdbb7c4519a1d92d719df31b755dede900307
use std::convert::TryFrom; use std::fmt::{self, Display}; use std::str::FromStr; use chrono::{DateTime, TimeZone, Utc}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use thiserror::Error; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Aid { pub timestamp: i64, ...
use std::convert::TryFrom; use std::fmt::{self, Display}; use std::str::FromStr; use chrono::{DateTime, TimeZone, Utc}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use thiserror::Error; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Aid { pub timestamp: i64, ...
Utc}; use rand::{self, Rng}; fn new() -> Aid { from_datetime(Utc::now()) } fn from_datetime<Tz>(datetime: DateTime<Tz>) -> Aid where Tz: TimeZone, { from_datetime_with_source(datetime, &mut rand::thread_rng()) } fn from_datetime_with_source<Tz, R>(datetime: Dat...
{ serializer.collect_str(self) } } impl<'de> Deserialize<'de> for Aid { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { String::deserialize(deserializer)? .parse() .map_err(de::Error::custom) } } #[cfg(...
random
[]
Rust
src/lib.rs
sotch-pr35mac/character_converter
9fc1fe8954cf37ae150fc7a23d468c7ed34352a1
#![cfg_attr(feature = "bench", feature(test))] extern crate bincode; use std::borrow::Cow; use std::collections::HashMap; use bincode::deserialize_from; use fst::raw::{Fst, Output}; use once_cell::sync::Lazy; static T2S: Lazy<HashMap<String, String>> = Lazy::new(|| deserialize_from(&include_bytes!("../data/t2s.p...
#![cfg_attr(feature = "bench", feature(test))] extern crate bincode; use std::borrow::Cow; use std::collections::HashMap; use bincode::deserialize_from; use fst::raw::{Fst, Output}; use once_cell::sync::Lazy; static T2S: Lazy<HashMap<String, String>> = Lazy::new(|| deserialize_from(&include_bytes!("../data/t2s.p...
ied = "人人生而自由﹐在尊严和权利上一律平等。他们赋有理性和良心﹐并应以兄弟关系的精神互相对待。"; b.iter(|| !is_traditional(simplified)); } #[bench] #[cfg(feature = "bench")] fn bench_tokenize(b: &mut Bencher) { let sentence = "人人生而自由﹐在尊严和权利上一律平等。他们赋有理性和良心﹐并应以兄弟关系的精神互相对待。"; b.iter(|| tokenize(sentence)); } }
_to_simplified(traditional)); } #[bench] #[cfg(feature = "bench")] fn bench_simplified_to_traditional(b: &mut Bencher) { let simplified = "人人生而自由﹐在尊严和权利上一律平等。他们赋有理性和良心﹐并应以兄弟关系的精神互相对待。"; b.iter(|| simplified_to_traditional(simplified)); } #[bench] #[cfg(feature = "bench")] fn bench_traditional_to_tradition...
random
[ { "content": "fn build_fst(input: &Path, output: &Path) {\n\n\tlet rdr = File::open(input).map(BufReader::new).unwrap();\n\n\tlet dictionary: HashMap<String, String> = deserialize_from(rdr).unwrap();\n\n\n\n\tlet mut keys: Vec<_> = dictionary.keys().collect();\n\n\tkeys.sort_unstable();\n\n\tlet fst = Fst::from...
Rust
api/src/toggl_api/endpoints.rs
simonrozsival/toggl-utopia
23a7ee33ae4d4237c97fe8c84470608676f1e222
use super::models::{Project, TimeEntry}; use serde::{de::DeserializeOwned, Serialize}; const BASE_URL: &str = "https://mobile.toggl.space/api"; type Url = String; #[derive(Debug)] pub enum Endpoint<T: Serialize + DeserializeOwned> { Get(Url), Post(Url, T), Put(Url, T), } pub trait CreateOrUpdate: Serial...
use super::models::{Project, TimeEntry}; use serde::{de::DeserializeOwned, Serialize}; const BASE_URL: &str = "https://mobile.toggl.space/api"; type Url = String; #[derive(Debug)] pub enum Endpoint<T: Serialize + DeserializeOwned> { Get(Url), Post(Url, T), Put(Url, T), } pub trait CreateOrUpdate: Serial...
fn update(self) -> Endpoint<Self> { Endpoint::<Project>::Put(format!("{}/v9/projects/{}", BASE_URL, self.id), self) } } impl CreateOrUpdate for TimeEntry { fn create(self) -> Endpoint<Self> { Endpoint::<TimeEntry>::Post( format!( "{}/v9/workspaces/{}/time_entri...
fn create(self) -> Endpoint<Self> { Endpoint::<Project>::Post( format!("{}/v9/workspaces/{}/projects", BASE_URL, self.workspace_id), self, ) }
function_block-full_function
[ { "content": "pub trait Entity: Clone + Serialize + PartialEq {\n\n fn id(&self) -> Id;\n\n fn is_deleted(&self) -> bool;\n\n fn last_update(&self) -> DateTime<Utc>;\n\n fn exists_on_server(&self) -> bool {\n\n self.id() > 0\n\n }\n\n}\n\n\n\nimpl Entity for User {\n\n fn id(&self) -> I...
Rust
dpx/src/dpx_vf.rs
burrbull/tectonic
3549a22ace6615043bc7570d1ca3f9df67c71577
/* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks. Copyright (C) 2002-2018 by Jin-Hwan Cho and Shunsaku Hirata, the dvipdfmx project team. Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu> This program is free software; you can redistribute it and/or modify it un...
/* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks. Copyright (C) 2002-2018 by Jin-Hwan Cho and Shunsaku Hirata, the dvipdfmx project team. Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu> This program is free software; you can redistribute it and/or modify it un...
tting on code={}", code); break; } } } } /* Unfortunately, the following code isn't smart enough to load the vf only once for multiple point sizes. You will get a separate copy of each VF in memory (and a separate opening and reading of the file) for each point size. Since VFs a...
= dvi_locate_font( &dev_font.name, sqxfw(vf_fonts[thisfont as usize].ptsize, dev_font.size as fixword), ) as i32; } unsafe fn process_vf_file<R: Read>(vf_handle: &mut R, thisfont: i32) { loop { let code = u8::get(vf_handle); match code { FNT_DEF1 | FNT_DEF2 | FNT_DEF3...
random
[]
Rust
src/utils.rs
jaredforth/servstat
b284e1bc5641a7cd5817228739fa27f1b84f9249
use regex::Regex; use url::{Url, ParseError}; use reqwest::Client; pub fn parse_url(url: String, is_secure: bool) -> Option<String> { match Url::parse(url.as_str()) { Ok(u) => { println!("{:?}", u); Some(u.into_string()) } Err(e) => { pri...
use regex::Regex; use url::{Url, ParseError}; use reqwest::Client; pub fn parse_url(url: String, is_secure: bool) -> Option<String> { match Url::parse(url.as_str()) { Ok(u) => { println!("{:?}", u); Some(u.into_string()) } Err(e) => { pri...
lazy_static! { static ref WWW_RE: Regex = Regex::new(r"www\.").unwrap(); static ref HTTP_RE: Regex = Regex::new(r"(?P<http>https?://)").unwrap(); static ref SLASH_RE: Regex = Regex::new(r"/$").unwrap(); static ref WHITESPACE_RE: Regex = Regex::new(r"\s"). unwrap(); static ref UNSAFE_RE...
e == "Squarespace" { Some(resp_url.to_string()) } else { None } } None => None } } } Err(e) =...
function_block-function_prefixed
[ { "content": "///\n\n/// ## Usage:\n\n///\n\n/// ```\n\n/// use clean_url::return_url;\n\n/// use tokio_test::block_on;\n\n///\n\n/// assert_eq!(block_on(return_url(String::from(\"httpbin.org/status/200\"))), Some(String::from(\"https://httpbin.org/status/200\")));\n\n/// assert_eq!(block_on(return_url(String::...
Rust
emerald-core/src/keystore/serialize/mod.rs
elaineo/emerald-rs
3e1ce49d57b4e4feffaa5941405dcdc42b60aeba
mod address; #[macro_use] mod byte_array; mod crypto; mod error; use self::address::try_extract_address; pub use self::crypto::{CoreCrypto, Iv, Mac, Salt, decode_str}; use self::error::Error; use super::{CIPHER_IV_BYTES, Cipher, CryptoType, KDF_SALT_BYTES, Kdf, KeyFile}; use super::HdwalletCrypto; use super::core::{...
mod address; #[macro_use] mod byte_array; mod crypto; mod error; use self::address::try_extract_address; pub use self::crypto::{CoreCrypto, Iv, Mac, Salt, decode_str}; use self::error::Error; use super::{CIPHER_IV_BYTES, Cipher, CryptoType, KDF_SALT_BYTES, Kdf, KeyFile}; use super::HdwalletCrypto; use super::core::{...
} impl Encodable for KeyFile { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { match SerializableKeyFileCore::try_from(self.clone()) { Ok(sf) => sf.encode(s), Err(_) => { match SerializableKeyFileHD::try_from(self.clone()) { Ok(...
h)?; for entry in entries { let path = entry?.path(); if path.is_dir() { continue; } let mut file = fs::File::open(&path)?; let mut content = String::new(); if file.read_to_string(&mut content).is_err() { ...
function_block-function_prefixed
[ { "content": "pub fn file_content<P: AsRef<Path>>(path: P) -> String {\n\n let mut text = String::new();\n\n\n\n File::open(path)\n\n .expect(\"Expect read file content\")\n\n .read_to_string(&mut text)\n\n .ok();\n\n\n\n text\n\n}\n\n\n", "file_path": "emerald-core/benches/cry...
Rust
src/handler/model/text_to_speech_message.rs
tktcorporation/discord-speech-bot
9375a1c9e2ec78bad9234f9d4828787c083b1716
pub use crate::model::Message; #[derive(Debug, PartialEq)] pub struct SpeechMessage { pub value: String, } impl Message { pub fn to_speech_message(&self) -> SpeechMessage { let str = if self.msg.content.contains("http") { "url".to_string() } else { self.msg.con...
pub use crate::model::Message; #[derive(Debug, PartialEq)] pub struct SpeechMessage { pub value: String, } impl Message { pub fn to_speech_message(&self) -> SpeechMessage { let str = if self.msg.content.contains("http") { "url".to_string() } else { self.msg.con...
#[cfg(test)] mod tests { use super::*; use serenity::model::channel::Message as SerenityMessage; #[cfg(test)] mod remove_mention_string_test { use super::*; #[test] fn test_remove_mention_string() { let str = "aaa<@!8379454856049>eeee"; let result = re...
p(); if re.captures(content).is_some() { "channel".to_string() } else { content.to_string() } }
function_block-function_prefixed
[ { "content": "/// Checks that a message successfully sent; if not, then logs why to stdout.\n\npub fn check_msg(result: SerenityResult<Message>) {\n\n if let Err(why) = result {\n\n println!(\"Error sending message: {:?}\", why);\n\n }\n\n}\n", "file_path": "src/commands/usecase/mod.rs", "r...
Rust
introspection-engine/connectors/sql-introspection-connector/src/introspection.rs
timsuchanek/prisma-engines
83ac782d5d93dcee37efeba8ccbeff596701148a
use crate::misc_helpers::{ calculate_backrelation_field, calculate_index, calculate_many_to_many_field, calculate_relation_field, calculate_scalar_field, is_migration_table, is_prisma_1_point_0_join_table, is_prisma_1_point_1_or_2_join_table, is_relay_table, }; use crate::version_checker::VersionChecker; us...
use crate::misc_helpers::{ calculate_backrelation_field, calculate_index, calculate_many_to_many_field, calculate_relation_field, calculate_scalar_field, is_migration_table, is_prisma_1_point_0_join_table, is_prisma_1_point_1_or_2_join_table, is_relay_table, }; use crate::version_checker::VersionChecker; us...
}
tes(&mut self) { let mut already_seen = vec![]; self.retain(|item| match already_seen.contains(item) { true => false, _ => { already_seen.push(item.clone()); true } }) }
function_block-function_prefixed
[ { "content": "pub fn deduplicate_field_names(datamodel: &mut Datamodel) {\n\n let mut duplicated_relation_fields = Vec::new();\n\n\n\n for model in &datamodel.models {\n\n for field in &model.fields {\n\n let is_duplicated = model.fields.iter().filter(|f| field.name == f.name).count() > ...
Rust
src/app.rs
zozs/scan-stream
4d0da46d30915f89781c58d48bcfe8e52994ade7
use serde_derive::{Deserialize, Serialize}; use serde_json; use std::collections::BTreeMap; use std::fmt; use std::time::Duration; use yew::format::Text; use yew::prelude::*; use yew::services::{ ConsoleService, IntervalService, interval::IntervalTask, Task, }; use crate::sse::{EventSourceService, Even...
use serde_derive::{Deserialize, Serialize}; use serde_json; use std::collections::BTreeMap; use std::fmt; use std::time::Duration; use yew::format::Text; use yew::prelude::*; use yew::services::{ ConsoleService, IntervalService, interval::IntervalTask, Task, }; use crate::sse::{EventSourceService, Even...
Msg::LogError("Could not deserialize Json event.".to_string()) } } _ => Msg::LogError("Something weird with event text or last message id :(".to_string()) } }))) } } impl Component for App { type Message ...
ring), Ok(last_event_id)) => match serde_json::from_str(&events_string) { Ok(events) => Msg::ScanEvent(events, last_event_id), Err(_) => {
function_block-random_span
[ { "content": "#[wasm_bindgen]\n\npub fn run_app() -> Result<(), JsValue> {\n\n wasm_logger::init(wasm_logger::Config::default());\n\n yew::start_app::<app::App>();\n\n Ok(())\n\n}\n", "file_path": "src/lib.rs", "rank": 3, "score": 48425.80983159394 }, { "content": "#[wasm_bindgen_te...
Rust
lib/src/search/mod.rs
yujh-yujh/rlifesrc
12f57c4a991213f9e20d95890668cc4d9d2fd7cd
use crate::{ cells::{CellRef, State}, config::NewState, rules::Rule, world::World, }; use rand::{thread_rng, Rng}; #[cfg(doc)] use crate::cells::LifeCell; #[cfg(feature = "serde")] use crate::{ error::Error, save::{ReasonSer, SetCellSer}, }; #[cfg(feature = "serde")] use serde::{Deserialize,...
use crate::{ cells::{CellRef, State}, config::NewState, rules::Rule, world::World, }; use rand::{thread_rng, Rng}; #[cfg(doc)] use crate::cells::LifeCell; #[cfg(feature = "serde")] use crate::{ error::Error, save::{ReasonSer, SetCellSer}, }; #[cfg(feature = "serde")] use serde::{Deserialize,...
pub fn search(&mut self, max_step: Option<u64>) -> Status { let mut step_count = 0; if self.next_unknown.is_none() && !self.retreat() { return Status::None; } while A::go(self, &mut step_count) { if let Some(result) = self.decid...
k() { self.set_stack.clear(); self.check_index = 0; return self; } else { self.conflicts += 1; if !self.retreat() { return self; } } } }
function_block-function_prefixed
[ { "content": "#[cfg_attr(not(github_io), doc = \"Some of its items are hidden in the doc.\")]\n\npub trait Rule: private::Sealed {\n\n /// The type of neighborhood descriptor of the rule.\n\n ///\n\n /// It describes the states of the successor and neighbors of a cell,\n\n /// and is used to determi...
Rust
day_25/src/lib.rs
Sousa99/AdventOfCode2021
081b9fae75f260d419d7d397350ee7ffebb15a02
use std::fmt; use std::collections::{HashMap}; type PositionUnit = i64; type Position = (PositionUnit, PositionUnit); #[derive(PartialEq, Copy, Clone)] enum PositionType { Free, EastFacingCucumber, SouthFacingCucumber } pub struct Map { iteration: usize, map_start: Position, map_end: Position, m...
use std::fmt; use std::collections::{HashMap}; type PositionUnit = i64; type Position = (PositionUnit, PositionUnit); #[derive(PartialEq, Copy, Clone)] enum PositionType { Free, EastFacingCucumber, SouthFacingCucumber } pub struct Map { iteration: usize, map_start: Position, map_end: Position, m...
; return (new_position.0 % (self.map_end.0 + 1) + self.map_start.0, new_position.1 % (self.map_end.1 + 1) + self.map_start.1); } fn iterate_type(&mut self, type_to_iterate: PositionType) -> bool { let target_points : Vec<(Position, Position)> = self.map.iter() .filter(|(_, &positi...
match position_type { PositionType::Free => position, PositionType::EastFacingCucumber => (position.0 + 1, position.1), PositionType::SouthFacingCucumber => (position.0, position.1 + 1), }
if_condition
[ { "content": "fn convert_position_type_to_characther(position_type: &PositionType) -> char {\n\n match position_type {\n\n PositionType::Wall => '#',\n\n PositionType::Hallway => '.',\n\n PositionType::Room => 'o',\n\n }\n\n}\n\n\n\n// =================================================...
Rust
db-traits/errors.rs
qpdb/mentat
5a65cd38c9c7a5dae29edd28aa0ae8f6047a6d40
#![allow(dead_code)] use failure::{Backtrace, Context, Fail}; use std::collections::{BTreeMap, BTreeSet}; use rusqlite; use edn::entities::TempId; use core_traits::{Entid, KnownEntid, TypedValue, ValueType}; pub type Result<T> = ::std::result::Result<T, DbError>; #[derive(Clone, Debug, Eq, PartialEq)] pub enum...
#![allow(dead_code)] use failure::{Backtrace, Context, Fail}; use std::collections::{BTreeMap, BTreeSet}; use rusqlite; use edn::entities::TempId; use core_traits::{Entid, KnownEntid, TypedValue, ValueType}; pub type Result<T> = ::std::result::Result<T, DbError>; #[derive(Clone, Debug, Eq, PartialEq)] pub enum...
date datoms: failed to add datoms not already present")] DatomsUpdateFailedToAdd, #[fail(display = "Failed to create temporary tables")] FailedToCreateTempTables, #[fail(display = "Could not insert non-fts one statements into temporary search table!")] NonFtsInsertionIntoTempSearchTableFailed, ...
ct> }, } impl ::std::fmt::Display for SchemaConstraintViolation { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { use self::SchemaConstraintViolation::*; match self { ConflictingUpserts { ref conflicting_upserts, } => { wr...
random
[ { "content": "/// A rough equivalent of mentat_db::debug::transactions_after\n\n/// for Tolstoy's Tx type.\n\npub fn txs_after(sqlite: &rusqlite::Connection, schema: &Schema, after: Entid) -> Vec<Tx> {\n\n let transactions = transactions_after(sqlite, schema, after).expect(\"remote transactions\");\n\n\n\n ...
Rust
src/algorithms.rs
galenbwill/tpscube
842ce0d874af78056bc6a90e5773d7f907a91f54
mod list; mod report; use crate::style::{content_visuals, side_visuals}; use crate::theme::Theme; use crate::widgets::CustomWidgets; use egui::{ Align, CentralPanel, CtxRef, Direction, Layout, SidePanel, Stroke, TopBottomPanel, Ui, Vec2, }; use report::TPSReport; use std::collections::HashMap; use tpscube_core::{ ...
mod list; mod report; use crate::style::{content_visuals, side_visuals}; use crate::theme::Theme; use crate::widgets::CustomWidgets; use egui::{ Align, CentralPanel, CtxRef, Direction, Layout, SidePanel, Stroke, TopBottomPanel, Ui, Vec2, }; use report::TPSReport; use std::collections::HashMap; use tpscube_core::{ ...
fn algorithm_options(&mut self, ui: &mut Ui) { if ui .mode_label( "OLL", self.mode == AlgorithmMode::Algorithms(AlgorithmType::OLL), ) .clicked() { self.mode = AlgorithmMode::Algorithms(AlgorithmType::OLL); } ...
1; oll_entry.total_moves += oll.moves.len(); oll_entry.total_recognition_time += oll.recognition_time as u64; oll_entry.total_execution_time += oll.execution_time as u64; } for pll in cfop.pll { ...
function_block-function_prefixed
[ { "content": "pub fn timer_ui(ui: &mut Ui, center: &Pos2, state: &TimerState) {\n\n // Render timer only in center of screen\n\n let timer_height = ui.fonts().row_height(FontSize::Timer.into());\n\n let galley = ui\n\n .fonts()\n\n .layout_single_line(FontSize::Timer.into(), state.current...
Rust
src/ur20_4ai_ui_12.rs
slowtec/ur20
e15914c7acfce7860e3c196f4d47b35952fd9727
use super::*; use crate::ur20_fbc_mod_tcp::{FromModbusParameterData, ProcessModbusTcpData}; use num_traits::cast::FromPrimitive; #[derive(Debug)] pub struct Mod { pub mod_params: ModuleParameters, pub ch_params: Vec<ChannelParameters>, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ModuleParameters { ...
use super::*; use crate::ur20_fbc_mod_tcp::{FromModbusParameterData, ProcessModbusTcpData}; use num_traits::cast::FromPrimitive; #[derive(Debug)] pub struct Mod { pub mod_params: ModuleParameters, pub ch_params: Vec<ChannelParameters>, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ModuleParameters { ...
#[test] fn test_process_output_data() { let m = Mod::default(); assert!(m.process_output_data(&vec![0; 4]).is_err()); assert_eq!( m.process_output_data(&[]).unwrap(), vec![ChannelValue::None; 4] ); } #[test] fn test_process_output_values() {...
if let ChannelValue::Decimal32(v) = input[0] { assert!((v - 1.19).abs() < 0.01); } else { panic!(); } if let ChannelValue::Decimal32(v) = input[1] { assert!((v - 0.8).abs() < 0.01); } else { panic!(); } }
function_block-function_prefix_line
[ { "content": "pub fn shift_data(data: &[u16]) -> Vec<u16> {\n\n let buf = u16_to_u8(data);\n\n let buf = &buf[1..]; // drop first byte\n\n let mut shifted = vec![];\n\n shifted.extend_from_slice(buf);\n\n shifted.push(0);\n\n u8_to_u16(&shifted)\n\n}\n\n\n", "file_path": "src/util.rs", ...
Rust
src/agent/stacktrace-parser/src/asan.rs
muhammadmeisam/onefuzz
a025d194547d39307bf804ebee0fc0e206759916
use crate::StackEntry; use anyhow::{bail, Result}; use regex::Regex; pub(crate) fn parse_asan_call_stack(text: &str) -> Result<Vec<StackEntry>> { let mut stack = vec![]; let mut parsing_stack = false; let base = r"\s*#(?P<frame>\d+)\s+0x(?P<address>[0-9a-fA-F]+)\s"; let entries = &[ ...
use crate::StackEntry; use anyhow::{bail, Result}; use regex::Regex; pub(crate) fn parse_asan_call_stack(text: &str) -> Result<Vec<StackEntry>> { let mut stack = vec![]; let mut parsing_stack = false; let base = r"\s*#(?P<frame>\d+)\s+0x(?P<address>[0-9a-fA-F]+)\s"; let entries = &[ ...
.to_string()), module_path: Some(r"/path/to/bin".to_string()), module_offset: Some(291), ..Default::default() }], ), ( r"#8 0x123 in from_file /path/to/source.c:67:12", vec![StackEntry { ...
e => None, }; let function_offset = match captures.name("function_offset_1").map(|x| x.as_str()) { Some(x) => Some(x.parse()?), None => None, }; let module_path = captures .name("module_path_1")...
random
[ { "content": "pub fn parse_call_stack(text: &str) -> Result<Vec<StackEntry>> {\n\n // eventually, this should be updated to support multiple callstack formats\n\n asan::parse_asan_call_stack(text)\n\n}\n\n\n", "file_path": "src/agent/stacktrace-parser/src/lib.rs", "rank": 0, "score": 410384.63...
Rust
crates/mani/fabled_render/src/mesh/primitive/capsule.rs
KDahir247/Fabled-Engine
31db8f20f9364ab707786f052fe6e314a77e7a5a
use crate::mesh::primitive::capsule::CapsuleUvProfile::Aspect; use crate::mesh::{Mesh, Model, Vertex}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum CapsuleUvProfile { Aspect = 0, Uniform = 1, Fixed = 2, } #[derive(Debug, Clone, Copy, PartialEq)] #[repr(align(16))] pub struct Capsule { pub radius:...
use crate::mesh::primitive::capsule::CapsuleUvProfile::Aspect; use crate::mesh::{Mesh, Model, Vertex}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum CapsuleUvProfile { Aspect = 0, Uniform = 1, Fixed = 2, } #[derive(Debug, Clone, Copy, PartialEq)] #[repr(align(16))] pub struct Capsule { pub radius:...
} impl From<Capsule> for Model { fn from(capsule: Capsule) -> Self { let Capsule { radius, rings, depth, latitude, longitude, v_profile, } = capsule; let rings = rings as usize; let longitud...
mut rings: u8, depth: f32, mut latitude: u8, mut longitude: u8, profile: CapsuleUvProfile, ) -> Capsule { latitude = latitude.min(90); longitude = longitude.min(180); rings = rings.min(5)...
function_block-function_prefix_line
[ { "content": "// Opposite operation of candela to lux\n\n// Illuminance in lux (lx) to Luminance intensity in candela (cd)\n\n// Iv(cd) = Ev(lx) * (d(m))^2\n\npub fn lux_to_candela(lux: f32, distance: f32) -> f32 {\n\n lux * distance * distance\n\n}\n\n\n", "file_path": "crates/mani/fabled_render/src/lig...
Rust
rust/src/service.rs
google/envoy-processor-examples
c904408579be62d1bcf43e3dae1f8ab4df91eb27
use { crate::base64::Encoder, envoy_control_plane::envoy::{ config::core::v3::{HeaderMap, HeaderValue, HeaderValueOption}, extensions::filters::http::ext_proc::v3::{processing_mode, ProcessingMode}, r#type::v3::HttpStatus, service::ext_proc::v3::{ body_mutation, external_processor_server::Exte...
use { crate::base64::Encoder, envoy_control_plane::envoy::{ config::core::v3::{HeaderMap, HeaderValue, HeaderValueOption}, extensions::filters::http::ext_proc::v3::{processing_mode, ProcessingMode}, r#type::v3::HttpStatus, service::ext_proc::v3::{ body_mutation, external_processor_server::Exte...
, ..Default::default() }; sender.send(Ok(resp_headers_resp)).await.ok(); } } async fn handle_check_json( request_headers: &HttpHeaders, mut sender: UnboundedSender<Result<ProcessingResponse, Status>>, mut stream: Streaming<ProcessingRequest>, ) { let is_json = matches!( get_header_value(...
Some(processing_response::Response::ResponseHeaders( HeadersResponse { response: Some(resp_headers_cr), }, ))
call_expression
[ { "content": "#[derive(Parser, Debug)]\n\n#[clap()]\n\nstruct Args {\n\n #[clap(short, long)]\n\n port: u16,\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let args = Args::parse();\n\n println!(\"Server listening on port {}\", args.port);\n\n let server = Exa...
Rust
client/gantryclient/src/broker.rs
ewbankkit/gantry
5291cefa3921482e577c7b9e8e9c914820b5cf8d
use gantry_protocol as protocol; use natsclient::{AuthenticationStyle, Client, ClientOptions}; use protocol::catalog::*; use protocol::stream::*; use std::time::Duration; use protocol::{serialize, deserialize}; pub const CHUNK_SIZE: u64 = 256 * 1024; pub(crate) fn query( client: &Client, query: &CatalogQuery...
use gantry_protocol as protocol; use natsclient::{AuthenticationStyle, Client, ClientOptions}; use protocol::catalog::*; use protocol::stream::*; use std::time::Duration; use protocol::{serialize, deserialize}; pub const CHUNK_SIZE: u64 = 256 * 1024; pub(crate) fn query( client: &Client, query: &CatalogQuery...
pub(crate) fn get_client( nats_urls: Vec<String>, jwt: Option<&str>, seed: Option<&str>, ) -> Result<Client, Box<dyn ::std::error::Error>> { let mut auth_style = AuthenticationStyle::Anonymous; if jwt.is_some() && seed.is_some() { auth_style = AuthenticationStyle::UserCredentials( ...
t = format!( "{}{}", protocol::stream::SUBJECT_STREAM_UPLOAD_PREFIX, actor ); let _res = c.request(&subject, &buf, std::time::Duration::from_millis(2000))?; Ok(()) }
function_block-function_prefixed
[]
Rust
vapi-logger/src/main.rs
bsundsrud/vapi-rs
596d92bc143ef836ba991fc00255401484325459
use anyhow::Result; use config::Config; use crossbeam::thread; use crossbeam_channel::bounded; use crossbeam_channel::{select, unbounded}; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; use std::sync::Arc; use structopt::StructOpt; use tracing::{error, info}; use vapi::prelude:...
use anyhow::Result; use config::Config; use crossbeam::thread; use crossbeam_channel::bounded; use crossbeam_channel::{select, unbounded}; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; use std::sync::Arc; use structopt::StructOpt; use tracing::{error, info}; use vapi::prelude:...
cs_config.port)) .unwrap(), ); info!( "Starting {} thread(s) for metrics requests, URL: {}:{}", metrics_config.worker_threads, &metrics_config.address, metrics_config.port ); for _ in 0..metri...
select! { recv(overrun_watcher_stop_signal) -> _res => { info!("Watchdog received shutdown."); break; } recv(rx_reacquired) -> res => match res { Ok(_) => { metrics::OVERRUN_COUNTER.inc()...
function_block-random_span
[ { "content": "pub fn consume_logs_forever(output: &OutputConfig, rx: Receiver<LogRecord>) {\n\n let res = match output {\n\n OutputConfig::Stdout => send_to_stdout(rx),\n\n OutputConfig::Tcp {\n\n host,\n\n port,\n\n connect_timeout_secs,\n\n retry_in...
Rust
src/nifti.rs
neuro/wmparc
55d3413c0d7893bf61ef3f1bfc152c54fa2792d0
use std::error::Error; use std::mem; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub type NIfTI1Data = Vec<Vec<Vec<Vec<f32>>>>; #[repr(C)] pub struct NIfTI1Header{ pub sizeof_hdr: i32, pub data_type: [u8; 10], pub db_name: [u8; 18], pub extents: i32, ...
use std::error::Error; use std::mem; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub type NIfTI1Data = Vec<Vec<Vec<Vec<f32>>>>; #[repr(C)] pub struct NIfTI1Header{ pub sizeof_hdr: i32, pub data_type: [u8; 10], pub db_name: [u8; 18], pub extents: i32, ...
display, Error::description(&why)), Ok(file) => file, }; for t in data.iter(){ for z in t{ for y in z{ for x in y{ tmp = unsafe{ mem::transmute(*x) }; ...
pub slice_start: i16, pub pixdim: [f32; 8], pub vox_offset: f32, pub scl_slope: f32, pub scl_inter: f32, pub slice_end: i16, pub slice_code: u8, pub xyzt_units: u8, pub cal_max: f32, ...
random
[ { "content": "//Return probability for a given label in a label list\n\nfn label_prob(labels: &Vec<i32>, label: i32) -> f32 {\n\n let mut label_count = 0.0;\n\n\n\n for i in 0..labels.len(){\n\n if labels[i] == label {\n\n label_count += 1.0;\n\n }\n\n }\n\n\n\n return label...
Rust
src/main.rs
resol-de/vbus-sync
37d467544c2e72d0b09f1f72181bd9270462a7a1
use std::io::Write; use async_std::{fs::create_dir_all, net::TcpStream}; use http_types::{Method, Request, Url}; use resol_vbus::{chrono::Duration, Language, RecordingReader, Specification, SpecificationFile}; use tracing::debug; use tracing_subscriber::EnvFilter; #[derive(Debug)] struct Error(String); impl From<Stri...
use std::io::Write; use async_std::{fs::create_dir_all, net::TcpStream}; use http_types::{Method, Request, Url}; use resol_vbus::{chrono::Duration, Language, RecordingReader, Specification, SpecificationFile}; use tracing::debug; use tracing_subscriber::EnvFilter; #[derive(Debug)] struct Error(String); impl From<Stri...
} } } Ok(()) } async fn sync_and_convert_for_datecode(host: &str, spec: &Specification, datecode: &str) -> Result<()> { debug!("Fetching information about log file dated {}", datecode); let vbus_filename = format!("{}/{}.vbus", host, datecode); let addr = format!("{}:80", ho...
if suffix == "_packets.vbus" { let datecode = &body [start_idx..mid_idx]; sync_and_convert_for_datecode(host, spec, datecode).await?; }
if_condition
[ { "content": "# vbus-sync\n\n\n\nDownloads recorded data from a RESOL datalogging device and converts it to CSV.\n\n\n\n\n\n## Summary\n\n\n\nThis application downloads all recorded data files from a RESOL data logging device into a\n\ndirectory named like the host name itself. If the file exists locally, the d...
Rust
src/lib.rs
parafoxia/piston_rs
2bc7b4f5c6c3d81790a7b2a91cb865280f15d3d0
use serde::{Deserialize, Serialize}; use std::fs; use std::path::{Path, PathBuf}; mod client; mod executor; pub use client::Client; pub use executor::ExecResponse; pub use executor::ExecResult; pub use executor::Executor; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Runtime { pub language: S...
use serde::{Deserialize, Serialize}; use std::fs; use std::path::{Path, PathBuf}; mod client; mod executor; pub use client::Client; pub use executor::ExecResponse; pub use executor::ExecResult; pub use executor::Executor; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Runtime { pub language: S...
} fn load_contents(path: &Path) -> LoadResult<String> { match fs::read_to_string(path) { Ok(content) => Ok(content), Err(e) => Err(LoadError::new(&e.to_string())), } } ...
Ok(Self { name: name.to_string(), content: File::load_contents(&path)?, encoding: String::from("utf8"), })
call_expression
[ { "content": " language: executor.language.clone(),\n\n version: executor.version.clone(),\n\n run: exec_result,\n\n compile: None,\n\n status: status.as_u16(),\n\n ...
Rust
src/selection.rs
eliheuer/efont
15adf0e032c850e7b04314e5e47ecfe2c779b0a2
use std::collections::BTreeSet; use std::sync::Arc; use druid::Data; use crate::path::EntityId; #[derive(Debug, Clone, Data)] pub struct Selection { items: Arc<BTreeSet<EntityId>>, } impl Selection { pub fn new() -> Selection { Selection { items: Arc::new(BTreeSet::new()), } ...
use std::collections::BTreeSet; use std::sync::Arc; use druid::Data; use crate::path::EntityId; #[derive(Debug, Clone, Data)] pub struct Selection { items: Arc<BTreeSet<EntityId>>, } impl Selection { pub fn new() -> Selection { Selection { items: Arc::new(BTreeSet::new()), } ...
pub fn contains(&self, item: &EntityId) -> bool { self.items.contains(item) } pub fn select_one(&mut self, item: EntityId) { let items = self.items_mut(); items.clear(); items.insert(item); } pub fn clear(&mut self) { if !self.is_empty() { ...
ins(item) { false } else { assert!(self.items_mut().remove(item)); true } }
function_block-function_prefixed
[ { "content": "fn iter_handle_circles(session: &EditSession) -> impl Iterator<Item = (Quadrant, Circle)> {\n\n let bbox = session\n\n .viewport\n\n .rect_to_screen(session.selection_dpoint_bbox());\n\n let handle_frame = bbox + SELECTION_BBOX_HANDLE_PADDING;\n\n Quadrant::all()\n\n ...
Rust
src/hypervisor/src/lock.rs
diodesign/diosix
68e9de71d0a097cf5f49d07a3ad61ac3e4414da7
/* diosix high-level hypervisor's locking primitives * * Provides a standard spin lock and a mutex * * The mutex is reentrant, which means when a physical * core holds a mutex and then tries to acquire it * again, this operation will succeed. * * this is so that, eg, if a core holds a mutex * and is interrup...
/* diosix high-level hypervisor's locking primitives * * Provides a standard spin lock and a mutex * * The mutex is reentrant, which means when a physical * core holds a mutex and then tries to acquire it * again, this operation will succeed. * * this is so that, eg, if a core holds a mutex * and is interrup...
} } /* acquire the lock, and block until successful */ pub fn lock(&self) { self.spin(false, true); } /* release the lock */ pub fn unlock(&self) { self.spin(true, false); } } pub struct Mutex<T> { /* the data we're protecting */ content:...
if self.lock.compare_exchange(must_equal, new_value, Ordering::Acquire, Ordering::Relaxed) == Ok(must_equal) { return; }
if_condition
[ { "content": "pub fn write_debug_string(msg: &str) -> bool\n\n{\n\n /* avoid blocking if we can */\n\n if HARDWARE.is_locked() == true\n\n {\n\n return false;\n\n }\n\n\n\n match &*(HARDWARE.lock())\n\n {\n\n Some(d) =>\n\n {\n\n d.write_debug_string(msg);\n\n ...
Rust
src/networks/terra/denom.rs
iqlusioninc/delphi
ccfbc5b9794bc6a72c63202b56b0635efcdd52c0
use crate::{ currency::Currency, error::{Error, ErrorKind}, prelude::*, sources::Sources, trading_pair::TradingPair, }; use rust_decimal::Decimal; use serde::{de, ser, Deserialize, Serialize}; use std::{ convert::TryInto, fmt::{self, Display}, str::FromStr, }; use tokio::try_join; #[d...
use crate::{ currency::Currency, error::{Error, ErrorKind}, prelude::*, sources::Sources, trading_pair::TradingPair, }; use rust_decimal::Decimal; use serde::{de, ser, Deserialize, Serialize}; use std::{ convert::TryInto, fmt::{self, Display}, str::FromStr, }; use tokio::try_join; #[d...
pub async fn get_exchange_rate(self, sources: &Sources) -> Result<stdtx::Decimal, Error> { match self { Denom::Ukrw => { let bithumb_response = sources .bithumb .trading_pairs(&TradingPair(Currency::Luna, Currency::Krw)) ...
Denom::Ueur => "ueur", Denom::Ucny => "ucny", Denom::Ujpy => "ujpy", Denom::Ugbp => "ugbp", Denom::Uinr => "uinr", Denom::Ucad => "ucad", Denom::Uchf => "uchf", Denom::Uhkd => "uhkd", Denom::Uaud => "uaud", Denom...
function_block-function_prefix_line
[ { "content": "/// Deserialize decimal value\n\nfn deserialize_decimal<'de, D>(deserializer: D) -> Result<Decimal, D::Error>\n\nwhere\n\n D: de::Deserializer<'de>,\n\n{\n\n // TODO: avoid floating point/string conversions\n\n let value = f64::deserialize(deserializer)?;\n\n value.to_string().parse()....
Rust
src/binary/mod.rs
condy0919/rua
14dde360eaad51dd60f79a39d03dae27ab7af6dc
use std::fs::File; use std::io::{self, BufReader}; use std::mem; mod reader; use reader::Reader; const RUA_SIGNATURE: &[u8; 4] = b"\x1bLua"; const RUA_MAJOR_VERSION: u8 = 5; const RUA_MINOR_VERSION: u8 = 3; const RUA_RELEASE_VERSION: u8 = 0; const RUA_VERSION: u8 = RUA_MAJOR_VERSION * 16 + RUA_MINOR_VERSION; const ...
use std::fs::File; use std::io::{self, BufReader}; use std::mem; mod reader; use reader::Reader; const RUA_SIGNATURE: &[u8; 4] = b"\x1bLua"; const RUA_MAJOR_VERSION: u8 = 5; const RUA_MINOR_VERSION: u8 = 3; const RUA_RELEASE_VERSION: u8 = 0; const RUA_VERSION: u8 = RUA_MAJOR_VERSION * 16 + RUA_MINOR_VERSION; const ...
reader.read_byte()?, RUA_INSTRUCTION_SIZE, "sizeof(instruction) mismatch" ); assert_eq!( reader.read_byte()?, RUA_INTEGER_SIZE, "sizeof(Integer) mismatch" ); assert_eq!( reader.read_byte()?, RUA_NUMBER_SIZE, "sizeof(Number) mism...
function_block-function_prefix_line
[ { "content": "/// an instruction\n\npub trait Instruction {\n\n fn name(&self) -> &'static str;\n\n fn mode(&self) -> Mode;\n\n fn opcode(&self) -> u8;\n\n fn kind1(&self) -> ArgKind;\n\n fn kind2(&self) -> ArgKind;\n\n fn get<T: ArgGetter>(&self) -> i32;\n\n}\n\n\n\nimpl Instruction for u32 {...
Rust
src/binding/axum/extract.rs
rrcwang/sdk-rust
934915d9105c94e2cacf202577445639d6445c0d
use axum_lib as axum; use async_trait::async_trait; use axum::extract::{FromRequest, RequestParts}; use http::StatusCode; use http_body::Body; use hyper::body; use crate::binding::http::to_event; use crate::event::Event; type BoxError = Box<dyn std::error::Error + Send + Sync>; #[async_trait] impl<B> FromRequest<B>...
use axum_lib as axum; use async_trait::async_trait; use axum::extract::{FromRequest, RequestParts}; use http::StatusCode; use http_body::Body; use hyper::body; use crate::binding::http::to_event; use crate::event::Event; type BoxError = Box<dyn std::error::Error + Send + Sync>; #[async_trait] impl<B> FromRequest<B>...
#[tokio::test] async fn axum_test_request_with_full_data() { let expected = fixtures::v10::full_binary_json_data_string_extension(); let mut request = RequestParts::new( Request::builder() .method(http::Method::POST) .header("ce-specversion", "1.0")...
"http://localhost/") .header("ce-someint", "10") .header("ce-time", fixtures::time().to_rfc3339()) .body(Body::empty()) .unwrap(), ); let result = Event::from_request(&mut request).await; assert!(result.is_err()); let rejec...
random
[ { "content": "/// Method to fill a [`RequestBuilder`] with an [`Event`].\n\npub fn event_to_request(event: Event, request_builder: RequestBuilder) -> Result<RequestBuilder> {\n\n BinaryDeserializer::deserialize_binary(event, RequestSerializer::new(request_builder))\n\n}\n\n\n", "file_path": "src/binding/...