lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
crates/core/src/year2019/day20.rs
fornwall/advent-of-code-2019-rs
67bb6a48860f20a773f9e913c7e498c921370eeb
use crate::input::Input; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet, VecDeque}; const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (0, -1), (-1, 0), (1, 0)]; struct Maze { cols: usize, array: Vec<u8>, portals: HashMap<(i32, i32), ((i32, i32), i32)>, start_location: (i32, ...
use crate::input::Input; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet, VecDeque}; const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (0, -1), (-1, 0), (1, 0)]; struct Maze { cols: usize, array: Vec<u8>, portals: HashMap<(i32, i32), ((i32, i32), i32)>, start_location: (i32, ...
use crate::input::{test_part_one, test_part_two}; let example = include_str!("day20_example.txt"); test_part_one!(example => 23); let input = include_str!("day20_input.txt"); test_part_one!(input => 580); test_part_two!(input => 6362); let other_input = include_str!("day20_input_ray.txt"); ...
function_block-function_prefix_line
[ { "content": "pub fn solve(input: &mut Input) -> Result<i32, String> {\n\n let trench = Trench::parse(input.text).ok_or_else(|| \"Unable to parse trench\".to_string())?;\n\n\n\n let mut max_y = 0;\n\n let mut count = 0;\n\n let max_x_to_try = *trench.x_range.end();\n\n let min_y_to_try = *trench....
Rust
libbit/src/index.rs
andyyu2004/bit
4041637b56445b3857a256c8f552a79cdac307d2
mod index_entry; mod index_inner; mod reuc; mod tree_cache; pub use self::tree_cache::BitTreeCache; pub use index_entry::*; pub use index_inner::{BitIndexInner, Conflict, ConflictType, Conflicts}; use self::reuc::BitReuc; use crate::diff::*; use crate::error::BitResult; use crate::hash::OID_SIZE; use crate::io::{Hash...
mod index_entry; mod index_inner; mod reuc; mod tree_cache; pub use self::tree_cache::BitTreeCache; pub use index_entry::*; pub use index_inner::{BitIndexInner, Conflict, ConflictType, Conflicts}; use self::reuc::BitReuc; use crate::diff::*; use crate::error::BitResult; use crate::hash::OID_SIZE; use crate::io::{Hash...
Ok(()) } } type IndexStdIterator = impl Iterator<Item = BitIndexEntry> + Clone + std::fmt::Debug; pub type IndexEntryIterator = impl BitEntryIterator; #[derive(Clone, Debug, PartialEq)] pub struct BitIndexHeader { signature: [u8; 4], version: u32, entryc: u32, } impl Default for BitIndexHeader ...
me: Option<Timespec>, inner: Filelock<BitIndexInner>, } impl<'rcx> Deref for BitIndex<'rcx> { type Target = BitIndexInner; fn deref(&self) -> &Self::Target { &self.inner } } impl<'rcx> DerefMut for BitIndex<'rcx> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inne...
random
[ { "content": "pub fn crc_of(bytes: impl AsRef<[u8]>) -> u32 {\n\n let mut crc = flate2::Crc::new();\n\n crc.update(bytes.as_ref());\n\n crc.sum()\n\n}\n\n\n", "file_path": "libbit/src/hash.rs", "rank": 0, "score": 221022.04712330012 }, { "content": "// TODO too lazy to implement all...
Rust
src/developer/ffx/logger/utils/src/symbolizer.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { anyhow::{Context, Result}, async_channel::{Receiver, Sender}, async_io::Async, async_lock::Mutex, ffx_config::get_sdk, fuchsia_async::Task, futures::{AsyncBufReadExt, AsyncWriteExt, FutureExt, StreamExt}, futures_lite::io::BufReader, std::process::{Child, Command, Stdio}, ...
use { anyhow::{Context, Result}, async_channel::{Receiver, Sender}, async_io::Async, async_lock::Mutex, ffx_config::get_sdk, fuchsia_async::Task, futures::{AsyncBufReadExt, AsyncWriteExt, FutureExt, StreamExt}, futures_lite::io::BufReader, std::process::{Child, Command, Stdio}, ...
} impl Drop for LogSymbolizer { fn drop(&mut self) { let mut inner = self.inner.borrow_mut(); log::info!("LogSymbolizer dropped. Killing `symbolizer` process."); if let Some(mut inner) = inner.take() { if let Err(_) = inner.child.kill() { log::warn!("symbolizer ...
async fn start( &self, mut rx: Receiver<String>, tx: Sender<String>, extra_args: Vec<String>, ) -> Result<()> { if let Err(e) = ensure_symbol_index_registered().await { log::warn!("ensure_symbol_index_registered failed, error was: {:#?}", e); } le...
function_block-full_function
[]
Rust
tuftool/tests/update_command.rs
tjkirch/tough
f60bcec6ba508bf06056faec21af7a41f0f2f38e
mod utl; use assert_cmd::Command; use chrono::{Duration, Utc}; use std::fs::File; use std::path::Path; use tempfile::TempDir; use tough::{ExpirationEnforcement, Limits, Repository, Settings}; fn create_repo<P: AsRef<Path>>(repo_dir: P) { let timestamp_expiration = Utc::now().checked_add_signed(Duration::days(1)...
mod utl; use assert_cmd::Command; use chrono::{Duration, Utc}; use std::fs::File; use std::path::Path; use tempfile::TempDir; use tough::{ExpirationEnforcement, Limits, Repository, Settings}; fn create_repo<P: AsRef<Path>>(repo_dir: P) { let timestamp_expiration = Utc::now().checked_add_signed(Duration::days(1)...
root_key.to_str().unwrap(), "--root", root_json.to_str().unwrap(), "--metadata-url", metadata_base_url, "--targets-expires", new_targets_expiration.to_rfc3339().as_str(), "--targets-version", format!("{}", new_targets...
update_command_with_new_targets() { let root_json = utl::test_data().join("simple-rsa").join("root.json"); let root_key = utl::test_data().join("snakeoil.pem"); let repo_dir = TempDir::new().unwrap(); create_repo(repo_dir.path()); let new_timestamp_expiration = Utc::now().checked_add_si...
random
[ { "content": "#[test]\n\nfn repository_editor_from_repository() {\n\n // Load the reference_impl repo\n\n let mut repo_paths = RepoPaths::new();\n\n let root = repo_paths.root_path.clone();\n\n let repo = load_tuf_reference_impl(&mut repo_paths);\n\n\n\n assert!(RepositoryEditor::from_repo(&root,...
Rust
src/cli.rs
s-arash/polonius
7fe7cca808115828b1105c86003a768a6749383f
use log::{error, Level, LevelFilter, Metadata, Record, SetLoggerError}; use pico_args as pico; use polonius_engine::Algorithm; use std::env; use std::error; use std::fmt; use std::path::Path; use std::process::exit; use std::str::FromStr; use std::time::{Duration, Instant}; use crate::dump; use crate::dump::Output; us...
use log::{error, Level, LevelFilter, Metadata, Record, SetLoggerError}; use pico_args as pico; use polonius_engine::Algorithm; use std::env; use std::error; use std::fmt; use std::path::Path; use std::process::exit; use std::str::FromStr; use std::time::{Duration, Instant}; use crate::dump; use crate::dump::Output; us...
} struct Logger; impl log::Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= Level::Info } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { eprintln!("{} {} - {}", record.level(), record.target(), record.args()); ...
Error(match error { Error::ArgumentParsingFailed { cause } => format!("failed to parse ({})", cause), Error::Utf8ArgumentParsingFailed { value, cause } => { format!("'{}' isn't a valid value ({})", value, cause) } Error::OptionWithoutAValue(_) => "missing value".to_string(), ...
call_expression
[ { "content": "fn test_fn(dir_name: &str, fn_name: &str, algorithm: Algorithm) -> Result<(), Box<dyn Error>> {\n\n let facts_dir = Path::new(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"inputs\")\n\n .join(dir_name)\n\n .join(\"nll-facts\")\n\n .join(fn_name);\n\n println!(\"facts_...
Rust
src/main.rs
FarhadF/geoip-server-rs
1c94bbf03ed13edf74a94cd25f914f8d66fee206
use std::ffi::OsStr; use std::fs; use std::net::IpAddr; use std::str::FromStr; use std::sync::Arc; use actix_web::*; use anyhow::{anyhow, Result}; use async_std::io::ErrorKind; use clap::{App as clapApp, Arg}; use flate2::read::GzDecoder; use maxminddb::{MaxMindDBError, Reader}; use reqwest::header::{HeaderValue, CONT...
use std::ffi::OsStr; use std::fs; use std::net::IpAddr; use std::str::FromStr; use std::sync::Arc; use actix_web::*; use anyhow::{anyhow, Result}; use async_std::io::ErrorKind; use clap::{App as clapApp, Arg}; use flate2::read::GzDecoder; use maxminddb::{MaxMindDBError, Reader}; use reqwest::header::{HeaderValue, CONT...
} } #[get("/geoip/json/{ip}")] async fn get_ip(ip: web::Path<String>, state: web::Data<AppState>) -> impl Responder { let ip: core::result::Result<IpAddr, std::net::AddrParseError> = (ip).parse(); let ip: IpAddr = match ip { Ok(ip) => ip, Err(e) => { return HttpResponse::Intern...
if self.start > self.end { None } else { let prev_start = self.start; self.start += std::cmp::min(self.buffer_size as u64, self.end - self.start + 1); Some( HeaderValue::from_str(&format!("bytes={}-{}", prev_start, self.start - 1)) ...
if_condition
[ { "content": "# geoip-server-rs\n\nBlazing fast geoip server written in Rust\n\n\n\n\n\n## Build:\n\n1. Install rust\n\n2. Clone repo and build optimized for production\n\n```\n\ngit clone https://FarhadF/geoip-server-rs\n\ncd geoip-server-rs\n\ncargo build --release \n\n```\n\nThe binary will be located at ```...
Rust
serenade/src/bin/paper_micro_benchmark_runtimes.rs
bolcom/serenade-experiments-sigmod
0a4c7f19d800d1c2784ea5536abb1a628cb12f7a
#![allow(warnings)] extern crate bencher; extern crate itertools; extern crate num_format; extern crate rand_pcg; extern crate rayon; extern crate serenade_optimized; use std::borrow::Borrow; use std::collections::HashMap; use std::ops::Add; use std::time::{Duration, Instant}; use bencher::black_box; use inc_stats::...
#![allow(warnings)] extern crate bencher; extern crate itertools; extern crate num_format; extern crate rand_pcg; extern crate rayon; extern crate serenade_optimized; use std::borrow::Borrow; use std::collections::HashMap; use std::ops::Add; use std::time::{Duration, Instant}; use bencher::black_box; use inc_stats::...
let path_test = format!("data/private-clicks-{}_test.txt", dataset); let historical_sessions = io::read_training_data(&path_train); let vmis_noopt_index = VMISSkNNIndexNoOpt::new(&path_train, *m); let vmis_index = VMISSkNNIndex::new(&path_train, *m); let vsknn_index = V...
function_block-function_prefix_line
[ { "content": "fn linear_score(pos: usize) -> f64 {\n\n if pos < 100 { 1.0 - (0.1 * pos as f64) } else { 0.0 }\n\n}\n\n\n", "file_path": "vmis_diff/src/lib.rs", "rank": 0, "score": 155708.85673132475 }, { "content": "fn linear_score(pos: usize) -> f64 {\n\n if pos < 100 {\n\n 1.0...
Rust
src/pipeline/narrow_phase/contact_generator/convex_polyhedron_convex_polyhedron_manifold_generator.rs
kpdonn/ncollide
e9019b988ba187c428b56714db2f8f32e89406f7
use na::{self, Point2, Real, Unit}; #[cfg(feature = "dim3")] use alga::linear::FiniteDimInnerSpace; use math::{Isometry, Vector}; use pipeline::narrow_phase::{ContactDispatcher, ContactManifoldGenerator}; use query::algorithms::VoronoiSimplex; use query::algorithms::gjk::GJKResult; #[cfg(feature = "dim3")] use query::...
use na::{self, Point2, Real, Unit}; #[cfg(feature = "dim3")] use alga::linear::FiniteDimInnerSpace; use math::{Isometry, Vector}; use pipeline::narrow_phase::{ContactDispatcher, ContactManifoldGenerator}; use query::algorithms::VoronoiSimplex; use query::algorithms::gjk::GJKResult; #[cfg(feature = "dim3")] use query::...
#[inline] fn num_contacts(&self) -> usize { self.contact_manifold.len() } #[inline] fn contacts<'a: 'b, 'b>(&'a self, out: &'b mut Vec<&'a ContactManifold<N>>) { if self.contact_manifold.len() != 0 { out.push(&self.contact_manifold) } } }
fn update( &mut self, _: &ContactDispatcher<N>, ida: usize, ma: &Isometry<N>, a: &Shape<N>, idb: usize, mb: &Isometry<N>, b: &Shape<N>, prediction: &ContactPrediction<N>, ids: &mut IdAllocator, ) -> bool { if let (Some(cpa), Som...
function_block-full_function
[ { "content": "/// Computes the minimum distance separating two shapes.\n\n///\n\n/// Returns `0.0` if the objects are touching or penetrating.\n\npub fn shape_against_shape<N: Real>(m1: &Isometry<N>, g1: &Shape<N>, m2: &Isometry<N>, g2: &Shape<N>) -> N {\n\n if let (Some(b1), Some(b2)) = (\n\n g1.as_s...
Rust
src/stun/pacer.rs
nils-ohlmeier/librice
14c20755a25cf69c41816f89073bafff4601670f
use std::sync::Mutex; use std::time::{Duration, Instant}; use futures_timer::Delay; use crate::socket::ChannelBroadcast; pub const STUN_REQUEST_PACE_TIME: Duration = Duration::from_millis(2000); #[derive(Debug)] pub struct ChannelPacer<T> where T: std::fmt::Debug, { recv_r: async_channel::Receiver<T>, ...
use std::sync::Mutex; use std::time::{Duration, Instant}; use futures_timer::Delay; use crate::socket::ChannelBroadcast; pub const STUN_REQUEST_PACE_TIME: Duration = Duration::from_millis(2000); #[derive(Debug)] pub struct ChannelPacer<T> where T: std::fmt::Debug, { recv_r: async_channel::Receiver<T>, ...
pub async fn send_loop(&self) { while let Ok(item) = self.recv_r.recv().await { let delay = { let state = self.state.lock().unwrap(); if let Some(last_ts) = state.last_message_ts { trace!( "elapsed, {...
pub fn new(pacing: Duration) -> Self { let (send, recv) = async_channel::bounded(16); Self { recv_r: recv, recv_s: send, sender_broadcast: ChannelBroadcast::default(), state: Mutex::new(PaceState { pacing, last_message_ts: N...
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct StunAgentState {\n\n receive_loop_started: bool,\n\n outstanding_requests: HashMap<u128, Message>,\n\n local_credentials: Option<MessageIntegrityCredentials>,\n\n remote_credentials: Option<MessageIntegrityCredentials>,\n\n}\n\n\n\nimpl StunAgent {\n\n pub...
Rust
src/decoder.rs
dvc94ch/rust-cbor
5335bdb0b9c7c5be371ba99011b5fdda8f02b1ca
use std::cmp; use std::convert::Into; use std::collections::hash_map::HashMap; use std::io::{self, Read}; use std::mem::transmute; use byteorder::{ReadBytesExt, BigEndian}; use rustc_serialize::Decodable; use rustc_decoder::CborDecoder; use { Cbor, CborUnsigned, CborSigned, CborFloat, CborBytes, CborTag, Type, ...
use std::cmp; use std::convert::Into; use std::collections::hash_map::HashMap; use std::io::{self, Read}; use std::mem::transmute; use byteorder::{ReadBytesExt, BigEndian}; use rustc_serialize::Decodable; use rustc_decoder::CborDecoder; use { Cbor, CborUnsigned, CborSigned, CborFloat, CborBytes, CborTag, Type, ...
4(try!(self.rdr.read_u64::<BigEndian>())), v => return Err(self.errat( ReadError::InvalidAddValue { ty: Type::UInt, val: v })), }) } fn read_int(&mut self, first: u8) -> CborResult<CborSigned> { Ok(match first & 0b000_11111 { n @ 0...23 => CborSigned::Int...
()), Cbor::Break => return Ok(Cbor::Bytes(CborBytes(chunks.concat()))), other => return Err(CborError::AtOffset { kind: ReadError::mismatch(Type::Bytes, &other), offset: at, }) } } ...
random
[ { "content": "fn cbor_encode<T: Encodable>(v: T) -> Vec<u8> {\n\n let mut enc = Encoder::from_memory();\n\n enc.encode(&[v]).unwrap();\n\n enc.as_bytes().to_vec()\n\n}\n\n\n", "file_path": "benches/bench.rs", "rank": 2, "score": 130091.88226118372 }, { "content": "/// A very light l...
Rust
src/witten_arith.rs
mgrabmueller/campross
5944c3cf8f30330c25b13bcb80bb87b7e7650b6f
use std::io::{Read, Write, Bytes}; use std::io; use error::Error; const CODE_VALUE_BITS: usize = 32; type CodeValue = u64; const TOP_VALUE: CodeValue = (1u64 << CODE_VALUE_BITS) - 1; const FIRST_QTR: CodeValue = (TOP_VALUE / 4) + 1; const HALF: CodeValue = 2 * FIRST_QTR; const THIRD_QTR: CodeValue = 3 * FIRST_QT...
use std::io::{Read, Write, Bytes}; use std::io; use error::Error; const CODE_VALUE_BITS: usize = 32; type CodeValue = u64; const TOP_VALUE: CodeValue = (1u64 << CODE_VALUE_BITS) - 1; const FIRST_QTR: CodeValue = (TOP_VALUE / 4) + 1; const HALF: CodeValue = 2 * FIRST_QTR; const THIRD_QTR: CodeValue = 3 * FIRST_QT...
fn encode_symbol(&mut self, symbol: Symbol) -> io::Result<()> { let range = (self.high - self.low) + 1; let total = self.model.cum_freq[0] as CodeValue; debug_assert!(total <= MAX_FREQUENCY as CodeValue); let hi_freq = self.model.cum_freq[symbol-1] as CodeValue; let lo_fr...
pub fn new(output: W) -> Self { let enc = Encoder{ inner: output, model: Model::new(), low: 0, high: TOP_VALUE, bits_to_follow: 0, buffer: 0, bits_to_go: 8, }; enc }
function_block-full_function
[ { "content": "pub fn decompress<R: Read, W: Write>(input: R, mut output: W) -> Result<W, Error> {\n\n let mut cr = try!(Reader::new(input));\n\n try!(io::copy(&mut cr, &mut output));\n\n Ok(output)\n\n}\n\n\n\n\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::io::{Cursor, Write, Read};\n\n use...
Rust
starlark/src/values/layout/arena.rs
jsgf/starlark-rust-1
64c620945dff592141d6932af073175815d02fa0
/* * Copyright 2019 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/lic...
/* * Copyright 2019 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/lic...
} impl<T> Drop for Arena<T> { fn drop(&mut self) { for chunk in self.iter_chunks() { for x in chunk { let x = x as *const T as *mut T; unsafe { ptr::drop_in_place(x) } } } } } #[cfg(test)] mod test { use super::*; ...
if mem::size_of_val(e) == 0 { slice::from_raw_parts(e.as_ptr() as *const U, 0) } else { assert_eq!(mem::size_of_val(e) % mem::size_of::<U>(), 0); assert_eq!((e.as_ptr() as usize) % mem::align_of::<U>(), 0); slice::from_raw_parts( e.as_ptr() as *const U, ...
if_condition
[ { "content": "#[starlark_module]\n\npub fn global(builder: &mut GlobalsBuilder) {\n\n /// Creates a struct.\n\n ///\n\n /// `struct` creates a struct. It accepts keyword arguments, keys become\n\n /// struct field names, and values become field values.\n\n ///\n\n /// Examples:\n\n ///\n\n ...
Rust
rust-sgx/dcap-provider/src/lib.rs
jethrosun/SafeBricks
290734c3f50a41dfd7bcd155d0447dd250e4fc10
/* Copyright (c) Fortanix, Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; use std:...
/* Copyright (c) Fortanix, Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; use std:...
#[no_mangle] pub extern "C" fn sgx_ql_get_quote_config( cert_id: &PckCertId, p_cert_config: *mut *const Config, ) -> Quote3Error { lazy_static! { static ref CERTDATA_CACHE: Mutex<HashMap<quote::QeId<'static>, quote::Qe3CertDataPpid<'static>>> = Mutex::default(); static ref CERT...
ckCertInfo { certchain: vec![].into(), tcbm_cpusvn: tcbm.into(), tcbm_pcesvn, }; let buf = cert.certchain.to_mut(); response.copy_to(buf).map_err(|e| { error!("Failed to obtain PCK certificate: {:?}", e); Quote3Error::NoPlatformCertData })?; if buf.last() != ...
function_block-function_prefixed
[ { "content": "pub fn report<L: Load>(targetinfo: &Targetinfo, enclave_loader: &mut L) -> Result<Report, Error> {\n\n ReportBuilder::new(targetinfo).build(enclave_loader)\n\n}\n", "file_path": "rust-sgx/report-test/src/lib.rs", "rank": 0, "score": 378186.82556624076 }, { "content": "/// Tu...
Rust
host/transact/src/hash.rs
haydnv/tinychain
3ce912677c8359ee3050cd084c29b3c855d7f461
use async_trait::async_trait; use bytes::Bytes; use futures::future::TryFutureExt; use futures::stream::{self, Stream, StreamExt, TryStreamExt}; use futures::try_join; use sha2::{Digest, Sha256}; use tc_error::*; use tc_value::{Number, Value}; use tcgeneric::{Id, Map, TCBoxTryStream, Tuple}; use crate::fs::Dir; use c...
use async_trait::async_trait; use bytes::Bytes; use futures::future::TryFutureExt; use futures::stream::{self, Stream, StreamExt, TryStreamExt}; use futures::try_join; use sha2::{Digest, Sha256}; use tc_error::*; use tc_value::{Number, Value}; use tcgeneric::{Id, Map, TCBoxTryStream, Tuple}; use crate::fs::Dir; use c...
(hash)).await } async fn hashable(&self, txn: &Self::Txn) -> TCResult<TCBoxTryStream<Self::Item>>; } async fn hash_stream<S: Stream<Item = TCResult<Bytes>> + Unpin>(mut items: S) -> TCResult<Bytes> { let mut hasher = Sha256::default(); while let Some(hash) = items.try_next().await? { hash...
inalize().to_vec().into()) } } #[async_trait] impl<T> Hash for Tuple<T> where T: Hash, { async fn hash(&self) -> TCResult<Bytes> { let item_hashes = stream::iter(self.iter()).then(|item| item.hash()); hash_stream(item_hashes).await } } #[async_trait] impl<T> Hash for Vec<T> where T...
random
[ { "content": "/// The data contained by a single block on the filesystem.\n\npub trait BlockData: Clone + Send + Sync + 'static {\n\n fn ext() -> &'static str;\n\n}\n\n\n\n#[cfg(feature = \"tensor\")]\n\nimpl BlockData for afarray::Array {\n\n fn ext() -> &'static str {\n\n \"array\"\n\n }\n\n}\...
Rust
ext/rust-sfml-0.16.0/src/graphics/color.rs
esavier/silent-rs
b7ffd16f1f7e63657d75fc7dde039db025e96b42
use csfml_graphics_sys as ffi; use std::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}; #[repr(transparent)] #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Color(pub(super) ffi::sfColor); impl Color { #[must_use] pub const fn rgb(red: u8, green: u8, blue...
use csfml_graphics_sys as ffi; use std::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}; #[repr(transparent)] #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Color(pub(super) ffi::sfColor); impl Color { #[must_use] pub const fn rgb(red: u8, green: u8, blue...
t self, rhs: Self) { *self = *self * rhs; } }
const fn blue(&self) -> u8 { self.0.b } #[must_use] pub fn blue_mut(&mut self) -> &mut u8 { &mut self.0.b } #[must_use] pub const fn alpha(&self) -> u8 { self.0.a } #[must_use] pub fn alpha_mut(&mut self) -> &mut u8 { &mut self.0.a ...
random
[]
Rust
crates/stun-types/src/attributes/turn.rs
kbalt/ezk
6886981a5d13954fb8536cf69d83b147551fd55c
use super::{Attribute, BytesAttribute, XorMappedAddress}; use crate::builder::MessageBuilder; use crate::parse::{ParsedAttr, ParsedMessage}; use crate::{Error, NE}; use byteorder::ReadBytesExt; use bytes::BufMut; use std::convert::TryInto; use std::net::SocketAddr; pub struct ChannelNumber(pub u16); impl Attribute<'_...
use super::{Attribute, BytesAttribute, XorMappedAddress}; use crate::builder::MessageBuilder; use crate::parse::{ParsedAttr, ParsedMessage}; use crate::{Error, NE}; use byteorder::ReadBytesExt; use bytes::BufMut; use std::convert::TryInto; use std::net::SocketAddr; pub struct ChannelNumber(pub u16); impl Attribute<'_...
fn encode(&self, ctx: Self::Context, builder: &mut MessageBuilder) -> Result<(), Error> { XorMappedAddress(self.0).encode(ctx, builder) } fn encode_len(&self) -> Result<u16, Error> { XorMappedAddress(self.0).encode_len() } } pub struct EvenPort(pub bool); impl Attribute<'_> for Even...
msg: &mut ParsedMessage, attr: ParsedAttr, ) -> Result<Self, Error> { XorMappedAddress::decode(ctx, msg, attr).map(|xma| Self(xma.0)) }
function_block-function_prefix_line
[ { "content": "fn decode_addr(mut buf: &[u8], xor16: u16, xor32: u32, xor128: u128) -> Result<SocketAddr, Error> {\n\n if buf.read_u8()? != 0 {\n\n return Err(Error::InvalidData(\"first byte must be zero\"));\n\n }\n\n\n\n let family = buf.read_u8()?;\n\n let port = buf.read_u16::<NE>()? ^ xor...
Rust
src/bin.rs
FFY00/delsum
355cb866baeff8adafdb602f3139bf577e3624e0
use delsum_lib::checksum::{RelativeIndex, Relativity}; use delsum_lib::{find_algorithm, find_checksum, find_checksum_segments}; #[cfg(feature = "parallel")] use rayon::prelude::*; use std::ffi::OsString; use std::fs::File; use std::io::Read; use std::process::exit; use structopt::StructOpt; fn main() { let opt = O...
use delsum_lib::checksum::{RelativeIndex, Relativity}; use delsum_lib::{find_algorithm, find_checksum, find_checksum_segments}; #[cfg(feature = "parallel")] use rayon::prelude::*; use std::ffi::OsString; use std::fs::File; use std::io::Read; use std::process::exit; use structopt::StructOpt; fn main() { let opt = O...
format!("{}", n), RelativeIndex::FromEnd(n) => format!("-{}", n), }) .collect::<Vec<_>>() .join(","); list.push_str(&format!("\t{}:{}\n", a_list, b_list)); } print!("{}", list); } }; ...
t rel = if opts.start { Relativity::Start } else { Relativity::End }; #[cfg(feature = "parallel")] let parallel = opts.parallel; #[cfg(not(feature = "parallel"))] let parallel = false; let subsum_print = |model| { let segs = find_checksum_segments(model, &...
random
[ { "content": "/// For figuring out what type of integer to use, we need to parse the width from the\n\n/// model string, but to parse the model string, we need to know the integer type,\n\n/// so it is done here separately.\n\n/// We also need the prefix to find out what algorithm to use\n\nfn find_prefix_width...
Rust
tests/feed_s3_tests.rs
xianwill/kafka-delta-ingest
65ee89b995231fc0e037b3d3942c78cdd7baf8a6
#[allow(dead_code)] mod helpers; use kafka_delta_ingest::IngestOptions; use maplit::hashmap; use rdkafka::producer::FutureProducer; use serde::{Deserialize, Serialize}; use serde_json::json; use std::sync::Arc; use std::time::Duration; use tokio::runtime::Runtime; use tokio::task::JoinHandle; use tokio_util::sync::Ca...
#[allow(dead_code)] mod helpers; use kafka_delta_ingest::IngestOptions; use maplit::hashmap; use rdkafka::producer::FutureProducer; use serde::{Deserialize, Serialize}; use serde_json::json; use std::sync::Arc; use std::time::Duration; use tokio::runtime::Runtime; use tokio::task::JoinHandle; use tokio_util::sync::Ca...
} helpers::send_json(&producer, &topic, &json!("{}")).await; tokio::time::sleep(Duration::from_millis(50)).await; } }); (handle, token) }
last = Some(tokio::spawn(async move { helpers::send_kv_json(&p, &topic, format!("{}", id), &m.unwrap()).await })); } } tokio::spawn(async move { let (p, o) = last.unwrap().await.unwrap(); println!( "Send last message for feed {} where...
random
[ { "content": "pub fn commit_file_path(table: &str, version: i64) -> String {\n\n format!(\"{}/_delta_log/{:020}.json\", table, version)\n\n}\n\n\n\npub async fn inspect_table(path: &str) {\n\n let table = deltalake::open_table(path).await.unwrap();\n\n println!(\"Inspecting table {}\", path);\n\n fo...
Rust
AoC17/rust/src/day21.rs
yury-fedorov/AoC18
23dcb580a978df7fa05220f6709f56707278f61f
use std::collections::HashMap; extern crate regex; use regex::Regex; type Point = (i32,i32); type Image = HashMap<Point,char>; type Image2 = HashMap<Point, Image>; fn inverse( v : i32, n : i32 ) -> i32 { n - v - 1 } fn original ( p : Point, _ : i32 ) -> Point { p } fn rotate90 ( p : Point, n : i32 ) -> Point { ( in...
use std::collections::HashMap; extern crate regex; use regex::Regex; type Point = (i32,i32); type Image = HashMap<Point,char>; type Image2 = HashMap<Point, Image>; fn inverse( v : i32, n : i32 ) -> i32 { n - v - 1 } fn original ( p : Point, _ : i32 ) -> Point { p } fn rotate90 ( p : Point, n : i32 ) -> Point { ( in...
fn transform( image : &Image, map : &HashMap<String,String> ) -> Image { let key = from_image( image ); let value = map.get(&key); if value.is_none() { panic!( "No value found for: {}", key ); } to_image( value.unwrap() ) } fn unify( big_image : &Image2 ) -> Image { let n = big_image.len(); l...
fn split( image : &Image, size : i32 ) -> Image2 { let mut result = Image2::new(); let n = image.len(); let piece_size = size * size; let n_pieces = n / piece_size as usize; let n_pieces_side = to_side( n_pieces ); for x in 0 .. n_pieces_side { for y in 0 .. n_pieces_side { ...
function_block-full_function
[ { "content": "fn parse_line(line: &str ) -> (i32, i32) {\n\n let a : Vec<i32> = line.trim().split( \": \" )\n\n .map( |e| i32::from_str( e ).unwrap() ).collect();\n\n ( a[0], a[1] )\n\n}\n\n\n", "file_path": "AoC17/rust/src/day13.rs", "rank": 9, "score": 256102.72556629928 }, { ...
Rust
src/stwo.rs
nikkolasg/cryptopals-rs
e892e2265afae8ee2594f4312d4a1aeec81671a9
extern crate crypto; extern crate rand; use self::crypto::symmetriccipher::SymmetricCipherError; use self::crypto::aes; use self::crypto::blockmodes; use self::crypto::buffer; use self::crypto::buffer::{BufferResult,WriteBuffer,ReadBuffer}; use self::rand::{ Rng, OsRng }; use constants; use sone; use xor; #[derive(...
extern crate crypto; extern crate rand; use self::crypto::symmetriccipher::SymmetricCipherError; use self::crypto::aes; use self::crypto::blockmodes; use self::crypto::buffer; use self::crypto::buffer::{BufferResult,WriteBuffer,ReadBuffer}; use self::rand::{ Rng, OsRng }; use constants; use sone; use xor; #[derive(...
; }, BlockMode::CBC => { let iv = random_bytes(16); match cbc_encrypt(&padded,&key,&iv) { Ok(cipher) => return Ok((cipher,BlockMode::CBC)), Err(e) => return Err(e), } }, } } fn fill_random(mut buff :&mut [u8])...
match sone::encrypt_aes_ecb_pkcs(&padded,&key) { Ok(cipher) => return Ok((cipher,BlockMode::ECB)), Err(e) => return Err(BlockError::Symmetric(e)), }
if_condition
[ { "content": "// xor a key against a message repeatedly\n\npub fn xor_repeat(msg :&[u8], key :&[u8]) -> Vec<u8> {\n\n let mut it = msg.iter();\n\n let mut idx :usize = 0;\n\n let mut out = Vec::with_capacity(msg.len());\n\n while let Some(by) = it.next() {\n\n //println!(\"byte = {}, key = {...
Rust
src/vendor/handlebars/src/error.rs
ryoon/rustc-1.19.0
4ca47e69f710b93580101782576ebad2bef64749
use std::io::Error as IOError; use std::error::Error; use std::fmt; use template::Parameter; use render::RenderError; quick_error! { #[derive(PartialEq, Debug, Clone)] pub enum TemplateErrorReason { MismatchingClosedHelper(open: String, closed: String) { display("helper {:?} was opened, b...
use std::io::Error as IOError; use std::error::Error; use std::fmt; use template::Parameter; use render::RenderError; quick_error! { #[derive(PartialEq, Debug, Clone)] pub enum TemplateErrorReason { MismatchingClosedHelper(open: String, closed: String) { display("helper {:?} was opened, b...
TemplateError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match (self.line_no, self.column_no) { (Some(line), Some(col)) => { write!(f, "Template \"{}\" line {}, col {}: {}", self.template_name.as_ref().unwrap_...
} InvalidSyntax { display("invalid handlebars syntax.") description("invalid handlebars syntax") } InvalidParam (param: String) { display("invalid parameter {:?}", param) description("invalid parameter") } NestedSubexpression { ...
random
[]
Rust
linux-rt/examples/priorities.rs
Nauscar/linux-rtfm
c21c531dd561a989c0671ae2551fb28f600b1e9b
#![deny(rust_2018_compatibility)] #![deny(rust_2018_idioms)] #![deny(warnings)] #![feature(proc_macro_hygiene)] #![no_main] #![no_std] use core::{mem, ptr}; use cty::c_void; use linux_io::Stdout; use linux_sys::{sigaction, sighandler_t, siginfo_t, SIGRTMIN}; use panic_stderr as _; use ufmt::uwriteln; use ufmt_utils::...
#![deny(rust_2018_compatibility)] #![deny(rust_2018_idioms)] #![deny(warnings)] #![feature(proc_macro_hygiene)] #![no_main] #![no_std] use core::{mem, ptr}; use cty::c_void; use linux_io::Stdout; use linux_sys::{sigaction, sighandler_t, siginfo_t, SIGRTMIN}; use panic_stderr as _; use ufmt::uwriteln; use ufmt_utils::...
extern "C" fn p1(sig: i32, si: &mut siginfo_t, _: *mut c_void) { let mut stdout = LineBuffered::<_, consts::U100>::new(Ignore::new(Stdout)); let sp = &mut 0; uwriteln!( &mut stdout, "p1(sig={}, si={}, sp={:?})", sig, si.si_value, sp as *mut i32, ) .ok(); } ...
linux_sys::rt_sigaction( SIGRTMIN + 2, &sigaction { sa_: sighandler_t { sigaction: p3 }, sa_flags: linux_sys::SA_RESTORER | linux_sys::SA_SIGINFO, sa_restorer: Some(__restorer), sa_mask: 0, }, ...
function_block-function_prefix_line
[ { "content": "#[panic_handler]\n\nfn panic(_: &PanicInfo<'_>) -> ! {\n\n linux_sys::exit_group(101)\n\n}\n", "file_path": "panic-exit/src/lib.rs", "rank": 0, "score": 133742.21379397938 }, { "content": "#[linux_rt::entry]\n\nfn main() {\n\n panic!();\n\n}\n", "file_path": "linux-rt...
Rust
rs/monitoring/prober/src/prober.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use crate::metrics::ProberMetrics; use crate::probe::{Probe, ProbeResult, ProbeResultHelper}; use ic_metrics::{MetricsRegistry, Timer}; use prometheus::{Encoder, TextEncoder}; use slog::{info, warn, Logger}; use std::sync::Arc; use std::time::{Duration, Instant}; use std::{borrow::Cow, convert::TryFrom, io::Cursor, n...
use crate::metrics::ProberMetrics; use crate::probe::{Probe, ProbeResult, ProbeResultHelper}; use ic_metrics::{MetricsRegistry, Timer}; use prometheus::{Encoder, TextEncoder}; use slog::{info, warn, Logger}; use std::sync::Arc; use std::time::{Duration, Instant}; use std::{borrow::Cow, convert::TryFrom, io::Cursor, n...
pub async fn handle_probe( name: &str, deadline: Instant, params: ParamIterator<'_>, metrics: &ProberMetrics, log: &Logger, ) -> ProbeResult { let timer = Timer::start(); let probe = Probe::try_from(name)?; let result = probe.run(params, deadline, log).await; metrics .pro...
g ); } (PROBE_PATH_PREFIX, res.status_code(), res.into_response()) } METRICS_PATH => (METRICS_PATH, STATUS_CODE_OK, encode(registry)), _ => { info!(log, "No matching handler for {}", url); ( OTHER_PATH, ...
function_block-function_prefixed
[]
Rust
crates/shim-client/src/shim/mount.rs
jiangliu/rust-extensions
b8252e525bdd0e87559ce0d9603b52fd105d5196
#![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_...
#![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_...
fn default_instance() -> &'static Mount { static instance: ::protobuf::rt::LazyV2<Mount> = ::protobuf::rt::LazyV2::INIT; instance.get(Mount::new) } } impl ::protobuf::Clear for Mount { fn clear(&mut self) { self.field_type.clear(); self.source.clear(); self.target....
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::refle...
function_block-full_function
[ { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-client/src/events/mount.rs", "rank": 0, "score": 109945.42943754244 }, ...
Rust
crates/wasmtime/src/types/matching.rs
yuyang-ok/wasmtime
67c0d55fbb1f86af0595815e3a9c7f39593f3bd0
use crate::linker::Definition; use crate::store::StoreOpaque; use crate::{signatures::SignatureCollection, Engine, Extern}; use anyhow::{anyhow, bail, Result}; use wasmtime_environ::{ EntityType, Global, Memory, ModuleTypes, SignatureIndex, Table, WasmFuncType, WasmType, }; use wasmtime_runtime::VMSharedSignatureIn...
use crate::linker::Definition; use crate::store::StoreOpaque; use crate::{signatures::SignatureCollection, Engine, Extern}; use anyhow::{anyhow, bail, Result}; use wasmtime_environ::{ EntityType, Global, Memory, ModuleTypes, SignatureIndex, Table, WasmFuncType, WasmType, }; use wasmtime_runtime::VMSharedSignatureIn...
d {}", entity_desc(actual)), }, EntityType::Function(expected) => match actual { EntityType::Function(actual) => { let expected = &expected_types[*expected]; let actual = &actual_types[*actual]; if expected == actual { Ok(()...
}", msg); } }; Err(func_ty_mismatch(msg, expected, &actual)) } pub fn extern_(&self, expected: &EntityType, actual: &Extern) -> Result<()> { match expected { EntityType::Global(expected) => match actual { Extern::Global(actual) => self.globa...
random
[ { "content": "/// Construct a dummy `Extern` from its type signature\n\npub fn dummy_extern<T>(store: &mut Store<T>, ty: ExternType) -> Result<Extern> {\n\n Ok(match ty {\n\n ExternType::Func(func_ty) => Extern::Func(dummy_func(store, func_ty)),\n\n ExternType::Global(global_ty) => Extern::Glob...
Rust
examples/shared/vertex.rs
thomcc/bad3d
e8ecd7f4f37444c8336480d3ae754e5a83204d01
use glium::vertex as gv; use std::borrow::Cow; use std::convert::TryFrom; use t3m::prelude::*; #[repr(C)] #[derive(Copy, Clone)] pub struct VertexP { pub position: [f32; 4], } implement_vertex!(VertexP, position); #[repr(C)] #[derive(Copy, Clone)] pub struct VertexC { pub position: [f32; 4], pub color: [u8...
use glium::vertex as gv; use std::borrow::Cow; use std::convert::TryFrom; use t3m::prelude::*; #[repr(C)] #[derive(Copy, Clone)] pub struct VertexP { pub position: [f32; 4], } implement_vertex!(VertexP, position); #[repr(C)] #[derive(Copy, Clone)] pub struct VertexC { pub position: [f32; 4], pub color: [u8...
pub fn vertex_slice(v3s: &[t3m::V3]) -> &[VertexP] { unsafe { std::slice::from_raw_parts(v3s.as_ptr() as *const VertexP, v3s.len()) } } impl gv::Vertex for VertexC { #[inline] fn build_bindings() -> gv::VertexFormat { use gv::AttributeType::*; use Cow::Borrowed as S; Cow::Borrowed...
pub fn smooth_verts<I>(verts: &[V3], tris: &[[u16; 3]]) -> Vec<FullVertex> { chek::lt!(verts.len(), u16::max_value() as usize, "Too many vertices!"); let mut mesh_verts = verts .iter() .map(|&p| FullVertex { position: p.arr(), texcoord: [p.x(), p.y()], orient...
function_block-full_function
[ { "content": "#[inline]\n\npub fn tri_area(v0: V3, v1: V3, v2: V3) -> f32 {\n\n tri_face_dir(v0, v1, v2).length()\n\n}\n\n\n", "file_path": "t3m/src/geom.rs", "rank": 0, "score": 437912.94043480523 }, { "content": "#[inline]\n\npub fn tri_area_sq(v0: V3, v1: V3, v2: V3) -> f32 {\n\n tr...
Rust
src/components/table.rs
jbtrystram/patternfly-yew-quickstart
90963af1ea91f462631acee6f16806b63fe148a4
use crate::{example, example::ExamplePage}; use patternfly_yew::*; use yew::prelude::*; use chrono::Utc; pub struct TableExample { link: ComponentLink<Self>, model4: SharedTableModel<ExampleEntry>, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct ExampleEntry { pub foo: String, } impl TableRenderer ...
use crate::{example, example::ExamplePage}; use patternfly_yew::*; use yew::prelude::*; use chrono::Utc; pub struct TableExample { link: ComponentLink<Self>, model4: SharedTableModel<ExampleEntry>, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct ExampleEntry { pub foo: String, } impl TableRenderer ...
let example5 = example! {"Compact, Expandable Table, Shared Model" => <> <Table<SharedTableModel<ExampleEntry>> mode=TableMode::CompactExpandable header={html_nested!{ <TableHeader> <TableColumn label="foo"/> ...
let example4 = example! {"Compact, Expandable Table, Shared Model" => <> <Table<SharedTableModel<ExampleEntry>> mode=TableMode::CompactExpandable header={html_nested!{ <TableHeader> <TableColumn label="foo"/> ...
assignment_statement
[ { "content": "struct Model {}\n\n\n\n#[derive(Switch, Debug, Clone, PartialEq)]\n\npub enum Component {\n\n #[to = \"/alert\"]\n\n Alert,\n\n #[to = \"/applauncher\"]\n\n AppLauncher,\n\n #[to = \"/badge\"]\n\n Badge,\n\n #[to = \"/clipboard\"]\n\n Clipboard,\n\n #[to = \"/context_sel...
Rust
crates/lib/src/stdlib/filters/string/strip.rs
fasterthanlime/liquid-rust
fb4e944d4633d96491ba27f19719765faf25770d
use liquid_core::Result; use liquid_core::Runtime; use liquid_core::{Display_filter, Filter, FilterReflection, ParseFilter}; use liquid_core::{Value, ValueView}; #[derive(Clone, ParseFilter, FilterReflection)] #[filter( name = "strip", description = "Removes all whitespace (tabs, spaces, and newlines) from bot...
use liquid_core::Result; use liquid_core::Runtime; use liquid_core::{Display_filter, Filter, FilterReflection, ParseFilter}; use liquid_core::{Value, ValueView}; #[derive(Clone, ParseFilter, FilterReflection)] #[filter( name = "strip", description = "Removes all whitespace (tabs, spaces, and newlines) from bot...
#[test] fn unit_strip_one_argument() { liquid_core::call_filter!(Strip, " \n \r test \n \r ", 0f64).unwrap_err(); } #[test] fn unit_strip_shopify_liquid() { assert_eq!( liquid_core::call_filter!(Strip, " So much room for activities! ") ...
); } #[test] fn unit_rstrip_leading_sequence() { assert_eq!( liquid_core::call_filter!(Rstrip, " \n \r test \n \r ").unwrap(), liquid_core::value!(" \n \r test") ); } #[test] fn unit_rstrip_leading_sequence_only() { assert_eq!( ...
random
[ { "content": "#[test]\n\npub fn default_use() {\n\n let text = \"{{ text | default: 'bar' }}\";\n\n let globals = liquid::object!({\"text\": false});\n\n let template = liquid::ParserBuilder::with_stdlib()\n\n .build()\n\n .unwrap()\n\n .parse(text)\n\n .unwrap();\n\n let...
Rust
day_08/src/main.rs
sirodoht/adventofcode-2020
544d797a3a19bca7312462e0a14ad936672d3600
use std::collections::HashMap; use std::collections::HashSet; use std::convert::TryInto; use std::fs::File; use std::io::Read; use std::path::Path; #[derive(Debug, Clone)] struct Instruction { cmd: String, op: char, val: u32, } fn parse_code(filename: &str) -> HashMap<u32, Instruction> { let path...
use std::collections::HashMap; use std::collections::HashSet; use std::convert::TryInto; use std::fs::File; use std::io::Read; use std::path::Path; #[derive(Debug, Clone)] struct Instruction { cmd: String, op: char, val: u32, } fn parse_code(filename: &str) -> HashMap<u32, Instruction> { let path...
fn main() { let filename = String::from("./src/input"); let code = parse_code(&filename); let (acc_value, sequence, _) = process_code(&code); println!("==result=="); println!("{}", acc_value); let mut acc_when_terminates = 0; for n in sequence.iter().rev() { ...
fn process_code(code: &HashMap<u32, Instruction>) -> (i64, Vec<u32>, bool) { let mut acc: i64 = 0; let mut current: u32 = 1; let mut execution_set = HashSet::new(); let mut sequence: Vec<u32> = vec![]; let mut terminated = false; loop { if current - 1 == code.len().try_into().unwrap() {...
function_block-full_function
[ { "content": "fn read_content(filename: &str) -> String {\n\n // open file\n\n let path = Path::new(&filename);\n\n let path_display = path.display();\n\n let mut file = match File::open(&path) {\n\n Err(why) => panic!(\"could not open {}: {}\", path_display, why),\n\n Ok(file) => file...
Rust
src/musicplayer.rs
Fuzen-py/Melody
c40398e1ff05434a0ad519b68162542b40516603
use errors::{MelodyErrors, MelodyErrorsKind}; use rand::{seq::SliceRandom, thread_rng}; use rodio; use song::{Playlist, Song}; use std::fmt; use std::fs::File; use std::io::{BufReader, Write}; use tabwriter::TabWriter; use utils::fmt_duration; #[derive(Clone, Debug)] pub enum MusicPlayerStatus { Stopped(...
use errors::{MelodyErrors, MelodyErrorsKind}; use rand::{seq::SliceRandom, thread_rng}; use rodio; use song::{Playlist, Song}; use std::fmt; use std::fs::File; use std::io::{BufReader, Write}; use tabwriter::TabWriter; use utils::fmt_duration; #[derive(Clone, Debug)] pub enum MusicPlayerStatus { Stopped(...
pub fn resume(&mut self) { self.sink.play(); self.playing_time.0 = ::std::time::Instant::now(); } pub fn pause(&mut self) { self.sink.pause(); self.playing_time.1 += self.playing_time.0.elapsed(); } pub fn stop(&mut self)...
MelodyErrorsKind::EmptyQueue, "Playlist is empty", None, )) } else { if self.sink.empty() { self.playing_time.0 = ::std::time::Instant::now(); let current = self.playlist.remove(0); let file ...
function_block-function_prefix_line
[ { "content": "/// Function meant to organize a specific song\n\n/// Song: Song to organize\n\n/// to: Directory move song to\n\npub fn organize_song(song: Song, mut to: PathBuf) -> Result<(), MelodyErrors> {\n\n use self::MelodyErrorsKind::*;\n\n if song.file().is_dir() {\n\n return Err(MelodyError...
Rust
src/service/api_mirrormaker.rs
ansrivas/aiven-rs
6e98f93b484fd44387b4592d9a0391fbdb4d7417
use crate::{ client::{encode_param, HTTPClient}, errors::AivenError, make_json_request, make_request, }; use crate::service::types_mirrormaker::*; use serde::Serialize; pub struct ServiceKafkaMirrorMaker { http_client: HTTPClient, } impl ServiceKafkaMirrorMaker { pub(crate) fn new(client: HTTPClient) -> Self {...
use crate::{ client::{encode_param, HTTPClient}, errors::AivenError, make_json_request, make_request, }; use crate::service::types_mirrormaker::*; use serde::Serialize; pub struct ServiceKafkaMirrorMaker { http_client: HTTPClient, } impl ServiceKafkaMirrorMaker { pub(crate) fn new(client: HTTPClient) -> Self {...
er = encode_param("source-cluster"), target_cluster = encode_param("target-cluster") ); let _m = testutil::create_mock_server(&query_url, "", "DELETE"); match client .service_kafka_mirrormaker() .delete_replication_flow( "project", "service_name", "source-cluster", "target-clust...
format!("{:?}", e)), } } #[tokio::test] async fn test_service_mirrormaker_get_replication_flows() { let client = testutil::prepare_test_client(); let query_url = format!( "/project/{project}/service/{service_name}/mirrormaker/replication-flows", project = encode_param("project"), service_name = encod...
random
[ { "content": "mod aiven_client;\n\nmod http_client;\n\n\n\npub use aiven_client::AivenClient;\n\npub(crate) use http_client::encode_param;\n\npub use http_client::{APIError, APIResponse, HTTPClient};\n", "file_path": "src/client/mod.rs", "rank": 0, "score": 79954.48994410297 }, { "content": ...
Rust
components/css/src/values/specified/transform.rs
MQuy/mbrowser
e9d54deb776b3284279e85e020829978d8285134
use cssparser::{Parser, ToCss, _cssparser_internal_to_lowercase, match_ignore_ascii_case}; use super::angle::Angle; use super::length::LengthPercentage; use super::number::{Number, Zero}; use crate::parser::ParseError; use crate::stylesheets::rule_parser::StyleParseErrorKind; #[derive(Clone, Debug)] pub enum AngleOrZ...
use cssparser::{Parser, ToCss, _cssparser_internal_to_lowercase, match_ignore_ascii_case}; use super::angle::Angle; use super::length::LengthPercentage; use super::number::{Number, Zero}; use crate::parser::ParseError; use crate::stylesheets::rule_parser::StyleParseErrorKind; #[derive(Clone, Debug)] pub enum AngleOrZ...
fn parse_scale_x<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { let sx = Number::parse(input)?; Ok(TransformFunction::ScaleX(sx)) } fn parse_scale_y<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { let sy = Number::parse(input)?; Ok(TransformFunction::ScaleY(sy)...
i>> { let sx = Number::parse(input)?; let sy = input .try_parse(|input| { input.expect_comma()?; Number::parse(input) }) .map_or(sx.clone(), |v| v); Ok(TransformFunction::Scale(sx, sy)) }
function_block-function_prefixed
[ { "content": "pub fn write_elements<W>(dest: &mut W, elements: &[Option<&str>], delimiter: char) -> std::fmt::Result\n\nwhere\n\n\tW: std::fmt::Write,\n\n{\n\n\telements\n\n\t\t.iter()\n\n\t\t.flatten()\n\n\t\t.enumerate()\n\n\t\t.map(|(index, e)| {\n\n\t\t\tif index > 0 {\n\n\t\t\t\tdest.write_char(delimiter)?...
Rust
src/output/images.rs
Christoph-D/gallery
8a36f4a3235b9ea6727f9b40ee0f40ffc9fa21e5
use super::Item; use super::{create_parent_directories, Config, RunMode}; use crate::error::PathErrorContext; use crate::model::{Image, ImageGroup, ThumbnailType}; use anyhow::{anyhow, Result}; use std::path::{Path, PathBuf}; use std::{fs, process}; pub(super) fn render_images( image_group: &ImageGroup, con...
use super::Item; use super::{create_parent_directories, Config, RunMode}; use crate::error::PathErrorContext; use crate::model::{Image, ImageGroup, ThumbnailType}; use anyhow::{anyhow, Result}; use std::path::{Path, PathBuf}; use std::{fs, process}; pub(super) fn render_images( image_group: &ImageGroup, con...
} impl ThumbnailFile { fn write_internal(&self, dimensions: &str, crop: &str) -> Result<()> { super::create_parent_directories(&self.output_path)?; let result = process::Command::new("convert") .arg(&self.input_path) .args(&[ "-resize", dimensions, "-gravity...
pe::Small => self.write_internal("400x", "400x267+0+0"), ThumbnailType::Large => self.write_internal("2000x", "2000x1335+0+0"), }, RunMode::DryRun => Ok(()), } }
function_block-function_prefixed
[ { "content": "/// Converts a single-element path into something suitable for a URL.\n\nfn to_web_path(path: &Path) -> Result<PathBuf> {\n\n if path.components().count() != 1 {\n\n return Err(path_error(\n\n \"Cannot convert multi-component paths into URLs\",\n\n &path,\n\n ...
Rust
src/chain/chain_visitor.rs
provotum/node-rs
17c7ff8b92ec90f35a3ba690a1f28c15f1dde13d
use ::chain::block::Block; use ::chain::transaction::{Transaction, TransactionType}; use crypto_rs::el_gamal::ciphertext::CipherText; use crypto_rs::el_gamal::additive::Operate; use crypto_rs::el_gamal::encryption::{PublicKey, encrypt}; use crypto_rs::arithmetic::mod_int::ModInt; use num::Zero; use std::collections::Ha...
use ::chain::block::Block; use ::chain::transaction::{Transaction, TransactionType}; use crypto_rs::el_gamal::ciphertext::CipherText; use crypto_rs::el_gamal::additive::Operate; use crypto_rs::el_gamal::encryption::{PublicKey, encrypt}; use crypto_rs::arithmetic::mod_int::ModInt; use num::Zero; use std::collections::Ha...
} impl ChainVisitor for HeaviestBlockVisitor { fn visit_block(&mut self, height: usize, block: &Block) { match self.heaviest_block { Some(ref block_hash) => { panic!("Cannot assign the heaviest block a second time. Previous heaviest block was {:?}", block_hash); ...
pub fn new() -> HeaviestBlockVisitor { HeaviestBlockVisitor { height: None, heaviest_block: None, } }
function_block-function_prefix_line
[ { "content": "/// A codec is able to encode as well decode a particular `Message`\n\n/// into a corresponding `String` representation.\n\npub trait Codec {\n\n /// Encode the given message into a string.\n\n fn encode(message: Message) -> String;\n\n /// Decode the given string into a message.\n\n f...
Rust
src/map/mod.rs
IceSentry/bevy_df
81e5b6dee4c228ab55fb127445d856122afd09fe
use anyhow::{bail, Result}; use bevy::prelude::*; use bevy_ecs_tilemap::prelude::*; use bevy_inspector_egui::InspectorPlugin; use noise::{Seedable, SuperSimplex}; use self::{ generator::{generate_map, NoiseSettings}, renderer::{set_map_textures, update_layer_visibility, update_tiles}, }; pub mod ge...
use anyhow::{bail, Result}; use bevy::prelude::*; use bevy_ecs_tilemap::prelude::*; use bevy_inspector_egui::InspectorPlugin; use noise::{Seedable, SuperSimplex}; use self::{ generator::{generate_map, NoiseSettings}, renderer::{set_map_textures, update_layer_visibility, update_tiles}, }; pub mod ge...
} } pub struct MapData { pub layers: Vec<Layer>, } pub struct VisibleLayers(Vec<bool>); impl VisibleLayers { pub fn new(z_levels: usize) -> Self { Self(vec![true; z_levels]) } } impl MapData { pub fn new(width: usize, height: usize, z_levels: usize) -> Self { S...
if let Some(elem) = self.data.get_mut(y * WIDTH + x) { *elem = new_tile; Ok(()) } else { bail!("tile out of bounds") }
if_condition
[ { "content": "/// Transforms a point in world coordinates to an isometric projection\n\n/// WARN only works with a single layer, doesn't take into accound any z-levels\n\npub fn world_to_iso(pos: Vec2, tile_width: f32, tile_height: f32) -> Vec2 {\n\n let x = (pos.x / tile_width) + (-pos.y / tile_height);\n\n...
Rust
src/exec/debug.rs
ricardo-massaro/bleepscript
acf9d772e8e0ce5469a69897c397d227d673682b
use std::fmt; use super::*; trait DebugIndent { fn fmt_indent(&self, f : &mut fmt::Formatter, indent : usize) -> Result<(), fmt::Error>; } impl DebugIndent for FuncDef { fn fmt_indent(&self, f : &mut fmt::Formatter, indent : usize) -> Result<(), fmt::Error> { try!(write!(f, "function ("))...
use std::fmt; use super::*; trait DebugIndent { fn fmt_indent(&self, f : &mut fmt::Formatter, indent : usize) -> Result<(), fmt::Error>; } impl DebugIndent for FuncDef { fn fmt_indent(&self, f : &mut fmt::Formatter, indent : usize) -> Result<(), fmt::Error> { try!(write!(f, "function ("))...
} impl DebugIndent for MapLiteral { fn fmt_indent(&self, f : &mut fmt::Formatter, indent : usize) -> Result<(), fmt::Error> { try!(writeln!(f, "{{")); for &(ref k, ref v) in &self.entries { try!(write!(f, "{1:0$}", indent + 2, "")); try!(write!(f, "\"{}\" : ", k)); ...
fn fmt_indent(&self, f : &mut fmt::Formatter, indent : usize) -> Result<(), fmt::Error> { try!(writeln!(f, "[")); for i in &self.vec { try!(write!(f, "{1:0$}", indent + 2, "")); try!(i.fmt_indent(f, indent + 2)); try!(writeln!(f, ",")); } try!(w...
function_block-full_function
[ { "content": "fn un_arithmetic(args : &[Value], op : fn(f64)->f64, name : &str) -> Result<f64,RunError> {\n\n let arg = try!(get_arg(args, 0));\n\n match *arg {\n\n Value::Number(x) => Ok(op(x)),\n\n _ => Err(RunError::new_native_str(&format!(\"invalid argument for '{}'\", name)))\n\n }\n...
Rust
src/elf/defs.rs
prettykernel/elfcat
ebbf9465ba19730a7753c0296e0ad9b264cc5cc8
#![allow(dead_code)] pub const ELF_EI_MAG0: u8 = 0; pub const ELF_EI_MAG1: u8 = 1; pub const ELF_EI_MAG2: u8 = 2; pub const ELF_EI_MAG3: u8 = 3; pub const ELF_EI_CLASS: u8 = 4; pub const ELF_EI_DATA: u8 = 5; pub const ELF_EI_VERSION: u8 = 6; pub const ELF_EI_OSABI: u8 = 7; pub const ELF_EI_ABIVERSION: u8 = 8; pub cons...
#![allow(dead_code)] pub const ELF_EI_MAG0: u8 = 0; pub const ELF_EI_MAG1: u8 = 1; pub const ELF_EI_MAG2: u8 = 2; pub const ELF_EI_MAG3: u8 = 3; pub const ELF_EI_CLASS: u8 = 4; pub const ELF_EI_DATA: u8 = 5; pub const ELF_EI_VERSION: u8 = 6; pub const ELF_EI_OSABI: u8 = 7; pub const ELF_EI_ABIVERSION: u8 = 8; pub cons...
pub fn ptype_to_string(ptype: u32) -> String { match ptype { PT_NULL => String::from("NULL"), PT_LOAD => String::from("LOAD"), PT_DYNAMIC => String::from("DYNAMIC"), PT_INTERP => String::from("INTERP"), PT_NOTE => String::from("NOTE"), PT_SHLIB => String::from("SHLI...
pub fn machine_to_string(e_machine: u16) -> String { match e_machine { 0 => String::from("None"), 1 => String::from("AT&T WE 32100"), 2 => String::from("SPARC"), 3 => String::from("x86"), 4 => String::from("Motorolla 68000"), 5 => String::from("Motorolla 88000"), ...
function_block-full_function
[ { "content": "pub fn human_format_bytes(bytes: u64) -> String {\n\n let base: u64 = 1024;\n\n\n\n if bytes < base {\n\n return format!(\"{} B\", bytes);\n\n }\n\n\n\n let prefixes = [\"K\", \"M\", \"G\", \"T\", \"P\", \"E\"];\n\n let exponent = (bytes as f64).log(base as f64) as u32;\n\n\n...
Rust
algo/dijkstra/src/lib.rs
ia7ck/rust-competitive-programming
b60dc67706797611e680510aa6492f6397a2e104
use std::cmp::Reverse; use std::collections::BinaryHeap; use std::fmt::Debug; use std::ops::Add; pub trait Edge<T> { fn from(&self) -> usize; fn to(&self) -> usize; fn dist(&self, d: T) -> T; } #[derive(Copy, Clone)] pub struct ConstEdge<T> { from: usi...
use std::cmp::Reverse; use std::collections::BinaryHeap; use std::fmt::Debug; use std::ops::Add; pub trait Edge<T> { fn from(&self) -> usize; fn to(&self) -> usize; fn dist(&self, d: T) -> T; } #[derive(Copy, Clone)] pub struct ConstEdge<T> { from: usi...
const INF: u64 = std::u64::MAX; fn floyd_warshall(n: usize, edges: &Vec<(usize, usize, u64)>) -> Vec<u64> { let mut d = vec![vec![INF; n]; n]; for i in 0..n { d[i][i] = 0; } for &(a, b, c) in edges { d[a][b] = d[a][b].min(c); } for k in ...
fn generate(n: usize, m: usize) -> Vec<(usize, usize, u64)> { let nodes = Uniform::from(0..n); let costs = Uniform::from(0..=1_000_000_000); let mut rng = thread_rng(); (0..m) .map(|_| { let a = nodes.sample(&mut rng); let b = nodes.sample(&mut...
function_block-full_function
[ { "content": "pub trait Modulo: Copy + Clone + Debug {\n\n const P: i64;\n\n}\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct ModInt<M>(i64, PhantomData<M>);\n\n\n\nimpl<M: Modulo> ModInt<M> {\n\n /// 整数を `0 <= x < p` に正規化してインスタンスを作ります。\n\n pub fn new(x: i64) -> Self {\n\n if 0 <= x && x < M:...
Rust
src/lib.rs
durch/google-bigtable-postgres-extension
540ddbde544c3b0bf89809e21b1aeb6f85955afb
extern crate libc; extern crate rpgffi as pg; extern crate bigtable as bt; extern crate serde_json; extern crate protobuf; extern crate goauth; extern crate rustc_serialize; use rustc_serialize::base64::{STANDARD, ToBase64, FromBase64}; use goauth::auth::Token; use goauth::credentials::Credentials; use std::io::prelud...
extern crate libc; extern crate rpgffi as pg; extern crate bigtable as bt; extern crate serde_json; extern crate protobuf; extern crate goauth; extern crate rustc_serialize; use rustc_serialize::base64::{STANDARD, ToBase64, FromBase64}; use goauth::auth::Token; use goauth::credentials::Credentials; use std::io::prelud...
alifier, q_l); let rows = str_from_ptr(c_rows, r_l); let token = token_from_credential_ptr(credentials, c_l); let credentials = credentials_from_db(credentials, c_l); let instance_name = str_from_ptr(instance_ptr, i_l); let table_name = str_from_ptr(table_ptr, t_l); let table = bt_table(crede...
e); match read_rows(table, token, Some(lim)) { Ok(x) => pg_return(x), Err(e) => pg_return(e.into()) } } #[no_mangle] pub extern "C" fn bt_rust_write_rows(c_family: *const c_char, f_l: usize, c_qualifier: *const c_char, q_l: usize, ...
random
[ { "content": "CREATE FUNCTION _bt_read_rows(lim INT, credentials TEXT, instance TEXT, tb TEXT)\n\n RETURNS JSON\n\nAS '$libdir/bigtable'\n\nLANGUAGE C;\n\n\n", "file_path": "sql/bigtable.sql", "rank": 11, "score": 93035.29666569042 }, { "content": "CREATE FUNCTION _bt_write(family TEXT...
Rust
src/crawler.rs
eigenein/blitz-dashboard
7fbfe1e014448e549dcf82f3bf9d9a5bc1fb7a7a
use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration as StdDuration, Instant}; use anyhow::Context; use chrono::{Duration, Utc}; use futures::{stream, Stream, StreamExt, TryStreamExt}; use humantime::format_duration; use itertools::Itertools; use redis::aio::MultiplexedConnection; use sqlx::PgPo...
use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration as StdDuration, Instant}; use anyhow::Context; use chrono::{Duration, Utc}; use futures::{stream, Stream, StreamExt, TryStreamExt}; use humantime::format_duration; use itertools::Itertools; use redis::aio::MultiplexedConnection; use sqlx::PgPo...
.await?; } } let mut transaction = self.database.begin().await?; insert_tank_snapshots(&mut transaction, &tanks).await?; replace_account(&mut transaction, &new_info.base).await?; transaction .commit() .await .with_...
push_incremental_updates( &self.database, &mut self.redis, stream_duration, &self.metrics, account.id, &tanks, )
call_expression
[ { "content": "pub fn subtract_tanks(left: Vec<Tank>, mut right: HashMap<TankId, Tank>) -> Vec<Tank> {\n\n left.into_iter()\n\n .filter_map(\n\n |left_tank| match right.remove(&left_tank.statistics.base.tank_id) {\n\n Some(right_tank)\n\n if left_tank.statis...
Rust
src/bin/cargo-perf.rs
fujita/perf-tools
03b8164187ba0bfe89869afe38de7aafb2d19e3c
use cargo_metadata::Message; use clap::Parser; use inferno::collapse::Collapse; use std::io; use std::io::{BufReader, BufWriter}; use std::process::{Command, Stdio}; use perf_tools::pprof; #[derive(Parser)] #[clap(author, version, about, long_about = None)] struct Cli { #[clap(subcommand)] command: Commands...
use cargo_metadata::Message; use clap::Parser; use inferno::collapse::Collapse; use std::io; use std::io::{BufReader, BufWriter}; use std::process::{Command, Stdio}; use perf_tools::pprof; #[derive(Parser)] #[clap(author, version, about, long_about = None)] struct Cli { #[clap(subcommand)] command: Commands...
const PERF_DATA_FILE: &str = "perf.data"; const DEFAULT_PPROF_OUTPUT: &str = "cpu.pprof"; const DEFAULT_FLAMEGRAPH_OUTPUT: &str = "flamegraph.svg"; const DEFAULT_RECORD_FREQ: u32 = 99; fn main() { let Commands::Perf(args) = Cli::parse().command; let artifact = build_binary(&args).unwrap(); let binary_pa...
Err(io::Error::new( io::ErrorKind::Other, "can't find binary name to be specified", )) } else { if artifact.len() == 1 { return Ok(artifact[0].executable.as_ref().unwrap().to_string()); } Err(io::Error::new( io::ErrorKind::Other, ...
function_block-function_prefix_line
[ { "content": "fn main() -> Result<()> {\n\n prost_build::compile_protos(&[\"proto/profile.proto\"], &[\"proto/\"])?;\n\n Ok(())\n\n}\n", "file_path": "build.rs", "rank": 0, "score": 36452.65945294507 }, { "content": "struct PerfReader {\n\n sample: HashMap<Sample, u64>,\n\n captu...
Rust
src/contractors/strategies.rs
oracleofnj/einsum
b0d43e882f4e9ec1116517b92b0aaf73b07b385e
use crate::SizedContraction; use std::collections::{HashMap, HashSet}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Copy, Clone, Debug)] pub enum SingletonMethod { Identity, Permutation, Summation, Diagonalizat...
use crate::SizedContraction; use std::collections::{HashMap, HashSet}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Copy, Clone, Debug)] pub enum SingletonMethod { Identity, Permutation, Summation, Diagonalizat...
} #[allow(dead_code)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy, Clone)] pub enum PairMethod { HadamardProduct, HadamardProductGeneral, TensordotFixedPosition, TensordotGeneral, ScalarMatrixProduct, ScalarMatrixProductGeneral, MatrixScalarProduct, ...
0, _, _) => SingletonMethod::Diagonalization, (_, 0, _) => SingletonMethod::PermutationAndSummation, (_, _, _) => SingletonMethod::DiagonalizationAndSummation, } }
function_block-function_prefixed
[ { "content": "/// Returns a set of all the indices in the LHS or the RHS\n\nfn get_existing_indices(lhs_indices: &[char], rhs_indices: &[char]) -> HashSet<char> {\n\n let mut result: HashSet<char> = lhs_indices.iter().cloned().collect();\n\n for &c in rhs_indices.iter() {\n\n result.insert(c);\n\n ...
Rust
src/menu.rs
mockersf/corylus
6ffc7cf34fd55e8fe37c2595388407bf2dc778c2
use amethyst::{ ecs::prelude::Entity, input::{is_close_requested, is_key_down}, prelude::*, ui::{Anchor, UiEvent, UiEventType, UiFinder}, winit::VirtualKeyCode, }; use tracing::{event, instrument, Level}; use crate::{about::AboutScreen, game::Game}; const BUTTON_START: &str = "start"; const BUTTO...
use amethyst::{ ecs::prelude::Entity, input::{is_close_requested, is_key_down}, prelude::*, ui::{Anchor, UiEvent, UiEventType, UiFinder}, winit::VirtualKeyCode, }; use tracing::{event, instrument, Level}; use crate::{about::AboutScreen, game::Game}; const BUTTON_START: &str = "start"; const BUTTO...
Trans::None } #[instrument(skip(_data), level = "info")] fn handle_event( &mut self, _data: StateData<'_, GameData<'_, '_>>, event: StateEvent, ) -> SimpleTrans { match event { StateEvent::Window(event) => { if is_close_requested(&ev...
if self.button_start.is_none() || self.button_about.is_none() { world.exec(|ui_finder: UiFinder<'_>| { self.button_start = ui_finder.find(&format!("{}", BUTTON_START)); self.button_about = ui_finder.find(&format!("{}", BUTTON_ABOUT)); }); }
if_condition
[ { "content": "pub fn load_image(world: &World, name: &str) -> Handle<amethyst::renderer::Texture> {\n\n load(world, name, amethyst::renderer::ImageFormat::default())\n\n}\n\n\n", "file_path": "src/ui_scheme.rs", "rank": 0, "score": 120114.90046673823 }, { "content": "pub fn load_font(worl...
Rust
src/package.rs
sagebind/respk
05ccc2b748801612c14e2b8b13022951123cf139
use crate::compression; use crate::Error; use crate::resource::*; use rusqlite::{Connection, DatabaseName}; use rusqlite::blob::Blob; use rusqlite::types::ToSql; use std::io::{self, Read}; use std::path::Path; const SCHEMA: &'static str = " CREATE TABLE resources ( path TEXT NOT NULL, si...
use crate::compression; use crate::Error; use crate::resource::*; use rusqlite::{Connection, DatabaseName}; use rusqlite::blob::Blob; use rusqlite::types::ToSql; use std::io::{self, Read}; use std::path::Path; const SCHEMA: &'static str = " CREATE TABLE resources ( path TEXT NOT NULL, si...
pub fn len(&self) -> u64 { self.db.query_row(" SELECT COUNT(*) FROM resources ", &[] as &[&str], |row| row.get::<_, i64>(0) as u64).unwrap_or(0) } pub fn resources(&self) -> Result<Vec<ResourceInfo>, Error> { let mut stmt = self.db.prepare(" SELEC...
pub fn temporary() -> Result<Package, Error> { let connection = Connection::open_in_memory()?; connection.execute(SCHEMA, &[] as &[&str])?; Ok(Package { db: connection, }) }
function_block-full_function
[ { "content": "/// Decompress an input stream and return the results.\n\npub fn decompress<R: Read>(input: R) -> Result<Vec<u8>, Error> {\n\n let mut buf = Vec::new();\n\n\n\n let mut decoder = lz4::Decoder::new(input)\n\n .map_err(|_| Error::DecompressionError)?;\n\n\n\n io::copy(&mut decoder, &...
Rust
compiler/crates/graphql-transforms/src/util.rs
visshaljagtap/relay
efdbcd100528e368541291d680db235f0f22605e
/* * Copyright (c) Facebook, 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 graphql_ir::{Condition, Selection}; use graphql_text_printer::write_arguments; use graphql_text_printer::write_directives; use ...
/* * Copyright (c) Facebook, 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 graphql_ir::{Condition, Selection}; use graphql_text_printer::write_arguments; use graphql_text_printer::write_directives; use ...
rite_directives(schema, &node.directives, &mut directives).unwrap(); } NodeIdentifier::InlineFragment { type_condition: node.type_condition, directives, } } Selection::LinkedField(node) => { let mut arguments_and_directives ...
function_block-function_prefixed
[ { "content": "/// If the type has an `id` field and the type implments interfaces\n\n/// other than `Node`, then the change isn't safe:\n\n/// If the object type implements an `Actor` interfaces (for example).\n\n/// We may need to add an inline spread with\n\n/// ... on ThisNewType {\n\n/// id\n\n/// }...
Rust
src/grapheme_iterator.rs
mmaietta/spellchecker-wasm
c4fb118e86128210eac86062d6d45cd756f6f456
use std::str; use std::ops::{Range, Index}; use std::cell::RefCell; pub struct GraphemeClusters<'a> { bytes: &'a [u8], cursor: usize, byte_indices: RefCell<Vec<usize>>, } impl GraphemeClusters<'_> { pub fn new(s: &str) -> GraphemeClusters { GraphemeClusters { bytes: s.as_...
use std::str; use std::ops::{Range, Index}; use std::cell::RefCell; pub struct GraphemeClusters<'a> { bytes: &'a [u8], cursor: usize, byte_indices: RefCell<Vec<usize>>, } impl GraphemeClusters<'_> { pub fn new(s: &str) -> GraphemeClusters { GraphemeClusters { bytes: s.as_...
} impl<'a> Index<usize> for GraphemeClusters<'a> { type Output = str; fn index(&self, index: usize) -> &Self::Output { let range = self.get_slice_range(index..index + 1); unsafe { str::from_utf8_unchecked(&self.bytes[range]) } } } #[cfg(test)] mod grapheme_iterator_tests { use crate:...
m> { if self.bytes.len() <= self.cursor { self.cursor = 0; return None; } let next_byte = &self.bytes[self.cursor]; let len = GraphemeClusters::grapheme_len(next_byte); let end = self.cursor + len; let s = unsafe { str::from_utf8_unchecked(&self.by...
function_block-function_prefixed
[ { "content": "/// <summary>Calculates starting position and lengths of two strings such that common\n\n/// prefix and suffix substrings are excluded.</summary>\n\n/// <remarks>Expects string1.Length to be less than or equal to string2.Length</remarks>\n\npub fn prefix_suffix_prep(string1: &str, string2: &str) -...
Rust
protocols/kad/src/cli.rs
HiZhongxh/libp2p-rs
d31b74065afd7899d77f34ba1acfa2aa1fbb75b8
use async_std::task; use std::str::FromStr; use crate::Control; use libp2prs_core::{Multiaddr, PeerId}; use xcli::*; const DHT: &str = "dht"; pub fn dht_cli_commands<'a>() -> Command<'a> { let bootstrap_cmd = Command::new("bootstrap") .about("Show or edit the list of bootstrap peers") .usage("boo...
use async_std::task; use std::str::FromStr; use crate::Control; use libp2prs_core::{Multiaddr, PeerId}; use xcli::*; const DHT: &str = "dht"; pub fn dht_cli_commands<'a>() -> Command<'a> { let bootstrap_cmd = Command::new("bootstrap") .about("Show or edit the list of bootstrap peers") .usage("boo...
eerId::from_str(pid).map_err(|e| XcliError::BadArgument(e.to_string()))?; task::block_on(async { kad.remove_node(peer).await; println!("remove node completed"); }); Ok(CmdExeCode::Ok) } fn cli_dump_kbuckets(app: &App, args: &[&str]) -> XcliResult { let mut kad = handler(app); let...
lt { let mut kad = handler(app); if args.len() != 1 { return Err(XcliError::MismatchArgument(1, args.len())); } let pid = args.get(0).unwrap(); let peer = P
function_block-random_span
[ { "content": "fn cli_show_peers(app: &App, args: &[&str]) -> XcliResult {\n\n let swarm = handler(app);\n\n\n\n let pid = match args.len() {\n\n 0 => None,\n\n 1 => Some(PeerId::try_from(args[0]).map_err(|e| XcliError::BadArgument(e.to_string()))?),\n\n _ => return Err(XcliError::Mism...
Rust
src/can.rs
Tmplt/daredevil-small
d9adb96ead5bea114369931986792a5e0797dd8c
use s32k144; const MSG_BUF_SIZE: usize = 18; const MAX_MSG_LENGTH: usize = 64; pub struct CAN { can: s32k144::CAN0, } impl CAN { pub fn init( pcc: &s32k144::PCC, can: s32k144::CAN0, porte: &s32k144::PORTE, portd: &s32k144::PORTD, ptd: &s32k144::PTD, ) -> Self { ...
use s32k144; const MSG_BUF_SIZE: usize = 18; const MAX_MSG_LENGTH: usize = 64; pub struct CAN { can: s32k144::CAN0, } impl CAN { pub fn init( pcc: &s32k144::PCC, can: s32k144::CAN0, porte: &s32k144::PORTE, portd: &s32k144::PORTD, ptd: &s32k144::PTD, ) -> Self { ...
2 => w.data_byte_2().bits(payload[i]), 3 => w.data_byte_3().bits(payload[i]), _ => unreachable!(), }); } self.can.embedded_ram[(0 * MSG_BUF_SIZE) + 0].write(|w| w.bits(0xcc4f0000 | (8 << 16))); } ...
n transmit(&self, payload: &[u8]) { unsafe { self.can.iflag1.write(|w| w.bits(0x1)); self.can.embedded_ram[(0 * MSG_BUF_SIZE) + 1].write(|w| w.bits(0x15540000)); for i in 0..core::cmp::min(MAX_MSG_LENGTH, payload.len()) { ...
random
[ { "content": "fn adc_init(pcc: &s32k144::PCC, adc: &s32k144::ADC0) {\n\n unsafe {\n\n pcc.pcc_adc0.modify(|_, w| w.cgc()._0()); //Disable clock\n\n pcc.pcc_adc0.modify(|_, w| w.pcs()._001()); // PCS=1\n\n pcc.pcc_adc0.modify(|_, w| w.cgc()._1()); // Enable Clock\n\n adc.sc1a.write...
Rust
contracts/nebula-incentives-custody/src/testing/tests.rs
nebula-protocol/nebula-contracts
c24615f7921bb7c92c5bcffcc6d8669dcd803588
use crate::contract::{execute, instantiate, migrate, query}; use crate::error::ContractError; use crate::state::{read_neb, read_owner}; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{attr, from_binary, to_binary, CosmosMsg, S...
use crate::contract::{execute, instantiate, migrate, query}; use crate::error::ContractError; use crate::state::{read_neb, read_owner}; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, mock_info, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{attr, from_binary, to_binary, CosmosMsg, S...
#[test] fn test_query_balance() { let msg = InstantiateMsg { owner: h(OWNER), nebula_token: h(NEB_TOKEN), }; let info = mock_info(OWNER, &[]); let mut deps = mock_dependencies(&[]); let _res = instantiate(deps.as_mut(), mock_env(), info, msg) .expect("contract successfully...
ract successfully executes InstantiateMsg"); let neb_amount = Uint128::new(1000u128); deps.querier.with_token_balances(&[( &h(NEB_TOKEN), &[(&MOCK_CONTRACT_ADDR.to_string(), &neb_amount)], )]); let info = mock_info("random", &[]); let msg = ExecuteMsg::RequestNeb { amount: neb_amoun...
function_block-function_prefixed
[ { "content": "/// Convenience function for creating inline String\n\npub fn h(s: &str) -> String {\n\n s.to_string()\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! q {\n\n ($deps:expr, $val_type:ty, $env:expr, $msg: expr) => {{\n\n let res = query($deps, $env, $msg).unwrap();\n\n let val: $val_...
Rust
src/gpioint/clr2.rs
pie-flavor/lpc176x-5x
73db36798b51bcb3ae27595d527f2890e392e7f4
#[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CLR2 { #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w....
#[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CLR2 { #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w....
; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _P2_8CIW<'a> { w: &'a mut W, } impl<'a> _P2_8CIW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true...
(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _P2_1CIW<'a> { w: &'a mut W, } impl<'a> _P2_1CIW<'a> { ...
random
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
src/rtccntl/int_ena_w1ts.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
#[doc = "Writer for register INT_ENA_W1TS"] pub type W = crate::W<u32, super::INT_ENA_W1TS>; #[doc = "Register INT_ENA_W1TS `reset()`'s with value 0"] impl crate::ResetValue for super::INT_ENA_W1TS { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy f...
#[doc = "Writer for register INT_ENA_W1TS"] pub type W = crate::W<u32, super::INT_ENA_W1TS>; #[doc = "Register INT_ENA_W1TS `reset()`'s with value 0"] impl crate::ResetValue for super::INT_ENA_W1TS { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy f...
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `SLP_WAKEUP_INT_ENA_W1TS`"] pub struct SLP_WAKEUP_INT_ENA_W1TS_W<'a> { w: &'a mut W, } impl<'a> SLP_WAKEUP_INT_ENA_W1TS_W<'a> { #[doc = r"Sets the field bit"] #[inline(alw...
#[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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Write proxy for field `WDT_INT_ENA_W1TS`"] pub struct WDT_INT_ENA_W1TS_W<'a> { w: &'...
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/manager.rs
alex-dow/psistats-rs
7e5c235fb83c6265abe0c1cfe5c134d253f94894
use crate::reporters::Report; use crate::reporters::ReporterCb; use crate::reporters::get_reporter; use crate::publishers::{get_publisher, get_commander, Publisher, Commander}; use std::thread; use crossbeam_channel::{Receiver, Sender}; use std::thread::JoinHandle; use std::collections::HashMap; use std::time::Duratio...
use crate::reporters::Report; use crate::reporters::ReporterCb; use crate::reporters::get_reporter; use crate::publishers::{get_publisher, get_commander, Publisher, Commander}; use std::thread; use crossbeam_channel::{Receiver, Sender}; use std::thread::JoinHandle; use std::collections::HashMap; use std::time::Duratio...
pub fn start_reporters(conf: Value, reports_sender: Sender<Report>, commands_receiver: Receiver<String>) -> JoinHandle<()> { return thread::spawn(move || { let c = conf.as_table().unwrap(); let settings = c["settings"].as_table().unwrap(); let workers = settings["workers"].as_integer()....
e { match get_publisher(publisher_id.clone()) { Some(publisher) => { info!("Enabled publisher: {}", publisher_id); publishers.push(publisher); } None => () } ...
function_block-function_prefixed
[ { "content": "pub fn publish(_conf: &Map<String, Value>, report: &Report) {\n\n info!(\"{}\", report);\n\n}\n", "file_path": "src/publishers/log.rs", "rank": 2, "score": 81016.31312569528 }, { "content": "pub fn publish(conf: &Map<String, Value>, report: &Report) {\n\n let mut mqtt = C...
Rust
src/manual/linked_list.rs
saligrama/concache
0a23bfc41f5d8c4614038a473e502ec8d7fe938e
use std::ptr; use std::sync::atomic::{AtomicPtr, Ordering}; const OSC: Ordering = Ordering::SeqCst; #[derive(Debug)] pub(super) struct Node<K, V> { key: Option<K>, pub val: AtomicPtr<V>, next: AtomicPtr<Node<K, V>>, } impl<K, V> Node<K, V> { fn empty() -> Self { Node { key: None, ...
use std::ptr; use std::sync::atomic::{AtomicPtr, Ordering}; const OSC: Ordering = Ordering::SeqCst; #[derive(Debug)] pub(super) struct Node<K, V> { key: Option<K>, pub val: AtomicPtr<V>, next: AtomicPtr<Node<K, V>>, } impl<K, V> Node<K, V> { fn empty() -> Self { Node { key: None, ...
}
fn more_linked_list_tests() { let mut remove_nodes = Vec::new(); let new_linked_list = LinkedList::default(); println!( "Insert: {:?}", new_linked_list.insert(5, 3, &mut remove_nodes) ); println!( "Insert: {:?}", new_linked_list.in...
function_block-full_function
[ { "content": "struct Node<K, V> {\n\n kv: (K, Atomic<V>),\n\n active: AtomicBool,\n\n next: Atomic<Node<K, V>>,\n\n prev: Atomic<Node<K, V>>,\n\n}\n\n\n\nimpl<K, V> Node<K, V> {\n\n fn new(k: K, v: V) -> Self {\n\n Node {\n\n kv: (k, Atomic::new(v)),\n\n active: Atomi...
Rust
discord_game_sdk/src/error.rs
AlexApps99/discord_game_sdk
0ab2f707fefbea2905b27768e7ff6e3c3629003c
use crate::sys; use std::fmt; pub type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Error { ServiceUnavailable, InvalidVersion, LockFailed, Internal, InvalidPayload, InvalidCommand, InvalidPe...
use crate::sys; use std::fmt; pub type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Error { ServiceUnavailable, InvalidVersion, LockFailed, Internal, InvalidPayload, InvalidCommand, InvalidPe...
} impl std::error::Error for Error {}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Error::*; let message = match self { ServiceUnavailable => "service unavailable", InvalidVersion => "invalid version", LockFailed => "lock failed", Internal => "internal error", In...
function_block-full_function
[ { "content": "/// Trait providing callbacks for the SDK.\n\n///\n\n/// All methods have a default empty implementation.\n\npub trait EventHandler: Sized {\n\n /// Fired when an User Achievement is updated\n\n ///\n\n /// > [Method in official docs](https://discordapp.com/developers/docs/game-sdk/achiev...
Rust
controller/src/dataflow/topology.rs
stephanie-wang/ds2
68d0a41e139b9e9618adeb39c01d3152b3e25077
extern crate petgraph; use std::collections::{HashMap,HashSet}; use self::petgraph::graph::{Graph,NodeIndex}; use dataflow::{Epoch,Rates,ChannelId,OperatorId,OperatorInstances}; #[derive(Debug)] pub struct Operator { pub id: OperatorId, pub name: String, pub instances: OperatorInstances, ...
extern crate petgraph; use std::collections::{HashMap,HashSet}; use self::petgraph::graph::{Graph,NodeIndex}; use dataflow::{Epoch,Rates,ChannelId,OperatorId,OperatorInstances}; #[derive(Debug)] pub struct Operator { pub id: OperatorId, pub name: String, pub instances: OperatorInstances, ...
pub fn add_unique_edge(&mut self, source_node: NodeIndex, target_node: NodeIndex) { let _ = self.logical_graph.update_edge(source_node,target_node,Flow{}); } pub(super) fn get_node_idx(&self, op_id: &OperatorId) -> NodeIndex { ...
pub fn add_unique_node(&mut self, id: &str, name: &str, instances: u32) -> NodeIndex { let d = &mut self.dictionary; let lg = &mut self.logical_graph; let idx = d.entry(id.to_string()) .or_insert_with(|| { let op1 = Oper...
function_block-full_function
[ { "content": "/// Converts a dataflow configuration `conf` to a vector of pairs `(OperatorId,OperatorInstances)`\n\npub fn as_vec(conf: &String) -> Vec<(OperatorId,OperatorInstances)>\n\n{\n\n let v = conf.split(\",\").collect::<Vec<&str>>();\n\n assert_eq!(v.len() % 2,0);\n\n let mut c = Vec::new();\n...
Rust
web_glitz_macros/src/vertex.rs
RSSchermer/web_glitz.rs
a2e26ef0156705f0b5ac7707c4fc24a4a994d84b
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Attribute, Data, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type}; use crate::util::ErrorLog; pub fn expand_derive_vertex(input: &DeriveInput) -> Result<TokenStream, String> { if let Data...
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Attribute, Data, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type}; use crate::util::ErrorLog; pub fn expand_derive_vertex(input: &DeriveInput) -> Result<TokenStream, String> { if let Data...
enum VertexField { Attribute(AttributeField), Excluded, } impl VertexField { pub fn from_ast(ast: &Field, position: usize, log: &mut ErrorLog) -> Self { let vertex_attributes: Vec<&Attribute> = ast .attrs .iter() .filter(|a| a.path.is_ident("vertex_attribute"))...
let impl_block = quote! { #[automatically_derived] unsafe impl #impl_generics #mod_path::Vertex for #struct_name #ty_generics #where_clause { const INPUT_RATE: #mod_path::InputRate = #input_rate; const ATTRIBUTE_DESCRIPTORS: &'static [#mod_path::VertexAttributeD...
function_block-function_prefix_line
[ { "content": "pub fn expand_derive_resources(input: &DeriveInput) -> Result<TokenStream, String> {\n\n if let Data::Struct(ref data) = input.data {\n\n let struct_name = &input.ident;\n\n let mod_path = quote!(web_glitz::pipeline::resources);\n\n let mut log = ErrorLog::new();\n\n\n\n ...
Rust
src/main.rs
atonkyra/jaspy-nexus
847b6a5c3959b30dd73a7da966e7e92a73e11a77
#![feature(custom_attribute)] #![feature(plugin)] #![plugin(rocket_codegen)] #![allow(proc_macro_derive_resolution_fallback)] #[macro_use] extern crate serde_derive; #[macro_use] extern crate diesel; extern crate rocket; extern crate rocket_contrib; extern crate r2d2; extern crate r2d2_diesel; extern crate time; mod r...
#![feature(custom_attribute)] #![feature(plugin)] #![plugin(rocket_codegen)] #![allow(proc_macro_derive_resolution_fallback)] #[macro_use] extern crate serde_derive; #[macro_use] extern crate diesel; extern crate rocket; extern crate rocket_contrib; extern crate r2d2; extern crate r2d2_diesel; extern crate time; mod r...
g::Relaxed); imds_worker_thread.join().unwrap(); }
routes::metrics::metrics_fast, routes::metrics::metrics, ] ) .manage(db::connect()) .manage(imds.clone()) .manage(metric_miss_cache.clone()) .launch(); (*running).store(false, std::sync::atomic::Orderin
function_block-random_span
[ { "content": "#[put(\"/device\", data = \"<discovery_json>\")]\n\nfn discovery_device(discovery_json: rocket_contrib::Json<models::json::DiscoveredDevice>, connection: db::Connection, metric_miss_cache: State<Arc<Mutex<models::metrics::DeviceMetricRefreshCacheMiss>>>) {\n\n let discovered_device : &models::j...
Rust
crates/entity/src/primary/iter.rs
mickare/runwell
e2400e5b6a077ffa81ac939438e6d6d2c3ac704e
use crate::{Idx, RawIdx}; use core::{ iter::{DoubleEndedIterator, FusedIterator, Zip}, marker::PhantomData, }; #[derive(Debug)] pub struct Indices<'a, T> { start: u32, end: u32, key: PhantomData<fn() -> &'a T>, } impl<'a, T> Indices<'a, T> { ...
use crate::{Idx, RawIdx}; use core::{ iter::{DoubleEndedIterator, FusedIterator, Zip}, marker::PhantomData, }; #[derive(Debug)] pub struct Indices<'a, T> { start: u32, end: u32, key: PhantomData<fn() -> &'a T>, } impl<'a, T> Indices<'a, T> { ...
} impl<'a, T> Iterator for Indices<'a, T> { type Item = Idx<T>; fn size_hint(&self) -> (usize, Option<usize>) { let remaining = (self.end - self.start) as usize; (remaining, Some(remaining)) } fn next(&mut self) -> Option<Self::Item> { if self.start == self.end { ...
pub(super) fn new(min_idx: RawIdx, max_idx: RawIdx) -> Self { let start_index = min_idx.into_u32(); let end_index = max_idx.into_u32(); assert!(start_index <= end_index); Self { start: start_index, end: end_index, key: Default::default(), } ...
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct InitSegment {\n\n /// The length in bytes of the element segment.\n\n len: usize,\n\n /// The offset of the element segment within the table.\n\n offset: InitExpr,\n\n}\n\n\n\nimpl TableInit {\n\n /// Pushes bytes for initialization at the offset.\n\n p...
Rust
protocol-tokio/src/protocol/codec/handshake.rs
2nd-Layer/rust-cardano
f21424d6972a3f9021585feae0c1acf99767cebb
use std::{ collections::BTreeMap, fmt, io::{BufRead, Cursor, Write}, }; use cbor_event::{ self, de::{self, Deserializer}, se::{self, Serializer}, }; use super::{MessageCode, MessageType}; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] #[repr(C)] pub struct ProtocolMagic(u32); i...
use std::{ collections::BTreeMap, fmt, io::{BufRead, Cursor, Write}, }; use cbor_event::{ self, de::{self, Deserializer}, se::{self, Serializer}, }; use super::{MessageCode, MessageType}; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] #[repr(C)] pub struct ProtocolMagic(u32); i...
; } let tag = raw.tag()?; if tag != 24 { return Err(cbor_event::Error::CustomError(format!( "Invalid tag, expected 24, received {}", tag ))); } let mut inner = Deserializer::from(Cursor::new(raw.bytes()?)); let v = i...
Err(cbor_event::Error::CustomError(format!( "Invalid value, expected 0, received {}", t )))
call_expression
[ { "content": "pub fn txaux_serialize<'se, W>(\n\n tx: &Tx,\n\n in_witnesses: &Vec<TxInWitness>,\n\n serializer: &'se mut Serializer<W>,\n\n) -> cbor_event::Result<&'se mut Serializer<W>>\n\nwhere\n\n W: Write,\n\n{\n\n serializer\n\n .write_array(cbor_event::Len::Len(2))?\n\n .seria...
Rust
src/rust/pipeline-ingress/src/main.rs
inickles/grapl
f906aba74b2249c9c7d7b1afe6fc540551cdee8b
use std::{ env::VarError, num::ParseIntError, time::{ Duration, SystemTime, }, }; use kafka::{ ConfigurationError as KafkaConfigurationError, Producer, ProducerError, }; use opentelemetry::{ global, sdk::propagation::TraceContextPropagator, trace::TraceError, }; ...
use std::{ env::VarError, num::ParseIntError, time::{ Duration, SystemTime, }, }; use kafka::{ ConfigurationError as KafkaConfigurationError, Producer, ProducerError, }; use opentelemetry::{ global, sdk::propagation::TraceContextPropagator, trace::TraceError, }; ...
}
match handler().await { Ok(res) => { tracing::info!("shutting down"); Ok(res) } Err(err) => { tracing::error!( message = "configuration error", error = ?err, ); Err(err) } }
if_condition
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut config = tonic_build::configure();\n\n println!(\"cargo:rerun-if-changed=Cargo.toml\");\n\n println!(\"cargo:rerun-if-changed=../Cargo.lock\");\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n\n\n change_on_dir(...
Rust
src/interpreter/mod.rs
CyberGsus/Voila
9040d682de7cd8a6b4f38e8fa3dfa67256be9db9
use super::ast::Lookup; use super::ast::Script; use rayon::ThreadPoolBuilder; use std::error::Error; use std::sync::mpsc; use walkdir::WalkDir; mod partial_reader; pub use partial_reader::PartialReader; mod error; pub use error::*; mod cache; pub use cache::*; mod hash; pub use hash::*; pub fn run( script: Script<...
use super::ast::Lookup; use super::ast::Script; use rayon::ThreadPoolBuilder; use std::error::Error; use std::sync::mpsc; use walkdir::WalkDir; mod partial_reader; pub use partial_reader::PartialReader; mod error; pub use error::*; mod cache; pub use cache::*; mod hash; pub use hash::*; pub fn run( script: Script<...
pub fn cast_to_bool(self) -> Result<bool, CastError> { Ok(match self { Self::Regex(_) => { return Err(CastError::IncompatibleCast { from: "regex", to: "boolean", }) }, Self::Boolean(b) => b, ...
pub fn cast_to_string(self) -> Result<String, CastError> { Ok(match self { Self::Boolean(b) => b.to_string(), Self::Numeric(n) => n.to_string(), Self::String(str) => str, Self::Regex(_) => { return Err(CastError::IncompatibleCast { ...
function_block-full_function
[]
Rust
src/main.rs
asukiaaa/rust_relm_and_camera_practice
8253de02bb4ec6ce3cc82c63b66a9f496177974f
extern crate futures_glib; extern crate gtk; extern crate gdk_pixbuf; #[macro_use] extern crate relm; #[macro_use] extern crate relm_derive; extern crate rscam; use futures_glib::Timeout; use gdk_pixbuf::{Pixbuf, PixbufLoader}; use gtk::{ Button, ButtonExt, ContainerExt, Image, ImageExt, Inhibi...
extern crate futures_glib; extern crate gtk; extern crate gdk_pixbuf; #[macro_use] extern crate relm; #[macro_use] extern crate relm_derive; extern crate rscam; use futures_glib::Timeout; use gdk_pixbuf::{Pixbuf, PixbufLoader}; use gtk::{ Button, ButtonExt, ContainerExt, Image, ImageExt, Inhibi...
type Msg = Msg; fn model(relm: &Relm<Self>, _: ()) -> Model { Model { relm: relm.clone(), started_camera: None, } } fn update(&mut self, event: Msg) { match event { Msg::ToggleCamera => { if self.model.started_camera.is_some() ...
Type, }; use gtk::Orientation::Vertical; use relm::{Relm, Update, Widget}; use rscam::{Camera, Config}; use std::time::Duration; struct Model { relm: Relm<Win>, started_camera: Option<Camera>, } #[derive(Msg)] enum Msg { ToggleCamera, Quit, UpdateCameraImage(()), } struct Win { state_label: L...
random
[ { "content": "# rust_relm_and_camera_practice\n\n\n\n# Requirement\n\n[Rust](https://www.rust-lang.org)\n\n\n\nTested in 1.22.1.\n\n\n\n# Setup\n\n```\n\nsudo apt install libv4l-dev\n\nsudo apt install libgtk-3-dev\n\n```\n\n\n\n# Run\n\n```\n\ncargo run\n\n```\n\n\n\n# License\n\nMIT\n\n\n\n# References\n\n- [...
Rust
llvm-rs/src/type_builder.rs
Angeart/sapphire-rust
ebb3e32f8f35ecf7279bac9f55ddc4d2a55e39e8
use super::*; #[macro_export] macro_rules! llvm_type { ($builder:expr, void) => { $crate::TypeBuilder::void_type(&$builder) }; ($builder:expr, i1) => { $crate::TypeBuilder::int_type(&$builder, 1) }; ($builder:expr, i8) => { $crate::TypeBuilder::int_type(&$builder, 8) }; ...
use super::*; #[macro_export] macro_rules! llvm_type { ($builder:expr, void) => { $crate::TypeBuilder::void_type(&$builder) }; ($builder:expr, i1) => { $crate::TypeBuilder::int_type(&$builder, 1) }; ($builder:expr, i8) => { $c
($builder:expr, (struct ... $tys:expr)) => { $crate::TypeBuilder::struct_type( &$builder, &$tys, ) }; ($builder:expr, (struct $( $element:tt )*)) => { $crate::TypeBuilder::struct_type( &$builder, &[$( llvm_type!($builder, $element).as_type...
rate::TypeBuilder::int_type(&$builder, 8) }; ($builder:expr, i16) => { $crate::TypeBuilder::int_type(&$builder, 16) }; ($builder:expr, i32) => { $crate::TypeBuilder::int_type(&$builder, 32) }; ($builder:expr, i64) => { $crate::TypeBuilder::int_type(&$builder, 64) }; ...
random
[ { "content": "use super::*;\n\nuse llvm_sys::target_machine::*;\n\nuse std::borrow::Cow;\n\nuse std::ffi::{CStr, CString};\n\nuse std::fmt;\n\n\n", "file_path": "llvm-rs/src/target.rs", "rank": 0, "score": 11.150214929597773 }, { "content": "use super::*;\n\nuse llvm_sys::analysis::*;\n\nuse...
Rust
src/graph.rs
msuesskraut/calc
a3d5e3983f139d238f7f443d67d4f0d7f53aa877
use crate::{ ast::{Function, Number}, calc::{calc_operand, Env, TopLevelEnv}, }; use num::iter::range_step_from; use thiserror::Error; use std::cmp::PartialEq; use std::fmt::Debug; #[derive(Error, Debug, PartialEq, Eq)] pub enum GraphError { #[error("Unknown function `{0}` to plot")] UnknownFunction...
use crate::{ ast::{Function, Number}, calc::{calc_operand, Env, TopLevelEnv}, }; use num::iter::range_step_from; use thiserror::Error; use std::cmp::PartialEq; use std::fmt::Debug; #[derive(Error, Debug, PartialEq, Eq)] pub enum GraphError { #[error("Unknown function `{0}` to plot")] UnknownFunction...
#[test] #[should_panic(expected = "min 4.0 must be smaller than max 3.0")] fn range_construct_failure() { let _ = Range::new(4., 3.); } #[test] fn range_distance_f64() { assert_eq!(4.0, Range::new(10.0, 14.0).get_distance()); } #[test] fn range_project_plot_to_scr...
body: Operand::Symbol("x".to_string()), }); let env = TopLevelEnv::default(); let graph = Graph { fun: fun, env }; assert_eq!(Some(1.0), graph.calc(1.0)); }
function_block-function_prefix_line
[ { "content": "pub fn calc_term(term: &Term, env: &dyn Env) -> Result<Number, CalcError> {\n\n use self::Operation::*;\n\n let lhs = calc_operand(&term.lhs, env)?;\n\n let rhs = calc_operand(&term.rhs, env)?;\n\n Ok(match term.op {\n\n Add => lhs + rhs,\n\n Sub => lhs - rhs,\n\n ...
Rust
libfoxlive/src/format/reader.rs
bkfox/foxlive
4e73ef9fd21014576d847305376fa36e002d314c
use std::ops::{Deref}; use std::ptr::null_mut; use std::time::Duration; use std::sync::*; use core::pin::Pin; use futures; use ringbuf::Producer; use crate::data::*; use super::ffi; use super::error::{Error,av_strerror}; use super::futures::*; use super::codec::CodecContext; use super::format::FormatContext; use s...
use std::ops::{Deref}; use std::ptr::null_mut; use std::time::Duration; use std::sync::*; use core::pin::Pin; use futures; use ringbuf::Producer; use crate::data::*; use super::ffi; use super::error::{Error,av_strerror}; use super::futures::*; use super::codec::CodecContext; use super::format::FormatContext; use s...
x = self.context.as_ref().unwrap(); let r = unsafe { ffi::av_read_frame(ctx.format.context, ctx.packet) }; if r >= 0 { let mut r = ctx.codec.send_packet(ctx.packet); if let Poll::Pending = r { r = self.receive_frame(); if let Poll::Ready(Ok(_)) = r...
ayout: Option<ChannelLayout>) -> Self { Self { context: None, cache: cache, buffer: VecBuffer::new(true, 1), rate: rate, layout: layout, stopped: false, } } pub fn open(&mut self, path: &str, stream_id: Option<Stre...
random
[ { "content": "/// Time to NSamples\n\npub fn ts_to_samples(duration: Duration, rate: SampleRate) -> NSamples {\n\n (duration.as_micros() as NSamples ) * (rate as NSamples) / 1000000\n\n}\n\n\n", "file_path": "libfoxlive/src/data/time.rs", "rank": 0, "score": 194766.56744461518 }, { "conte...
Rust
src/interface.rs
ShotaroTsuji/mdplayscript
43f8f14925efd169e7f5a02dc12d359d793b29c9
use std::collections::VecDeque; use pulldown_cmark::{Event, Tag}; use crate::parser::{FuseOnParagraphEnd, Speeches}; use crate::speech::{parse_speech, parse_body}; use crate::renderer::HtmlRenderer; #[derive(Debug)] enum Mode { Nop, PlayScript, Monologue, } impl Mode { fn is_off(&self) -> bool { ...
use std::collections::VecDeque; use pulldown_cmark::{Event, Tag}; use crate::parser::{FuseOnParagraphEnd, Speeches}; use crate::speech::{parse_speech, parse_body}; use crate::renderer::HtmlRenderer; #[derive(Debug)] enum Mode { Nop, PlayScript, Monologue, } impl Mode { fn is_off(&self) -> bool { ...
lf.mode = Mode::PlayScript; }, Some(Directive::PlayScriptOn) => { self.mode = Mode::PlayScript; }, Some(Directive::PlayScriptOff) => { self.mode = Mode::Nop; }, Some(Directive::Title) => { emit_title(...
Some(Directive::MonologueBegin) => { self.mode = Mode::Monologue; }, Some(Directive::MonologueEnd) => { se
random
[ { "content": "/// Split speech heading and body.\n\n///\n\n/// Speech format is `Character> speech`. This function splits at a first single right angle.\n\n/// If it has no right angle, or two or more right angles, it returns `None`.\n\npub fn split_speech_heading(s: &str) -> Option<(&str, &str)> {\n\n find_...
Rust
semilog/src/lib.rs
radicle-dev/semilattice
cf8bff31c37bfb3964b5b5ec90352de99cd4bc9a
#![no_std] #![forbid(unsafe_code)] #![cfg_attr(feature = "alloc", feature(slice_partition_dedup))] #[cfg(feature = "alloc")] extern crate alloc; use core::{cmp, fmt, mem}; pub use semilog_macros::Semilattice; mod datalog; mod guarded_pair; mod ord; mod pair; mod redactable; #[cfg(feature = "alloc")] mod map; #[cfg...
#![no_std] #![forbid(unsafe_code)] #![cfg_attr(feature = "alloc", feature(slice_partition_dedup))] #[cfg(feature = "alloc")] extern crate alloc; use core::{cmp, fmt, mem}; pub use semilog_macros::Semilattice; mod datalog; mod guarded_pair; mod ord; mod pair; mod redactable; #[cfg(feature = "alloc")] mod map; #[cfg...
ing::Less) => assert_eq!(&ab, &b), None => { assert!( ab > a, "Expected {:?} > {:?}; {:?}", ab, a, ab.partial_cmp(&a) ); ass...
] mod set; #[cfg(feature = "alloc")] mod vec; pub use { datalog::{DeferredRestore, Iteration, Simple}, guarded_pair::GuardedPair, ord::{Interval, Max, Min}, pair::Pair, redactable::Redactable, }; #[cfg(feature = "alloc")] pub use { map::{Map, MapLattice}, set::{Set, SetLattice}, vec::V...
random
[ { "content": "pub trait DeferredRestore {\n\n type Value;\n\n\n\n // fixme: accelerate ordered joins\n\n fn for_each_stable(&self, func: impl FnMut(&Self::Value));\n\n fn for_each_recent(&self, func: impl FnMut(&Self::Value));\n\n\n\n fn insert(&mut self, val: impl Into<Self::Value>);\n\n\n\n ...
Rust
src/ersatz.rs
k7f/ersatz
863c6248ed5aaaa0e2320c8ec5afe37bd1a84ddf
use std::{ collections::{hash_map, HashMap}, fs, path::Path, error::Error, }; use crate::{Entity, Site, State}; #[derive(Default, Debug)] pub struct Ersatz { ground: Ground, sites: Vec<Site>, max_steps: Option<usize>, } impl Ersatz { pub fn new() -> Self { Default::defau...
use std::{ collections::{hash_map, HashMap}, fs, path::Path, error::Error, }; use crate::{Entity, Site, State}; #[derive(Default, Debug)] pub struct Ersatz { ground: Ground, sites: Vec<Site>, max_steps: Option<usize>, } impl Ersatz { pub fn new() -> Self { Default::defau...
#[inline] pub fn get_id(&self, entity: &Entity) -> Option<usize> { match entity { Entity::Number(num) => self.get_number_id(num), Entity::Name(name) => self.get_name_id(&name), Entity::Identifier(_) => None, } } #[inline] pub fn get_number_id(&s...
l { match self.name_ids.entry(name) { hash_map::Entry::Occupied(_) => false, hash_map::Entry::Vacant(e) => { let name = e.key().clone(); e.insert(self.entities.len()); self.entities.push(Entity::Name(name)); true ...
function_block-function_prefixed
[ { "content": "#[derive(Default, Debug)]\n\nstruct SiteAst<'a> {\n\n tropes: Vec<Trope<'a>>,\n\n compiled: Option<Vec<Reaction>>,\n\n}\n\n\n\nimpl<'a> SiteAst<'a> {\n\n fn compile(&mut self, ground: &mut Ground) {\n\n if self.compiled.is_none() {\n\n for trope in self.tropes.iter_mut...
Rust
src/lib.rs
vkill/async-tls-lite
dc2d36c9bb47e3a497f8dd3edfa11fe0df60e15d
use std::future::Future; use std::io::{self, Read, Write}; use std::pin::Pin; use std::task::{Context, Poll}; use futures_io_traits_sync_wrapper::Wrapper as AsyncRWSyncWrapper; use futures_util::io::{AsyncRead, AsyncWrite}; use rustls::{ClientSession, ServerSession, Session, Stream}; #[cfg(feature = "acceptor")] mod ...
use std::future::Future; use std::io::{self, Read, Write}; use std::pin::Pin; use std::task::{Context, Poll}; use futures_io_traits_sync_wrapper::Wrapper as AsyncRWSyncWrapper; use futures_util::io::{AsyncRead, AsyncWrite}; use rustls::{ClientSession, ServerSession, Session, Stream}; #[cfg(feature = "acceptor")] mod ...
ESS: Session + Unpin, S: AsyncRead + AsyncWrite + Unpin, { Handshake(Some((session, stream))).await } struct Handshake<SESS, S>(Option<(SESS, S)>); impl<SESS, S> Future for Handshake<SESS, S> where SESS: Session + Unpin, S: AsyncRead + AsyncWrite + Unpin, { type Output = io::Result<TlsStream<SESS,...
, S> { pub fn get_mut(&mut self) -> &mut S { &mut self.inner.stream } pub fn get_ref(&self) -> &S { &self.inner.stream } pub fn get_session_mut(&mut self) -> &mut SESS { &mut self.inner.session } pub fn get_session_ref(&self) -> &SESS { &self.inner.session ...
random
[ { "content": "pub fn get_server_session() -> io::Result<ServerSession> {\n\n let mut server_config = ServerConfig::new(NoClientAuth::new());\n\n\n\n let mkcert_path = get_mkcert_path();\n\n let certs = pemfile::certs(&mut BufReader::new(File::open(\n\n mkcert_path.join(\"tls.lvh.me.crt\"),\n\n ...
Rust
examples/gpiote-demo/src/main.rs
Sandraak/nrf-hal
190679d0a03bf0bfe5506c47b287ac7f3ed94192
#![no_std] #![no_main] use {core::panic::PanicInfo, nrf52840_hal as hal, rtt_target::rprintln}; #[rtic::app(device = crate::hal::pac, peripherals = true, dispatchers = [SWI0_EGU0])] mod app { use embedded_hal::digital::v2::InputPin; use systick_monotonic::*; use { hal::{ gpio::{Input, ...
#![no_std] #![no_main] use {core::panic::PanicInfo, nrf52840_hal as hal, rtt_target::rprintln}; #[rtic::app(device = crate::hal::pac, peripherals = true, dispatchers = [SWI0_EGU0])] mod app { use embedded_hal::digital::v2::InputPin; use systick_monotonic::*; use { hal::{ gpio::{Input, ...
#[task(binds = GPIOTE, shared = [gpiote])] fn on_gpiote(mut ctx: on_gpiote::Context) { ctx.shared.gpiote.lock(|gpiote| { if gpiote.channel0().is_event_triggered() { rprintln!("Interrupt from channel 0 event"); } if gpiote.port().is_event_triggered() ...
fn init(ctx: init::Context) -> (Shared, Local, init::Monotonics) { let _clocks = hal::clocks::Clocks::new(ctx.device.CLOCK).enable_ext_hfosc(); rtt_init_print!(); let p0 = hal::gpio::p0::Parts::new(ctx.device.P0); let btn1 = p0.p0_11.into_pullup_input().degrade(); let btn2 = p0.p...
function_block-full_function
[ { "content": "/// Traits that extends the [Ppi](trait.Ppi.html) trait, marking a channel as fully configurable.\n\npub trait ConfigurablePpi: Ppi {\n\n /// Sets the task that must be triggered when the configured event occurs. The user must provide\n\n /// a reference to the task.\n\n fn set_task_endpo...
Rust
src/logging/spec.rs
EgorDm/nauman
1998b259f1891f27b678b2e748c1cc161142f313
use std::path::PathBuf; use crate::config::{LogHandlers, LogHandler, LogHandlerType}; use crate::execution::{ExecutionContext}; use anyhow::{format_err, Result}; use crate::utils::resolve_cwd; #[derive(Debug, Clone, Copy)] pub enum InputStream { Stdout, Stderr, Both, None, } impl InputStream { #[a...
use std::path::PathBuf; use crate::config::{LogHandlers, LogHandler, LogHandlerType}; use crate::execution::{ExecutionContext}; use anyhow::{format_err, Result}; use crate::utils::resolve_cwd; #[derive(Debug, Clone, Copy)] pub enum InputStream { Stdout, Stderr, Both, None, } impl InputStream { #[a...
; result.extend(PipeSpec::from_handler(handler, input_stream, context)?); } Ok(Self { pipes: result, }) } }
if handler.options.stdout && handler.options.stderr { InputStream::Both } else if handler.options.stdout { InputStream::Stdout } else if handler.options.stderr { InputStream::Stderr } else { InputStream::None ...
if_condition
[ { "content": "fn true_default() -> bool {\n\n true\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 0, "score": 130913.447645456 }, { "content": "fn false_default() -> bool {\n\n false\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct LogOptions {\n\n /// W...
Rust
src/data/package.rs
evanacox/welder
6f1b877b886d317a56f4bb620b856ffd490aa66c
use super::targets::*; use semver::Version; #[derive(PartialEq, Clone, Debug)] pub struct Author { pub name: String, pub email: Option<String>, } impl Author { pub fn new(name: String, email: Option<String>) -> Self { Self { name, email } } ...
use super::targets::*; use semver::Version; #[derive(PartialEq, Clone, Debug)] pub struct Author { pub name: String, pub email: Option<String>, } impl Author { pub fn new(name: String, email: Option<String>) -> Self { Self { name, email } } ...
let expected = [ Author::new("John Pkief".to_owned(), None), Author::new( "Evan Cox".to_owned(), Some("evanacox00 at mailservice dot com".to_owned()), ), Author::new("Really Meanly Spaced Organization".to_owned(), None), ...
let input_data = [ "John Pkief", "Evan Cox <evanacox00 at mailservice dot com>", " Really Meanly Spaced Organization ", "<qwetewfjiowgjiojwfweopew@gmail.com>", ];
assignment_statement
[]
Rust
2015/19/src/main.rs
amhk/advent-of-code
41f0c590e6aee377b91ecde1df1c91ce9d2f4081
use std::collections::HashSet; fn main() { let input = include_str!("input.txt"); let answer = part_one(input).expect("no solution for part one"); println!("part 1: {}", answer); let answer = part_two(input).expect("no solution for part two"); println!("part 2: {}", answer); } #[derive(Debug, Pa...
use std::collections::HashSet; fn main() { let input = include_str!("input.txt"); let answer = part_one(input).expect("no solution for part one"); println!("part 1: {}", answer); let answer = part_two(input).expect("no solution for part two"); println!("part 2: {}", answer); } #[derive(Debug, Pa...
fn part_one(input: &str) -> Result<usize, Error> { let (rules, molecule) = parse_input(input)?; Ok(expand(&rules, &molecule).len()) } fn part_two(input: &str) -> Result<usize, Error> { let (rules, molecule) = parse_input(input)?; construct(&rules, &molecule).ok_or(Error::BadInput) } #[cfg(test)] mod...
1.. { let expanded = expand(&rules, &molecule); if expanded.contains("e") { return Some(i); } molecule = expanded.iter().min_by_key(|s| s.len())?.to_string(); } None }
function_block-function_prefixed
[ { "content": "fn part_two(input: &str) -> Result<String, Error> {\n\n let (mut paper, instructions) = parse_input(input)?;\n\n for instr in instructions {\n\n paper.fold(&instr)?;\n\n }\n\n Ok(paper.to_string())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n const INP...
Rust
carbide_core/src/state/value_state.rs
HolgerGottChriestensen/conrod
48b80a0c8915b2d478a445f1e5a8e0f396598652
use std::fmt::{Debug, Formatter}; use std::ops::{Deref, DerefMut}; use std::str::FromStr; use crate::environment::Environment; use crate::state::{BoolState, MapOwnedState, MapState, ResStringState, State, StateContract, StateExt, StringState, TState}; use crate::state::{ValueRef, ValueRefMut}; use crate::state::widget...
use std::fmt::{Debug, Formatter}; use std::ops::{Deref, DerefMut}; use std::str::FromStr; use crate::environment::Environment; use crate::state::{BoolState, MapOwnedState, MapState, ResStringState, State, StateContract, StateExt, StringState, TState}; use crate::state::{ValueRef, ValueRefMut}; use crate::state::widget...
}).into() } } impl Into<BoolState> for ResStringState { fn into(self) -> BoolState { self.mapped(|val: &Result<String, String>| { val.is_err() }) } }
<f64> { fn from(t: u32) -> Self { ValueState::new(t as f64) } } impl From<&str> for TState<String> { fn from(t: &str) -> Self { ValueState::new(t.to_string()) } } impl<T: StateContract + Default + 'static> Into<TState<Result<T, String>>> for TState<T> { fn into(self) -> TState<Resu...
random
[ { "content": "pub trait StateExt<T>: Into<TState<T>> + Clone where T: StateContract + 'static {\n\n fn mapped<TO: StateContract + Default + 'static, M: Map<T, TO> + Clone>(&self, map: M) -> TState<TO> {\n\n MapOwnedState::<T, TO>::new(self.clone(), move |s: &T, _: &_, _: &_| { map(s) }).into()\n\n ...
Rust
src/main.rs
kawaemon/kotio
6df218f7f77125c334dfdfcc949e6c5197823d91
use std::{ cell::RefCell, collections::{HashMap, VecDeque}, future::Future, marker::PhantomData, mem::MaybeUninit, os::raw::c_int, path::Path, pin::Pin, ptr::NonNull, task::{Context, Poll, RawWaker, RawWakerVTable, Waker}, time::{Duration, Instant}, borrow::BorrowMut, }; use...
use std::{ cell::RefCell, collections::{HashMap, VecDeque}, future::Future, marker::PhantomData, mem::MaybeUninit, os::raw::c_int, path::Path, pin::Pin, ptr::NonNull, task::{Context, Poll, RawWaker, RawWakerVTable, Waker}, time::{Duration, Instant}, borrow::BorrowMut, }; use...
KWaker { id: TaskID, } impl KWaker { const VTABLE: RawWakerVTable = RawWakerVTable::new( KWaker::clone, KWaker::wake, KWaker::wake_by_ref, KWaker::drop, ); fn new(id: TaskID) -> Self { Self { id } } fn as_waker(&self) -> RawWaker { RawWaker::new...
r = unsafe { Waker::from_raw(kwaker.as_waker()) }; let mut context = Context::from_waker(&waker); RUNTIME.with(|f| *f.borrow_mut() = Some(self)); EPOLL.with(|f| *f.borrow_mut() = Some(Epoll::new())); loop { let future = unsafe { Pin::new_unchecked(&mut future) ...
random
[ { "content": "int main(void) {\n\n int timer1 = timerfd_create(CLOCK_BOOTTIME, 0);\n\n if (timer1 == -1) {\n\n fail(\"timer\");\n\n }\n\n\n\n int timer2 = timerfd_create(CLOCK_BOOTTIME, 0);\n\n if (timer2 == -1) {\n\n fail(\"timer\");\n\n }\n\n\n\n printfln(\"timer1 fd: %d\", ...
Rust
memo_js/src/lib.rs
xcesiv/xray
5b4d7ec7040666688321b86e0db5c8644655f734
extern crate bincode; extern crate js_sys; extern crate memo_core; #[macro_use] extern crate serde_derive; extern crate base64; extern crate serde; extern crate wasm_bindgen; use memo_core::*; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::char; use std::collections::HashMap; use std::collecti...
extern crate bincode; extern crate js_sys; extern crate memo_core; #[macro_use] extern crate serde_derive; extern crate base64; extern crate serde; extern crate wasm_bindgen; use memo_core::*; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::char; use std::collections::HashMap; use std::collecti...
} impl<'de1, T: for<'de2> Deserialize<'de2>> Deserialize<'de1> for Base64<T> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de1>, { use serde::de::Error; let bytes = base64::decode(&String::deserialize(deserializer)?).map_err(Error::custom)?; ...
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { use serde::ser::Error; base64::encode(&bincode::serialize(&self.0).map_err(Error::custom)?).serialize(serializer) }
function_block-full_function
[]
Rust
tests/query.rs
qwerty541/modio-rs
0a0e6ed67e9c4aad342d1c243d21c19acb1626fc
use futures_core::Stream; use futures_util::TryStreamExt; use httptest::{matchers::*, responders::*}; use httptest::{Expectation, Server}; use modio::filter::prelude::*; use modio::{Modio, Result}; macro_rules! expect_requests { ($server:expr, $(query:$query:expr, body:$body:expr),*) => { $( $...
use futures_core::Stream; use futures_util::TryStreamExt; use httptest::{matchers::*, responders::*}; use httptest::{Expectation, Server}; use modio::filter::prelude::*; use modio::{Modio, Result}; macro_rules! expect_requests { ($server:expr, $(query:$query:expr, body:$body:expr),*) => { $( $...
#[tokio::test] async fn first() -> Result<()> { let server = create_first_page_only(); let modio = Modio::host(server.url_str("/v1"), "foobar")?; let first = modio.games().search(Default::default()).first().await?; assert!(first.is_some()); assert_eq!(1, first.unwrap().id); Ok(()) } #[tokio...
let modio = Modio::host(server.url_str("/v1"), "foobar")?; let first = modio.games().search(Default::default()).first().await?; assert!(first.is_none()); Ok(()) }
function_block-function_prefix_line
[ { "content": "fn prompt(prompt: &str) -> io::Result<String> {\n\n print!(\"{}\", prompt);\n\n io::stdout().flush()?;\n\n let mut buffer = String::new();\n\n io::stdin().read_line(&mut buffer)?;\n\n Ok(buffer.trim().to_string())\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<(), Box<dyn s...
Rust
src/main.rs
JMS55/metaballs
cc8d416752b4eee53cde2b67e6bc94f71008b9f3
use bytemuck::{Pod, Zeroable}; use std::io::Cursor; use std::time::Instant; use wgpu::*; use winit::event::{ElementState, Event, VirtualKeyCode, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::Window; #[repr(C)] #[derive(Copy, Clone)] struct TimeUniform { time: f32, } unsafe impl ...
use bytemuck::{Pod, Zeroable}; use std::io::Cursor; use std::time::Instant; use wgpu::*; use winit::event::{ElementState, Event, VirtualKeyCode, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::Window; #[repr(C)] #[derive(Copy, Clone)] struct TimeUniform { time: f32, } unsafe impl ...
age::COPY_SRC, ); encoder.copy_buffer_to_buffer( &staging_buffer, 0, &zoom_uniform_buffer, 0, ...
device.create_command_encoder(&CommandEncoderDescriptor { label: None }); screen_size_uniform.screen_size = [screen_size.width as f32, screen_size.height as f32]; let staging_buffer = device.create_buffer_with_data( bytemuck::cast_sl...
random
[]
Rust
csv-to-graph/src/main.rs
mrd0ll4r/ipfs-resolver
45011bbf9129ab218e58d45d88f0458ae27b1ff9
#[macro_use] extern crate log; #[macro_use] extern crate failure; use failure::{err_msg, ResultExt}; use ipfs_resolver_common::logging; use ipfs_resolver_common::Result; use ipfs_resolver_db::canonicalize_cid_from_str_to_cidv1; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::Seek; con...
#[macro_use] extern crate log; #[macro_use] extern crate failure; use failure::{err_msg, ResultExt}; use ipfs_resolver_common::logging; use ipfs_resolver_common::Result; use ipfs_resolver_db::canonicalize_cid_from_str_to_cidv1; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::Seek; con...
r_to_cidv1(&record.referenced_cidv1) .context("invalid CID")?; let b = cid.to_bytes(); let target_id = { if let Some(id) = blocks.get(&b) { *id } else { max_id += 1; blocks.insert(b, max_...
: &str = "% asym unweighted"; #[derive(Debug, Deserialize)] struct Block { id: i64, cidv1: String, } #[derive(Debug, Deserialize)] struct Link { parent_block_id: i64, referenced_cidv1: String, } #[derive(Debug, Deserialize, Serialize)] struct ProcessedLink { parent_block_id: i64, referenced_c...
random
[ { "content": "ALTER TABLE successful_resolves ADD id SERIAL NOT NULL PRIMARY KEY;\n", "file_path": "db/migrations/2020-04-09-160051_add-surrogate-resolve-ids/up.sql", "rank": 0, "score": 57333.48509672894 }, { "content": "ALTER TABLE failed_resolves ADD id SERIAL NOT NULL PRIMARY KEY;\n", ...
Rust
program/src/positions_book/tree_nodes.rs
alienbri/audaces-perps
aa5b0e14eae4944dd0a18af60a72b119ff17fd84
use crate::error::{PerpError, PerpResult}; use super::memory::{Memory, Pointer}; #[derive(Clone, Copy)] pub enum InnerNodeSchema { Critbit = 1, LiquidationIndexMin = 2, LeftPointer = 10, RightPointer = 14, Collateral = 22, VCoin = 30, VPc = 38, CalculationFlag = 46, } pub enum LeafN...
use crate::error::{PerpError, PerpResult}; use super::memory::{Memory, Pointer}; #[derive(Clone, Copy)] pub enum InnerNodeSchema { Critbit = 1, LiquidationIndexMin = 2, LeftPointer = 10, RightPointer = 14, Collateral = 22, VCoin = 30, VPc = 38, CalculationFlag = 46, } pub enum LeafN...
} pub(super) fn get_v_pc(&self, mem: &Memory) -> Result<u64, PerpError> { match self { Node::InnerNode(i) => i.get_v_pc(mem), Node::Leaf(i) => i.get_v_pc(mem), } } pub(super) fn free(&self, mem: &mut Memory) -> PerpResult { match self { Node:...
match self { Node::InnerNode(i) => i.get_v_coin(mem), Node::Leaf(i) => i.get_v_coin(mem), }
if_condition
[ { "content": "#[cfg(not(target_arch = \"bpf\"))]\n\npub fn print_node(pt: Pointer, mem: &Memory, offset: u8) {\n\n let indent = vec![\" \"; 8 * offset as usize].join(\"\");\n\n match FromPrimitive::from_u8(mem.read_byte(pt, 0).unwrap()).unwrap() {\n\n SlotType::InnerNode => {\n\n let cri...
Rust
src/predicates/types.rs
sthiele/flatzinc
20dd58d7a09a38cb454c83305a03a071b384891c
use std::str; use nom::{ branch::alt, bytes::complete::tag, character::complete::char, error::{FromExternalError, ParseError}, IResult, }; use crate::{ comments::{space_or_comment0, space_or_comment1}, parameters::types::{basic_par_type, BasicParType}, primitive_literals::index_set, ...
use std::str; use nom::{ branch::alt, bytes::complete::tag, character::complete::char, error::{FromExternalError, ParseError}, IResult, }; use crate::{ comments::{space_or_comment0, space_or_comment1}, parameters::types::{basic_par_type, BasicParType}, primitive_literals::index_set, ...
(input)?; Ok((input, bppt)) } fn bppt_basic_par_type<'a, E: ParseError<&'a str>>( input: &'a str, ) -> IResult<&'a str, BasicPredParType, E> { let (input, bpt) = basic_par_type(input)?; Ok((input, BasicPredParType::BasicParType(bpt))) } fn bppt_basic_var_type<'a, E: ParseError<&'a str>>( input: &'...
alt(( bppt_basic_par_type, bppt_basic_var_type, bppt_var_set_of_int, bppt_int_in_range, bppt_int_in_set, bppt_bounded_float, bppt_float_in_set, bppt_subset_of_int_set, bppt_subset_of_int_range, ))
call_expression
[ { "content": "pub fn bounded_float<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, (f64, f64), E>\n\nwhere\n\n E: FromExternalError<&'a str, std::num::ParseFloatError>,\n\n{\n\n let (input, lb) = float_literal(input)?;\n\n let (input, _) = space_or_comment0(input)?;\n\n let (input, _...
Rust
packages/astroport/src/asset.rs
akropolisio/astroport
9b7bbf80b977c7e803174aa3a6d659556438d579
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt; use crate::factory::PairType; use crate::querier::{query_balance, query_token_balance, query_token_symbol}; use cosmwasm_std::{ to_binary, Addr, Api, BankMsg, Coin, CosmosMsg, Decimal, MessageInfo, QuerierWrapper, StdError, StdResult,...
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt; use crate::factory::PairType; use crate::querier::{query_balance, query_token_balance, query_token_symbol}; use cosmwasm_std::{ to_binary, Addr, Api, BankMsg, Coin, CosmosMsg, Decimal, MessageInfo, QuerierWrapper, StdError, StdResult,...
?, funds: vec![], })), AssetInfo::NativeToken { .. } => Ok(CosmosMsg::Bank(BankMsg::Send { to_address: recipient.to_string(), amount: vec![self.deduct_tax(querier)?], })), } } pub fn assert_sent_native_token_balance(&se...
to_binary(&Cw20ExecuteMsg::Transfer { recipient: recipient.to_string(), amount, })
call_expression
[]
Rust
Day 09 - Explosives in Cyberspace/src/main.rs
kAworu/adventofcode-2016
1c93f92c45b3a27e357b959ecf19c3992595525b
#[macro_use] extern crate nom; mod explosives_in_cyberspace { #[derive(Debug)] enum EzipNode { Uncompressed(String), Compressed(usize, Ezip), } impl EzipNode { fn uncompressed_len(&self) -> usize { match *self { EzipNode::Uncompres...
#[macro_use] extern crate nom; mod explosives_in_cyberspace { #[derive(Debug)] enum EzipNode { Uncompressed(String), Compressed(usize, Ezip), } impl EzipNode { fn uncompressed_len(&self) -> usize { match *self { EzipNode::Uncompres...
, do_parse!( mark: peek!(marker) >> children: map!(length_value!(marker_len, nodes_v2), Ezip::build) >> (EzipNode::Compressed(mark.1, children)) ) ); named!(nodes_v1<Vec<EzipNode>>, many1!(alt!(compressed_v1 | uncompresse...
rse_v1(s: &str) -> Result<Ezip, ::nom::IError> { parsing::ezipv1(s).to_full_result() } pub fn parse_v2(s: &str) -> Result<Ezip, ::nom::IError> { parsing::ezipv2(s).to_full_result() } pub fn uncompressed_len(&self) -> usize { ...
random
[ { "content": "fn main() {\n\n // acquire data from stdin\n\n let mut input = String::new();\n\n let stdin = std::io::stdin();\n\n stdin.lock().read_to_string(&mut input).expect(\"no input given\");\n\n\n\n // parse the provided document instructions\n\n let document: BathroomDocument = input.p...
Rust
src/main.rs
koji-m/VanillaText
827287bc14a1eb582bf4d41d1b9ceb8c210ebb56
extern crate gtk; extern crate gio; extern crate gdk; extern crate gdk_pixbuf; mod win; mod page; use std::env::Args; use std::path::Path; use std::rc::Rc; use std::cell::RefCell; use gtk::{ GtkApplicationExt }; use gio::{ ApplicationExt, ApplicationExtManual, ActionMapExt, SimpleActionExt }; use win::{ ...
extern crate gtk; extern crate gio; extern crate gdk; extern crate gdk_pixbuf; mod win; mod page; use std::env::Args; use std::path::Path; use std::rc::Rc; use std::cell::RefCell; use gtk::{ GtkApplicationExt }; use gio::{ ApplicationExt, ApplicationExtManual, ActionMapExt, SimpleActionExt }; use win::{ ...
fn run(args: Args) { match gtk::Application::new("com.github.koji-m.vanilla_text", gio::APPLICATION_HANDLES_OPEN) { Ok(app) => { let wins = Rc::new(RefCell::new(Vec::<Window>::new())); { let wins = wins.clone(); app.connect_startup(move |app| { ...
fn init_accels(app: &gtk::Application) { app.add_accelerator("<Ctrl>q", "app.quit", None); app.add_accelerator("<Ctrl>n", "app.new_window", None); app.add_accelerator("<Ctrl>o", "win.open", None); app.add_accelerator("<Ctrl>s", "win.save", None); app.add_accelerator("<Shift><Ctrl>s", "win.saveas", N...
function_block-full_function
[ { "content": "fn run_file_chooser_dialog() -> Option<gio::File> {\n\n let dialog = gtk::FileChooserDialog::new::<gtk::Window>(Some(\"Open File\"),\n\n None,\n\n gtk::FileChooserAction::Open);\n\n dialog.add_button(\"Cancel\", gtk::Res...
Rust
revai/src/lib.rs
stuck-overflow/cio
8c2d57600dea2abffd632c05ead825e3d14345db
/*! * A rust library for interacting with the RevAI API. * * For more information, you can check out their documentation at: * https://www.rev.ai/docs * * Example: * * ``` * use revai::RevAI; * use serde::{Deserialize, Serialize}; * * async fn geocode() { * // Initialize the RevAI client. * let re...
/*! * A rust library for interacting with the RevAI API. * * For more information, you can check out their documentation at: * https://www.rev.ai/docs * * Example: * * ``` * use revai::RevAI; * use serde::{Deserialize, Serialize}; * * async fn geocode() { * // Initialize the RevAI client. * let re...
} pub struct APIError { pub status_code: StatusCode, pub body: String, } impl fmt::Display for APIError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "APIError: status code -> {}, body -> {}", self.status_code.to_string(), self.body) } } impl fmt::Debug for APIError { ...
let resp = self.client.execute(request).await.unwrap(); match resp.status() { StatusCode::OK => (), s => { return Err(APIError { status_code: s, body: resp.text().await.unwrap(), }) } }; ...
function_block-function_prefix_line
[ { "content": "/// Get the API key from the AIRTABLE_API_KEY env variable.\n\npub fn api_key_from_env() -> String {\n\n env::var(\"AIRTABLE_API_KEY\").unwrap()\n\n}\n\n\n\nimpl Airtable {\n\n /// Create a new Airtable client struct. It takes a type that can convert into\n\n /// an &str (`String` or `Vec...
Rust
src/dart.rs
wareya/notmecab-rs
c465e9dcfdaad4c75dc633213628ba5e7231ba63
use crate::HashMap; use crate::HashSet; use std::io::Cursor; use std::io::Read; use std::io::Seek; use std::ops::Range; use std::hash::{BuildHasherDefault, Hasher}; use super::blob::*; use super::file::*; use super::FormatToken; type BuildNoopHasher = BuildHasherDefault<NoopHasher>; #[derive(Default)] struct NoopHa...
use crate::HashMap; use crate::HashSet; use std::io::Cursor; use std::io::Read; use std::io::Seek; use std::ops::Range; use std::hash::{BuildHasherDefault, Hasher}; use super::blob::*; use super::file::*; use super::FormatToken; type BuildNoopHasher = BuildHasherDefault<NoopHasher>; #[derive(Default)] struct NoopHa...
#[derive(Debug)] #[derive(Clone)] #[derive(Copy)] pub(crate) struct DictInfo { first : u32, end : u32, } fn entries_to_tokens(entries : Vec<(String, u32)>) -> HashMap<String, DictInfo> { entries.into_iter().map(|entry| { let first : u32 = entry.1 / 0x100; let end : u32 = (entry.1 % 0x...
s, base, base).is_ok() { if let Ok(key) = read_str_buffer(&key) { collection.push((key, !links[base as usize].base)); } } for i in 0..0x100 { if check_valid_link(links, base, base+1+i).is_ok() { let mut newkey = key.to_owned(); ...
function_block-function_prefixed
[ { "content": "fn generate_potential_tokens_at<'a>(dict : &'a Dict, text : &str, mut start : usize, output : &mut Vec<Token<'a>>) -> usize\n\n{\n\n let initial_output_len = output.len();\n\n let rank = start;\n\n\n\n let space_count;\n\n if dict.use_space_stripping\n\n {\n\n space_count = t...
Rust
src/sentences/bwc.rs
afonso360/nmea
39eead51a0df56f067205190dad1093b08f4d2eb
use arrayvec::ArrayString; use chrono::NaiveTime; use nom::bytes::complete::is_not; use nom::character::complete::char; use nom::combinator::{map_res, opt}; use nom::number::complete::float; use crate::parse::NmeaSentence; use crate::sentences::utils::{parse_hms, parse_lat_lon}; use crate::NmeaError; const MAX_LEN: u...
use arrayvec::ArrayString; use chrono::NaiveTime; use nom::bytes::complete::is_not; use nom::character::complete::char; use nom::combinator::{map_res, opt}; use nom::number::complete::float; use crate::parse::NmeaSentence; use crate::sentences::utils::{parse_hms, parse_lat_lon}; use crate::NmeaError; const MAX_LEN: u...
; Ok(BwcData { fix_time, latitude: lat_lon.map(|v| v.0), longitude: lat_lon.map(|v| v.1), true_bearing, magnetic_bearing, distance, waypoint_id, }) } pub fn parse_bwc(sentence: NmeaSentence) -> Result<BwcData, NmeaError> { if sentence.message_id != b...
if let Some(waypoint_id) = waypoint_id { Some( ArrayString::from(waypoint_id) .map_err(|_e| NmeaError::SentenceLength(waypoint_id.len()))?, ) } else { None }
if_condition
[ { "content": "/// parse nmea 0183 sentence and extract data from it\n\npub fn parse(xs: &[u8]) -> Result<ParseResult, NmeaError> {\n\n let nmea_sentence = parse_nmea_sentence(xs)?;\n\n let calculated_checksum = nmea_sentence.calc_checksum();\n\n\n\n if nmea_sentence.checksum == calculated_checksum {\n\...
Rust
garmin_lib/src/common/garmin_lap.rs
ddboline/garmin_rust
170ab41ba7c53855af753fc0050dee9cb2779f13
use anyhow::Error; use chrono::{DateTime, Utc}; use fitparser::{FitDataField, Value}; use roxmltree::{Node, NodeType}; use serde::{Deserialize, Serialize}; use stack_string::StackString; use std::fmt; use crate::utils::{ garmin_util::{convert_time_string, convert_xml_local_time_to_utc, get_f64, get_i64}, iso_8...
use anyhow::Error; use chrono::{DateTime, Utc}; use fitparser::{FitDataField, Value}; use roxmltree::{Node, NodeType}; use serde::{Deserialize, Serialize}; use stack_string::StackString; use std::fmt; use crate::utils::{ garmin_util::{convert_time_string, convert_xml_local_time_to_utc, get_f64, get_i64}, iso_8...
pub fn read_lap_xml(entries: &Node) -> Result<Self, Error> { let mut new_lap = Self::new(); for d in entries.descendants() { if d.node_type() == NodeType::Element { match d.tag_name().name() { "max_speed" => new_lap.lap_max_speed = d.text().and_then(...
p_type = None; self.lap_index = -1; self.lap_start = sentinel_datetime(); self.lap_duration = 0.0; self.lap_distance = 0.0; self.lap_trigger = None; self.lap_max_speed = None; self.lap_calories = 0; self.lap_avg_hr = None; self.lap_max_hr = None; ...
function_block-function_prefixed
[ { "content": "pub fn get_f64(value: &Value) -> Option<f64> {\n\n match value {\n\n Value::Timestamp(val) => Some(val.timestamp() as f64),\n\n Value::Byte(val) | Value::Enum(val) | Value::UInt8(val) | Value::UInt8z(val) => {\n\n Some(f64::from(*val))\n\n }\n\n Value::SIn...
Rust
conmon-rs/server/src/rpc.rs
containers/conmon-rs
ad675171238eb7a57a44347770e95420850601ab
use crate::{ attach::Attach, child::Child, container_io::{ContainerIO, SharedContainerIO}, container_log::ContainerLog, server::Server, version::Version, }; use anyhow::Context; use capnp::{capability::Promise, Error}; use capnp_rpc::pry; use conmon_common::conmon_capnp::conmon; use log::{debug,...
use crate::{ attach::Attach, child::Child, container_io::{ContainerIO, SharedContainerIO}, container_log::ContainerLog, server::Server, version::Version, }; use anyhow::Context; use capnp::{capability::Promise, Error}; use capnp_rpc::pry; use conmon_common::conmon_capnp::conmon; use log::{debug,...
ntainer request for container id {}", container_id, ); let child = pry_err!(self.reaper().get(container_id)); let width = req.get_width(); let height = req.get_height(); Promise::from_future(async move { capnp_err!(child.io().resize(width, height).await) }) } }
!(req.get_id()).to_string(); let timeout = req.get_timeout_sec(); let pidfile = pry_err!(ContainerIO::temp_file_name( Some(self.config().runtime_dir()), "exec_sync", "pid" )); debug!( "Got exec sync container request for id {} with timeou...
random
[ { "content": "fn main() -> Result<(), Error> {\n\n CompilerCommand::new().file(\"proto/conmon.capnp\").run()\n\n}\n", "file_path": "conmon-rs/common/build.rs", "rank": 0, "score": 148531.87310890772 }, { "content": "fn main() -> Result<()> {\n\n Server::new()\n\n .context(\"crea...
Rust
src/repository/controller.rs
henrybarreto/nitro_repo
b0c7feab8047fb6847cd81baa29abce14a0c0055
use crate::api_response::APIResponse; use crate::error::request_error::RequestError; use crate::error::request_error::RequestError::NotFound; use crate::repository::action::{get_repo_by_name_and_storage, get_repositories_by_storage}; use crate::repository::maven::MavenHandler; use crate::repository::models::Repository...
use crate::api_response::APIResponse; use crate::error::request_error::RequestError; use crate::error::request_error::RequestError::NotFound; use crate::repository::action::{get_repo_by_name_and_storage, get_repositories_by_storage}; use crate::repository::maven::MavenHandler; use crate::repository::models::Repository...
itory( pool: web::Data<DbPool>, r: HttpRequest, path: web::Path<(String, String, String)>, ) -> Result<HttpResponse, RequestError> { let connection = pool.get()?; installed(&connection)?; let storage = get_storage_by_name(path.0.0, &connection)?.ok_or(RequestError::NotFound)?; let repositor...
e = get_storage_by_name(path.0.0, &connection)?.ok_or(RequestError::NotFound)?; let repository = get_repo_by_name_and_storage(path.0.1.clone(), storage.id.clone(), &connection)? .ok_or(RequestError::NotFound)?; let t = repository.repo_type.clone(); let string = path.0.2.clone(); le...
random
[ { "content": "fn get_artifacts(path: PathBuf) -> Vec<String> {\n\n let dir = read_dir(path).unwrap();\n\n let mut values = Vec::new();\n\n for x in dir {\n\n let x1 = x.unwrap();\n\n if x1.file_type().unwrap().is_file() {\n\n let file_name = x1.file_name().to_str().unwrap().to_...
Rust
src/cache_service/cache.rs
Scarjit/rust_fast_cache
904fe6a19740f69638ca95270aa55809f6aa8b84
use crate::memdb::memory_database::{DatabaseItem, FastDB}; use crate::tools::get_nano_time; use directories::ProjectDirs; use rayon::{ThreadPool, ThreadPoolBuilder}; use std::io; use std::path::Path; extern crate rand; use crate::tools::logger; use rand::Rng; use std::fs::File; use std::io::Read; pub const ONE_BYTE: u...
use crate::memdb::memory_database::{DatabaseItem, FastDB}; use crate::tools::get_nano_time; use directories::ProjectDirs; use rayon::{ThreadPool, ThreadPoolBuilder}; use std::io; use std::path::Path; extern crate rand; use crate::tools::logger; use rand::Rng; use std::fs::File; use std::io::Read; pub const ONE_BYTE: u...
} impl Cache { pub fn set_cache_path(&mut self, new_cache_path: String) { if !Path::new(&new_cache_path).exists() { logger::log("Cache path does not exist, creating!"); std::fs::create_dir_all(&new_cache_path).expect("Could not create cache path"); } self....
size: 0, diskdb_size: 0, management_threadpool: ThreadPoolBuilder::new() .num_threads(num_cpus::get_physical()) .build() .expect("Couldn't create threadpool"), } }
function_block-function_prefixed
[ { "content": "pub fn fmt_bytes(b: u64) -> String {\n\n match NumberPrefix::binary(b as f64) {\n\n Standalone(bytes) => format!(\"{} bytes\", bytes),\n\n Prefixed(prefix, n) => format!(\"{:.0} {}B\", n, prefix),\n\n }\n\n}\n\n\n", "file_path": "src/tools/mod.rs", "rank": 0, "score...
Rust
src/machine.rs
doitian/ckb-vm
85fa44cf65569c0cb643660c976ddd22af30246e
use super::bits::rounddown; use super::decoder::build_imac_decoder; use super::instructions::{Instruction, Register}; use super::memory::{Memory, PROT_EXEC, PROT_READ, PROT_WRITE}; use super::syscalls::Syscalls; use super::{ Error, A0, A7, REGISTER_ABI_NAMES, RISCV_GENERAL_REGISTER_NUMBER, RISCV_MAX_MEMORY, RIS...
use super::bits::rounddown; use super::decoder::build_imac_decoder; use super::instructions::{Instruction, Register}; use super::memory::{Memory, PROT_EXEC, PROT_READ, PROT_WRITE}; use super::syscalls::Syscalls; use super::{ Error, A0, A7, REGISTER_ABI_NAMES, RISCV_GENERAL_REGISTER_NUMBER, RISCV_MAX_MEMORY, RIS...
}
pub fn run(&mut self, program: &[u8], args: &[Vec<u8>]) -> Result<u8, Error> { self.load_elf(program)?; for syscall in &mut self.syscalls { syscall.initialize(&mut self.core)?; } self.initialize_stack( args, RISCV_MAX_MEMORY - DEFAULT_STACK_SIZE, ...
function_block-full_function
[ { "content": "pub fn run<R: Register, M: Memory + Default>(\n\n program: &[u8],\n\n args: &[Vec<u8>],\n\n) -> Result<u8, Error> {\n\n DefaultMachine::<R, M>::default().run(program, args)\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 268369.80272689404 }, { "content": "pub ...
Rust
server/src/guards/auth.rs
aaronleopold/stump
5e972a0ccb8e638cedfc3563266177f488945045
use rocket::{ http::Status, request::{FromRequest, Outcome, Request}, }; use crate::{ prisma, types::{ alias::{Context, Session}, errors::AuthError, models::AuthenticatedUser, }, utils::{self}, }; pub struct StumpAuth(pub AuthenticatedUser); #[rocket::async_trait] impl...
use rocket::{ http::Status, request::{FromRequest, Outcome, Request}, }; use crate::{ prisma, types::{ alias::{Context, Session}, errors::AuthError, models::AuthenticatedUser, }, utils::{self}, }; pub struct StumpAuth(pub AuthenticatedUser); #[rocket::async_trait] impl...
}
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> { let session: Session<'_> = req.guard().await.expect("TODO"); match session.get().await { Ok(res) => { println!("{:?}", res); if res.is_some() { println!("Session e...
function_block-full_function
[ { "content": "#[catch(401)]\n\nfn opds_unauthorized(_req: &rocket::Request) -> UnauthorizedResponse {\n\n UnauthorizedResponse {}\n\n}\n\n\n\n#[launch]\n\nasync fn rocket() -> _ {\n\n #[cfg(debug_assertions)]\n\n dotenv().ok();\n\n\n\n rocket::build()\n\n .manage(Context::new().await)\n\n ...
Rust
sql_engine/data_manipulation/untyped_tree/src/tests/implicit_type_casting.rs
fossabot/isomorphicdb
b0c00b6f9862fb440dd2f5684a07d84aa712a0f9
use super::*; #[cfg(test)] mod booleans { use super::*; #[test] fn to_string() { assert_eq!( UntypedValue::Bool(Bool(true)).implicit_cast_to(SqlType::char(4)), Ok(UntypedValue::String("true".to_owned())) ); } #[test] fn to_string_not_enough_length() {...
use super::*; #[cfg(test)] mod booleans { use super::*; #[test] fn to_string() { assert_eq!( UntypedValue::Bool(Bool(true)).implicit_cast_to(SqlType::char(4)), Ok(UntypedValue::String("true".to_owned())) ); } #[test] fn to_string_not_enough_length() {...
).implicit_cast_to(SqlType::char(1)), Ok(UntypedValue::String("0".to_owned())) ); } #[test] fn to_string_too_long() { assert_eq!( UntypedValue::Number(BigDecimal::from(10)).implicit_cast_to(SqlType::char(1)), Err(ImplicitCastError::string_data_right_trunc...
typedValue::Number(BigDecimal::from(0)).implicit_cast_to(SqlType::bool()), Err(ImplicitCastError::datatype_mismatch( SqlType::bool(), SqlType::integer() )) ); assert_eq!( UntypedValue::Number(BigDecimal::from(i64::max_value())).implici...
random
[ { "content": "fn number(value: i16) -> Value {\n\n Value::Int(value as i32)\n\n}\n\n\n", "file_path": "sql_engine/query_analyzer/src/tests/mod.rs", "rank": 0, "score": 191582.75287907908 }, { "content": "fn boolean(value: bool) -> Expr {\n\n Expr::Value(Value::Boolean(value))\n\n}\n\n\...
Rust
tooling/metrics-histogram-fidelity/src/main.rs
TimonPost/metrics
9a7bb97d5186e655e7b4d5f1764a9a4c42ed41b9
use metrics_util::Summary; use ndarray::{Array1, Axis}; use ndarray_stats::{interpolate::Linear, QuantileExt}; use noisy_float::types::n64; use ordered_float::NotNan; use rand::{distributions::Distribution, thread_rng}; use rand_distr::Uniform; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::BufRe...
use metrics_util::Summary; use ndarray::{Array1, Axis}; use ndarray_stats::{interpolate::Linear, QuantileExt}; use noisy_float::types::n64; use ordered_float::NotNan; use rand::{distributions::Distribution, thread_rng}; use rand_distr::Uniform; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::BufRe...
let mut handle = Command::new("../ddsketch-reference-generator/main.py") .arg("input.csv") .arg("output.csv") .arg("0.0001") .arg("32768") .spawn()?; let status = handle.wait()?; if !status.success() { println!("failed to run DDSketch reference generator"); } ...
function_block-function_prefixed
[ { "content": "def main():\n\n parser = argparse.ArgumentParser(description='Process some integers.')\n\n parser.add_argument('input', type=argparse.FileType('r'))\n\n parser.add_argument('output', type=argparse.FileType('w'))\n\n parser.add_argument('alpha', type=float, nargs='?', default=0.0001)\n\...
Rust
src/format.rs
avvo/avvoenv
a9f0a282df9a8c8d15738b4342d06c2003dea1d1
use std::{ collections::HashMap, error::Error, ffi::OsStr, fmt, io::{self, Write}, path::Path, str::FromStr, }; #[derive(Debug)] pub enum Format { Env, Defaults, Hocon, Json, Properties, Yaml, } impl Format { pub fn from_path<P: AsRef<Path>>(path: P) -> Format {...
use std::{ collections::HashMap, error::Error, ffi::OsStr, fmt, io::{self, Write}, path::Path, str::FromStr, }; #[derive(Debug)] pub enum Format { Env, Defaults, Hocon, Json, Properties, Yaml, } impl Format { pub fn from_path<P: AsRef<Path>>(path: P) -> Format {...
} #[derive(Debug)] pub enum FormatError { IoError(io::Error), JsonError(serde_json::Error), YamlError(serde_yaml::Error), } impl fmt::Display for FormatError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { FormatError::IoError(e) => e.fmt(f), Form...
fn from_str(s: &str) -> Result<Self, Self::Err> { match s.trim().to_lowercase().as_str() { "env" => Ok(Format::Env), "defaults" => Ok(Format::Defaults), "hcon" => Ok(Format::Hocon), "json" => Ok(Format::Json), "properties" => Ok(Format::Properties), ...
function_block-function_prefix_line
[ { "content": "pub fn prompt_default(prompt: &str, default: Option<String>) -> Result<String> {\n\n let mut stdout = stdout();\n\n match default {\n\n Some(ref v) => write!(stdout, \"{}({}) \", prompt, v)?,\n\n None => write!(stdout, \"{}\", prompt)?,\n\n };\n\n stdout.flush()?;\n\n\n\n...
Rust
src/registration.rs
JBA-Khalifa/mx-tester
838f1f13e89e9f998c95f262d9adfd655bf84e8d
use anyhow::{anyhow, Error}; use data_encoding::HEXLOWER; use hmac::{Hmac, Mac, NewMac}; use log::debug; use reqwest::StatusCode; use serde::{Deserialize, Serialize}; use sha1::Sha1; type HmacSha1 = Hmac<Sha1>; #[derive(Debug, Deserialize)] pub struct User { #[serde(default)] pub admin: bool, pub ...
use anyhow::{anyhow, Error}; use data_encoding::HEXLOWER; use hmac::{Hmac, Mac, NewMac}; use log::debug; use reqwest::StatusCode; use serde::{Deserialize, Serialize}; use sha1::Sha1; type HmacSha1 = Hmac<Sha1>; #[derive(Debug, Deserialize)] pub struct User { #[serde(default)] pub admin: bool, pub ...
} } } pub async fn login(base_url: &str, user: &User) -> Result<(), Error> { #[derive(Debug, Serialize)] struct Identifier { #[serde(rename(serialize = "type"))] identifier_type: String, user: String, } #[derive(Debug, Serialize)] struct LoginPayload { #...
Err(anyhow!( "Homeserver responded with errcode: {}, error: {}", body.errcode, body.error ))
call_expression
[ { "content": "/// Check if the named docker network has previously been created.\n\nfn is_network_created(network_name: &str) -> Result<bool, Error> {\n\n let mut command = std::process::Command::new(\"docker\");\n\n command\n\n .arg(\"network\")\n\n .arg(\"ls\")\n\n .arg(\"--no-trunc...
Rust
src/memory/frame_controller.rs
garyGLgan/g8os
6848c6bc2ddb900971ec07edbca12f275ee2318a
use crate::kernel_const::{ BOOT_TMP_MMAP_BUFFER, FRAME_SIZE, FRAME_SIZE_BIT_WIDTH, MEMORY_RESERVED_BELOW, }; use crate::println; use crate::util::Locked; use lazy_static::lazy_static; use x86_64::{ structures::paging::{FrameAllocator, FrameDeallocator, PhysFrame, Size2MiB, UnusedPhysFrame}, PhysAddr, }; la...
use crate::kernel_const::{ BOOT_TMP_MMAP_BUFFER, FRAME_SIZE, FRAME_SIZE_BIT_WIDTH, MEMORY_RESERVED_BELOW, }; use crate::println; use crate::util::Locked; use lazy_static::lazy_static; use x86_64::{ structures::paging::{FrameAllocator, FrameDeallocator, PhysFrame, Size2MiB, UnusedPhysFrame}, PhysAddr, }; la...
; self.blocks[cur as usize].as_mut().unwrap().next = _next; } } else { let _size = (_next_end - addr.as_u64()) >> FRAME_SIZE_BIT_WIDTH; self.blocks[next as usize].as_mut().unwrap().addr = addr; self.b...
Some(UnusedBlock { addr, size: size >> FRAME_SIZE_BIT_WIDTH, next: next, })
call_expression
[ { "content": "pub fn vaddr_from_table(l4: u32, l3: u32, l2: u32, offset: u32) -> VirtAddr {\n\n VirtAddr::new(((l4 as u64) << 39) | ((l3 as u64) << 30) | ((l2 as u64) << 21) | (offset as u64))\n\n}\n", "file_path": "src/memory/paging/g8_page_table.rs", "rank": 2, "score": 105323.36432193214 }, ...
Rust
src/actions.rs
Flaise/sclan
f3ac7950f00d1ff1f64bddbab9a048e959851ee3
use std::error::Error; use std::mem::take; use std::time::Duration; use std::net::IpAddr; use std::cmp::min; use crossterm::event::{Event, KeyCode, KeyModifiers, read, poll}; use clipboard::{ClipboardProvider, ClipboardContext}; use crate::data::{App, InputMode, now_fmt, Message, MessageType, set_status, Peer, LogState...
use std::error::Error; use std::mem::take; use std::time::Duration; use std::net::IpAddr; use std::cmp::min; use crossterm::event::{Event, KeyCode, KeyModifiers, read, poll}; use clipboard::{ClipboardProvider, ClipboardContext}; use crate::data::{App, InputMode, now_fmt, Message, MessageType, set_status, Peer, LogState...
}
match app.logging { LogState::Pending | LogState::Active => {} LogState::Inactive => { if let Err(_) = message_to_net(app, ToNet::LogStart) { show_error(app, "async thread not started".into()); return; } app.logging = LogSt...
if_condition
[ { "content": "pub fn message_to_net(app: &mut App, message: ToNet) -> Result<(), ()> {\n\n let state = app.lan_io.as_ref().ok_or(())?;\n\n if let Err(_) = state.to_lan.send(message) {\n\n app.lan_io = None;\n\n return Err(());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/network...
Rust
alvr/xtask/src/dependencies.rs
ccjuuc/ALVR
5265570d06c697de46cb5734884394f0d87b0d76
use crate::command; use alvr_filesystem as afs; use std::{error::Error, fs}; pub fn choco_install(package: &str) -> Result<(), Box<dyn Error>> { command::run_without_shell( "powershell", &[ "Start-Process", "choco", "-ArgumentList", &format!("\"instal...
use crate::command; use alvr_filesystem as afs; use std::{error::Error, fs}; pub fn choco_install(package: &str) -> Result<(), Box<dyn Error>> { command::run_without_shell( "powershell", &[ "Start-Process", "choco", "-ArgumentList", &format!("\"instal...
command::run_as_bash_in( &final_path, &format!( "./configure {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}", "--enable-gpl --enable-version3", "--disable-static --enable-shared", "--disable-programs", "--disable-doc", "--disable...
fn prepare_ffmpeg_windows() { let download_path = afs::deps_dir().join("windows"); command::download_and_extract_zip( &format!( "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/{}", "ffmpeg-n5.0-latest-win64-gpl-shared-5.0.zip" ), &download_path, ...
random
[ { "content": "pub fn dynlib_fname(name: &str) -> String {\n\n format!(\"{DLL_PREFIX}{name}{DLL_SUFFIX}\")\n\n}\n\n\n", "file_path": "alvr/filesystem/src/lib.rs", "rank": 1, "score": 303451.15232053905 }, { "content": "pub fn exec_fname(name: &str) -> String {\n\n format!(\"{name}{EXE_S...