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/core/search/query/term_query.rs
sonic182/rucene
5b55f842c2bb03beb96898d520e880c180c91adf
use error::Result; use std::fmt; use core::codec::Codec; use core::codec::{PostingIterator, PostingIteratorFlags}; use core::doc::Term; use core::index::reader::LeafReaderContext; use core::search::explanation::Explanation; use core::search::query::{Query, Weight}; use core::search::scorer::{Scorer, TermScorer}; us...
use error::Result; use std::fmt; use core::codec::Codec; use core::codec::{PostingIterator, PostingIteratorFlags}; use core::doc::Term; use core::index::reader::LeafReaderContext; use core::search::explanation::Explanation; use core::search::query::{Query, Weight}; use core::search::scorer::{Scorer, TermScorer}; us...
fn extract_terms(&self) -> Vec<TermQuery> { vec![self.clone()] } fn as_any(&self) -> &dyn (::std::any::Any) { self } } impl fmt::Display for TermQuery { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "TermQuery(field: {}, term: {...
self.ctx.as_ref(), self.boost, ); Ok(Box::new(TermWeight::new( self.term.clone(), self.boost, similarity, sim_weight, needs_scores, ))) }
function_block-function_prefix_line
[]
Rust
src/geometry.rs
alteous/alteous-three-rs
d09d2699d8909dc38d469d8f564449d2f85c9ce6
use genmesh::{EmitTriangles, Triangulate, Vertex as GenVertex}; use genmesh::generators::{self, IndexedPolygon, SharedVertex}; use mint; use std::collections::HashMap; #[derive(Clone, Debug, Default)] pub struct Shape { pub vertices: Vec<mint::Point3<f32>>, pub normals: Vec<mint::Vector3<f32>>, ...
use genmesh::{EmitTriangles, Triangulate, Vertex as GenVertex}; use genmesh::generators::{self, IndexedPolygon, SharedVertex}; use mint; use std::collections::HashMap; #[derive(Clone, Debug, Default)] pub struct Shape { pub vertices: Vec<mint::Point3<f32>>, pub normals: Vec<mint::Vector3<f32>>, ...
pub fn cuboid( width: f32, height: f32, depth: f32, ) -> Self { Self::generate( generators::Cube::new(), |GenVertex { pos, .. }| { [ pos[0...
pub fn plane( width: f32, height: f32, ) -> Self { Self::generate( generators::Plane::new(), |GenVertex { pos, .. }| [pos[0] * 0.5 * width, pos[1] * 0.5 * height, 0.0].into(), |v| v.normal.into(), ) }
function_block-full_function
[ { "content": "/// Reads the entire contents of a file into a `String`.\n\npub fn read_file_to_string<P: AsRef<path::Path>>(path: P) -> io::Result<String> {\n\n use self::io::Read;\n\n let file = fs::File::open(path)?;\n\n let len = file.metadata()?.len() as usize;\n\n let mut contents = String::with...
Rust
src/reader/error.rs
lo48576/fbx_direct
4f578295cc569df58d541e9cf1e5268cf0d423b0
use std::error; use std::fmt; use std::io; use std::str; use std::string; pub type Result<T> = ::std::result::Result<T, Error>; #[derive(Debug, Clone)] pub struct Error { pos: u64, kind: ErrorKind, } impl Error { pub fn new<K: Into<ErrorKind>>(pos: u64, kind: K) -> Self { Er...
use std::error; use std::fmt; use std::io; use std::str; use std::string; pub type Result<T> = ::std::result::Result<T, Error>; #[derive(Debug, Clone)] pub struct Error { pos: u64, kind: ErrorKind, } impl Error { pub fn new<K: Into<ErrorKind>>(pos: u64, kind: K) -> Self { Er...
fn cause(&self) -> Option<&dyn error::Error> { match self.kind { ErrorKind::Utf8Error(ref err) => Some(err as &dyn error::Error), ErrorKind::Io(ref err) => Some(err as &dyn error::Error), _ => None, } } } #[derive(Debug)] pub enum ErrorKind { Utf8E...
a", ErrorKind::UnexpectedEof => "Unexpected EOF", ErrorKind::Unimplemented(_) => "Attempt to use unimplemented feature", } }
function_block-function_prefixed
[ { "content": "fn indent<W: Write>(sink: &mut W, depth: usize) -> Result<()> {\n\n for _ in 0..depth {\n\n sink.write_all(b\"\\t\")?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/writer/emitter/ascii.rs", "rank": 0, "score": 72160.99466022922 }, { "content": "fn print_prope...
Rust
src/stats_api/mod.rs
Chronophylos/se-stats-exporter
ea58f9bf02b77cc4804368abd566684e95b20937
use chrono::{DateTime, Utc}; use serde::Deserialize; use std::{borrow::Cow, collections::HashMap}; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("Could not build http client")] BuildClientError(#[source] reqwest::Error), #[error("Could not send {method} reqwest to {url}")] SendRequestErr...
use chrono::{DateTime, Utc}; use serde::Deserialize; use std::{borrow::Cow, collections::HashMap}; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("Could not build http client")] BuildClientError(#[source] reqwest::Error), #[error("Could not send {method} reqwest to {url}")] SendRequestErr...
:ParseJsonError(e))?; Ok(stats) } } #[cfg(test)] mod tests { use super::{ApiClient, Error}; #[tokio::test] async fn get_top_channels() -> Result<(), Error> { let client = ApiClient::new()?; let channels = client.get_top_channels().await?; assert_eq!(channels.len(), 10...
nd() .await .map_err(|source| Error::SendRequestError { method: "GET", url: url.clone(), source, })? .json() .await .map_err(|e| Error:
random
[ { "content": "This is a prototype and only does what I need it to.\n\nIf anyone is interested I'll continue developing this\n", "file_path": "README.md", "rank": 0, "score": 16504.059525609697 }, { "content": "fn drain_to_gauge<'a, I, L, ValueF, LabelF>(\n\n name: &'static str,\n\n dat...
Rust
src/merkle_tree/incremental_merkle_tree.rs
stechu/crypto-primitives
fd9a0decc470a7c92d2ed2ef7a5fffa6952c9c83
use crate::crh::TwoToOneCRHScheme; use crate::merkle_tree::{Config, DigestConverter, LeafParam, Path, TwoToOneParam}; use crate::CRHScheme; use ark_std::borrow::Borrow; use ark_std::vec::Vec; #[derive(Derivative)] #[derivative(Clone(bound = "P: Config"))] pub struct IncrementalMerkleTree<P: Config> { leaf_nod...
use crate::crh::TwoToOneCRHScheme; use crate::merkle_tree::{Config, DigestConverter, LeafParam, Path, TwoToOneParam}; use crate::CRHScheme; use ark_std::borrow::Borrow; use ark_std::vec::Vec; #[derive(Derivative)] #[derivative(Clone(bound = "P: Config"))] pub struct IncrementalMerkleTree<P: Config> { leaf_nod...
}) } pub fn append<T: Borrow<P::Leaf>>(&mut self, new_leaf: T) -> Result<(), crate::Error> { assert!(self.next_available() != None, "index out of range"); let leaf_digest = P::LeafHash::evaluate(&self.leaf_hash_param, new_leaf)?; ...
lable(&self) -> Option<usize> { let current_index = self.current_path.leaf_index; if self.is_empty() { Some(0) } else if current_index < (1 << (self.height - 1)) - 1 { Some(current_index + 1) } else { None } } pub fn blank( ...
random
[ { "content": "#[inline]\n\nfn is_root(index: usize) -> bool {\n\n index == 0\n\n}\n\n\n\n/// Returns the index of the left child, given an index.\n", "file_path": "src/merkle_tree/mod.rs", "rank": 0, "score": 159094.4456264609 }, { "content": "pub trait ConfigGadget<P: Config, ConstraintF...
Rust
rustrat-client/tests/wasm.rs
rustrat/rustrat
28604668d54e5a00aad702ae411dc52ac1458f74
use rustrat_client::ffi::wrappers; use rustrat_client::ffi::FnTable; use rustrat_client::runtime::executor::Environment; use rustrat_client::runtime::CommonUtils; use wasm3; #[test] fn test_adder() { let common_utils = CommonUtils::new(); let mut env = Environment::new( &include_bytes!("wasm-test-bins...
use rustrat_client::ffi::wrappers; use rustrat_client::ffi::FnTable; use rustrat_client::runtime::executor::Environment; use rustrat_client::runtime::CommonUtils; use wasm3; #[test] fn test_adder() { let common_utils = CommonUtils::new(); let mut env = Environment::new( &include_bytes!("wasm-test-bins...
fn test_wasm_virtualalloc_virtualfree() { let common_utils = CommonUtils::new(); let mut env = Environment::new( &include_bytes!("wasm-test-bins/wasm_test_bins.wasm")[..], common_utils.clone(), |_| {}, ) .expect("Unable to create WASM environment."); let wasm_env = env.get_w...
function_block-full_function
[ { "content": "// TODO combine the two link functions?\n\npub fn link_print_closure<F: Fn(&str) + 'static>(\n\n module: &mut wasm3::Module,\n\n print_closure: F,\n\n) -> Result<()> {\n\n module\n\n .link_closure(\n\n \"rustrat\",\n\n \"print\",\n\n move |cc, (str_...
Rust
transformer/src/parsers/doc/etc/primitive_type.rs
ccouzens/vcloud-rest-openapi
b6c772aed95101891eeba529dcf180995be51ac7
use std::str::FromStr; use thiserror::Error; #[derive(Debug, PartialEq, Copy, Clone)] pub enum PrimitiveType { AnyType, AnyUri, Base64Binary, Boolean, DateTime, Decimal, Double, Float, HexBinary, Int, Integer, Long, NormalizedString, Short, String, } #[deriv...
use std::str::FromStr; use thiserror::Error; #[derive(Debug, PartialEq, Copy, Clone)] pub enum PrimitiveType { AnyType, AnyUri, Base64Binary, Boolean, DateTime, Decimal, Double, Float, HexBinary, Int, Integer, Long, NormalizedString, Short, String, } #[deriv...
}
t() }), PrimitiveType::Double => Self::Number(openapiv3::NumberType { format: openapiv3::VariantOrUnknownOrEmpty::Item(openapiv3::NumberFormat::Double), minimum: t.min_inclusive.as_ref().and_then(|m| m.parse().ok()), enumeration: t ...
function_block-function_prefixed
[ { "content": "fn html_to_mimes(html: &str) -> impl Iterator<Item = String> + '_ {\n\n html.split(\"<br>\")\n\n .filter(|&t| !(t.is_empty() || t == \"None\"))\n\n .map(String::from)\n\n}\n\n\n\nimpl<'a> TryFrom<DetailPage> for Operation {\n\n type Error = OperationParseError;\n\n\n\n fn tr...
Rust
wallpapers/MusicVisualization/res/raw/many.rs
xie-wenjie/AndroidBaseApplicationSourse
931ca8fa907b2e0a19dd35948c37da8d166abf90
#pragma version(1) #pragma stateVertex(PVBackground) #pragma stateRaster(parent) #pragma stateStore(PFSBackground) #define RSID_POINTS 1 void dumpState() { } void drawVU(float* ident) { int i; float mat1[16]; float scale = 0.0041; matrixLoadMat(mat1,ident); matrixRotate(mat1, 0.f, 0.f, 0.f,...
#pragma version(1) #pragma stateVertex(PVBackground) #pragma stateRaster(parent) #pragma stateStore(PFSBackground) #define RSID_POINTS 1 void dumpState() { } void drawVU(float* ident) { int i; float mat1[16]; float scale = 0.0041; matrixLoadMat(mat1,ident); matrixRotate(mat1, 0.f, 0.f, 0.f,...
500.0f, 0.f, 1.f, 1500, -60.0f, 1500.0f, 1.f, 1.f, 1500, -60.0f, -1500.0f, 1.f, 0.f, -1500.0f, -60.0f, -1500.0f, 0.f, 0.f); matrixScale(ident, ...
tion + State->mRotate, 0.f, 1.f, 0.f); matrixTranslate(ident, 0.f, -1.f, 0.f); matrixScale(ident, 1.f, -1.f, 1.f); drawVizLayer(ident); bindProgramFragment(NAMED_PFBackgroundMip); bindTexture(NAMED_PFBackgroundMip, 0, NAMED_Tvumeter_album); drawQuadTexCoords( -1500.0f, -6...
random
[ { "content": " private float mDelta;\n", "file_path": "apps/Gallery3D/src/com/cooliris/media/FloatAnim.java", "rank": 0, "score": 156138.519818536 }, { "content": " public static final boolean boundsContainsPoint(float left, float right, float top, float bottom, float posX, float posY)...
Rust
lib/src/lattice/dom_pair.rs
MingweiSamuel/spinach
622fdb841ec1130ff2c896a8ca8f87d0e3b8869b
use std::cmp::Ordering; use super::{Lattice, LatticeRepr, Merge, Compare, Convert, Debottom, Top}; use super::bottom::BottomRepr; use crate::tag; pub struct DomPair<La: Lattice, Lb: Lattice> { _phantom: std::marker::PhantomData<(La, Lb)>, } impl<La: Lattice, Lb: Lattice> Lattice for DomPair<La, Lb> {} pub struc...
use std::cmp::Ordering; use super::{Lattice, LatticeRepr, Merge, Compare, Convert, Debottom, Top}; use super::bottom::BottomRepr; use crate::tag; pub struct DomPair<La: Lattice, Lb: Lattice> { _phantom: std::marker::PhantomData<(La, Lb)>, } impl<La: Lattice, Lb: Lattice> Lattice for DomPair<La, Lb> {} pub struc...
Merge<ArraySetArraySet>, ); assert_not_impl_any!(ArraySetArraySet: Merge<HashSetHashSet>, Merge<HashSetArraySet>, Merge<ArraySetHashSet>, Merge<ArraySetArraySet>, ); }
function_block-function_prefix_line
[ { "content": "pub trait Merge<Delta: LatticeRepr>: LatticeRepr<Lattice = Delta::Lattice> {\n\n /// Merge DELTA into THIS. Return TRUE if THIS changed, FALSE if THIS was unchanged.\n\n fn merge(this: &mut Self::Repr, delta: Delta::Repr) -> bool;\n\n\n\n fn merge_hide<Y: Qualifier, Z: Qualifier>(this: &m...
Rust
src/iso/file_entry.rs
jmpesp/mkisofs-rs
7ffc9158ace73d7da9ee67a8a9eeaf4ef18a6fc0
use crate::iso::utils; use crate::iso::utils::{LOGIC_SIZE, LOGIC_SIZE_I64, LOGIC_SIZE_U32}; use byteorder::{BigEndian, LittleEndian, WriteBytesExt}; use chrono::prelude::*; use std; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::Cursor; use std::io::SeekFrom; use std::path::PathBuf; #[derive(D...
use crate::iso::utils; use crate::iso::utils::{LOGIC_SIZE, LOGIC_SIZE_I64, LOGIC_SIZE_U32}; use byteorder::{BigEndian, LittleEndian, WriteBytesExt}; use chrono::prelude::*; use std; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::Cursor; use std::io::SeekFrom; use std::path::PathBuf; #[derive(D...
tput_writter.write_u8(file_identifier_len as u8)?; output_writter.write_all(&file_identifier[..])?; output_writter.write_all(b";1")?; if (file_identifier_len % 2) == 0 { output_writter.write_u8(0x0u8)?; } output_writter.write_all(b"PX")?; o...
Debug, Clone)] pub struct FileEntry { pub file_type: FileType, pub size: usize, pub lba: u32, pub aligned_size: usize, } impl FileEntry { pub fn get_file_name(&self) -> String { match &self.file_type { FileType::Regular { path } => path.file_name().unwrap().to_str().unwrap().to_...
random
[ { "content": "pub fn create_iso(opt: &mut option::Opt) -> std::io::Result<()> {\n\n let volume_descriptor_list = generate_volume_descriptors(opt);\n\n\n\n let mut out_file = File::create(&opt.output)?;\n\n\n\n let mut current_lba: u32 = 0x10 + 1 + (volume_descriptor_list.len() as u32);\n\n\n\n let p...
Rust
backend/wallet/interface/src/controller/controller.rs
kzmake/osaifu
5b44ad071f201a14dfbde9f13b077acd77a86420
use crate::osaifu_wallet_v1::Wallet as PBWallet; use crate::osaifu_wallet_v1::{CreateRequest, CreateResponse}; use crate::osaifu_wallet_v1::{DeleteRequest, DeleteResponse}; use crate::osaifu_wallet_v1::{GetRequest, GetResponse}; use crate::osaifu_wallet_v1::{ListRequest, ListResponse}; use anyhow::Result; use derive_ne...
use crate::osaifu_wallet_v1::Wallet as PBWallet; use crate::osaifu_wallet_v1::{CreateRequest, CreateResponse}; use crate::osaifu_wallet_v1::{DeleteRequest, DeleteResponse}; use crate::osaifu_wallet_v1::{GetRequest, GetResponse}; use crate::osaifu_wallet_v1::{ListRequest, ListResponse}; use anyhow::Result; use derive_ne...
ng(|_| bail!("error")); get.expect_handle().returning(|_| bail!("error")); delete.expect_handle().returning(|_| bail!("error")); let sut = WalletController::new(create, list, get, delete); assert!(sut .create(Request::new(CreateRequest { owner: "alice".to_str...
}; let mut create = MockPort::<CreateWalletInputData, CreateWalletOutputData>::new(); let mut list = MockQueryPort::<ListWalletsInputData, ListWalletsOutputData>::new(); let mut get = MockPort::<GetWalletInputData, GetWalletOutputData>::new(); let mut delete = MockPort::<DeleteWalletInp...
random
[ { "content": "#[mockall::automock]\n\npub trait Port<Input: InputData, Output: OutputData> {\n\n fn handle(&self, input: Input) -> Result<Output, Error>;\n\n}\n", "file_path": "backend/wallet/usecase/src/port/port.rs", "rank": 0, "score": 237251.4002721125 }, { "content": "#[mockall::auto...
Rust
src/shapes/sphere.rs
mlunnay/rs_illume
a7e88118d829d24e35673df8a1f49a3b870a36e6
use std::sync::Arc; use crate::core::pbrt::{Float, consts::PI, gamma, radians}; use crate::core::shape::Shape; use crate::core::geometry::{Bounding3, Bounds3f, Ray, Point2f, Point3f, Normal3f, Vector3f, offset_ray_origin, dot_normal_vec, coordinate_system, spherical_direction_vec3}; use crate::core::transform::Transfor...
use std::sync::Arc; use crate::core::pbrt::{Float, consts::PI, gamma, radians}; use crate::core::shape::Shape; use crate::core::geometry::{Bounding3, Bounds3f, Ray, Point2f, Point3f, Normal3f, Vector3f, offset_ray_origin, dot_normal_vec, coordinate_system, spherical_direction_vec3}; use crate::core::transform::Transfor...
fn area(&self) -> Float { self.phi_max * self.radius * (self.z_max - self.z_min) } fn sample(&self, u: &Point2f, pdf: &mut Float) -> Box<dyn Interaction> { let mut p_obj = Point3f::new(0.0, 0.0, 0.0) + self.radius * uniform_sample_sphere(u); let mut it = SimpleInteraction::default...
fn intersect_p(&self, ray: &Ray, test_alpha_texture: bool) -> bool { let _p = Profiler::instance().profile("Sphere::intersect_p"); let mut phi: Float = 0.0; let mut p_hit: Point3f; let mut o_err = Vector3f::default(); let mut d_err = Vector3f::default(); let ray ...
function_block-full_function
[ { "content": "/// Find solution(s) of the quadratic equation at<sup>2</sup> + bt + c = 0 using\n\n/// *EFloat* instead of *Float* for error bounds.\n\npub fn quadratic(a: EFloat, b: EFloat, c: EFloat, t0: &mut EFloat, t1: &mut EFloat) -> bool {\n\n let discrim: f64 = b.v as f64 * b.v as f64 - 4.0f64 * a.v as...
Rust
src/macros.rs
MeirShpilraien/ijson
a5dbe78d7f22856f7deaeeeb2bf2df436409243c
macro_rules! value_subtype_impls { ($t:ty, $cf:ident, $rcf:ident, $mcf:ident) => { impl std::convert::AsRef<crate::IValue> for $t { fn as_ref(&self) -> &crate::IValue { &self.0 } } impl std::convert::AsMut<crate::IValue> for $t { fn as_mut(...
macro_rules! value_subtype_impls { ($t:ty, $cf:ident, $rcf:ident, $mcf:ident) => { impl std::convert::AsRef<crate::IValue> for $t { fn as_ref(&self) -> &crate::IValue { &self.0 } } impl std::convert::AsMut<crate::IValue> for $t { fn as_mut(...
(@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => { let _ = $object.insert(($($key)+), $value); ijson_internal!(@object $object () ($($rest)*) ($($rest)*)); }; (@object $object:ident [$($key:tt)+] ($value:expr) $unexpected:tt $($rest:tt)*) => { ijson_unexpect...
ther.$rcf().ok_or(()) } } impl<'a> std::convert::TryFrom<&'a mut crate::IValue> for &'a mut $t { type Error = (); fn try_from(other: &'a mut crate::IValue) -> Result<Self, ()> { other.$mcf().ok_or(()) } } }; } macro_rules! type...
random
[ { "content": "fn key_must_be_a_string() -> Error {\n\n Error::custom(\"Object key must be a string\")\n\n}\n\n\n\nimpl Serializer for ObjectKeySerializer {\n\n type Ok = IString;\n\n type Error = Error;\n\n\n\n type SerializeSeq = Impossible<IString, Error>;\n\n type SerializeTuple = Impossible<I...
Rust
src/generator.rs
zhipeng-jia/flood
d357dea3ef4019ef883ed63f25c31dbd5dc7800e
use std::collections::VecDeque; use std::fmt::{self, Write}; use std::iter; use std::sync::{atomic, Arc, Condvar, Mutex}; use std::thread; use bytes::{BufMut, Bytes, BytesMut}; use log::*; use quick_js::{self, JsValue}; static JS_LIB_CODE: &'static str = include_str!("lib.js"); pub struct Request { pub input: By...
use std::collections::VecDeque; use std::fmt::{self, Write}; use std::iter; use std::sync::{atomic, Arc, Condvar, Mutex}; use std::thread; use bytes::{BufMut, Bytes, BytesMut}; use log::*; use quick_js::{self, JsValue}; static JS_LIB_CODE: &'static str = include_str!("lib.js"); pub struct Request { pub input: By...
fn new_request(host: &str, js_context: &quick_js::Context) -> Result<Request> { let empty_args = iter::empty::<JsValue>(); let request = match js_context.call_function("newRequest", empty_args) { Ok(value) => expect_js_obj!(value, "newRequest must return an object"), Err(js...
pub fn load_user_script(&mut self, user_script: &str) -> Result<()> { self.test_user_script(user_script)?; self.thread_control.store(true, atomic::Ordering::SeqCst); for i in 0..self.num_threads { let control = self.thread_control.clone(); let queue = self.queue.clone(); ...
function_block-full_function
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n env_logger::Builder::from_env(Env::default().default_filter_or(\"info\")).init();\n\n let opt = Opt::from_args();\n\n\n\n let mut resolved_addrs = opt.host.to_socket_addrs()?;\n\n let addr: SocketAddr = resolved_addrs.next().unw...
Rust
gad/src/net_ext.rs
matbd/gad
83f2eb1c46cfb84e979fda940c9d6bf0e226c6d3
use crate::{ arith::ArithAlgebra, array::ArrayAlgebra, core::{CoreAlgebra, HasDims}, error::{check_equal_dimensions, Error, Result}, graph::Value, matrix::MatrixAlgebra, net::{HasGradientId, HasGradientReader, Net, WeightOps}, Graph1, Number, }; use serde::{Deserialize, Serialize}; pu...
use crate::{ arith::ArithAlgebra, array::ArrayAlgebra, core::{CoreAlgebra, HasDims}, error::{check_equal_dimensions, Error, Result}, graph::Value, matrix::MatrixAlgebra, net::{HasGradientId, HasGradientReader, Net, WeightOps}, Graph1, Number, }; use serde::{Deserialize, Serialize}; pu...
ut = <Algebra as ArrayAlgebra<N::Output>>::Scalar; type Weights = N::Weights; type GradientInfo = N::GradientInfo; fn eval_with_gradient_info( &self, graph: &mut Algebra, input: Self::Input, ) -> Result<(Self::Output, Self::GradientInfo)> { let (output, info) = self.0.ev...
Algebra: HasGradientReader + CoreAlgebra<Data, Value = Self::Output>, { fn add_square_loss(self) -> SquareLoss<Self, Data> where Self: Sized, { SquareLoss(self, std::marker::PhantomData) } } impl<Data, Algebra, N> SingleOutputNet<Data, Algebra> for N where N: Net<Algebra...
random
[ { "content": "/// A Neural Network over an algebra of operations.\n\npub trait Net<Algebra: HasGradientReader> {\n\n /// Input of the network.\n\n type Input;\n\n /// Output of the network.\n\n type Output;\n\n /// External representation for the weights of the network.\n\n type Weights;\n\n ...
Rust
src/backend/sprite.rs
skyne98/blackonyx
175e6cccf7fe97539639bb0e0a189400ef6a4eeb
use anyhow::Result; use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; use std::{ sync::mpsc::{channel, Receiver, Sender}, thread::JoinHandle, }; use crate::backend::vertex::Vertex; const BASE_VEC_A: ultraviolet::Vec3 = ultraviolet::Vec3::new(0.0, 1.0, 1.0); const BASE_VEC_B: ...
use anyhow::Result; use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; use std::{ sync::mpsc::{channel, Receiver, Sender}, thread::JoinHandle, }; use crate::backend::vertex::Vertex; const BASE_VEC_A: ultraviolet::Vec3 = ultraviolet::Vec3::new(0.0, 1.0, 1.0); const BASE_VEC_B: ...
pub fn len(&self) -> usize { self.length } pub fn remove(&mut self, index: usize) { self.length -= 1; self.texture_index.remove(index); self.source_position.remove(index); self.source_size.remove(index); self.position.remove(index); self.angle.remov...
pub fn set_origin(&mut self, index: usize, val: ultraviolet::Vec2) -> Option<()> { *(self.origin.get_mut(index)?) = val; let scale = self.scale.get(index)?; let source_size = self.source_size.get(index)?; *(self.origin_translation_mat.get_mut(index)?) = calculate_or...
function_block-full_function
[ { "content": "fn generate_sprites(n: usize) -> Sprites {\n\n let mut sprites = Sprites::new();\n\n for i in 0..n {\n\n sprites.add(\n\n 0,\n\n ultraviolet::Vec2::new(0.0, 0.0),\n\n ultraviolet::Vec2::new(128.0, 128.0),\n\n ultraviolet::Vec2::new(128.0 * i...
Rust
pulsar-binary-protocol-spec/src/frame/renderer.rs
bk-rs/pulsar-rs
c20d7558a0d4603ded5a473e687ce06fafce8760
use std::{cmp::Ordering, convert::TryFrom}; use crc32c::crc32c; use protobuf::{Message, ProtobufEnum as _, ProtobufError}; use thiserror::Error; use crate::{ command::{Command, PayloadCommandPayload}, types::CompressionType, }; use super::{MAGIC_NUMBER, MAX_FRAME_SIZE_DEFAULT}; #[derive(Default, Debug, Clon...
use std::{cmp::Ordering, convert::TryFrom}; use crc32c::crc32c; use protobuf::{Message, ProtobufEnum as _, ProtobufError}; use thiserror::Error; use crate::{ command::{Command, PayloadCommandPayload}, types::CompressionType, }; use super::{MAGIC_NUMBER, MAX_FRAME_SIZE_DEFAULT}; #[derive(Default, Debug, Clon...
pub fn get_mut_config(&mut self) -> &mut FrameRendererConfig { &mut self.config } pub fn render<C>(&mut self, command: C, buf: &mut Vec<u8>) -> Result<(), FrameRenderError> where C: Into<Command>, { let command: Command = command.into(); let n_start_with_total_siz...
pub fn with_config(config: FrameRendererConfig) -> Self { let compression_buf_capacity = config.get_compression_buf_capacity(); Self { config, compression_buf: Vec::with_capacity(compression_buf_capacity as usize), } }
function_block-full_function
[ { "content": "pub fn decompress(slice: &[u8], w: &mut Vec<u8>) -> io::Result<()> {\n\n let mut decoder = Decoder::new(Cursor::new(slice.to_vec()))?;\n\n io::copy(&mut decoder, w)?;\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use std::error;\n\n\n\n #[test]\n\n ...
Rust
examples/pingpong_client.rs
agemocui/ruyi
28c2b8be016d06b24926f87310b91385ed61b183
extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate env_logger; #[macro_use] extern crate log; extern crate chrono; extern crate futures; extern crate num_cpus; extern crate ruyi; use std::env; use std::mem; use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::sync::atomic::{...
extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate env_logger; #[macro_use] extern crate log; extern crate chrono; extern crate futures; extern crate num_cpus; extern crate ruyi; use std::env; use std::mem; use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::sync::atomic::{...
fn main() { let mut conf = Conf::from_args(); let mut builder = LogBuilder::new(); builder.format(|r| { format!( "{} {:<5} {}", Utc::now().format("%Y-%m-%d %H:%M:%S.%f"), r.level(), r.args() ) }); if let Ok(v) = env::var("RUST_LOG") ...
fn run(conf: &Conf) { info!("Start - {:?}", conf); let addr = SocketAddr::new(conf.host.unwrap(), conf.port.unwrap()); ruyi::net::init(); let timer = Timer::new(Duration::from_secs(conf.secs as u64)); let mut threads = Vec::with_capacity(conf.threads); let total_msgs = Arc::new(AtomicUsize::new(...
function_block-full_function
[ { "content": "#[inline]\n\npub fn connect<T>(addr: &SocketAddr) -> Connect<T>\n\nwhere\n\n T: AsRef<TcpStream> + AsMut<TcpStream> + From<TcpStream>,\n\n{\n\n Connect {\n\n inner: tcp::Connect::from(addr),\n\n }\n\n}\n\n\n", "file_path": "src/net/tcp.rs", "rank": 2, "score": 240904.23...
Rust
src/main.rs
Awarua-/Distributed-H264-to-H265-File-encoder
2634c4fe177fb6e12444ab49d30c75d5ae052be1
#[macro_use] extern crate log; extern crate log4rs; #[macro_use] extern crate clap; extern crate time; use clap::App; use std::process::{Command, Output, Stdio, ExitStatus}; use std::fs::{read_dir, DirEntry, copy, remove_file}; use std::path::Path; use std::io::{BufReader, BufRead, Read, Result}; use std::ffi::OsStr...
#[macro_use] extern crate log; extern crate log4rs; #[macro_use] extern crate clap; extern crate time; use clap::App; use std::process::{Command, Output, Stdio, ExitStatus}; use std::fs::{read_dir, DirEntry, copy, remove_file}; use std::path::Path; use std::io::{BufReader, BufRead, Read, Result}; use std::ffi::OsStr...
; let supports_nvenc = String::from_utf8_lossy(ffmpeg.stderr.as_slice()) .contains(NVENC_CHECK_STRING); if supports_nvenc { println!("Supports NVENC"); warn!("Supports NVENC"); } else { return; } let path = Path::new(matches.value_of("SRC_DIR").unwrap()); if !p...
run("ffmpeg".to_string(), vec![String::from("-f"), String::from("lavfi"), String::from("-i"), String::from("nullsrc"), String::from("-c:v"), String::from("nvenc"), ...
call_expression
[ { "content": "# Distributed-H264-to-H265-File-encoder\n\n\n\nOne day this will hopefully be distributed, but for now its really only a script written in Rust. Until I have enough hardware to justify becoming distributed.\n", "file_path": "README.md", "rank": 6, "score": 15258.789288423348 } ]
Rust
sqlite3ffi/src/test_placeholders.rs
sqlite-mpi/sqlite-mpi-rust
e55a4ae3ebf25c1f7818963b57404af79f878ce8
use super::*; use placeholder::PlaceholderTypes; use serde_json::json; use crate::stmt::ErrorBind; static TEST_OUTPUT_DIR: &'static str = "/tmp"; #[test] fn test_is_valid_handle() { } fn get_test_file() -> String { let now: DateTime<Utc> = Utc::now(); format!("{}/del-test-{:?}.sqlite3",...
use super::*; use placeholder::PlaceholderTypes; use serde_json::json; use crate::stmt::ErrorBind; static TEST_OUTPUT_DIR: &'static str = "/tmp"; #[test] fn test_is_valid_handle() { } fn get_test_file() -> String { let now: DateTime<Utc> = Utc::now(); format!("{}/del-test-{:?}.sqlite3",...
#[test] fn test_get_stmt_params_index_error() { let h = DbHandle::new(":memory:".to_string()).unwrap(); { let q = r#" SELECT ?, ?, ? "#; let s = StmtHandle::new(&h, q).expect("Syntax Ok"); let vals: Vec<Val> = vec![ Val::I64(1), ...
fn test_get_stmt_params_index_ok() { { let h = DbHandle::new(":memory:".to_string()).unwrap(); { let q = r#" SELECT ?, ?, ? "#; let s = StmtHandle::new(&h, q).expect("Syntax Ok"); let t = &s.placeholder_meta.types_used; ...
function_block-full_function
[ { "content": "fn create_table_a(c1: DbFile) -> Result<DbFile, ReturnStatus> {\n\n let wtx1 = c1.get_write_tx().expect(\"Ok\");\n\n wtx1.q(\"CREATE TABLE t1(a PRIMARY KEY, b);\").expect(\"Ok\");\n\n let p = Params::Index(vec![Val::I64(3), Val::I64(4)]);\n\n wtx1.q_params(\"INSERT INTO t1 (a, b) VALUE...
Rust
http-service-h1/src/lib.rs
chrisdickinson/http-service
430a1c6a675a9301d553fb61a76dc5d4b6bb5613
#![forbid(future_incompatible, rust_2018_idioms)] #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs, missing_doc_code_examples)] #![cfg_attr(test, deny(warnings))] use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use http_service::{Error, HttpService}; use a...
#![forbid(future_incompatible, rust_2018_idioms)] #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs, missing_doc_code_examples)] #![cfg_attr(test, deny(warnings))] use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use http_service::{Error, HttpService}; use a...
Ok(res) } .await }) .await?; Ok(()) } pub async fn serve<S: HttpService>(service: S, addr: SocketAddr) -> io::Result<()> where <<S as HttpService>::ResponseFuture as Future>::Output: Send, <S as HttpService>::Connection: Sync, { let listener = async_std::net::TcpLi...
let res = service .respond(conn, req) .await .map_err(|_| io::Error::from(io::ErrorKind::Other))?;
assignment_statement
[ { "content": "/// An async HTTP service\n\n///\n\n/// An instance represents a service as a whole. The associated `Conn` type\n\n/// represents a particular connection, and may carry connection-specific state.\n\npub trait HttpService: Send + Sync + 'static {\n\n /// An individual connection.\n\n ///\n\n ...
Rust
src/ui.rs
AidoP/blockade-recon
4116a6ff6e01ca040ca377719f6a6a9c2ff198b8
use std::{thread, sync::mpsc::{self, Receiver}, ops::{Deref, DerefMut}}; use termion::{event::Key, input::{MouseTerminal, TermRead}, raw::{IntoRawMode, RawTerminal}, screen::AlternateScreen}; use tui::{ backend::TermionBackend, layout::{Alignment, Constraint, Layout}, widgets::{Block, Borders, Paragraph}, ...
use std::{thread, sync::mpsc::{self, Receiver}, ops::{Deref, DerefMut}}; use termion::{event::Key, input::{MouseTerminal, TermRead}, raw::{IntoRawMode, RawTerminal}, screen::AlternateScreen}; use tui::{ backend::TermionBackend, layout::{Alignment, Constraint, Layout}, widgets::{Block, Borders, Paragraph}, ...
} #[macro_export] macro_rules! expect { ($ui:expr => $result:expr, $msg:expr) => { match $result { Ok(t) => t, Err(e) => { let location = format!("{}:{}:{}", file!(), line!(), column!()); $ui.error(location, $msg, &e); Err(e).expect($...
t() { if let Ok(key) = key { tx.send(key).expect("Input channel unexpectedly closed") } } }); Self { stdin: rx } }
function_block-function_prefixed
[ { "content": "type Result<T> = std::result::Result<T, Error>;\n\n#[derive(Debug)]\n\npub enum Error {\n\n UnexpectedEof,\n\n InvalidVersion(u8),\n\n UnrecognisedFrameType,\n\n MissingTag(&'static str),\n\n}\n\nimpl From<eui48::ParseError> for Error {\n\n fn from(_: eui48::ParseError) -> Self {\n\...
Rust
deuterium-plugin/src/model/macro_ext.rs
s-panferov/deuterium-orm
ee8b98773005dfda5271a3720cc1166744f1f2a7
#[macro_export] macro_rules! define_model { ( $model:ident, $model_meta:ident, $table:ident, $many_select_query_ext:ident, $one_select_query_ext:ident, $table_name:expr, [ $(( $field_name:ident,...
#[macro_export] macro_rules! define_model { ( $model:ident, $model_meta:ident, $table:ident, $many_select_query_ext:ident, $one_select_query_ext:ident, $table_name:expr, [ $(( $field_name:ident,...
gify!($field_name), self) } )+ } impl ::deuterium::From for $table { fn as_sql(&self) -> &::deuterium::FromToSql { &self.0 } fn upcast_from(&self) -> ::deuterium::SharedFrom { ::std::rc::Rc::new(Box::new(se...
pub fn table_name() -> &'static str { $table_name } pub fn table() -> $table { $table(::deuterium::TableDef::new($model::table_name())) } pub fn alias(alias: &str) -> $table { $table(::deuterium::TableDef::new_with_...
random
[ { "content": "pub fn from_row<T, L, M: FromRow>(query: &::deuterium::SelectQuery<T, L, M>, row: &::postgres::rows::Row) -> M {\n\n FromRow::from_row(query, row)\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! to_sql_string_pg {\n\n ($query:expr) => ({\n\n let mut ctx = ::deuterium::SqlContext::new(Box:...
Rust
components/dada-parse/src/parser/items.rs
ciyer/dada
af6ee8aa4c6eacbdf843b9a0805c6ce2cb4667a7
use crate::{parser::Parser, token_test::SpannedIdentifier}; use dada_ir::{ class::Class, code::{ syntax::{op::Op, Spans, Tables}, UnparsedCode, }, effect::Effect, function::Function, item::Item, kw::Keyword, return_type::{ReturnType, ReturnTypeKind}, source_file::{se...
use crate::{parser::Parser, token_test::SpannedIdentifier}; use dada_ir::{ class::Class, code::{ syntax::{op::Op, Spans, Tables}, UnparsedCode, }, effect::Effect, function::Function, item::Item, kw::Keyword, return_type::{ReturnType, ReturnTypeKind}, source_file::{se...
fn parse_item(&mut self) -> Option<Item> { if let Some(class) = self.parse_class() { Some(Item::Class(class)) } else if let Some(func) = self.parse_function() { Some(Item::Function(func)) } else { None } } fn parse_class(&mut self) -> Op...
e, Effect::Async, main_span, return_type, None, main_span, ); let syntax_tree = self.create_syntax_tree(start_span, vec![], tables, spans, exprs); crate::code_parser::parse_function_body::se...
function_block-function_prefixed
[ { "content": "#[salsa::component(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn parse_function_parameters(db: &dyn crate::Db, function: Function) -> Vec<Parameter> {\n\n if let Some(unparsed_code) = function.unparsed_code(db) {\n\n parse_parameters(db, unparsed_code.parameter_to...
Rust
src/main.rs
flattiverse/connector-rust
59693f71a3525a983e3abc84428201e4428e59c1
#![deny(intra_doc_link_resolution_failure)] #[macro_use] extern crate log; #[macro_use] extern crate num_derive; extern crate num_traits; use log::{LevelFilter, SetLoggerError}; use log4rs::append::console::ConsoleAppender; use log4rs::config::{Appender, Config, Logger, Root}; use log4rs::encode::pattern::PatternEnco...
#![deny(intra_doc_link_resolution_failure)] #[macro_use] extern crate log; #[macro_use] extern crate num_derive; extern crate num_traits; use log::{LevelFilter, SetLoggerError}; use log4rs::append::console::ConsoleAppender; use log4rs::config::{Appender, Config, Logger, Root}; use log4rs::encode::pattern::PatternEnco...
async fn query_print_universe_privileges(connector: &mut Connector, universe: u16) { info!( "Querying {:?} privileges", connector .universe(usize::from(universe)) .map(Universe::name) .expect("Invalid universe") ); let mut stream = connector .que...
async fn query_all_accounts(mut connector: Connector) { info!("Sending account query"); let mut stream = connector .query_accounts_by_name_pattern(None, false) .await .expect("Account query failed"); info!("Accounts:"); while let Some(Ok(account)) = stream.next().await { ...
function_block-full_function
[ { "content": "pub fn sha256(salt: &str) -> [u8; 32] {\n\n let mut sha = Sha256::default();\n\n sha.input(salt.as_bytes());\n\n sha.fixed_result().into()\n\n}\n\n\n\npub(crate) fn to_blocks<N>(data: &mut [u8]) -> &mut [GenericArray<u8, N>]\n\nwhere\n\n N: ArrayLength<u8>,\n\n{\n\n let n = N::to_us...
Rust
src/shakespeare.rs
MarcoIeni/poke-speare
1aabb22ee49c8c0268f497d4573cf93b695ad61a
use crate::ps_error::{PSError, PSResult}; use log::error; use reqwest::Client; use serde::Deserialize; use std::collections::HashMap; const SHAKESPEARE_API_PATH: &str = "/translate/shakespeare.json"; const FUNTRANSLATIONS_API_SECRET: &str = "X-Funtranslations-Api-Secret"; #[derive(Deserialize, Debug)] struct Translat...
use crate::ps_error::{PSError, PSResult}; use log::error; use reqwest::Client; use serde::Deserialize; use std::collections::HashMap; const SHAKESPEARE_API_PATH: &str = "/translate/shakespeare.json"; const FUNTRANSLATIONS_API_SECRET: &str = "X-Funtranslations-Api-Secret"; #[derive(Deserialize, Debug)] struct Translat...
let expected_translation = "Thee did giveth mr. Tim a hearty meal, but unfortunately what he did doth englut did maketh him kicketh the bucket."; let request_url = request_url(&mock_server.uri()); dbg!(&request_url); let actual_translation = retrieve_translation(&request_url, input_text...
speare_api_secret: Option<&str>, ) -> PSResult<String> { let mut json_param = HashMap::new(); json_param.insert("text", text); let post = Client::new().post(request_url); let client = match shakespeare_api_secret { Some(secret) => post.header(FUNTRANSLATIONS_API_SECRET, secret), None =...
random
[ { "content": "fn pokemon_path(pokemon_name: &str) -> String {\n\n format!(\"/api/v2/pokemon-species/{}\", pokemon_name)\n\n}\n\n\n\npub async fn get_description(pokemon_name: &str) -> PSResult<String> {\n\n let pokemon_path = pokemon_path(pokemon_name);\n\n let request_url = format!(\"https://pokeapi.c...
Rust
src/hash_ioc.rs
oliverdaff/ripioc
227c814ba9d5953cd7afa23fddd34857ee182064
#[cfg(feature = "serde_support")] use serde::Serialize; use crate::regex_builder::compile_re; use std::boxed::Box; use regex::Regex; use regex::RegexSet; use regex::RegexSetBuilder; #[cfg_attr(feature = "serde_support", derive(Serialize))] #[derive(Debug, PartialEq, Eq)] pub enum HashIOC<'a> { MD5(&'a st...
#[cfg(feature = "serde_support")] use serde::Serialize; use crate::regex_builder::compile_re; use std::boxed::Box; use regex::Regex; use regex::RegexSet; use regex::RegexSetBuilder; #[cfg_attr(feature = "serde_support", derive(Serialize))] #[derive(Debug, PartialEq, Eq)] pub enum HashIOC<'a> { MD5(&'a st...
pub fn parse_sha512(input: &str) -> Vec<HashIOC> { lazy_static! { static ref SHA512_RE: Box<Regex> = compile_re(SHA512_PATTERN); } SHA512_RE .find_iter(input) .map(|x| x.as_str()) .map(HashIOC::SHA512) .collect() } pub fn parse_ssdeep(input: &str) -> Vec<HashIOC> {...
x> = compile_re(SHA256_PATTERN); } SHA256_RE .find_iter(input) .map(|x| x.as_str()) .map(HashIOC::SHA256) .collect() }
function_block-function_prefixed
[ { "content": "/// Matches all IOCs against the input and returns\n\n/// the matches in a [`IOCS`](struct.IOCS.html).\n\n///\n\n/// # Arguments\n\n///\n\n/// * `input` - A string slice that contains the text to find IOCs in\n\n///\n\n/// ```\n\n/// use ripioc::parse_all_iocs;\n\n///\n\n/// let iocs = parse_all_...
Rust
src/router/mod.rs
verkehrsministerium/autobahnkreuz-rs
03d194257709ad9ef1226141b052bf9c0f2408d6
mod handshake; mod messaging; mod pubsub; mod machine; use crate::messages::{ErrorDetails, Message, Reason, URI}; use rand::distributions::{Distribution, Uniform}; use rand::thread_rng; use crate::router::pubsub::SubscriptionPatternNode; use crate::router::machine::send_message_json; use crate::router::machine::send_m...
mod handshake; mod messaging; mod pubsub; mod machine; use crate::messages::{ErrorDetails, Message, Reason, URI}; use rand::distributions::{Distribution, Uniform}; use rand::thread_rng; use crate::router::pubsub::SubscriptionPatternNode; use crate::router::machine::send_message_json; use crate::router::machine::send_m...
listen<A>(&self, url: A) where A: ToSocketAddrs + std::fmt::Debug + Send + Sync + 'static { let router_info = self.node.machine().clone(); let ws = Builder::new().with_settings(Settings { ..Settings::default() }).build(|sender| { let id = random_id(); ...
questManager<RouterCore>>, senders: Arc<Mutex<HashMap<u64, Sender>>>, } struct ConnectionHandler { info_id: u64, router: RouterInfo, subscribed_topics: Vec<(ID, ID)>, subscriptions: Arc<Mutex<SubscriptionPatternNode<u64>>>, } #[derive(Debug)] pub struct ConnectionInfo { state: ConnectionState,...
random
[ { "content": "pub fn send_message_msgpack(sender: &Sender, message: &Message) -> WSResult<()> {\n\n // Send the message\n\n let mut buf: Vec<u8> = Vec::new();\n\n message\n\n .serialize(&mut Serializer::with(&mut buf, StructMapWriter))\n\n .unwrap();\n\n sender.send(WSMessage::Binary(b...
Rust
src/main.rs
weltimperator/rust_portforwarder
2885b0c5153b7809476520f32a335d94c03fec8f
use mio::*; use mio::net::{TcpListener, TcpStream, UdpSocket}; use std::net::{SocketAddr, ToSocketAddrs}; use std::collections::HashMap; use multi_map::MultiMap; use std::*; use getopts::Options; struct TcpConnection { src: TcpStream, dst_id: usize, } struct UdpConnection { src: UdpSocket, addr: Socke...
use mio::*; use mio::net::{TcpListener, TcpStream, UdpSocket}; use std::net::{SocketAddr, ToSocketAddrs}; use std::collections::HashMap; use multi_map::MultiMap; use std::*; use getopts::Options; struct TcpConnection { src: TcpStream, dst_id: usize, } struct UdpConnection { src: UdpSocket, addr: Socke...
let dst_str = matches.opt_str("dst").unwrap_or("127.0.0.1:2815".to_string()); let src = get_ipv4_socket_addr(&src_str)?; let dst = get_ipv4_socket_addr(&dst_str)?; loop { if let Err(e) = forward(src, dst) { println!("Forwarding failed: {}", e); } } }
function_block-function_prefix_line
[]
Rust
src/futures_02.rs
overdrivenpotato/futures-compat
17ab0fa0eb895254a7ed0200591ea2e23a73978e
use std::io; use std::sync::Arc; use futures_v01x::{Async as Async01, Future as Future01, Poll as Poll01, Stream as Stream01}; use futures_v01x::task::{self as task01, Task as Task01}; use futures_v02x::{Async as Async02, Future as Future02, Never, Stream as Stream02}; use futures_v02x::task::{Context, LocalMap, Wak...
use std::io; use std::sync::Arc; use futures_v01x::{Async as Async01, Future as Future01, Poll as Poll01, Stream as Stream01}; use futures_v01x::task::{self as task01, Task as Task01}; use futures_v02x::{Async as Async02, Future as Future02, Never, Stream as Stream02}; use futures_v02x::task::{Context, LocalMap, Wak...
fn into_01_compat_never_unit<E>(self, exec: E) -> Future02NeverAs01Unit<E, Self> where Self: Sized, E: Executor02, { Future02NeverAs01Unit { exec, v02: self, } } } impl<E, F> Future01 for Future02As01<E, F> where F: Future02, E: Executor...
fn into_01_compat<E>(self, exec: E) -> Future02As01<E, Self> where Self: Sized, E: Executor02, { Future02As01 { exec, v02: self, } }
function_block-full_function
[ { "content": "/// Execute a function with the context used as a v0.1 `Notifier`, converting\n\n/// v0.1 `Poll` into v0.2 version.\n\npub fn with_context_poll<F, R, E>(cx: &mut Context, f: F) -> Poll02<R, E>\n\nwhere\n\n F: FnOnce() -> Poll01<R, E>,\n\n{\n\n with_context(cx, move || {\n\n match f() ...
Rust
src/c_interface.rs
henriquegemignani/randomprime
c2b31c0996d3c003d586be865c0a930f48619a54
use crate::patches; use crate::patch_config::PatchConfig; use std::{ cell::Cell, ffi::{CStr, CString}, panic, path::Path, os::raw::c_char, }; use serde::{Serialize}; #[derive(Serialize)] #[serde(tag = "type")] #[serde(rename_all = "camelCase")] enum CbMessage<'a> { Success, Error { ...
use crate::patches; use crate::patch_config::PatchConfig; use std::{ cell::Cell, ffi::{CStr, CString}, panic, path::Path, os::raw::c_char, }; use serde::{Serialize}; #[derive(Serialize)] #[serde(tag = "type")] #[serde(rename_all = "camelCase")] enum CbMessage<'a> { Success, Error { ...
#[no_mangle] pub extern fn randomprime_patch_iso(config_json: *const c_char , cb_data: *const (), cb: extern fn(*const (), *const c_char)) { thread_local! { static PANIC_DETAILS: Cell<Option<(String, u32)>> = Cell::new(None); } panic::set_hook(Box::new(|pinfo| {...
let config_json = unsafe { CStr::from_ptr(config_json) }.to_str() .map_err(|e| format!("JSON parse failed: {}", e))?; let patch_config = PatchConfig::from_json(config_json)?; let pn = ProgressNotifier::new(cb_data, cb); patches::patch_iso(patch_config, pn)?; Ok(()) }
function_block-function_prefix_line
[ { "content": "fn patch_main_strg(res: &mut structs::Resource, msg: &str) -> Result<(), String>\n\n{\n\n let strings = res.kind.as_strg_mut().unwrap()\n\n .string_tables\n\n .as_mut_vec()\n\n .iter_mut()\n\n .find(|table| table.lang == b\"ENGL\".into())\n\n .unwrap()\n\n ...
Rust
cst/src/lex_string.rs
ydzz/EternalR
8168f6b77a013f550a76b7639c4370d04c7dccf1
use core::str::{Chars}; use std::collections::{VecDeque}; static BACK_LEN:usize = 3usize; #[derive(Debug)] pub struct LexString<'a> { source:&'a str, chars:Chars<'a>, cache_list:VecDeque<char>, ahead_count:usize, cur_index:usize } impl<'a> LexString<'a> { pub fn new(str:&'a str) -> Self {...
use core::str::{Chars}; use std::collections::{VecDeque}; static BACK_LEN:usize = 3usize; #[derive(Debug)] pub struct LexString<'a> { source:&'a str, chars:Chars<'a>, cache_list:VecDeque<char>, ahead_count:usize, cur_index:usize } impl<'a> LexString<'a> { pub fn new(str:&'a str) -> Self {...
slice(&self,s:usize,e:usize) -> &str { let mut idx = 0usize; let mut u8idx_e = 0usize; let mut u8idx_s = 0usize; for chr in self.source.chars() { if idx < s { u8idx_s += chr.len_utf8(); } if idx < e { u8idx_e += chr.len_utf8(); ...
return Some(self.cache_list[idx as usize]); } } pub fn lookback(&mut self,count:usize) -> Option<char> { let sub_ahead:i32 = self.sub_ahead_len(); if sub_ahead < 0 { return None; } if sub_ahead - count as i32 >= 0 { return Some(self.cache_list[sub_a...
random
[ { "content": "pub fn text_delta(tex:&str) -> (i32,i32) {\n\n let mut l = 0;\n\n let mut c = 0;\n\n for chr in tex.chars() {\n\n if chr == '\\n' {\n\n l += 1;\n\n c = 1;\n\n } else {\n\n c += 1;\n\n }\n\n }\n\n (l,c)\n\n}\n\n\n", "file_path...
Rust
mayastor/tests/replica_uri.rs
payes/mayastor
917c4f7cd8a3d8642307a7ea9165e2403bc4b028
use composer::RpcHandle; use rpc::mayastor::{ Bdev, CreateNexusRequest, CreatePoolRequest, CreateReplicaRequest, Null, Replica, ShareProtocolReplica, ShareReplicaRequest, }; use std::str::FromStr; use tracing::info; pub mod common; use common::compose::Builder; const DISKSIZE_KB: u64 =...
use composer::RpcHandle; use rpc::mayastor::{ Bdev, CreateNexusRequest, CreatePoolRequest, CreateReplicaRequest, Null, Replica, ShareProtocolReplica, ShareReplicaRequest, }; use std::str::FromStr; use tracing::info; pub mod common; use common::compose::Builder; const DISKSIZE_KB: u64 =...
async fn get_bdev(handle: &mut RpcHandle) -> Bdev { let bdevs = handle.bdev.list(Null {}).await.unwrap().into_inner().bdevs; bdevs .iter() .find(|b| b.name == VOLUME_UUID) .expect("Should find our replica as a bdev") .clone() } async fn check_replica_uri(handle: &mut RpcHandle...
async fn replica_uri() { let test = Builder::new() .name("replica_uri") .network("10.1.0.0/16") .add_container("ms1") .add_container("ms2") .with_clean(true) .with_default_tracing() .build() .await .unwrap(); let mut hdls = test.grpc_handl...
function_block-full_function
[ { "content": "pub fn dd_urandom_file_size(device: &str, size: u64) -> String {\n\n let (exit, stdout, _stderr) = run_script::run(\n\n r#\"\n\n dd if=/dev/urandom of=$1 conv=fsync,nocreat,notrunc iflag=count_bytes count=$2\n\n \"#,\n\n &vec![device.into(), size.to_string()],\n\n ...
Rust
packages/profiler/src/instrumentation.rs
brew0722/cosmwasm-1
a0cf296c43aa092b81457d96a9c6bc2ab223f6d3
use std::{ path::Path, sync::{Arc, Mutex}, }; use cosmwasm_vm::{ testing::{MockApi, MockQuerier, MockStorage}, Backend, Instance, }; use loupe::MemoryUsage; use wasmer::{ internals::WithEnv, wasmparser::Operator, Exports, Function, FunctionMiddleware, HostFunction, LocalFunctionIndex, ModuleMid...
use std::{ path::Path, sync::{Arc, Mutex}, }; use cosmwasm_vm::{ testing::{MockApi, MockQuerier, MockStorage}, Backend, Instance, }; use loupe::MemoryUsage; use wasmer::{ internals::WithEnv, wasmparser::Operator, Exports, Function, FunctionMiddleware, HostFunction, LocalFunctionIndex, ModuleMid...
} type MockInstance = Instance<MockApi, MockStorage, MockQuerier>; pub struct InstrumentedInstance { #[allow(dead_code)] profiling: Arc<Profiling>, instance: MockInstance, } impl InstrumentedInstance { pub fn vm_instance(&mut self) -> &mut MockInstance { &mut self.instance } } fn add_im...
pub fn instrument<Env, F1, F2>( &self, block_store: Arc<Mutex<BlockStore>>, env: Env, start_measurement_fn: F1, take_measurement_fn: F2, ) -> InstrumentedInstance where Env: WasmerEnv + 'static, F1: HostFunction<(u32, u32), (), WithEnv, Env>, F2: H...
function_block-full_function
[ { "content": "#[allow(dead_code)] // used in Wasm and tests only\n\npub fn encode_sections(sections: &[&[u8]]) -> Vec<u8> {\n\n let mut out_len: usize = sections.iter().map(|section| section.len()).sum();\n\n out_len += 4 * sections.len();\n\n let mut out_data = Vec::with_capacity(out_len);\n\n for ...
Rust
src/lib.rs
newpavlov/parstream
6f55caa8187ba5b7a635f26a6996a5585bb5a00e
use std::collections::BinaryHeap; use std::collections::binary_heap::PeekMut; use std::cmp; use std::sync::atomic::AtomicIsize; use std::sync::atomic::Ordering; use crossbeam_channel as channel; use crossbeam_utils::thread as cb_thread; struct State<T> { pos: usize, payload: T, } impl<T> PartialEq for Stat...
use std::collections::BinaryHeap; use std::collections::binary_heap::PeekMut; use std::cmp; use std::sync::atomic::AtomicIsize; use std::sync::atomic::Ordering; use crossbeam_channel as channel; use crossbeam_utils::thread as cb_thread; struct State<T> { pos: usize, payload: T, } impl<T> PartialEq for Stat...
pub fn run<X: Send, Y: Send, E: Send>( xs: impl IntoIterator<Item=X>, threads: usize, f: impl Fn(X) -> Result<Y, E> + Sync, report: impl FnMut(Y) -> Result<(), E> + Send ) -> Result<usize, E> { let (tx, rx) = channel::bounded(2*threads); let (tx2, rx2) = channel::bounded(2*threads); ...
function_block-full_function
[ { "content": "# parstream [![crates.io](https://img.shields.io/crates/v/parstream.svg)](https://crates.io/crates/parstream) [![Documentation](https://docs.rs/parstream/badge.svg)](https://docs.rs/parstream) [![Build Status](https://travis-ci.org/newpavlov/parstream.svg?branch=master)](https://travis-ci.org/newp...
Rust
src/tests/data_type/interval.rs
Snowapril/gluesql
eaca157102aca8ad05c4f73c0d25349169d9fb8f
use crate::*; test_case!(interval, async move { run!( r#" CREATE TABLE IntervalLog ( id INTEGER, interval1 INTERVAL, interval2 INTERVAL, )"# ); run!( r#" INSERT INTO IntervalLog VALUES (1, INTERVAL "1-2" YEAR TO MONTH, INTERVAL "30" MONTH), (2, INTERVAL "12" DAY...
use crate::*; test_case!(interval, async move { run!( r#" CREATE TABLE IntervalLog ( id INTEGER, interval1 INTERVAL, interval2 INTERVAL, )"# ); run!( r#" INSERT INTO IntervalLog VALUES (1, INTERVAL "1-2" YEAR TO MONTH, INTERVAL "30" MONTH), (2, INTERVAL "12" DAY...
Err(IntervalError::FailedToParseDecimal("1.4ab".to_owned()).into()), r#"SELECT INTERVAL "1.4ab" HOUR FROM IntervalLog;"# ); test!( Err(IntervalError::FailedToParseTime("111:34".to_owned()).into()), r#"SELECT INTERVAL "111:34" HOUR TO MINUTE FROM IntervalLog;"# ); test!( ...
I::months(-12_011) I::seconds(-(30 * 60 + 11)) )), "SELECT * FROM IntervalLog;" ); test!( Ok(select!( id | i1 | i2 I64 | Interval | Interval; 1 I::months(28) I::months(66) )), r#"SELECT id, ...
random
[ { "content": "CREATE TABLE IdxValue (\n\n id INTEGER NULL,\n\n time TIME NULL,\n\n flag BOOLEAN\n\n)\"#\n\n );\n\n\n\n run!(\n\n r#\"\n\n INSERT INTO IdxValue\n\n VALUES\n\n (NULL, \"01:30 PM\", True),\n\n (1, \"12:10 AM\", False),\n\n (2, ...
Rust
wiz/wiz_syntax/src/syntax/expression.rs
ChanTsune/wiz
199d0f4698822a177ede8015bf8e04f190f39934
mod array_syntax; mod binary_operation_syntax; mod call_syntax; mod if_syntax; mod member_syntax; mod name_syntax; mod parenthesized_syntax; mod return_syntax; mod subscript_syntax; mod type_cast_syntax; mod unary_operation_syntax; pub use crate::syntax::expression::array_syntax::{ArrayElementSyntax, ArraySyntax}; pub...
mod array_syntax; mod binary_operation_syntax; mod call_syntax; mod if_syntax; mod member_syntax; mod name_syntax; mod parenthesized_syntax; mod return_syntax; mod subscript_syntax; mod type_cast_syntax; mod unary_operation_syntax; pub use crate::syntax::expression::array_syntax::{ArrayElementSyntax, ArraySyntax}; pub...
fn with_trailing_trivia(self, trivia: Trivia) -> Self { match self { Expr::Name(n) => Expr::Name(n.with_trailing_trivia(trivia)), Expr::Literal(l) => Expr::Literal(l.with_trailing_trivia(trivia)), Expr::BinOp(b) => Expr::BinOp(b.with_trailing_trivia(trivia)), ...
Expr::When { .. } => { todo!() } Expr::Lambda(_) => { todo!() } Expr::Return(r) => Expr::Return(r.with_leading_trivia(trivia)), Expr::TypeCast(t) => Expr::TypeCast(t.with_leading_trivia(trivia)), Expr::Parenthesized(...
function_block-function_prefix_line
[ { "content": "pub trait Syntax: Debug + Eq + PartialEq + Clone {\n\n fn with_leading_trivia(self, trivia: Trivia) -> Self;\n\n fn with_trailing_trivia(self, trivia: Trivia) -> Self;\n\n fn span(&self) -> Location {\n\n Location::default()\n\n }\n\n fn id(&self) -> NodeId {\n\n NodeI...
Rust
src/thread_pool.rs
tom-heimbrodt/stateful_async_worker
fc7f9994a0a8112ea599232359151fe7a07ebdc2
use std::thread; use std::future::Future; use std::sync::Arc; use crossbeam::channel::{self, Sender}; use crate::*; type TaskFunc<ThreadState, Result> = dyn FnOnce(&ThreadState) -> Result + Send + 'static; type BoxedTaskFunc<ThreadState, Result> = Box<TaskFunc<ThreadState, Result>>; pub struct ThreadPool<ThreadS...
use std::thread; use std::future::Future; use std::sync::Arc; use crossbeam::channel::{self, Sender}; use crate::*; type TaskFunc<ThreadState, Result> = dyn FnOnce(&ThreadState) -> Result + Send + 'static; type BoxedTaskFunc<ThreadState, Result> = Box<TaskFunc<ThreadState, Result>>; pub struct ThreadPool<ThreadS...
}
async fn test_rwlock() { let worker = ThreadPool::spawn_exactly_with(RwLock::new(0), 4); let long_computation1 = worker.work_on(|num: &RwLock<u64>| { thread::sleep(Duration::from_millis(80)); let mut num = num.write().unwrap(); *num += 1; *num })...
function_block-full_function
[ { "content": "type TaskFunc<ThreadState, Result> = dyn FnOnce(&mut ThreadState) -> Result + Send + 'static;\n", "file_path": "src/worker_thread.rs", "rank": 0, "score": 128334.61925333255 }, { "content": "struct Task<F, Result> {\n\n func: F,\n\n future: MutexFuture<Result>,\n\n}\n", ...
Rust
rive-rs/src/shapes/metrics_path.rs
Kangz/cassia
e003a0b7109b039a76e3d40103a2ad198a350222
use std::num::NonZeroUsize; use crate::{ math::{self, Mat}, shapes::command_path::{Command, CommandPath, CommandPathBuilder}, }; #[derive(Clone, Copy, Debug)] struct CubicSegment { t: f32, length: f32, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum PathPartType { Line, Cubic(NonZeroUsize...
use std::num::NonZeroUsize; use crate::{ math::{self, Mat}, shapes::command_path::{Command, CommandPath, CommandPathBuilder}, }; #[derive(Clone, Copy, Debug)] struct CubicSegment { t: f32, length: f32, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum PathPartType { Line, Cubic(NonZeroUsize...
#[derive(Debug)] pub struct MetricsPath { points: Vec<math::Vec>, transformed_points: Vec<math::Vec>, cubic_segments: Vec<CubicSegment>, parts: Vec<PathPart>, lengths: Vec<f32>, computed_length: f32, computed_length_transform: Mat, } impl MetricsPath { pub fn new(command_path: &Comman...
N_SEGMENT_LENGTH: f32 = 0.05; if should_split_cubic(from, from_out, to_in, to) { let half_t = (t1 + t2) / 2.0; let mut hull = [math::Vec::default(); 6]; compute_hull(from, from_out, to_in, to, 0.5, &mut hull); running_length = segment_cubic( from, hull[0], ...
function_block-function_prefixed
[ { "content": "pub fn lerp(a: f32, b: f32, ratio: f32) -> f32 {\n\n a + (b - a) * ratio\n\n}\n\n\n", "file_path": "rive-rs/src/math/mod.rs", "rank": 0, "score": 197363.3596401754 }, { "content": "fn lerp(t: f32, a: f32, b: f32) -> f32 {\n\n a * (1.0 - t) + b * t\n\n}\n\n\n\nmacro_rules!...
Rust
github/src/user.rs
gregnazario/bors
74537e15dac8136122b6d5d201cea649226a2e7b
use super::{DateTime, NodeId}; use serde::Deserialize; #[derive(Clone, Debug, PartialEq, Deserialize)] pub enum UserType { Bot, Organization, User, } #[derive(Clone, Debug, Deserialize)] pub struct User { pub login: String, pub id: u64, pub node_id: NodeId, pub avatar_url: String, pub ...
use super::{DateTime, NodeId}; use serde::Deserialize; #[derive(Clone, Debug, PartialEq, Deserialize)] pub enum UserType { Bot, Organization, User, } #[derive(Clone, Debug, Deserialize)] pub struct User { pub login: String, pub id: u64, pub node_id: NodeId, pub avatar_url: String, pub ...
}
fn org() { const ORGANIZATION_JSON: &str = r#" { "login": "Octocoders", "id": 38302899, "node_id": "MDEyOk9yZ2FuaXphdGlvbjM4MzAyODk5", "avatar_url": "https://avatars1.githubusercontent.com/u/38302899?v=4", "gravatar_id":...
function_block-full_function
[ { "content": "// Super quick and dirty parsing of raw http into a `Request<Body>` type.\n\n// This assumes that the content is JSON\n\nfn request_from_raw_http(raw: &'static str) -> Request<Body> {\n\n let (headers, payload) = raw.split_at(raw.find(\"{\\n\").unwrap());\n\n\n\n let mut headers = headers.li...
Rust
src/pagination/recent.rs
MaxOhn/Bathbot
609a9367ac60e86b0e54a333375d3a8eb3bd3e56
use super::{create_collector, Pages, Pagination}; use crate::{ embeds::{EmbedData, RecentEmbed}, MySQL, Osu, }; use failure::Error; use rosu::models::{Beatmap, Score, User}; use serenity::{ async_trait, cache::Cache, collector::ReactionCollector, http::Http, model::{channel::Message, id::U...
use super::{create_collector, Pages, Pagination}; use crate::{ embeds::{EmbedData, RecentEmbed}, MySQL, Osu, }; use failure::Error; use rosu::models::{Beatmap, Score, User}; use serenity::{ async_trait, cache::Cache, collector::ReactionCollector, http::Http, model::{channel::Message, id::U...
}
nwrap(); let global_lb = map.get_global_leaderboard(&osu, 50).await?; self.global.insert(map.beatmap_id, global_lb); }; let global_lb = self .global .get(&map.beatmap_id) .map(|global| global.as_slice()); RecentEmbed::new( ...
function_block-function_prefixed
[ { "content": "pub fn unchoke_score(score: &mut Score, map: &Beatmap) {\n\n score.pp = None;\n\n match map.mode {\n\n GameMode::STD => {\n\n let max_combo = map\n\n .max_combo\n\n .unwrap_or_else(|| panic!(\"Max combo of beatmap not found\"));\n\n ...
Rust
embedded-graphics/src/image/image_bmp.rs
wjakobczyk/embedded-graphics
c58e96a39d45f6ca5c5b13da2c671a36ba2db2cc
use super::ImageFile; use crate::drawable::{Drawable, Pixel}; use crate::geometry::{Dimensions, Point, Size}; use crate::pixelcolor::raw::{LittleEndian, RawData, RawDataIter}; use crate::pixelcolor::PixelColor; use crate::transform::Transform; use crate::DrawTarget; use core::marker::PhantomData; use tinybmp::Bmp; #[d...
use super::ImageFile; use crate::drawable::{Drawable, Pixel}; use crate::geometry::{Dimensions, Point, Size}; use crate::pixelcolor::raw::{LittleEndian, RawData, RawDataIter}; use crate::pixelcolor::PixelColor; use crate::transform::Transform; use crate::DrawTarget; use core::marker::PhantomData; use tinybmp::Bmp; #[d...
} impl<'a, C: 'a> Drawable<C> for &ImageBmp<'a, C> where C: PixelColor + From<<C as PixelColor>::Raw>, { fn draw<D: DrawTarget<C>>(self, display: &mut D) { display.draw_iter(self.into_iter()); } } #[cfg(test)] mod tests { use super::*; use crate::mock_display::MockDisplay; use crate::...
t); } let data = self.data.next()?; let mut point = Point::new(self.x as i32, self.y as i32); point += self.image.offset; self.x += 1; if self.x >= self.image.bmp.width() { self.y += 1; self.x = 0; } ...
function_block-function_prefixed
[ { "content": "/// Draw the seconds hand given a seconds value (0 - 59)\n\nfn draw_seconds_hand(seconds: u32) -> impl Iterator<Item = Pixel<BinaryColor>> {\n\n // Convert seconds into a position around the circle in radians\n\n let seconds_radians = ((seconds as f32 / 60.0) * 2.0 * PI) + START;\n\n\n\n ...
Rust
proc-macro/builder/src/lib.rs
2shiori17/learn
569a47494032a0a87196a0173f7036acd384b0cd
#![feature(if_let_guard)] #![feature(let_chains)] use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{format_ident, quote}; use syn::{ parse_macro_input, Attribute, Data, DataStruct, DeriveInput, Error as SynError, Expr, ExprAssign, Field, GenericArgument, Ident, Lit, PathArg...
#![feature(if_let_guard)] #![feature(let_chains)] use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{format_ident, quote}; use syn::{ parse_macro_input, Attribute, Data, DataStruct, DeriveInput, Error as SynError, Expr, ExprAssign, Field, GenericArgument, Ident, Lit, PathArg...
d::vec::Vec::new(), }, }) } fn gen_setters(&self) -> TokenStream2 { fields_map(&self.fields, |field| match field { FieldType::Normal { ident, ty } => quote! { pub fn #ident(&mut self, #ident: #ty) -> &mut Self { self.#ident = std::opti...
let builder = format_ident!("{}Builder", target); let partial = self.gen_partial(); let init = self.gen_init(); let setters = self.gen_setters(); let build = self.gen_build(); quote! { impl #target { pub fn builder() -> #builder { ...
random
[]
Rust
src/event/mod.rs
not-a-seagull/beetle
87e90ab8c71c4ae1787ae02ee5a7809c8bed62a0
/* ----------------------------------------------------------------------------------- * src/event/mod.rs - An event from the event loop. * beetle - Pull-based GUI framework. * Copyright © 2020 not_a_seagull * * This project is licensed under either the Apache 2.0 license or the MIT license, at * your option. For...
/* ----------------------------------------------------------------------------------- * src/event/mod.rs - An event from the event loop. * beetle - Pull-based GUI framework. * Copyright © 2020 not_a_seagull * * This project is licensed under either the Apache 2.0 license or the MIT license, at * your option. For...
} impl Event { #[inline] pub fn new(target_window: &Window, data: EventData) -> Self { Self { target_window: target_window.clone(), data, arguments: vec![], hidden_data: None, needs_quit: false, } } #[inline] pub(cra...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Event") .field("target_window", &self.target_window) .field("data", &self.data) .field("needs_quit", &self.needs_quit) .finish() }
function_block-full_function
[ { "content": "pub trait EventHandler = Fn(&Event) -> crate::Result<()> + Sync + Send + 'static;\n\n\n\npub(crate) fn default_event_handler(_ev: &Event) -> crate::Result<()> {\n\n log::debug!(\"Found event: {:?}\", _ev);\n\n Ok(())\n\n}\n\n\n", "file_path": "src/window/internal/mod.rs", "rank": 0, ...
Rust
src/connectivity/bluetooth/profiles/bt-a2dp-manager/src/inspect.rs
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
use { fidl_fuchsia_bluetooth_a2dp::Role, fuchsia_async as fasync, fuchsia_inspect::{self as inspect, Node, NumericProperty, Property}, fuchsia_inspect_contrib::nodes::NodeExt, fuchsia_inspect_derive::{AttachError, Inspect}, fuchsia_zircon as zx, futures::FutureExt, std::sync::Arc, }; ...
use { fidl_fuchsia_bluetooth_a2dp::Role, fuchsia_async as fasync, fuchsia_inspect::{self as inspect, Node, NumericProperty, Property}, fuchsia_inspect_contrib::nodes::NodeExt, fuchsia_inspect_derive::{AttachError, Inspect}, fuchsia_zircon as zx, futures::FutureExt, std::sync::Arc, }; ...
:now(); if let Some(prop) = &self.role_set_at { prop.set_at(now.into()); } else { self.role_set_at = Some(self.inspect_node.create_time_at("role_set_at_time", now.into())); } *self.set_at.lock().await = Some(now); } } fn duration_to_formatted_...
fn iattach<'a>(self, parent: &'a Node, name: impl AsRef<str>) -> Result<(), AttachError> { self.inspect_node = parent.create_child(name); self.role = self.inspect_node.create_string("role", "Not Set"); self.role_set_count = self.inspect_node.create_uint("role_set_count", 0); self.set...
random
[]
Rust
src/systems/gsm.rs
thebluefish/bevy_sandbox
de175f89cdfd04045c82b41988d50cd9ea743fd5
use crate::resources::*; use super::states; use bevy::{prelude::*, ecs::{Schedule, ThreadLocalExecution, SystemId, TypeAccess, ArchetypeAccess, ParallelExecutor}}; use std::borrow::Cow; pub struct GamePlugin; impl Plugin for GamePlugin { fn build(&self, app: &mut AppBuilder) { app .add_resourc...
use crate::resources::*; use super::states; use bevy::{prelude::*, ecs::{Schedule, ThreadLoc
peAccess { &self.resource_access } fn thread_local_execution(&self) -> ThreadLocalExecution { ThreadLocalExecution::Immediate } fn run(&mut self, _world: &World, _resources: &Resources) { } fn run_thread_local(&mut self, mut world: &mut World, mut resources: &mut Resources) { let state = *resour...
alExecution, SystemId, TypeAccess, ArchetypeAccess, ParallelExecutor}}; use std::borrow::Cow; pub struct GamePlugin; impl Plugin for GamePlugin { fn build(&self, app: &mut AppBuilder) { app .add_resource(Loader::default()) .add_resource(GameState::Stage0) .add_resource(...
random
[ { "content": "use bevy::prelude::*;\n\nuse crate::components::AnimSprite;\n\n\n", "file_path": "src/systems/anim_sprite.rs", "rank": 0, "score": 2.126389271913369 }, { "content": "use bevy::prelude::*;\n\nuse crate::{assets, core::loader::*, resources::LoadingScreen};\n\nuse crate::component...
Rust
src/zksolc/main.rs
matter-labs/compiler-solidity
4bd2b9c9786a234660f2012d8ee49874031ac9ff
pub mod arguments; use self::arguments::Arguments; fn main() { std::process::exit(match main_inner() { Ok(()) => compiler_common::EXIT_CODE_SUCCESS, Err(error) => { eprintln!("{}", error); compiler_common::EXIT_CODE_FAILURE } }) } fn main_inner() -> anyhow::R...
pub mod arguments; use self::arguments::Arguments; fn main() { std::process::exit(match main_inner() { Ok(()) => compiler_common::EXIT_CODE_SUCCESS, Err(error) => { eprintln!("{}", error); compiler_common::EXIT_CODE_FAILURE } }) }
fn main_inner() -> anyhow::Result<()> { let mut arguments = Arguments::new(); arguments.validate()?; let dump_flags = compiler_solidity::DumpFlag::from_booleans( arguments.dump_yul, arguments.dump_ethir, arguments.dump_evm, arguments.dump_llvm, arguments.dump_assembl...
function_block-full_function
[]
Rust
lib/interface-types/src/interpreter/instructions/strings.rs
terra-money/wasmer
567a790dae9e428650a5c85e6b4dae82a06bce47
use super::to_native; use crate::{ errors::{InstructionError, InstructionErrorKind}, interpreter::Instruction, types::InterfaceType, values::InterfaceValue, }; use std::{cell::Cell, convert::TryInto}; executable_instruction!( string_lift_memory(instruction: Instruction) -> _ { move |runtime...
use super::to_native; use crate::{ errors::{InstructionError, InstructionErrorKind}, interpreter::Instruction, types::InterfaceType, values::InterfaceValue, }; use std::{cell::Cell, convert::TryInto}; executable_instruction!( string_lift_memory(instruction: Instruction) -> _ { move |runtime...
ew(instruction, k))?; let memory_view = memory.view(); if length == 0 { runtime.stack.push(InterfaceValue::String("".into())); return Ok(()) } if memory_view.len() <= pointer + length - 1 { return Err(InstructionError::ne...
InstructionErrorKind::MemoryIsMissing { memory_index }, ) })?; let pointer: usize = to_native::<i32>(&inputs[0], instruction)? .try_into() .map_err(|e| (e, "pointer").into()) .map_err(|k| InstructionError::n...
random
[ { "content": "#[inline(always)]\n\nfn align_pointer(ptr: usize, align: usize) -> usize {\n\n // clears bits below aligment amount (assumes power of 2) to align pointer\n\n debug_assert!(align.count_ones() == 1);\n\n ptr & !(align - 1)\n\n}\n\n\n\n/// Methods for `WasmPtr`s to data that can be dereferen...
Rust
sources/rust/relm/html/src/parsers.rs
xunilrj/sandbox
f92c12f83433cac01a885585e41c02bb5826a01f
use syn::{ parse::{Parse, ParseStream}, token::{CustomToken, Token}, }; pub enum Or<A, B> { A(A), B(B), } impl<TA: Token, TB: Token> CustomToken for Or<TA, TB> { fn peek(cursor: syn::buffer::Cursor) -> bool { TA::peek(cursor) || TB::peek(cursor) } fn display() -> &'static str { ...
use syn::{ parse::{Parse, ParseStream}, token::{CustomToken, Token}, }; pub enum Or<A, B> { A(A), B(B), } impl<TA: Token, TB: Token> CustomToken for Or<TA, TB> { fn peek(cursor: syn::buffer::Cursor) -> bool { TA::peek(cursor) || TB::peek(cursor) } fn display() -> &'static str { ...
(_, Err(e), _, _) => Err(e), (_, _, Err(e), _) => Err(e), (_, _, _, Err(e)) => Err(e), } } #[allow(dead_code)] pub fn parse_seq5<T1: Parse, T2: Parse, T3: Parse, T4: Parse, T5: Parse>( stream: &mut ParseStream, ) -> syn::Result<(T1, T2, T3, T4, T5)> { let fork = stream.fork(); mat...
eam); let _ = T2::parse(&stream); let _ = T3::parse(&stream); let _ = T4::parse(&stream); Ok((a, b, c, d)) } (Err(e), _, _, _) => Err(e),
function_block-random_span
[ { "content": "fn parse_seq2<T1: Parse, T2: Parse>(stream: &mut ParseStream) -> syn::Result<(T1, T2)> {\n\n let fork = stream.fork();\n\n match (T1::parse(&fork), T2::parse(&fork)) {\n\n (Ok(a), Ok(b)) => {\n\n let _ = T1::parse(&stream);\n\n let _ = T2::parse(&stream);\n\n ...
Rust
07-rust/stm32f446/stm32f446_pac/src/tim5/ccmr2_output.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register CCMR2_Output"] pub type R = crate::R<u32, super::CCMR2_OUTPUT>; #[doc = "Writer for register CCMR2_Output"] pub type W = crate::W<u32, super::CCMR2_OUTPUT>; #[doc = "Register CCMR2_Output `reset()`'s with value 0"] impl crate::ResetValue for super::CCMR2_OUTPUT { type Type = u32; #[i...
#[doc = "Reader of register CCMR2_Output"] pub type R = crate::R<u32, super::CCMR2_OUTPUT>; #[doc = "Writer for register CCMR2_Output"] pub type W = crate::W<u32, super::CCMR2_OUTPUT>; #[doc = "Register CCMR2_Output `reset()`'s with value 0"] impl crate::ResetValue for super::CCMR2_OUTPUT { type Type = u32; #[i...
alse) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `CC4S`"] pub type CC4S_R = crate::R<u8, u8>; #[doc = "Wri...
11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `OC4FE`"] pub type OC4FE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OC4FE`"] pub struct OC4FE_W<'a> { w: &'a mut W, } impl<'a> OC4FE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/peripetyd/collector.rs
cathay4t/eureka
135da097feabc08fb395a1f7b9b3563b4d670519
use chrono::{Local, SecondsFormat, TimeZone}; use nix; use nix::sys::select::FdSet; use peripety::{LogSeverity, StorageEvent, StorageSubSystem, BlkInfo}; use sdjournal; use std::collections::HashMap; use std::os::unix::io::AsRawFd; use std::sync::mpsc::{Receiver, Sender}; use uuid::Uuid; use buildin_regex::BUILD_IN_...
use chrono::{Local, SecondsFormat, TimeZone}; use nix; use nix::sys::select::FdSet; use peripety::{LogSeverity, StorageEvent, StorageSubSystem, BlkInfo}; use sdjournal; use std::collections::HashMap; use std::os::unix::io::AsRawFd; use std::sync::mpsc::{Receiver, Sender}; use uuid::Uuid; use buildin_regex::BUILD_IN_...
pub fn new( sender: &Sender<StorageEvent>, config_changed: &Receiver<ConfCollector>, ) { let mut journal = sdjournal::Journal::new().expect("Failed to open systemd journal"); journal.timeout_us = 0; journal .seek_tail() .expect("Unable to seek to end of journal!")...
fn process_journal_entry( entry: &HashMap<String, String>, sender: &Sender<StorageEvent>, buildin_regex_confs: &[RegexConf], user_regex_confs: &[RegexConf], ) { let msg = match entry.get("MESSAGE") { Some(m) => { if m.is_empty() { return; } ...
function_block-full_function
[ { "content": "pub fn parser_start(sender: Sender<StorageEvent>) -> ParserInfo {\n\n let (event_in_sender, event_in_recver) = mpsc::channel();\n\n\n\n spawn(move || loop {\n\n match event_in_recver.recv() {\n\n Ok(event) => parse_event(&event, &sender),\n\n Err(e) => println!(\...
Rust
src/gc/src/heap/freelist/freelist_space.rs
qinsoon/zebu
6f6475568e38696b129cf81ff4d5ab0ea1f688cb
use common::ptr::*; use heap::*; use objectmodel::sidemap::*; use utils::mem::memsec::memzero; use utils::mem::*; use std::mem; use std::sync::Mutex; const LOG_BYTES_IN_PAGE: usize = 12; const BYTES_IN_PAGE: ByteSize = 1 << LOG_BYTES_IN_PAGE; const PAGES_IN_SPACE: usize = 1 << (LOG_BYTES_PREALLOC_SPACE - LOG_BYTE...
use common::ptr::*; use heap::*; use objectmodel::sidemap::*; use utils::mem::memsec::memzero; use utils::mem::*; use std::mem; use std::sync::Mutex; const LOG_BYTES_IN_PAGE: usize = 12; const BYTES_IN_PAGE: ByteSize = 1 << LOG_BYTES_IN_PAGE; const PAGES_IN_SPACE: usize = 1 << (LOG_BYTES_PREALLOC_SPACE - LOG_BYTE...
).len(), self.total_pages ); trace!( "-page type encode starts at {}", Address::from_ptr(&self.page_encode_table as *const LargeObjectEncode) ); trace!( "-page mark table starts at {}", Address::from_ptr(&self.page_mark_table as...
gn: ByteSize) -> Address { assert!(align <= BYTES_IN_PAGE); let size = math::align_up(size, BYTES_IN_PAGE); let mut usable_nodes = self.usable_nodes.lock().unwrap(); let mut candidate = None; for i in 0..usable_nodes.len() { let ref node = usable_nodes[i]; ...
random
[ { "content": "pub fn munmap(addr: Address, size: ByteSize) {\n\n use self::libc::*;\n\n unsafe {\n\n munmap(addr.to_ptr_mut() as *mut c_void, size as size_t);\n\n }\n\n}\n\n\n\n/// malloc's and zeroes the memory\n\npub unsafe fn malloc_zero(size: usize) -> *mut u8 {\n\n use self::memsec;\n\n ...
Rust
src/core/compression/zlib.rs
BlockProject3D/bpx-rs
e4e06ce6160ea5ed90e93db8f801d1abfc4006cd
use std::io::{Read, Write}; use libz_sys::{ deflate, deflateEnd, deflateInit_, inflate, inflateEnd, inflateInit_, z_stream, Z_DATA_ERROR, Z_DEFAULT_COMPRESSION, Z_FINISH, Z_MEM_ERROR, Z_NEED_DICT, Z_NO_FLUSH, Z_OK, Z_STREAM_ERROR, Z_VERSION_ERROR }; us...
use std::io::{Read, Write}; use libz_sys::{ deflate, deflateEnd, deflateInit_, inflate, inflateEnd, inflateInit_, z_stream, Z_DATA_ERROR, Z_DEFAULT_COMPRESSION, Z_FINISH, Z_MEM_ERROR, Z_NEED_DICT, Z_NO_FLUSH, Z_OK, Z_STREAM_ERROR, Z_VERSION_ERROR }; us...
deflated_size: usize, chksum: &mut TChecksum ) -> Result<(), InflateError> { let mut decoder = new_decoder()?; let res = do_inflate(&mut decoder, input, output, deflated_size, chksum); unsafe { inflateEnd(&mut decoder); } res } }
output: TWrite, inflated_size: usize, chksum: &mut TChecksum ) -> Result<usize, DeflateError> { let mut encoder = new_encoder()?; let res = do_deflate(&mut encoder, input, output, inflated_size, chksum); unsafe { deflateEnd(&mut encoder); } ...
random
[]
Rust
src/prepared_email.rs
mikedilger/mailstrom
0253dabc0c304f43991943b54e5b73da07192414
use crate::delivery_result::DeliveryResult; use email_format::rfc5322::headers::Bcc; use email_format::rfc5322::types::{Address, GroupList, Mailbox}; use email_format::Email; use crate::error::Error; use lettre::{EmailAddress, SendableEmail, Envelope}; use crate::message_status::InternalMessageStatus; use crate::recipi...
use crate::delivery_result::DeliveryResult; use email_format::rfc5322::headers::Bcc; use email_format::rfc5322::types::{Address, GroupList, Mailbox}; use email_format::Email; use crate::error::Error; use lettre::{EmailAddress, SendableEmail, Envelope}; use crate::message_status::InternalMessageStatus; use crate::recipi...
} pub fn prepare_email( mut email: Email, helo_name: &str, ) -> Result<(PreparedEmail, InternalMessageStatus), Error> { let recipients = determine_recipients(&email); email.clear_bcc(); let message_id = match email.get_message_id() { Some(mid) => format!("{}@{}", mid.0.id_left, mid....
r> { let to: Result<Vec<EmailAddress>, lettre::error::Error> = self.to.iter().map(|s| EmailAddress::new(s.clone())).collect(); let to = to?; Ok(SendableEmail::new( Envelope::new( Some(EmailAddress::new(self.from.clone())?), to)?, ...
function_block-function_prefixed
[ { "content": "// Deliver an email to an SMTP server\n\npub fn smtp_delivery(\n\n prepared_email: &PreparedEmail,\n\n smtp_server_domain: &str,\n\n port: u16,\n\n config: &Config\n\n) -> DeliveryResult {\n\n\n\n // lettre::EmailAddress checks validity. But we checked that when we created\n\n /...
Rust
src/main.rs
pandaman64/qopter
698240f06c530f767359b847a0bdfedb168d063e
#![feature(duration_as_u128)] extern crate clap; #[macro_use] extern crate failure; extern crate openqasm; extern crate qopter; extern crate rayon; use clap::{App, Arg, SubCommand}; use openqasm::Qasm; use qopter::*; use rayon::prelude::*; use std::str::FromStr; #[derive(Debug)] struct CommandLineOption { topolo...
#![feature(duration_as_u128)] extern crate clap; #[macro_use] extern crate failure; extern crate openqasm; extern crate qopter; extern crate rayon; use clap::{App, Arg, SubCommand}; use openqasm::Qasm; use qopter::*; use rayon::prelude::*; use std::str::FromStr; #[derive(Debug)] struct CommandLineOption { topolo...
e_qasm(qasm)?; (topology, qasm) } _ => return Err(NotEnoughArgumentsError.into()), }; let beams = match matches.value_of("beams") { Some(s) => FromStr::from_str(s)?, None => 10, }; let initial_mappings = match matches.value_of("mapping size") { Some(...
.value_name("NUM_MAPPING") .help("number of initial mappings"), ) .arg( Arg::with_name("number of paths") .short("p") .long("path") .value_name("NUM_PATHS") .help("number of paths"), ) .a...
function_block-random_span
[ { "content": "fn count_gates_on_same_qubits(size: usize, operations: &[openqasm::Operation]) -> usize {\n\n let mut last_target = vec![vec![]; size];\n\n let mut count = 0;\n\n for op in operations {\n\n use openqasm::Operation::*;\n\n match op {\n\n Unitary(_, _, target) => {\...
Rust
src/ra_proc_macro/tt.rs
qiaoruntao/cargo-equip
0f09aa7df4ea00fad38bcea3843251c86bb3fc81
use serde::{Deserialize, Serialize}; use smol_str::SmolStr; #[derive(Clone, Deserialize, Serialize)] enum TokenTree { Leaf(Leaf), Subtree(Subtree), } impl From<proc_macro2::TokenTree> for TokenTree { fn from(tt: proc_macro2::TokenTree) -> Self { match tt { proc_macro2::TokenTree::Group...
use serde::{Deserialize, Serialize}; use smol_str::SmolStr; #[derive(Clone, Deserialize, Serialize)] enum TokenTree { Leaf(Leaf), Subtree(Subtree), } impl From<proc_macro2::TokenTree> for TokenTree { fn from(tt: proc_macro2::TokenTree) -> Self { match tt { proc_macro2::TokenTree::Group...
} impl From<Subtree> for proc_macro2::Group { fn from(subtree: Subtree) -> Self { let delimiter = match subtree.delimiter.map(|Delimiter { kind, .. }| kind) { Some(DelimiterKind::Parenthesis) => proc_macro2::Delimiter::Parenthesis, Some(DelimiterKind::Brace) => proc_macro2::Delimit...
n Subtree { delimiter: match group.delimiter() { proc_macro2::Delimiter::Parenthesis => Some(delimiter(DelimiterKind::Parenthesis)), proc_macro2::Delimiter::Brace => Some(delimiter(DelimiterKind::Brace)), proc_macro2::Delimiter::Bracket => Some(delimiter(Delim...
function_block-function_prefixed
[ { "content": "fn targets_in_ws(metadata: &cm::Metadata) -> impl Iterator<Item = (&cm::Target, &cm::Package)> {\n\n metadata\n\n .packages\n\n .iter()\n\n .filter(move |cm::Package { id, .. }| metadata.workspace_members.contains(id))\n\n .flat_map(|p| p.targets.iter().map(move |t| ...
Rust
src/qqhtd.rs
signupsi/qht-rs
1d363d755b7797e05e3c44cbef8cef8e2f08e184
use crate::basicqht::*; use crate::filter::Filter; pub use rand::rngs::StdRng; pub use rand::{FromEntropy, Rng}; pub use std::collections::hash_map::DefaultHasher; pub use std::hash::{Hash, Hasher}; pub use rust_dense_bitset::DenseBitSetExtended; const FINGERPRINT_SIZE_LIMIT: usize = 8; pub struct QQuotientHashTabl...
use crate::basicqht::*; use crate::filter::Filter; pub use rand::rngs::StdRng; pub use rand::{FromEntropy, Rng}; pub use std::collections::hash_map::DefaultHasher; pub use std::hash::{Hash, Hasher}; pub use rust_dense_bitset::DenseBitSetExtended; const FINGERPRINT_SIZE_LIMIT: usize = 8; pub struct QQuotientHashTabl...
Hash) -> bool { let fingerprint = self.get_fingerprint(&e); let address = (get_hash(&e, 1, 0) as usize) % self.n_cells; self.in_cell(address, fingerprint) } fn insert(&mut self, e: impl Hash) -> bool { let fi...
print_size); if n_cells == 0 { panic!("[QHT Filter] Incorrect parameters, memory size should be at least n_buckets * fingerprint_size"); } Self { n_cells, n_buckets, fingerprint_size, pow_fingerprint_size, qht, } ...
random
[ { "content": "/// Returns the hash of (e, base, counter)\n\npub fn get_hash(e: impl Hash, base: u64, counter: u64) -> u64 {\n\n let mut s = DefaultHasher::new();\n\n e.hash(&mut s);\n\n base.hash(&mut s);\n\n counter.hash(&mut s);\n\n s.finish()\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! impl_ba...
Rust
sdk/cosmos/src/requests/execute_stored_procedure_builder.rs
extrawurst/azure-sdk-for-rust
bc74cad7cc5f9226cf39c4abae0d902a85765e74
use crate::prelude::*; use crate::resources::stored_procedure::Parameters; use crate::responses::ExecuteStoredProcedureResponse; use http::StatusCode; use serde::de::DeserializeOwned; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct ExecuteStoredProcedureBuilder<'a, 'b> { stored_procedure_client: &'a ...
use crate::prelude::*; use crate::resources::stored_procedure::Parameters; use crate::responses::ExecuteStoredProcedureResponse; use http::StatusCode; use serde::de::DeserializeOwned; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct ExecuteStoredProcedureBuilder<'a, 'b> { stored_procedure_client: &'a ...
pub fn with_partition_keys(self, partition_keys: &'b PartitionKeys) -> Self { Self { partition_keys: Some(partition_keys), ..self } } pub async fn execute<T>(&self) -> Result<ExecuteStoredProcedureResponse<T>, CosmosError> where T: DeserializeOwned, ...
pub fn with_allow_tentative_writes( self, allow_tentative_writes: TenativeWritesAllowance, ) -> Self { Self { allow_tentative_writes, ..self } }
function_block-full_function
[]
Rust
nannou-apps/src/bin/check.rs
reedrosenbluth/oscen
722829dd35beccaa141893a43d6c3d91e3622b62
use crossbeam::crossbeam_channel::{unbounded, Receiver, Sender}; use nannou::prelude::*; use nannou_audio as audio; use nannou_audio::Buffer; use oscen::envelopes::*; use oscen::filters::*; use oscen::operators::*; use oscen::oscillators::*; use oscen::rack::*; use std::sync::Arc; fn main() { nannou::app(model).up...
use crossbeam::crossbeam_channel::{unbounded, Receiver, Sender}; use nannou::prelude::*; use nannou_audio as audio; use nannou_audio::Buffer; use oscen::envelopes::*; use oscen::filters::*; use oscen::operators::*; use oscen::oscillators::*; use oscen::rack::*; use std::sync::Arc; fn main() { nannou::app(model).up...
amp).unwrap(); } } fn update(_app: &App, model: &mut Model, _update: Update) { let samples: Vec<f32> = model.receiver.try_iter().collect(); model.samples = samples; } fn view(app: &App, model: &Model, frame: Frame) { if frame.nth() == 0 { println!("Active module: 0 - Sine"); }; use nan...
synth.rack.mono( &synth.controls, &mut synth.state, &mut synth.outputs, &mut synth.buffers, sample_rate, ); for channel in frame { *channel = amp; } synth.sender.send(
function_block-random_span
[ { "content": "/// Generate the Environment variables needed for the synth.\n\npub fn tables() -> (Rack, Box<Controls>, Box<State>, Box<Outputs>, Box<Buffers>) {\n\n (\n\n Rack::new(),\n\n Box::new(Controls::new()),\n\n Box::new(State::new()),\n\n Box::new(Outputs::new()),\n\n ...
Rust
metalos/lib/package_download/src/lib.rs
facebookincubator/fs_image
3515a24bb0e93176a5584bdc8839464fa28390d7
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::fs::Permissions; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use anyhow::Con...
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::fs::Permissions; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use anyhow::Con...
pub async fn ensure_package_on_disk_ignoring_artifacts<D>( log: Logger, dl: D, pkg: &packages::generic::Package, ) -> Result<()> where D: PackageDownloader, { let dest = pkg.path(); if dest.exists() { return Ok(()); } let map_install_err = |error: anyhow::Error| Error::Install ...
function_block-full_function
[ { "content": "pub trait Kind: Debug + Copy + Clone + PartialEq + Eq + Sync + Send + __private::Sealed {\n\n const NAME: &'static str;\n\n const THRIFT: ThriftKind;\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub struct PackageTag(String);\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\npub struct Pack...
Rust
crates/nu-cli/src/commands/xpath.rs
wcarss/nushell
2573441e2875cb9c2075efe1f6ade35aeb87ebe3
extern crate sxd_document; extern crate sxd_xpath; use crate::commands::WholeStreamCommand; use crate::prelude::*; use bigdecimal::FromPrimitive; use nu_errors::ShellError; use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value}; use nu_source::Tagged; use sxd_document::parser;...
extern crate sxd_document; extern crate sxd_xpath; use crate::commands::WholeStreamCommand; use crate::prelude::*; use bigdecimal::FromPrimitive; use nu_errors::ShellError; use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value}; use nu_source::Tagged; use sxd_document::parser;...
#[cfg(test)] mod tests { use super::ShellError; use super::XPath; #[test] fn examples_work_as_expected() -> Result<(), ShellError> { use crate::examples::test as test_examples; Ok(test_examples(XPath {})?) } }
fn build_xpath(xpath_str: &str) -> sxd_xpath::XPath { let factory = Factory::new(); factory .build(xpath_str) .unwrap_or_else(|e| panic!("Unable to compile XPath {}: {}", xpath_str, e)) .expect("error with building the xpath factory") }
function_block-function_prefixed
[ { "content": "pub fn from_xml_string_to_value(s: String, tag: impl Into<Tag>) -> Result<Value, roxmltree::Error> {\n\n let parsed = roxmltree::Document::parse(&s)?;\n\n Ok(from_document_to_value(&parsed, tag))\n\n}\n\n\n\nasync fn from_xml(\n\n args: CommandArgs,\n\n registry: &CommandRegistry,\n\n)...
Rust
yatta/src/windows_event.rs
limethyst/yatta
50e26a4d6ce38bdfc02eb43c4855663c93657222
use std::{ sync::{ atomic::{AtomicIsize, Ordering}, Arc, Mutex, }, thread, time::Duration, }; use crossbeam_channel::{unbounded, Receiver, Sender}; use lazy_static::lazy_static; use log::{error, info}; use strum::Display; use bindings::Windows::Win32::{ Foundation::HWND, ...
use std::{ sync::{ atomic::{AtomicIsize, Ordering}, Arc, Mutex, }, thread, time::Duration, }; use crossbeam_channel::{unbounded, Receiver, Sender}; use lazy_static::lazy_static; use log::{error, info}; use strum::Display; use bindings::Windows::Win32::{ Foundation::HWND, ...
} #[derive(Clone, Debug)] pub struct WindowsEvent { pub event_type: WindowsEventType, pub event_code: WinEventCode, pub window: Window, pub title: Option<String>, } #[derive(Clone, Copy, FromPrimitive, ToPrimitive, PartialEq, Display, Debug)] #[repr(u32)] #[allow(dead_code)] pub enum WinEven...
nt_code: WinEventCode) -> Option<Self> { match event_code { WinEventCode::ObjectDestroy => Some(Self::Destroy), WinEventCode::ObjectCloaked | WinEventCode::ObjectHide | WinEventCode::SystemMinimizeStart => Some(Self::Hide), WinEventCode::ObjectShow ...
function_block-function_prefixed
[]
Rust
rust tezos+everscale/tezos_everscale/src/bin/bridge_without_comments.rs
everscale-experts/hackathon_new
dafaaea8b7f70cfdb9162a1b6752ac31d6a4a5df
mod tezos_send_transaction; use lib::functions::*; use ureq::Agent; use std::sync::Arc; use std::fs; use serde_json::Value; use tezos_send_transaction::transfer as tezos_transfer; fn tezos_get_transactions() -> Value { let agent = Agent::new(); let path = format!("https://api.hangzhounet.tzkt.io/v1/accounts/{}...
mod tezos_send_transaction; use lib::functions::*; use ureq::Agent; use std::sync::Arc; use std::fs; use serde_json::Value; use tezos_send_transaction::transfer as tezos_transfer; fn tezos_get_transactions() -> Value { let agent = Agent::new(); let path = format!("https://api.hangzhounet.tzkt.io/v1/accounts/{}...
} } } Err(err) => { println!("(Everscale listener) Error: {}", err); } } }, ).await.unwrap(); loop { let res = tezos_get_transactions(); let len = res.as_array().unwrap().len(); ...
().as_str() ).expect("failed to parse json") ); let ton = create_client_verbose(&config).unwrap(); let mut last_len = tezos_get_transactions().as_array().unwrap().len(); let context = Arc::new( ton_client::ClientContext::new(ton_client::ClientConfig { network: ton_client::net...
random
[ { "content": "fn get_config_field(name: &str) -> serde_json::Value {\n\n serde_json::from_str::<serde_json::Value>(std::fs::read_to_string(\"config.json\").unwrap().as_str())\n\n .unwrap()[name].clone()\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n let context = Arc::new(\n\n ton_clien...
Rust
src/msg.rs
JACKAL-DAO/RNS-Name-Service
132fc3eea6e6dcd3a378382992da783d192d76a9
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Addr; use crate::state::{ Name, Operator } ; use cw_utils::Expiration; use cosmwasm_std::Binary; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub blocks_per_year: u64, pub met...
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Addr; use crate::state::{ Name, Operator } ; use cw_utils::Expiration; use cosmwasm_std::Binary; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub blocks_per_year: u64, pub met...
}, NumTokens {}, ContractInfo {}, NftInfo { token_id: String, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct BlocksResponse { pub blocks_per_year: u64, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct OwnerResponse...
pub enum QueryMsg { GetOwner {}, GetBlocksPerYear {}, ResolveName { name : String }, ResolveAttributes { name : String }, OwnerOf { token_id: String, }, ApprovedForAll { owner: String, start_after: Option<String>, limit: Option<u32>,
random
[ { "content": "pub fn try_set_owner(deps: DepsMut, info: MessageInfo, owner: Addr) -> Result<Response, ContractError> {\n\n STATE.update(deps.storage, |mut state| -> Result<_, ContractError> {\n\n if info.sender != state.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\...
Rust
benchmark/src/lib.rs
mrobakowski/faster-rs
ab33be278ae752ba95e6563949672774174e5919
extern crate hwloc; extern crate libc; extern crate regex; use faster_rs::FasterKv; use hwloc::{CpuSet, ObjectType, Topology, CPUBIND_THREAD}; use regex::Regex; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::os::unix::prelude::FileExt; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; ...
extern crate hwloc; extern crate libc; extern crate regex; use faster_rs::FasterKv; use hwloc::{CpuSet, ObjectType, Topology, CPUBIND_THREAD}; use regex::Regex; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::os::unix::prelude::FileExt; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; ...
println!("Loaded {} txns", count); (init_keys, run_keys) } pub fn populate_store(store: &Arc<FasterKv>, keys: &Arc<Vec<u64>>, num_threads: u8) { let topo = Arc::new(Mutex::new(Topology::new())); let idx = Arc::new(AtomicUsize::new(0)); let mut threads = vec![]; for thread_idx in 0..num_threads { ...
t K_REFRESH_INTERVAL: usize = 64; const K_RUN_TIME: u64 = 360; const K_CHUNK_SIZE: usize = 3200; const K_FILE_CHUNK_SIZE: usize = 131072; const K_INIT_COUNT: usize = 250000000; const K_TXN_COUNT: usize = 1000000000; const K_NANOS_PER_SECOND: usize = 1000000000; const K_THREAD_STACK_SIZE: usize = 4 * 1024 * 1024; pub...
random
[ { "content": "fn populate(num_threads: usize) -> () {\n\n if let Ok(store) = FasterKvBuilder::new(TABLE_SIZE, LOG_SIZE).with_disk(STORAGE_DIR).build() {\n\n let store = Arc::new(store);\n\n let mut threads = vec![];\n\n let num_active_threads = Arc::new(AtomicUsize::new(0));\n\n f...
Rust
src/opts.rs
robatipoor/shell-hist
b931b50feb5608af38fb0991dbbef4f29e2a1cb0
use crate::eject; use dirs::home_dir; use regex::Regex; use std::env; use std::fmt; use std::path::PathBuf; use std::slice::Iter; use structopt::StructOpt; #[derive(StructOpt)] pub struct Options { #[structopt(flatten)] pub display: DisplayOpts, #[structopt(flatten)] pub shell: ShellOpts, #[...
use crate::eject; use dirs::home_dir; use regex::Regex; use std::env; use std::fmt; use std::path::PathBuf; use std::slice::Iter; use structopt::StructOpt; #[derive(StructOpt)] pub struct Options { #[structopt(flatten)] pub display: DisplayOpts, #[structopt(flatten)] pub shell: ShellOpts, #[...
lf.exact, self.heat) { (false, false, false) => DisplayMode::Fuzzy, (true, false, false) => DisplayMode::Fuzzy, (false, true, false) => DisplayMode::Exact, (false, false, true) => DisplayMode::Heat, _ => { eject("Multiple display modes selected...
> { if let Some(sh) = Self::detect_shell() { sh } else { eject("Unable to detect shell, please manually select a shell flavor"); } } (true, false) => HistoryFlavor::Zsh, (false, true) => HistoryFl...
random
[ { "content": "pub fn parse<'a>(path: Option<PathBuf>, flavor: HistoryFlavor) -> Node {\n\n let mut tree = Node::new();\n\n\n\n let path = path.unwrap_or_else(|| {\n\n flavor.history_path()\n\n });\n\n let (re, idx) = flavor.regex_and_capture_idx();\n\n\n\n let f = File::open(&path).unwrap...
Rust
src/coincheck/mock.rs
canpok1/trading-bot-rust
e45c4a0d2af25fdbacf05dfdedf20b7f29d51e75
use crate::bot::model::TradeInfo; use crate::bot::model::TradeInfoParam; use crate::coincheck::client::Client; use crate::coincheck::model::Pair; use crate::coincheck::model::{Balance, NewOrder, OpenOrder, Order, OrderBooks, OrderType}; use crate::config::Config; use crate::error::MyError::{EmptyCollection, KeyNotFound...
use crate::bot::model::TradeInfo; use crate::bot::model::TradeInfoParam; use crate::coincheck::client::Client; use crate::coincheck::model::Pair; use crate::coincheck::model::{Balance, NewOrder, OpenOrder, Order, OrderBooks, OrderType}; use crate::config::Config; use crate::error::MyError::{EmptyCollection, KeyNotFound...
wrap().iter().last() { Ok(Some(market.clone())) } else { Ok(None) } } pub fn make_info(&self, pair: &str, config: &Config) -> MyResult<TradeInfo> { if let Some(market) = self.get_market(pair)? { let mut param = TradeInfoParam::default(); ...
key: pair.to_owned(), collection_name: "markets".to_owned(), })); } if let Some(market) = self.markets.get(pair).un
function_block-random_span
[ { "content": "pub fn has_near_rate_order(\n\n buy_rate: f64,\n\n profit_ratio: f64,\n\n open_orders: &Vec<OpenOrder>,\n\n entry_skip_rate_ratio: f64,\n\n) -> (bool, String) {\n\n if open_orders.is_empty() {\n\n return (\n\n false,\n\n \"has not near rate order, open_o...
Rust
src/request.rs
rustysec/hasty-rs
0e7014c4288ac97b284c4b074ecdf54ed46685dd
extern crate mime; use std::collections::HashMap; use url::Url; use constants::HttpMethods; #[derive(Clone)] pub struct Request { host: String, path: String, method: HttpMethods, headers: HashMap<String,String>, body: Option<Vec<u8>>, body_type: mime::Mime, url: Option<Url>, } impl Requ...
extern crate mime; use std::collections::HashMap; use url::Url; use constants::HttpMethods; #[derive(Clone)] pub struct Request { host: String, path: String, method: HttpMethods, headers: HashMap<String,String>, body: Option<Vec<u8>>, body_type: mime::Mime, url: Option<Url>, } impl Requ...
pub fn add_raw_header(&mut self, name: String, value: String) { self.headers.insert(name, value); } pub fn with_raw_header(mut self, name: String, value: String) -> Self { self.headers.insert(name, value); self } pub fn with_url(mut self, url: Url) -> Self { self...
, content_type: mime::Mime) { self.body_type = content_type; } pub fn set_body(&mut self, body: Option<Vec<u8>>) { self.body = body; }
random
[ { "content": "#[test]\n\npub fn methods_post() {\n\n let s = HttpMethods::Post.to_string();\n\n assert_eq!(s, \"POST\".to_owned());\n\n}\n\n\n", "file_path": "src/constants.rs", "rank": 0, "score": 89164.04834883794 }, { "content": "#[test]\n\npub fn methods_get() {\n\n let s = Http...
Rust
tests/it/env.rs
oberblastmeister/xshell
f98f45a6a34a2dc3f526039685ba0972e9794c21
use std::collections::BTreeMap; use xshell::{cmd, pushenv}; use crate::setup; #[test] fn test_env() { setup(); let v1 = "xshell_test_123"; let v2 = "xshell_test_456"; assert_env(cmd!("echo_env {v1}").env(v1, "123"), &[(v1, Some("123"))]); assert_env( cmd!("echo_env {v1} {v2}").envs([(v...
use std::collections::BTreeMap; use xshell::{cmd, pushenv}; use crate::setup; #[test] fn test_env() { setup(); let v1 = "xshell_test_123"; let v2 = "xshell_test_456"; assert_env(cmd!("echo_env {v1}").env(v1, "123"), &[(v1, Some("123"))]); assert_env( cmd!("echo_env {v1} {v2}").envs([(v...
, "quark"); assert_env(cmd!("{echo_env} {v1} {v2}").env_clear(), &[(v1, None), (v2, None)]); assert_env( cmd!("{echo_env} {v1} {v2}").env_clear().env(v1, "baz"), &[(v1, Some("baz")), (v2, None)], ); assert_env(cmd!("{echo_env} {v1} {v2}").env(v1, "baz").env_clear(), &[(v1, None), (v2, N...
assert_env(cmd!("echo_env {v1} {v2}"), &[(v1, Some("foobar")), (v2, Some("quark"))]); assert_env( cmd!("echo_env {v1} {v2}").env(v1, "wombo"), &[(v1, Some("wombo")), (v2, Some("quark"))], ); assert_env(cmd!("echo_env {v1} {v2}").env_remove(v1), &[(v1, None), (v2, Some("quark"))]); ...
random
[ { "content": "fn setup() {\n\n static ONCE: std::sync::Once = std::sync::Once::new();\n\n ONCE.call_once(|| {\n\n if let Err(err) = install_mock_binaries() {\n\n panic!(\"failed to install binaries from mock_bin: {}\", err)\n\n }\n\n });\n\n\n\n fn install_mock_binaries() ->...
Rust
src/cluster/bootstrap.rs
FridgeSeal/blip
0a202eb0061d8e2ac34a4bd501cfa08051cb4087
use super::{ cut::{self, MultiNodeCut, Subscription}, proto::{ membership_client::MembershipClient, Endpoint, EndpointError, Join, JoinReq, JoinResp, NodeId, NodeMetadata, PreJoinReq, PreJoinResp, }, Cluster, State, }; use futures::{ future::TryFutureExt, stream::{FuturesUnorde...
use super::{ cut::{self, MultiNodeCut, Subscription}, proto::{ membership_client::MembershipClient, Endpoint, EndpointError, Join, JoinReq, JoinResp, NodeId, NodeMetadata, PreJoinReq, PreJoinResp, }, Cluster, State, }; use futures::{ future::TryFutureExt, stream::{FuturesUnorde...
async fn join_phase2(&self, req: JoinReq, observer: Endpoint) -> Result<JoinResp, JoinError> { let observer = self.resolve_endpoint(&observer)?; let mut c = MembershipClient::connect(observer) .map_err(|e| JoinError::Phase2(e.into())) .await?; (c.join(req).ma...
async fn join_phase1(&self, req: PreJoinReq, via: &Endpoint) -> Result<PreJoinResp, JoinError> { let seed = self.resolve_endpoint(via)?; let mut c = MembershipClient::connect(seed) .map_err(|e| JoinError::Phase1(e.into())) .await?; (c.pre_join(req).map_ok(|r| r.into_inn...
function_block-full_function
[ { "content": "#[derive(Copy, Clone, Debug, Error)]\n\nenum MemberResolutionError {\n\n #[error(\"invalid socketaddr: {}\", .0)]\n\n InvalidSocketAddr(#[from] SocketAddrError),\n\n\n\n #[error(\"missing metadata\")]\n\n MissingMetadata,\n\n}\n\n\n", "file_path": "src/cluster/mod.rs", "rank": ...
Rust
decadog_core/src/lib.rs
tommilligan/decadog
b8137b682ca7d9dbcbffb8f7efbb925b143b7417
#![deny(clippy::all)] use std::collections::hash_map::DefaultHasher; use std::fmt; use std::hash::Hasher; use chrono::{DateTime, FixedOffset}; mod core; pub mod error; pub mod github; pub mod secret; pub mod zenhub; pub use crate::core::{AssignedTo, Sprint}; pub use error::Error; use github::{ paginate::Paginat...
#![deny(clippy::all)] use std::collections::hash_map::DefaultHasher; use std::fmt; use std::hash::Hasher; use chrono::{DateTime, FixedOffset}; mod core; pub mod error; pub mod github; pub mod secret; pub mod zenhub; pub use crate::core::{AssignedTo, Sprint}; pub use error::Error; use github::{ paginate::Paginat...
fault(); update.title = Some(new_title); self.github .patch_milestone(&self.owner, &self.repo, milestone.number, &update) } pub fn close_milestone(&self, milestone: &Milestone) -> Result<Milestone, Error> { let mut update = MilestoneUpdate::default(); update.sta...
estone_title( &self, milestone: &Milestone, new_title: String, ) -> Result<Milestone, Error> { let mut update = MilestoneUpdate::de
function_block-random_span
[ { "content": "fn create_sprint(settings: &Settings) -> Result<(), Error> {\n\n let github = github::Client::new(&settings.github_url, &settings.github_token.value())?;\n\n let zenhub = zenhub::Client::new(\n\n settings\n\n .zenhub_url\n\n .as_ref()\n\n .ok_or(Error:...
Rust
kernel-rs/src/kernel.rs
coolofficials/rv6
2b93a86a7c9f332607670b545a219f40e5a216fe
use core::cell::UnsafeCell; use core::fmt::{self, Write}; use core::hint::spin_loop; use core::mem::MaybeUninit; use core::ops::Deref; use core::pin::Pin; use core::sync::atomic::{AtomicBool, Ordering}; use array_macro::array; use pin_project::pin_project; use crate::{ bio::Bcache, console::{consoleinit, Cons...
use core::cell::UnsafeCell; use core::fmt::{self, Write}; use core::hint::spin_loop; use core::mem::MaybeUninit; use core::ops::Deref; use core::pin::Pin; use core::sync::atomic::{AtomicBool, Ordering}; use array_macro::array; use pin_project::pin_project; use crate::{ bio::Bcache, console::{consoleinit, Cons...
} pub fn current_cpu(&self) -> *mut Cpu { let id: usize = cpuid(); self.cpus[id].get() } pub unsafe fn get_bcache(&self) -> &Bcache { &self.bcache } } #[macro_export] macro_rules! print { ($($arg:tt)*) => { $crate::...
if self.is_panicked() { unsafe { (*self.printer.get_mut_raw()).write_fmt(args) } } else { let mut lock = self.printer.lock(); lock.write_fmt(args) }
if_condition
[ { "content": "/// Trys to return a pinned mutable reference of the array's element at index `index`.\n\n/// Returns `Some(pin_mut)` if index is not out of bounds.\n\n/// Otherwise, returns `None`.\n\npub fn get_pin_mut<T, const N: usize>(arr: Pin<&mut [T; N]>, index: usize) -> Option<Pin<&mut T>> {\n\n if in...
Rust
logos/src/source.rs
mikolajpp/logos
7ebfe8aaae03df38db2be01b611882d1b576ba4b
use std::ops::Range; use std::fmt::Debug; pub trait Slice<'source>: Sized + PartialEq + Eq + Debug { fn as_bytes(&self) -> &'source [u8]; } impl<'source> Slice<'source> for &'source str { fn as_bytes(&self) -> &'source [u8] { (*self).as_bytes() } } impl<'source> Slice<'source> for &'sou...
use std::ops::Range; use std::fmt::Debug; pub trait Slice<'source>: Sized + PartialEq + Eq + Debug { fn as_bytes(&self) -> &'source [u8]; } impl<'source> Slice<'source> for &'source str { fn as_bytes(&self) -> &'source [u8] { (*self).as_bytes() } } impl<'source> Slice<'source> for &'sou...
1) < (*self).len() { Some(unsafe { Array::from_ptr((*self).as_ptr().add(offset)) }) } else { None } } #[inline] fn slice(&self, range: Range<usize>) -> Option<&'source [u8]> { self.get(range) } #[inline] unsafe fn slice_unchecked(&self, range: Ra...
ZE: usize = 1; } impl<'source> ByteArray<'source> for [u8; 2] { const SIZE: usize = 2; } impl<'source> ByteArray<'source> for [u8; 3] { const SIZE: usize = 3; } impl<'source> ByteArray<'source> for [u8; 4] { const SIZE: usize = 4; } impl<'source> ByteArray<'source> for [u8; 5] { const SIZE: usize = 5; } impl<'source> B...
random
[ { "content": "/// Trait implemented for an enum representing all tokens. You should never have\n\n/// to implement it manually, use the `#[derive(Logos)]` attribute on your enum.\n\npub trait Logos: Sized {\n\n /// Associated type `Extras` for the particular lexer. Those can handle things that\n\n /// are...
Rust
day-08/part-2/enizor.rs
lypnol/adventofcode-2021
8ba277d698e8c59ca9cd554acc135473f5964b87
use std::env::args; use std::time::Instant; fn main() { let now = Instant::now(); let output = run(&args().nth(1).expect("Please provide an input")); let elapsed = now.elapsed(); println!("_duration:{}", elapsed.as_secs_f64() * 1000.); println!("{}", output); } #[allow(unused)] fn dbg_deductions(d...
use std::env::args; use std::time::Instant; fn main() { let now = Instant::now(); let output = run(&args().nth(1).expect("Please provide an input")); let elapsed = now.elapsed(); println!("_duration:{}", elapsed.as_secs_f64() * 1000.); println!("{}", output); } #[allow(unused)] fn dbg_deductions(d...
#[test] fn run_test() { let input = "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg fbegc...
fn line_test() { let input = "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe"; assert_eq!(solve_line(input), 8394); let input = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"; assert_eq!(s...
function_block-full_function
[ { "content": "fn line_score(line: &str) -> usize {\n\n let mut stack = Vec::<u8>::new();\n\n\n\n for c in line.as_bytes() {\n\n match c {\n\n b'(' | b'{' | b'[' | b'<' => stack.push(*c),\n\n b')' => {\n\n if stack.pop().unwrap() != b'(' {\n\n ...
Rust
executor/src/executor.rs
alyssaverkade/neuromancer
7d1d03e32a3c46ab90f0c1fb0f2e8e7f341a89e7
use std::collections::BTreeMap; use std::collections::HashSet; use conhash::{ConsistentHash, Node}; use crossbeam_utils::sync::ShardedLock; use smol_str::SmolStr; use uuid::Uuid; use neuromancer::{read_lock, write_lock, DefaultHasher}; pub(crate) struct Executor { pub(crate) identifier_mappings: ShardedLock<BTre...
use std::collections::BTreeMap; use std::collections::HashSet; use conhash::{ConsistentHash, Node}; use crossbeam_utils::sync::ShardedLock; use smol_str::SmolStr; use uuid::Uuid; use neuromancer::{read_lock, write_lock, DefaultHasher}; pub(crate) struct Executor { pub(crate) identifier_mappings: ShardedLock<BTre...
}
w(); let first_removed = known.modify_membership(&baseline); let removed = known.modify_membership(&request); let removed_predicate = vec![Librarian::new("bar")]; assert_eq!(first_removed, Vec::new()); assert_eq!(removed_predicate, removed); assert_eq!(known.set, reques...
function_block-function_prefixed
[]
Rust
src/node.rs
h4sh3d/monero-swap-lib
882159ca97dae811351f2bbb45e659af326af36d
use crate::{Protocol, Phase, Btc, Xmr}; use crate::types::{common, xmr, btc, RelativeLocktime}; use rand::rngs::OsRng; use bitcoin_hashes::hex::FromHex; use wasm_bindgen::prelude::*; use wasm_bindgen::JsValue; #[wasm_bindgen] pub struct Seller { parameters: Option<xmr::SetupParams>, setup: Option<xmr::Setup...
use crate::{Protocol, Phase, Btc, Xmr}; use crate::types::{common, xmr, btc, RelativeLocktime}; use rand::rngs::OsRng; use bitcoin_hashes::hex::FromHex; use wasm_bindgen::prelude::*; use wasm_bindgen::JsValue; #[wasm_bindgen] pub struct Seller { parameters: Option<xmr::SetupParams>, setup: Option<xmr::Setup...
pub fn export_setup(&mut self) -> Result<btc::ExportedSetupParams, JsValue> { match &self.parameters { Some(params) => Ok(btc::ExportedSetupParams::from(params)), None => Err("Parameters is missing".into()), } } pub fn verify_setup(&mut self, seller_param...
pub fn generate_params(&mut self, t0: u16, t1: u16) -> Result<(), JsValue> { let mut rng = OsRng::new().expect("OsRng"); let params = common::Params::new( RelativeLocktime::Blocks(t0), RelativeLocktime::Blocks(t1), ); self.parameters = Some(Btc::setup(params.clone...
function_block-full_function
[ { "content": "fn setup() -> (xmr::Setup, btc::Setup, Client, String) {\n\n let mut rng = OsRng::new().expect(\"OsRng\");\n\n let params = common::Params::new(\n\n RelativeLocktime::Blocks(T_0),\n\n RelativeLocktime::Blocks(T_1),\n\n );\n\n let xmr_params = Xmr::setup(params.clone(), &m...
Rust
src/parser/parser.rs
origis-lang/origis-lang
dc9e3dc93901e2791587a222ca5127a958a5e166
use std::cell::UnsafeCell; use crate::parser::lexer::Lexer; use crate::parser::rollbackable::{rollbackable, Rollbackable}; use crate::parser::token::{Token, TokenStream}; pub struct Parser<'s> { pub token_stream: UnsafeCell<Rollbackable<TokenStream<'s>>>, pub current: UnsafeCell<Token<'s>>, source: &'s st...
use std::cell::UnsafeCell; use crate::parser::lexer::Lexer; use crate::parser::rollbackable::{rollbackable, Rollbackable}; use crate::parser::token::{Token, TokenStream}; pub struct Parser<'s> { pub token_stream: UnsafeCell<Rollbackable<TokenStream<'s>>>, pub current: UnsafeCell<Token<'s>>, source: &'s st...
.map(|x| { $parser.next_token(); x }) } #[cfg(test)] mod tests { use crate::parser::parse::decl::Decl; use std::assert_matches::assert_matches; use crate::parser::parse::expr::{Expr, LiteralExpr}; use crate::parser::parse::ident::{ MaybeTypedIdent, TypedIdent, UntypedI...
match $parser.peek_token() { token @ crate::parser::token::Token { inner: $token_inner, .. } => Ok(token), token => Err( crate::parser::parse::error::Error::expected_but_found( &[stringify!($token_inner)], token, ), ...
if_condition
[]
Rust
src/software/control/src/display/screen.rs
ejuliot/makair
a024a4cec0b7e3ff4faf177410e1c2f1d696149c
use conrod_core::color::{self, Color}; use telemetry::structures::MachineStateSnapshot; use crate::config::environment::DISPLAY_WIDGET_SPACING_FROM_BOTTOM; use super::fonts::Fonts; use super::widget::{ BackgroundWidgetConfig, BrandingWidgetConfig, ControlWidget, ControlWidgetType, ErrorWidgetConfig, GraphW...
use conrod_core::color::{self, Color}; use telemetry::structures::MachineStateSnapshot; use crate::config::environment::DISPLAY_WIDGET_SPACING_FROM_BOTTOM; use super::fonts::Fonts; use super::widget::{ BackgroundWidgetConfig, BrandingWidgetConfig, ControlWidget, ControlWidgetType, ErrorWidgetConfig, GraphW...
last_widget_position = self .widgets .render(ControlWidgetType::Telemetry(ratio_config)); let tidal_config = TelemetryWidgetConfig { title: "Tidal volume", value: "0".to_string(), unit: "mL (milliliters)", ids: ( ...
let ratio_config = TelemetryWidgetConfig { title: "Insp-exp ratio", value: "0:0".to_string(), unit: "insp:exp.", ids: ( self.ids.ratio_parent, self.ids.ratio_title, self.ids.ratio_value, self.ids.ratio_unit,...
assignment_statement
[ { "content": "pub fn gather_telemetry(\n\n port_id: &str,\n\n tx: Sender<TelemetryChannelType>,\n\n mut file_buf: Option<BufWriter<File>>,\n\n) {\n\n loop {\n\n info!(\"Opening {}\", &port_id);\n\n match serial::open(&port_id) {\n\n Err(e) => {\n\n error!(\"{:...
Rust
src/limiting.rs
Icelk/kvarn
9b3e0f0909b73712ad2057aa2875bcb3da01d3c8
use crate::prelude::*; use threading::atomic; #[inline] #[must_use] pub fn get_too_many_requests() -> Response<Bytes> { let body = Bytes::from_static("<html>\ <head>\ <title>429 Too Many Requests</title>\ </head>\ <body>\ <center>\ <h1>429 Too Many Requests</h1>\ ...
use crate::prelude::*; use threading::atomic; #[inline] #[must_use] pub fn get_too_many_requests() -> Response<Bytes> { let body = Bytes::from_static("<html>\ <head>\ <title>429 Too Many Requests</title>\ </head>\ <body>\ <center>\ <h1>429 Too Many Requests</h1>\ ...
ing()) .header("content-encoding", "identity") .body(body) .unwrap() } #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)] pub enum Action { Passed, Send, Drop, } #[derive(Debug, Clone)] #[must_use] pub struct Manager { connection_map_and_time: Arc<Mutex<(Has...
ver too many times. <i>Please Enhance Your Calm.</i></p>\ <p>Try to access this page again in a minute. If this error persists, please contact the website administrator.</p>\ </center>\ </body>\ </html>".as_bytes()); Response::builder() .status(StatusCode::TOO_MANY_REQUESTS) ...
function_block-random_span
[ { "content": "#[inline]\n\npub fn get_body_length_request<T>(request: &Request<T>) -> usize {\n\n use std::str::FromStr;\n\n if method_has_request_body(request.method()) {\n\n request\n\n .headers()\n\n .get(\"content-length\")\n\n .map(HeaderValue::to_str)\n\n ...
Rust
src/geom/bound.rs
nwtnni/photon
60c15cca7509a8b43a8ab9aa4cb444c29775ad78
use std::iter; use std::ops::BitOr; use std::ops::BitOrAssign; use crate::math; use crate::math::{Axis, Ray, Vec3}; use crate::geom; #[readonly::make] #[derive(Copy, Clone, Debug)] pub struct Box3 { pub min: Vec3, pub max: Vec3, } impl Default for Box3 { fn default() -> Self { let min = std::f32...
use std::iter; use std::ops::BitOr; use std::ops::BitOrAssign; use crate::math; use crate::math::{Axis, Ray, Vec3}; use crate::geom; #[readonly::make] #[derive(Copy, Clone, Debug)] pub struct Box3 { pub min: Vec3, pub max: Vec3, } impl Default for Box3 { fn default() -> Self { let min = std::f32...
rhs: &'_ Box3) { *self = self.union_b(rhs); } } impl BitOrAssign<&'_ Box3> for &'_ mut Box3 { fn bitor_assign(&mut self, rhs: &'_ Box3) { **self = self.union_b(rhs); } } impl BitOrAssign<Vec3> for Box3 { fn bitor_assign(&mut self, rhs: Vec3) { *self = self.union_v(&rhs); } ...
} else { if y > z { Axis::Y } else { Axis::Z } } } pub fn intersect(&self, rhs: &Self) -> Self { let min = self.min.max(&rhs.min); let max = self.max.min(&rhs.max); Box3 { min, max } } pub fn union_b(&self, rhs: &Self) -> Self { let min = self.mi...
random
[ { "content": "pub fn basis(w: &Vec3) -> (Vec3, Vec3) {\n\n let x = w.x().abs();\n\n let y = w.y().abs();\n\n let z = w.z().abs();\n\n let v = if x <= y && x <= z {\n\n Vec3::new(1.0, 0.0, 0.0)\n\n } else if y <= x && y <= z {\n\n Vec3::new(0.0, 1.0, 0.0)\n\n } else {\n\n V...
Rust
src/apis/fsa_results_api.rs
cholcombe973/isilon
928234ce6928a47e061c8afac4e4e589d3b22ea9
/* * Isilon SDK * * Isilon SDK - Language bindings for the OneFS API * * OpenAPI spec version: 5 * Contact: sdk@isilon.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ use std::borrow::Borrow; use std::rc::Rc; use futures; use futures::Future; use hyper; use super::{configuration, qu...
/* * Isilon SDK * * Isilon SDK - Language bindings for the OneFS API * * OpenAPI spec version: 5 * Contact: sdk@isilon.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ use std::borrow::Borrow; use std::rc::Rc; use futures; use futures::Future; use hyper; use super::{configuration, qu...
} fn get_result_directory( &self, result_directory_id: i32, id: &str, sort: &str, limit: i32, comp_report: i32, dir: &str, ) -> Box<dyn Future<Item = crate::models::ResultDirectories, Error = Error>> { let q = ::url::form_urlencoded::Serializ...
query( self.configuration.borrow(), &uri_str, &"", hyper::Method::GET, )
call_expression
[ { "content": "fn query<T, R, C: hyper::client::connect::Connect + 'static>(\n\n config: &configuration::Configuration<C>,\n\n url: &str,\n\n body: &T,\n\n method: hyper::Method,\n\n) -> Box<dyn Future<Item = R, Error = Error>>\n\nwhere\n\n T: Serialize,\n\n R: DeserializeOwned + 'static,\n\n{\...
Rust
src/day14.rs
runfalk/advent-of-code-2021
0be69d30f5037d59a7364beecbaaffe59ce66666
use anyhow::{anyhow, Result}; use std::collections::HashMap; use std::path::Path; struct PolymerExpander { rules: HashMap<(char, char), char>, cache: HashMap<(char, char, usize), HashMap<char, usize>>, } impl PolymerExpander { fn new(rules: &HashMap<(char, char), char>) -> Self { Self { ...
use anyhow::{anyhow, Result}; use std::collections::HashMap; use std::path::Path; struct PolymerExpander { rules: HashMap<(char, char), char>, cache: HashMap<(char, char, usize), HashMap<char, usize>>, } impl PolymerExpander { fn new(rules: &HashMap<(char, char), char>) -> Self { Self { ...
fn parse_insertion_rule(rule: &str) -> Option<((char, char), char)> { let (pair, insertion) = rule.split_once(" -> ")?; if pair.len() != 2 || insertion.len() != 1 { return None; } Some(( (pair.chars().next()?, pair.chars().nth(1)?), insertion.chars().next()?, )) } pub fn m...
ashMap<(char, char), char>) -> usize { let mut polymer_expander = PolymerExpander::new(rules); let counts = polymer_expander.expand_template(template, 40); let most_common = counts.values().copied().max().unwrap(); let least_common = counts.values().copied().min().unwrap(); most_common - least_comm...
function_block-function_prefixed
[ { "content": "fn count_ones<R: AsRef<str>>(report: impl Iterator<Item = R>) -> Result<Vec<usize>> {\n\n let mut iter = report.peekable();\n\n\n\n let num_digits = match iter.peek() {\n\n Some(line) => line.as_ref().len(),\n\n None => return Ok(Vec::new()),\n\n };\n\n\n\n let mut ones =...
Rust
src/inline_object/mod.rs
ngirard/directwrite-rs
c453b8a3793c0bfc4e7db0203674b4878b7cb56d
use crate::effects::ClientEffect; use crate::enums::BreakCondition; use crate::error::DWResult; use crate::factory::Factory; use crate::inline_object::custom::CustomInlineObject; use crate::metrics::overhang::OverhangMetrics; use crate::metrics::InlineObjectMetrics; use crate::text_format::TextFormat; use crate::text...
use crate::effects::ClientEffect; use crate::enums::BreakCondition; use crate::error::DWResult; use crate::factory::Factory; use crate::inline_object::custom::CustomInlineObject; use crate::metrics::overhang::OverhangMetrics; use crate::metrics::InlineObjectMetrics; use crate::text_format::TextFormat; use crate::text...
pub fn draw(&self, context: &DrawingContext) -> DWResult<()> { unsafe { let hr = self.ptr.Draw( context.client_context.ptr(), context.renderer.get_raw(), context.origin.x, context.origin.y, context.is_sideways...
pub fn break_conditions(&self) -> BreakConditions { unsafe { let (mut before, mut after) = std::mem::zeroed(); self.ptr.GetBreakConditions(&mut before, &mut after); BreakConditions { preceding: before.into(), following: after.into(), ...
function_block-full_function
[ { "content": "/// Custom implementation of an inline text object in Rust.\n\npub trait CustomInlineObject: Send + Sync + 'static {\n\n /// Report metrics about your inline object to the runtime.\n\n fn metrics(&self) -> InlineObjectMetrics;\n\n\n\n /// Report your object's overhang values to the runtim...
Rust
rng/src/lib.rs
undecidedzogvisvitalispotent8stars360/stm32wl-hal
e0ecfee11c36be1a3ff1545113e0ac361a49572b
#![cfg_attr(not(test), no_std)] use core::{ mem::transmute, num::NonZeroU32, sync::atomic::{compiler_fence, Ordering::SeqCst}, }; pub use rand_core; cfg_if::cfg_if! { if #[cfg(feature = "stm32wl5x_cm0p")] { pub use stm32wl::stm32wl5x_cm0p as pac; } else if #[cfg(feature = "stm32...
#![cfg_attr(not(test), no_std)] use core::{ mem::transmute, num::NonZeroU32, sync::atomic::{compiler_fence, Ordering::SeqCst}, }; pub use rand_core; cfg_if::cfg_if! { if #[cfg(feature = "stm32wl5x_cm0p")] { pub use stm32wl::stm32wl5x_cm0p as pac; } else if #[cfg(feature = "stm32...
fn recover_from_noise_error(&mut self) -> Result<(), Error> { self.rng.cr.modify(|_, w| w.condrst().set_bit()); self.rng.cr.modify(|_, w| w.condrst().clear_bit()); while self.rng.cr.read().condrst().bit_is_set() { compiler_fence(SeqCst)...
self.wait_for_new_entropy()?; for dw in chunk { *dw = self.rng.dr.read().bits(); } } Ok(()) }
function_block-function_prefix_line
[ { "content": "fn hclk3_prescaler_div(rcc: &pac::RCC) -> u16 {\n\n match rcc.extcfgr.read().shdhpre().bits() {\n\n 0b0001 => 3,\n\n 0b0010 => 5,\n\n 0b0101 => 6,\n\n 0b0110 => 10,\n\n 0b0111 => 32,\n\n 0b1000 => 2,\n\n 0b1001 => 4,\n\n 0b1010 => 8,\n\n ...
Rust
src/process/thread.rs
maroider/winproc-rs
a702364bcd96b2508a9ff8b4e607ea7f49a01d0c
use crate::{Error, Handle, Process, WinResult}; use std::{ mem, ops::Deref, os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle}, }; use winapi::{ shared::{ basetsd::{DWORD_PTR, ULONG64}, minwindef::DWORD, }, um::{ processthreadsapi::{ GetCu...
use crate::{Error, Handle, Process, WinResult}; use std::{ mem, ops::Deref, os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle}, }; use winapi::{ shared::{ basetsd::{DWORD_PTR, ULONG64}, minwindef::DWORD, }, um::{ processthreadsapi::{ GetCu...
} impl Default for PriorityLevel { fn default() -> PriorityLevel { PriorityLevel::Normal } }
riorityLevel::Lowest => THREAD_PRIORITY_LOWEST, PriorityLevel::BelowNormal => THREAD_PRIORITY_BELOW_NORMAL, PriorityLevel::Normal => THREAD_PRIORITY_NORMAL, PriorityLevel::AboveNormal => THREAD_PRIORITY_ABOVE_NORMAL, PriorityLevel::Highest => THREAD_PRIORITY_HIGHEST, ...
function_block-function_prefixed
[ { "content": "#[derive(Debug)]\n\nstruct ProcessIter {\n\n snapshot: Handle,\n\n access: Access,\n\n}\n\n\n\nimpl Iterator for ProcessIter {\n\n type Item = WinResult<Process>;\n\n\n\n fn next(&mut self) -> Option<WinResult<Process>> {\n\n unsafe {\n\n let mut entry: PROCESSENTRY32...
Rust
crates/storage/src/oauth2/access_token.rs
matrix-org/matrix-authentication-service
0c2950a160e4a831c4d18047412d007df06909ec
use anyhow::Context; use chrono::{DateTime, Duration, Utc}; use mas_data_model::{ AccessToken, Authentication, BrowserSession, Client, Session, User, UserEmail, }; use sqlx::PgExecutor; use thiserror::Error; use crate::{DatabaseInconsistencyError, IdAndCreationTime, PostgresqlBackend}; pub async fn add_access_t...
use anyhow::Context; use chrono::{DateTime, Duration, Utc}; use mas_data_model::{ AccessToken, Authentication, BrowserSession, Client, Session, User, UserEmail, }; use sqlx::PgExecutor; use thiserror::Error; use crate::{DatabaseInconsistencyError, IdAndCreationTime, PostgresqlBackend}; pub async fn add_access_t...
pub async fn cleanup_expired(executor: impl PgExecutor<'_>) -> anyhow::Result<u64> { let res = sqlx::query!( r#" DELETE FROM oauth2_access_tokens WHERE created_at + (expires_after * INTERVAL '1 second') + INTERVAL '15 minutes' < now() "#, ) .execute(executor) .awa...
function_block-full_function
[ { "content": "fn hash<H: Digest>(mut hasher: H, token: &str) -> anyhow::Result<String> {\n\n hasher.update(token);\n\n let hash = hasher.finalize();\n\n // Left-most 128bit\n\n let bits = hash\n\n .get(..16)\n\n .context(\"failed to get first 128 bits of hash\")?;\n\n Ok(BASE64URL_N...
Rust
roller_web/src/lib.rs
jacobh/roller
4640ac9e2feec6aa211ba0b47b77f287a439f67b
use async_std::sync::{Mutex, Receiver, Sender}; use broadcaster::BroadcastChannel; use futures::prelude::*; use rustc_hash::FxHashMap; use std::sync::Arc; use warp::{ ws::{self, WebSocket, Ws}, Filter, }; use roller_protocol::{ control::{ButtonCoordinate, ButtonGridLocation, ButtonState, InputEvent}, f...
use async_std::sync::{Mutex, Receiver, Sender}; use broadcaster::BroadcastChannel; use futures::prelude::*; use rustc_hash::FxHashMap; use std::sync::Arc; use warp::{ ws::{self, WebSocket, Ws}, Filter, }; use roller_protocol::{ control::{ButtonCoordinate, ButtonGridLocation, ButtonState, InputEvent}, f...
}) }); let app = warp::path::end().and(index).or(websocket).or(assets); let mut rt = tokio::runtime::Runtime::new().unwrap(); std::thread::spawn(move || { rt.block_on(async { warp::serve(app).bind(([0, 0, 0, 0], 8888)).await; }); }); }
browser_session( websocket, fixture_params, initial_button_states, initial_fixture_group_states, server_message_recv, event_sender, )
call_expression
[]
Rust
particle-node/src/node.rs
ktzanida/fluence
51c44cbdb9a530aa986eb9f3af1d84508877dcec
/* * Copyright 2020 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or a...
/* * Copyright 2020 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or a...
; let libp2p_metrics = metrics_registry.as_mut().map(Metrics::new); let connectivity_metrics = metrics_registry.as_mut().map(ConnectivityMetrics::new); let connection_pool_metrics = metrics_registry.as_mut().map(ConnectionPoolMetrics::new); let plumber_metrics = metrics_registry.as_mut()...
if config.metrics_config.metrics_enabled { Some(Registry::default()) } else { None }
if_condition
[ { "content": "pub fn create_swarm(config: SwarmConfig) -> (PeerId, Box<Node<AVM>>, KeyPair, SwarmConfig) {\n\n create_swarm_with_runtime(config, aqua_vm_config)\n\n}\n", "file_path": "crates/created-swarm/src/swarm.rs", "rank": 0, "score": 359754.6415028821 }, { "content": "/// Retrieves ...
Rust
arch/x86/src/instr/arith.rs
ConsoleLogLuke/Firn
d3cebbd7403a790e19f412940a016c24ceec4cdf
use crate::GeneralByteReg::{Ah, Al}; use crate::GeneralWordReg::{Ax, Dx}; use crate::{arith, GeneralByteReg, GeneralWordReg, RegMem, System}; use firn_arch_x86_macros::{arith_instr, instr}; arith_instr!(ADD); arith_instr!(ADC); arith_instr!(SUB); arith_instr!(SBB); #[instr("CMP AL, imm8")] pub fn cmp_al_imm8(sys: &mu...
use crate::GeneralByteReg::{Ah, Al}; use crate::GeneralWordReg::{Ax, Dx}; use crate::{arith, GeneralByteReg, GeneralWordReg, RegMem, System}; use firn_arch_x86_macros::{arith_instr, instr}; arith_instr!(ADD); arith_instr!(ADC); arith_instr!(SUB); arith_instr!(SBB); #[instr("CMP AL, imm8")] pub fn cmp_al_imm8(sys: &mu...
#[instr("MUL r/m16")] pub fn mul_rm16(sys: &mut System, rm: RegMem) { let multiplicand = rm.get_16(sys); let multiplier = sys.cpu.reg_16(Ax.into()); let value = multiplicand as u32 * multiplier as u32; let low = (value & 0xff) as u16; let high = (value >> 8) as u16; sys.cpu.set_reg_16(Ax.into...
pub fn mul_rm8(sys: &mut System, rm: RegMem) { let multiplicand = rm.get_8(sys); let multiplier = sys.cpu.reg_8(Al); let value = multiplicand as u16 * multiplier as u16; sys.cpu.set_reg_16(Ax.into(), value); let extended = value > u8::MAX as u16; sys.cpu.flags.carry = extended; sys.cpu.flag...
function_block-full_function
[ { "content": "#[instr(\"MOV r/m16, imm16\")]\n\npub fn mov_rm16_imm16(sys: &mut System, rm: RegMem, imm: u16) {\n\n rm.set_16(sys, imm);\n\n}\n\n\n", "file_path": "arch/x86/src/instr/transfer.rs", "rank": 2, "score": 441492.8412339837 }, { "content": "#[instr(\"MOV r/m8, imm8\")]\n\npub f...
Rust
battleships_engine/src/main.rs
r-o-b-o-t-o/quantum-battleships
3c2aaeeb08830634bcac23c411d504f5d168010c
#[macro_use] extern crate serde_derive; use q1tsim::circuit::Circuit; use std::io::{ Error, ErrorKind }; pub mod ship; pub mod player; pub mod coords; use player::Player; macro_rules! arr { ( $( $n:expr )? ) => { { $( let mut array = Vec::with_capacity($n); fo...
#[macro_use] extern crate serde_derive; use q1tsim::circuit::Circuit; use std::io::{ Error, ErrorKind }; pub mod ship; pub mod player; pub mod coords; use player::Player; macro_rules! arr { ( $( $n:expr )? ) => { { $( let mut array = Vec::with_capacity($n); fo...
fn main() -> Result<(), Box<dyn std::error::Error>> { loop { let command = read_line()?; if command == "blankGameState" { let game_state = GameState::default(); println!("{}", serde_json::to_string(&game_state)?); } else if command == "updateGameState" { ...
for power in find_powers_of_two(key as i32) { let block_idx = which_power_of_two(power) as usize; let dmg = ((val as f32 / query.shots as f32) * 100.0).round() as i32; let ship = &mut game_state.players[player].ships[ship_idx]; ship.add_dam...
function_block-function_prefix_line
[ { "content": "#[derive(Default, Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]\n\npub struct Coords {\n\n pub x: i32,\n\n pub y: i32,\n\n}\n\n\n\nimpl Coords {\n\n pub fn new(x: i32, y: i32) -> Self {\n\n Self { x, y }\n\n }\n\n}\n", "file_path": "battleships_engine/src/coords.rs...
Rust
sources/rust/epoll/src/platform/api.rs
xunilrj/sandbox
f92c12f83433cac01a885585e41c02bb5826a01f
use super::EpollEvent; use crate::platform::linux_x86_64::{ accept4, bind, close, epoll_ctl, listen, read, socket, write, Accept4Flags::NonBlock, EpollEventBuilder, EpollOperation, Errno, Protocol, SinFamily, SockType, SocketAddress, SocketAddressInet, SocketAddressInetBuilder, }; use log::trace; use std::{...
use super::EpollEvent; use crate::platform::linux_x86_64::{ accept4, bind, close, epoll_ctl, listen, read, socket, write, Accept4Flags::NonBlock, EpollEventBuilder, EpollOperation, Errno, Protocol, SinFamily, SockType, SocketAddress, SocketAddressInet, SocketAddressInetBuilder, }; use log::trace; use std::{...
EpollEvent::new(idx); epoll_ctl(epoll.fd, EpollOperation::Add, fd, &mut event).unwrap(); EpollSocket { fd, epoll, idx } } } #[derive(Copy, Clone)] struct EpollData { free: bool, data: usize, } pub struct Epoll { pub fd: u16, ptrs: Mutex<Vec<EpollData>>, nextptr: usize, } impl...
t<'a> { let mut fd = 0; std::mem::swap(&mut fd, &mut self.0); let idx = epoll.reserve(); let mut event =
function_block-random_span
[ { "content": "#[inline(always)]\n\npub fn listen(sockfd: u16, backlog: u16) -> Result<(), Errno> {\n\n syscall2::<usize>(Syscall::Listen, sockfd as usize, backlog as usize).map(|_| {})\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\n#[allow(dead_code)]\n\npub enum SockType {\n\n Stream = 1,\n\n NonBlock =...
Rust
src/mir/trees.rs
nystrom/rivo-mu
494a99e96842ce445386d0a0b95e4639b5d4f6a1
use crate::common::names::Name; use crate::mir::ops::*; #[derive(Clone, Debug)] pub struct Root { pub externs: Vec<Param>, pub data: Vec<Data>, pub procs: Vec<Proc> } #[derive(Clone, Debug)] pub struct Data { pub ty: Type, pub name: Name, pub init: Lit, } #[derive(Clone, Debug, PartialEq, Eq...
use crate::common::names::Name; use crate::mir::ops::*; #[derive(Clone, Debug)] pub struct Root { pub externs: Vec<Param>, pub data: Vec<Data>, pub procs: Vec<Proc> } #[derive(Clone, Debug)] pub struct Data { pub ty: Type, pub name: Name, pub init: Lit, } #[derive(Clone, Debug, PartialEq, Eq...
Return { exp: Box<Exp> }, } #[derive(Clone, Debug)] pub enum Exp { Block { body: Vec<Stm>, exp: Box<Exp> }, Call { fun_type: Type, fun: Box<Exp>, args: Vec<Exp> }, Load { ty: Type, ptr: Box<Exp> }, Binary { op: Bop, e1: Box<Exp>, e2: Box<Exp> }, Unary { op: Uop, exp: B...
bug)] pub enum Stm { Nop, CJump { cond: Box<Exp>, if_true: Name, if_false: Name }, Jump { label: Name }, Label { label: Name }, Move { ty: Type, lhs: Name, rhs: Box<Exp> }, Store { ty: Type, ptr: Box<Exp>, value: Box<Exp> },
random
[ { "content": "pub fn translate_lir(name: &str, h: &hir::Root) -> lir::Root {\n\n println!(\"HIR {:#?}\", h);\n\n\n\n let m = mir_gen::Translate::translate(h);\n\n println!(\"MIR {:#?}\", m);\n\n\n\n let l = lir_gen::Translate::translate(&m);\n\n println!(\"LIR {:#?}\", l);\n\n\n\n l\n\n}\n\n\n...
Rust
src/event/tank.rs
zKevz/GrowRust
c76d21f28a38d70d450a5e1223e09b6c11f8cef2
use std::{cell::RefMut, time::Instant}; use super::event::EventContext; use crate::{ consts::{item_type, items, packet::TankUpdatePacket, packet_type}, item::iteminfo_manager::ITEM_MANAGER, utils::{ error::{Error, Result}, math::Vec2f, variant_function::VariantFunction::*, }, ...
use std::{cell::RefMut, time::Instant}; use super::event::EventContext; use crate::{ consts::{item_type, items, packet::TankUpdatePacket, packet_type}, item::iteminfo_manager::ITEM_MANAGER, utils::{ error::{Error, Result}, math::Vec2f, variant_function::VariantFunction::*, }, ...
fn on_tile_punch_request( _: &mut EventContext, mut tankpacket: TankUpdatePacket, world: &mut RefMut<World>, ) -> Result<()> { let tile = world.get_tile_safe(tankpacket.tile_x as u32, tankpacket.tile_y as u32)?; let base = tile.get_base()?; if base.id == items::BLANK { return Ok(()); ...
ctx.player.char_flags = tankpacket.flags; if world.peers.len() > 1 { world.push_tankpacket(tankpacket); world.send_all(); } } packet_type::TILE_CHANGE_REQUEST => { let item = ITEM_MANAGER.get_item_safe(tank...
function_block-function_prefix_line
[ { "content": "pub fn save_world(mut world: RefMut<World>) -> Result<()> {\n\n if !Path::new(\"data/worlds\").exists() {\n\n fs::create_dir(\"data/worlds\")?;\n\n }\n\n\n\n let mut data = Vec::<u8>::with_capacity((world.width * world.height * 20) as usize);\n\n world.serialize(&mut data, None)...
Rust
src/protocol.rs
Sliman4/bevy_slinet
32f7a3a95f029bf16f7fab1fd665a7ad84fe2f4d
use io::Write; use std::fmt::{Debug, Formatter}; use std::io; use std::net::SocketAddr; use std::sync::atomic::Ordering; use async_trait::async_trait; use crate::connection::MAX_PACKET_SIZE; use crate::packet_length_serializer::PacketLengthDeserializationError; use crate::{PacketLengthSerializer, Serializer}; #[as...
use io::Write; use std::fmt::{Debug, Formatter}; use std::io; use std::net::SocketAddr; use std::sync::atomic::Ordering; use async_trait::async_trait; use crate::connection::MAX_PACKET_SIZE; use crate::packet_length_serializer::PacketLengthDeserializationError; use crate::{PacketLengthSerializer, Serializer}; #[as...
et, serializer: &S, length_serializer: &LS, ) -> io::Result<()> where ReceivingPacket: Send + Sync + Debug + 'static, SendingPacket: Send + Sync + Debug + 'static, S: Serializer<ReceivingPacket, SendingPacket>, LS: PacketLengthSerializer, { let seriali...
trait ReadStream: Send + Sync + 'static { async fn read_exact(&mut self, buffer: &mut [u8]) -> io::Result<()>; async fn receive<ReceivingPacket, SendingPacket, S, LS>( &mut self, serializer: &S, length_serializer: &LS, ) -> Result<ReceivingPacket, ReceiveError<R...
random
[ { "content": "/// A server plugin config.\n\npub trait ServerConfig: Send + Sync + 'static {\n\n /// A client-side packet type.\n\n type ClientPacket: Send + Sync + Debug + 'static;\n\n /// A server-side packet type.\n\n type ServerPacket: Send + Sync + Debug + 'static;\n\n /// The connection's p...
Rust
src/ipfs.rs
sne-os3-rp2/routinator
7a53dabf5013c206b6f0d3d1e376fb2682a60332
use std::path::{PathBuf, Path}; use crate::config::Config; use crate::operation::Error; use std::{fs, env, io, process}; use log::{error, info, warn}; use std::sync::{RwLock, Mutex, Arc}; use std::collections::{HashSet, HashMap}; use bytes::Bytes; use rpki::uri; use crate::metrics::IpfsModuleMetrics; use std::time::Sys...
use std::path::{PathBuf, Path}; use crate::config::Config; use crate::operation::Error; use std::{fs, env, io, process}; use log::{error, info, warn}; use s
pub fn value(&self) -> &String { &self.0 } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct IpfsPath(pub PathBuf); impl IpfsPath { pub fn value(&self) -> &PathBuf { &self.0 } pub fn to_string(&self) -> String { String::from(&self.0.display().to_string()) } } #[deriv...
td::sync::{RwLock, Mutex, Arc}; use std::collections::{HashSet, HashMap}; use bytes::Bytes; use rpki::uri; use crate::metrics::IpfsModuleMetrics; use std::time::SystemTime; #[derive(Clone, Debug, PartialEq, Eq)] pub struct IpnsPubkey(pub String); impl IpnsPubkey { pub fn value(&self) -> &String { &self.0 ...
random
[ { "content": "/// Creates a new path name.\n\npub fn random_path(path: &Path) -> PathBuf {\n\n path.join(format!(\"{}\", random::<u32>()))\n\n}\n\n\n", "file_path": "src/rrdp/utils.rs", "rank": 0, "score": 70571.3919880939 }, { "content": "fn process_line<B: io::BufRead, T: FromStr>(\n\n ...
Rust
2021/src/day_nine.rs
Majekdor/AdventOfCode
561942ae3200faf55e1ce166a30fac482f5bcbf4
use std::collections::HashSet; use std::fs; use std::ops::Index; pub fn run() { println!("----------\n Day Nine\n----------"); let contents = fs::read_to_string("inputs/day_nine.txt").expect("File not found!"); let lines:Vec<String> = contents.split("\n").map(|s| s.parse().unwrap()).collect(); const ...
use std::collections::HashSet; use std::fs; use std::ops::Index; pub fn run() { println!("----------\n Day Nine\n----------"); let contents = fs::read_to_string("inputs/day_nine.txt").expect("File not found!"); let lines:Vec<String> = contents.split("\n").map(|s| s.parse().unwrap()).collect(); const ...
} else { false } } } fn num_below_greater(&mut self, row: usize, column: usize) -> bool { return if row == 99 { true } else { if self.data[row + 1][column] > self.data[row][column] { true } else { ...
ter(&mut self, row: usize, column: usize) -> bool { return if row == 0 { true } else { if self.data[row - 1][column] > self.data[row][column] { true
function_block-random_span
[ { "content": "// Life times are weird...\n\nfn part_one<'a>(path: &HashMap<&'a str, Vec<&'a str>>, location: &'a str, seen: &mut HashSet<&'a str>) -> usize {\n\n if location == \"end\" {\n\n return 1;\n\n }\n\n\n\n if location.chars().all(|c| c.is_lowercase()) && !seen.insert(location) {\n\n ...
Rust
src/http/server/request.rs
ragagno/bwf
87f417df9d818e0f0917fbe3ddf88d10f5eed918
use std::fmt; use std::io; use super::Result; use super::Error; use super::super::{MIN_LENGTH_METHOD, LENGTH_SPACE, MIN_LENGTH_TARGET, LENGTH_PROTOCOL, LENGTH_EOL}; use crate::http::Method; const MAX_LENGTH_HEADER: usize = 4096usize; const MIN_LENGTH_REQUEST_LINE_FULL: usize = MIN_LENGTH_METHOD + LENGTH_SPACE + MI...
use std::fmt; use std::io; use super::Result; use super::Error; use super::super::{MIN_LENGTH_METHOD, LENGTH_SPACE, MIN_LENGTH_TARGET, LENGTH_PROTOCOL, LENGTH_EOL}; use crate::http::Method; const MAX_LENGTH_HEADER: usize = 4096usize; const MIN_LENGTH_REQUEST_LINE_FULL: usize = MIN_LENGTH_METHOD + LENGTH_SPACE + MI...
} mod assertions { #[test] fn parse_reader() { use super::StringRead; use super::Request; let mut reader_request_get_homepage = StringRead::new(super::REQUEST_GET_HOMEPAGE); let mut reader_request_delete_homepage = StringRead::new(super::REQUEST...
buffer[i] = x; } else { return Ok(i); } } return Ok(buffer.len()); }
function_block-function_prefix_line
[]
Rust
src/main.rs
zikani03/git-down
8612a59cb8e4beaf467ec900dd5b4afdbfe36da0
use std::fs; use std::process::Command; use std::path::{Path, PathBuf}; const COLON: &'static str = ":"; const DOT_GIT: &'static str = ".git"; #[derive(Debug, Clone)] struct GitDir { repo_url: String, repo_name: String, dirs: Vec<String>, } impl GitDir { fn url(&self) -> &str { self.re...
use std::fs; use std::process::Command; use std::path::{Path, PathBuf}; const COLON: &'static str = ":"; const DOT_GIT: &'static str = ".git"; #[derive(Debug, Clone)] struct GitDir { repo_url: String, repo_name: String, dirs: Vec<String>, } impl GitDir { fn url(&self) -> &str { self.re...
if exit_code.success() { true } else { false } } fn parse_source(source_uri: &str) -> GitDir { let mut colon_pos = 0; match source_uri.rfind(COLON) { Some(n) => { colon_pos = n; }, None => (), }; if colon_pos > 0 { return ...
let exit_code = git_command.wait() .expect("Failed to download directory/files from repository");
assignment_statement
[ { "content": "Git Down\n\n========\n\n\n\n`git-down` lets you download one or multiple directories from a Git repository without the\n\nhassle of cloning or downloading the whole repository, with one simple command.\n\n\n\n## Usage\n\n\n\nIt's really easy to use.\n\n\n\n```sh\n\n$ git-down <REPO_URL.git/DIRECTO...
Rust
src/lib.rs
colstrom/lockpipes
ad774d6950225f1973bfc6f058a2efe93bf66016
pub mod command; pub mod logging; pub use command::Command; pub use nix; use nix::errno::errno; use nix::errno::Errno; use nix::sys::stat; use nix::unistd; use nix::Error as NixError; use std::fs; use std::io; use std::path::PathBuf; use std::process; #[derive(Debug)] pub struct LockPipe { path: PathBuf, } impl L...
pub mod command; pub mod logging; pub use command::Command; pub use nix; use nix::errno::errno; use nix::errno::Errno; use nix::sys::stat; use nix::unistd; use nix::Error as NixError; use std::fs; use std::io; use std::path::PathBuf; use std::process; #[derive(Debug)] pub struct LockPipe { path: PathBuf, } impl L...
; log::debug!("writing to pipe at {:?}", &self.pipe.path); match self.pipe.write() { Ok(_) => { log::info!("wrote to pipe at {:?}", &self.pipe.path); 0 } Err(error) => { log::error!( "failed writing to pipe at {:?}: {:?}", &self.pipe.path, ...
at {:?}", &self.pipe.path); match self.pipe.create() { Ok(_) => { log::info!("created pipe at {:?}", &self.pipe.path); 0 } Err(error) => match error { NixError::Sys(Errno::EEXIST) => { log::warn!("pipe already exists at {:?}", &self.pipe.path); 0 ...
random
[ { "content": "pub fn init() {\n\n Builder::from_env(\n\n Env::new()\n\n .filter_or(LOG_FILTER_ENVIRONMENT_VARIABLE, LOG_FILTER_DEFAULT_VALUE)\n\n .write_style_or(LOG_STYLE_ENVIRONMENT_VARIABLE, LOG_STYLE_DEFAULT_VALUE),\n\n )\n\n .format_timestamp(None)\n\n .init()\n\n}\n", "file_path": "sr...
Rust
src/windows.rs
Vlad-Shcherbina/whoami
14f0e4a4cebb5debf7284da5b83152689161857c
use crate::{DesktopEnv, Platform}; use std::{ convert::TryInto, ffi::OsString, os::{ raw::{c_char, c_int, c_uchar, c_ulong}, windows::ffi::OsStringExt, }, ptr, }; #[allow(unused)] #[repr(C)] enum ExtendedNameFormat { Unknown, FullyQualifiedDN, SamCompatible, ...
use crate::{DesktopEnv, Platform}; use std::{ convert::TryInto, ffi::OsString, os::{ raw::{c_char, c_int, c_uchar, c_ulong}, windows::ffi::OsStringExt, }, ptr, }; #[allow(unused)] #[repr(C)] enum ExtendedNameFormat { Unknown, FullyQualifiedDN, SamCompatible, ...
); } debug_assert_eq!(orig_size, size); unsafe { name.set_len(size.try_into().unwrap()); } debug_assert_eq!(name.pop(), Some(0u16)); OsString::from_wide(&name) } #[inline(always)] pub fn realname() -> String { string_from_os(realname_os()) } #[inline(always)] pub fn realname...
.cast(), &mut size) == 0 }; if fail { panic!( "Failed to get username: {}, report at https://github.com/libcala/whoami/issues", unsafe { GetLastError() }
random
[ { "content": "pub fn username_os() -> OsString {\n\n // Unwrap never fails\n\n getpwuid(false).unwrap()\n\n}\n\n\n", "file_path": "src/unix.rs", "rank": 0, "score": 139876.23296355503 }, { "content": "#[inline(always)]\n\npub fn username_os() -> OsString {\n\n native::username_os()\...