lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/app.rs
storycraft/direct-share
a2145aa035464e484f9271d8f73503958c642972
/* * Created on Sat Feb 05 2022 * * Copyright (c) storycraft. Licensed under the MIT Licence. */ use std::{ error::Error, fmt::Display, net::SocketAddr, num::NonZeroU8, ops::RangeBounds, path::Path, sync::Arc, }; use hyper::{ header, server::conn::AddrStream, service::{make_service_fn, service...
/* * Created on Sat Feb 05 2022 * * Copyright (c) storycraft. Licensed under the MIT Licence. */ use std::{ error::Error, fmt::Display, net::SocketAddr, num::NonZeroU8, ops::RangeBounds, path::Path, sync::Arc, }; use hyper::{ header, server::conn::AddrStream, service::{make_service_fn, service...
async fn deliver_file<R: RangeBounds<u64>>(&self, path: &str, _: R) -> Response<Body> { let file_path = match self.path_map.get(path) { Some(file_path) => file_path, None => return self.not_found_page(), }; match File::open(file_path).await { Ok(file) =...
r, req: Request<Body>, ) -> hyper::Result<Response<Body>> { if req.method() != Method::GET { return Ok(self.not_found_page()); } let path = &req.uri().path()[1..]; log::info!("Received path: {} from {}", path, remote_addr); Ok(self.deliver_file(path, .....
function_block-function_prefixed
[ { "content": "fn gen_key(size: usize) -> String {\n\n const LIST: [char; 64] = [\n\n '_', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',\n\n 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',\n\n 'y', 'z', 'A', ...
Rust
src/lib.rs
finegeometer/four-dimensions
7a367f5799bd5c66e88f33732f9d8f012c67a618
#![forbid(unsafe_code)] mod fps; mod model; mod render; mod utils; mod world; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use model::{Model, Msg}; use std::cell::RefCell; use std::rc::Rc; #[wasm_bindgen] pub fn run() -> Result<(), JsValue> { std::panic::set_hook(Box::new(console_error_panic_hook::ho...
#![forbid(unsafe_code)] mod fps; mod model; mod render; mod utils; mod world; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use model::{Model, Msg}; use std::cell::RefCell; use std::rc::Rc; #[wasm_bindgen] pub fn run() -> Result<(), JsValue> { std::panic::set_hook(Box::new(console_error_panic_hook::ho...
f())?; closure.forget(); } { let state = state.clone(); let closure: Closure<dyn FnMut(web_sys::WheelEvent)> = Closure::wrap(Box::new(move |evt| { state .borrow_mut() .update(Msg::MouseWheel(evt.delta_y())) ...
function_block-function_prefixed
[ { "content": "pub fn make_fn(\n\n canvas: &web_sys::HtmlCanvasElement,\n\n) -> Result<\n\n impl 'static + Fn(&[render_4d::Triangle], to_tex::Mat4Wrapper) -> Result<(), JsValue>,\n\n JsValue,\n\n> {\n\n let gl = canvas\n\n .get_context(\"webgl2\")?\n\n .ok_or(\"\\\"webgl2\\\" context id...
Rust
src/live_data_reader.rs
danielwippermann/resol-vbus.rs
6df4b3ab7a68c191f643c110a8e57b72a10be788
use std::io::Read; use crate::{data::Data, error::Result, live_data_buffer::LiveDataBuffer}; #[derive(Debug)] pub struct LiveDataReader<R: Read> { buf: LiveDataBuffer, reader: R, } impl<R: Read> LiveDataReader<R> { pub fn new(channel: u8, reader: R) -> LiveDataReader<R> { LiveDataReader { ...
use std::io::Read; use crate::{data::Data, error::Result, live_data_buffer::LiveDataBuffer}; #[derive(Debug)] pub struct LiveDataReader<R: Read> { buf: LiveDataBuffer, reader: R, } impl<R: Read> LiveDataReader<R> { pub fn new(channel: u8, reader: R) -> LiveDataReader<R> { LiveDataReader { ...
= ldr.read_bytes().expect("No error"); assert_eq!(None, result); } #[test] fn test_read_data() { let channel = 0x11; let mut ldr = LiveDataReader::new(channel, LIVE_DATA_1); let data = ldr.read_data().unwrap().unwrap(); assert_eq!("11_0010_7E11_10_0100", data.id_s...
&mut self.reader } } #[cfg(test)] mod tests { use super::*; use crate::test_data::LIVE_DATA_1; #[test] fn test_read_bytes() { let mut ldr = LiveDataReader::new(0, LIVE_DATA_1); for expected_len in [172, 70, 16, 94, 16].iter() { let result = ldr.read_bytes().expect("...
random
[ { "content": "/// Stores a \"VBus channel marker\" record in the provided byte slice.\n\npub fn bytes_from_channel(channel: u8, buf: &mut [u8]) {\n\n bytes_from_record(0x77, 16, Utc.timestamp(0, 0), buf);\n\n buf[14] = channel;\n\n buf[15] = 0;\n\n}\n\n\n", "file_path": "src/recording_encoder.rs", ...
Rust
crypto/src/random.rs
provotum/provotum-mixnet
b9c7d56a2522c5a39519e0356acede7da396ba01
use crate::{ encryption::ElGamal, types::{Cipher, PublicKey}, }; use alloc::vec::Vec; use core::ops::{AddAssign, Sub}; use num_bigint::{BigUint, RandBigInt}; use num_traits::{One, Zero}; use rand::Rng; use std::boxed::Box; use std::panic; #[derive(Clone, Eq, PartialEq, Debug, Hash)] pub struct Random; impl Ra...
use crate::{ encryption::ElGamal, types::{Cipher, PublicKey}, }; use alloc::vec::Vec; use core::ops::{AddAssign, Sub}; use num_bigint::{BigUint, RandBigInt}; use num_traits::{One, Zero}; use rand::Rng; use std::boxed::Box; use std::panic; #[derive(Clone, Eq, PartialEq, Debug, Hash)] pub struct Random; impl Ra...
unwrap(); let is_prime = Random::is_prime(&number, 20); assert!(is_prime); } #[test] fn check_that_84532560_is_not_prime() { let number = BigUint::parse_bytes(b"84532560", 10).unwrap(); let is_prime = Random::is_prime(&number, 20); assert!(!is_prime); } #[te...
::get_random_less_than(q); let result = Self::catch_unwind_silent(|| ElGamal::encrypt(&nr, &r, pk)); if result.is_ok() { let enc = result.unwrap(); encryptions.push(enc.clone()); } i += 1u32; } encryptions } ...
random
[ { "content": "pub fn get_public_key<T: Trait>(vote_id: &VoteId) -> Result<SubstratePK, Error<T>> {\n\n PublicKey::get(vote_id).ok_or(Error::<T>::PublicKeyNotExistsError)\n\n}\n", "file_path": "node/pallets/mixnet/src/helpers/params.rs", "rank": 0, "score": 180629.38738463202 }, { "content...
Rust
necsim/impls/no-std/src/parallelisation/monolithic/averaging.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
use necsim_core::{ cogs::{ CoalescenceSampler, DispersalSampler, EventSampler, Habitat, LineageReference, LocallyCoherentLineageStore, PeekableActiveLineageSampler, RngCore, SpeciationProbability, TurnoverRate, }, reporter::Reporter, simulation::Simulation, }; use necsim_core_bon...
use necsim_core::{ cogs::{ CoalescenceSampler, DispersalSampler, EventSampler, Habitat, LineageReference, LocallyCoherentLineageStore, PeekableActiveLineageSampler, RngCore, SpeciationProbability, TurnoverRate, }, reporter::Reporter, simulation::Simulation, }; use necsim_core_bon...
ocal_partition.migrate_individuals( simulation.emigration_exit_mut(), MigrationMode::Default, MigrationMode::Default, ) { immigrant.event_time = immigrant .event_time .max(global_safe_time + independent_tim...
A: PeekableActiveLineageSampler< H, G, R, S, DomainEmigrationExit<H, O>, D, C, T, N, E, BufferedImmigrationEntry, >, P: Reporter, L: LocalPartition<P>, >( mut simulation: Simulation< H, G, ...
random
[ { "content": "#[contract_trait]\n\npub trait EmigrationExit<H: Habitat, G: RngCore, R: LineageReference<H>, S: LineageStore<H, R>>:\n\n crate::cogs::Backup + core::fmt::Debug\n\n{\n\n #[must_use]\n\n #[debug_ensures(match &ret {\n\n Some((\n\n ret_lineage_reference,\n\n ret...
Rust
src/day4.rs
glanham-jr/advent-code-2021
5ecfe29075160f1774fe0ac36a7997ba8e834650
use std::borrow::BorrowMut; use std::fs::File; use std::collections::hash_map::HashMap; use std::collections::hash_map::Entry; use std::io::{BufReader, BufRead}; #[derive(Copy, Clone)] struct BingoPosition { value: u16, row: usize, column: usize, checked: bool, } #[derive(Clone)] struct BingoGame { ...
use std::borrow::BorrowMut; use std::fs::File; use std::collections::hash_map::HashMap; use std::collections::hash_map::Entry; use std::io::{BufReader, BufRead}; #[derive(Copy, Clone)] struct BingoPosition { value: u16, row: usize, column: usize, checked: bool, } #[derive(Clone)] struct BingoGame { ...
pub fn p2_bingo() -> u16 { let bingo = &mut read_bingo(); let (result, mv) = _bingo(bingo, bingo.games.len()); let sum = result.board .values() .filter(|x| !x.checked) .map(|x| x.value) .sum::<u16>(); return sum * mv; }...
pub fn p1_bingo() -> u16 { let bingo = &mut read_bingo(); let (result, mv) = _bingo(bingo, 1); let sum = result.board .values() .filter(|x| !x.checked) .map(|x| x.value) .sum::<u16>(); return sum * mv; }
function_block-function_prefix_line
[ { "content": "fn read_file() -> BufReader<File> {\n\n let file_path = \"data/day5_hydrothermal_vents.txt\";\n\n let file = match File::open(file_path) {\n\n Ok(f) => f,\n\n Err(e) => panic!(\"Failed to open file: {:?}\", e),\n\n };\n\n return BufReader::new(file);\n\n}\n\n\n", "fi...
Rust
crates/mirror/src/main.rs
njeffords/cargo-proxy-mirror
8cb236087a10857c1a2c48d4a88ed22c5818b206
use std::{ sync::Arc, str::FromStr, convert::Infallible, net::SocketAddr, path::PathBuf, env }; use futures::{select, FutureExt}; use tokio::pin; use hyper::{Body, Request, Response, Server}; use hyper::service::{make_service_fn, service_fn}; use hyper::http::{Uri, Method,StatusCode}; use hyp...
use std::{ sync::Arc, str::FromStr, convert::Infallible, net::SocketAddr, path::PathBuf, env }; use futures::{select, FutureExt}; use tokio::pin; use hyper::{Body, Request, Response, Server}; use hyper::service::{make_service_fn, service_fn}; use hyper::http::{Uri, Method,StatusCode}; use hyp...
#[derive(Error,Display,Debug)] enum StreamError{ Unexpected } async fn proxy_download(proxy: ProxyRef, package: &str, version: &str, _cache_path: Option<PathBuf>) -> Result<Response<Body>,u16> { let mut stream = proxy.begin_download(package.into(), version.into()).await.map_err(|_|404u16)?; if let...
async fn download_cached(req: &Request<Body>, cache_path: PathBuf) -> Result<Response<Body>,u16> { let file = tokio::fs::File::open(cache_path).await.map_err(|_|500u16)?; let metadata = file.metadata().await.map_err(|_|500u16)?; FileResponseBuilder::new() .request(req) .build(file, metadata)...
function_block-full_function
[ { "content": "/// checks the provided package list for missing entries in the cache\n\nfn check_missing(cache_path: &Path, packages: &mut Vec<PackageId>) {\n\n packages.retain(|id| {\n\n let mut cache_path : PathBuf = cache_path.into();\n\n cache_path.push(&id.name);\n\n cache_path.push(...
Rust
src/session.rs
agoric-labs/tmkms
007c35552c8175c8eb5c7f0db1760c68965c88cc
use crate::{ amino_types::{ PingResponse, PubKeyRequest, PubKeyResponse, RemoteError, SignedMsgType, TendermintRequest, }, chain::{self, state::StateErrorKind, Chain}, config::ValidatorConfig, connection::{tcp, unix::UnixConnection, Connection}, error::{Error, ErrorKind::*}, prelud...
use crate::{ amino_types::{ PingResponse, PubKeyRequest, PubKeyResponse, RemoteError, SignedMsgType, TendermintRequest, }, chain::{self, state::StateErrorKind, Chain}, config::ValidatorConfig, connection::{tcp, unix::UnixConnection, Connection}, error::{Error, ErrorKind::*}, prelud...
if let Some(remote_err) = self.update_consensus_state(chain, &request)? { return Ok(request.build_response(Some(remote_err))); } let mut to_sign = vec![]; request.sign_bytes( self.config.chain_id.clone(), self.config.protocol_version, ...
let chain = registry .get_chain(&self.config.chain_id) .unwrap_or_else(|| { panic!("chain '{}' missing from registry!", &self.config.chain_id); });
assignment_statement
[ { "content": "/// Initialize the keyring from the configuration file\n\npub fn load_config(registry: &mut chain::Registry, config: &ProviderConfig) -> Result<(), Error> {\n\n #[cfg(feature = \"softsign\")]\n\n providers::softsign::init(registry, &config.softsign)?;\n\n\n\n #[cfg(feature = \"yubihsm\")]...
Rust
engine/src/algo/contraction_hierarchy/query.rs
pka/rust_road_router
2bef5b54ca2c85e82bceee852b13aa7ad28c6945
use super::*; pub struct Server { forward_dijkstra: StandardDijkstra<OwnedGraph>, backward_dijkstra: StandardDijkstra<OwnedGraph>, tentative_distance: Weight, meeting_node: NodeId, shortcut_middle_nodes: Option<(Vec<NodeId>, Vec<NodeId>)>, order: NodeOrder, } impl Server { pub fn new(ch:...
use super::*; pub struct Server { forward_dijkstra: StandardDijkstra<OwnedGraph>, backward_dijkstra: StandardDijkstra<OwnedGraph>, tentative_distance: Weight, meeting_node: NodeId, shortcut_middle_nodes: Option<(Vec<NodeId>, Vec<NodeId>)>, order: NodeOrder, } impl Server { pub fn new(ch:...
fn path(&self, query: Query) -> Vec<NodeId> { use std::collections::LinkedList; let &(ref forward_middle_nodes, ref backward_middle_nodes) = self.shortcut_middle_nodes.as_ref().unwrap(); let mut forwad_path = LinkedList::new(); forwad_path.push_front(self.meeting_node); ...
e = distance + self.forward_dijkstra.tentative_distance(node); self.meeting_node = node; } if node == from { backward_done = true; } } else { backward_done = true; ...
function_block-function_prefixed
[ { "content": "/// Utility function for preprocessing graphs with parallel edges.\n\n/// Will ensure, that all parallel edges have the lowest weight.\n\n/// Currently used to preprocess OSM graphs before CCH customization\n\n/// because the respecting will not necessarily use the parallel edge with the lowest we...
Rust
437_path_sum/path_sum.rs
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
/* * @Date: 2021-09-28 09:55:34 * @Author: Mengsen Wang * @LastEditors: Mengsen Wang * @LastEditTime: 2021-09-28 11:31:27 */ use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>,...
/* * @Date: 2021-09-28 09:55:34 * @Author: Mengsen Wang * @LastEditors: Mengsen Wang * @LastEditTime: 2021-09-28 11:31:27 */ use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>,...
let root = Some(Rc::new(RefCell::new(TreeNode { val: 5, left: Some(Rc::new(RefCell::new(TreeNode { val: 4, left: Some(Rc::new(RefCell::new(TreeNode { val: 11, left: Some(Rc::new(RefCell::new(TreeNode::new(7)))), ...
function_block-function_prefix_line
[ { "content": "pub fn self_dividing_numbers(left: i32, right: i32) -> Vec<i32> {\n\n (left..=right)\n\n .filter(|&n| {\n\n let mut x = n;\n\n while x > 0 {\n\n let digit = x % 10;\n\n if digit == 0 || n % digit != 0 {\n\n return fal...
Rust
src/accelerator/mod.rs
gillett-hernandez/rust-pathtracer
5ee181616fbca2cf0544e698baf13be74fc133f2
mod bvh; mod lbvh; pub use bvh::{BHShape, BVHNode, BoundingHierarchy, BVH}; pub use lbvh::FlatBVH; use crate::aabb::*; use crate::geometry::Instance; use crate::hittable::{HitRecord, Hittable}; use crate::math::*; #[derive(Clone, Copy, Debug)] pub enum AcceleratorType { List, BVH, } #[derive(Clone, Debug)] ...
mod bvh; mod lbvh; pub use bvh::{BHShape, BVHNode, BoundingHierarchy, BVH}; pub use lbvh::FlatBVH; use crate::aabb::*; use crate::geometry::Instance; use crate::hittable::{HitRecord, Hittable}; use crate::math::*; #[derive(Clone, Copy, Debug)] pub enum AcceleratorType { List, BVH, } #[derive(Clone, Debug)] ...
stances } => instances.get(index).unwrap(), Accelerator::BVH { instances, bvh: _ } => instances.get(index).unwrap(), } } }
hit < t0 || t0_aabb_hit > t1 { continue; } if t0_aabb_hit > closest_so_far { continue; } ...
random
[ { "content": "pub fn phase_hg(cos_theta: f32, g: f32) -> f32 {\n\n let denom = 1.0 + g * g + 2.0 * g * cos_theta;\n\n debug_assert!(\n\n denom > 0.0,\n\n \"1.0 + {:?} + {:?} == {:?}\",\n\n g * g,\n\n 2.0 * g * cos_theta,\n\n denom\n\n );\n\n (1.0 - g * g) / (denom ...
Rust
vendor/cfb-mode/src/lib.rs
wking/cincinna
a7e970ccb22153b8c250b96c95ac260f404afa7f
#![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" )] #![warn(missing_docs, rust_2018_idioms)] pub use cipher; use cipher::{ block::{BlockCipher, NewBlockCipher, Pa...
#![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" )] #![warn(missing_docs, rust_2018_idioms)] pub use cipher; use cipher::{ block::{BlockCipher, NewBlockCipher, Pa...
#[inline(always)] fn xor_set2(buf1: &mut [u8], buf2: &mut [u8]) { for (a, b) in buf1.iter_mut().zip(buf2) { let t = *a; *a ^= *b; *b = t; } }
fn xor_set1(buf1: &mut [u8], buf2: &mut [u8]) { for (a, b) in buf1.iter_mut().zip(buf2) { let t = *a ^ *b; *a = t; *b = t; } }
function_block-full_function
[]
Rust
execution_engine/src/core/engine_state/transfer.rs
HysMagus/casper-node
7001d2d72dd3d998749dc9a19258add093131764
use std::{cell::RefCell, rc::Rc}; use casper_types::{ account::AccountHash, AccessRights, ApiError, CLType, Key, RuntimeArgs, URef, U512, }; use crate::{ core::{ engine_state::Error, execution::Error as ExecError, tracking_copy::{TrackingCopy, TrackingCopyExt}, }, shared::{self...
use std::{cell::RefCell, rc::Rc}; use casper_types::{ account::AccountHash, AccessRights, ApiError, CLType, Key, RuntimeArgs, URef, U512, }; use crate::{ core::{ engine_state::Error, execution::Error as ExecError, tracking_copy::{TrackingCopy, TrackingCopyExt}, }, shared::{self...
l_value.cl_type() == CLType::FixedList(Box::new(CLType::U8), 32) => { let account_key: Key = { let hash = match cl_value.clone().into_t() { Ok(hash) => hash, Err(error) => { return Err(Error::Exec...
ror::Revert(error.into()))); } }; if !self.purse_exists(uref, correlation_id, tracking_copy) { return Err(Error::Exec(ExecError::Revert(ApiError::InvalidPurse))); } Ok(TransferTargetMode::PurseExists(uref)) ...
random
[ { "content": "#[doc(hidden)]\n\npub fn record_transfer(source: URef, target: URef, amount: U512) -> Result<(), ApiError> {\n\n let (source_ptr, source_size, _bytes1) = contract_api::to_ptr(source);\n\n let (target_ptr, target_size, _bytes2) = contract_api::to_ptr(target);\n\n let (amount_ptr, amount_si...
Rust
src/bot.rs
winks/cerith
2a8e9b91b288125b46fbe58d338ee667c56f8239
extern crate cerith; extern crate getopts; extern crate toml; use cerith::{IRCStream, get_version, Config, Server, Reaction, DEFAULT_PORT}; use getopts::Options; use std::env; use std::io::Read; use std::path::Path; use std::fs::File; use toml::Value; fn print_usage(program: &str, opts: Options) { let brief = for...
extern crate cerith; extern crate getopts; extern crate toml; use cerith::{IRCStream, get_version, Config, Server, Reaction, DEFAULT_PORT}; use getopts::Options; use std::env; use std::io::Read; use std::path::Path; use std::fs::File; use toml::Value; fn print_usage(program: &str, opts: Options) { let brief = for...
fn parse_reactions(val: &Value) -> Vec<Reaction> { let mut reactions = Vec::<Reaction>::new(); match val.get("reactions") { None => reactions, Some(xr) => { for (name, _section) in xr.as_table().unwrap() { let mut trigger = String::new(); let mut act...
g(), None => continue, }; let port = match a[1].as_str() { Some(s) => parse_int(s.to_string()), None => continue, }; let s = Server::new(host, port); servers.push(s); }...
function_block-function_prefixed
[ { "content": "pub fn get_version() -> String {\n\n format!(\"{} {}\", NAME, VERSION.unwrap_or(VERSION_NONE))\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Server {\n\n host: String,\n\n port: i32,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Reaction {\n\n trigger: String,\n\n action: String,\n...
Rust
src/lib.rs
Scratchcat1/pi-hole-api
7fddc1fd63ebc137dd747a2a66d029252ab840a0
use reqwest::{self}; use serde::{de::DeserializeOwned, Deserialize}; use simple_error; use std::collections::HashMap; use std::error::Error; use std::net::IpAddr; #[derive(Deserialize, Debug)] pub struct SummaryRaw { pub domains_being_blocked: u64, pub dns_queries_today: u64, pub ads_block...
use reqwest::{self}; use serde::{de::DeserializeOwned, Deserialize}; use simple_error; use std::collections::HashMap; use std::error::Error; use std::net::IpAddr; #[derive(Deserialize, Debug)] pub struct SummaryRaw { pub domains_being_blocked: u64, pub dns_queries_today: u64, pub ads_block...
async fn authenticated_json_request<T>(&self, path_query: &str) -> Result<T, Box<dyn Error>> where T: DeserializeOwned, { if self.api_key.is_none() { simple_error::bail!("API key is required for authenticated requests"); } let auth_path_query; match path...
T: DeserializeOwned, { let response = reqwest::get(&format!("{}{}", self.host, path_query)).await?; Ok(response.json().await?) }
function_block-function_prefix_line
[ { "content": "fn pi_hole_api_test_target() -> String {\n\n env::var(\"PI_HOLE_API_TEST_TARGET\").expect(\"Missing environmental var PI_HOLE_API_TEST_TARGET\")\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 0, "score": 31989.232811866917 }, { "content": "fn pi_hole_api_test_api_key() ...
Rust
crate2nix/src/lock.rs
JJJollyjim/crate2nix
7f9750f76cf08239b56b902d3df3538db9164553
use anyhow::{format_err, Error}; use cargo_metadata::PackageId; use serde::{de, ser, Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; use std::fmt; use std::path::Path; use std::str::FromStr; impl EncodableResolve { pub fn load_lock_file(path: &Path) -> Result<EncodableResolve, Error> { ...
use anyhow::{format_err, Error}; use cargo_metadata::PackageId; use serde::{de, ser, Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; use std::fmt; use std::path::Path; use std::str::FromStr; impl EncodableResolve { pub fn load_lock_file(path: &Path) -> Result<EncodableResolve, Error> { ...
} #[test] fn test_no_legacy_checksums() { let config = r#" [[package]] name = "aho-corasick" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] "#; let resolve = Encod...
if key.starts_with(CHECKSUM_PREFIX) { let package_id = PackageId { repr: key.trim_start_matches(CHECKSUM_PREFIX).to_string(), }; if value != "<none>" { hashes.insert(package_id, value.clone()); ...
function_block-function_prefix_line
[ { "content": "/// Returns the completed Source::CratesIo definition by prefetching the hash.\n\npub fn crates_io_source(name: String, version: Version) -> Result<config::Source, Error> {\n\n let prefetchable = CratesIoSource {\n\n name: name.clone(),\n\n version: version.clone(),\n\n sha...
Rust
examples/ism/src/main.rs
Nereuxofficial/radiate
bc2d9adf0f95f9c19560f74a665c598bdb1ac49f
extern crate csv; extern crate radiate; extern crate rayon; use radiate::prelude::*; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { rayon::ThreadPoolBuilder::new() .num_threads(8) .build_global() .unwrap(); let neat_env = NeatEnvironment::new() .set...
extern crate csv; extern crate radiate; extern crate rayon; use radiate::prelude::*; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { rayon::ThreadPoolBuilder::new() .num_threads(8) .build_global() .unwrap(); let neat_env = NeatEnvironment::new() .set...
{ nums.iter().fold(1000.0, |min, curr| { if curr[0] < min { return curr[0]; } min }) } fn maximum(nums: &[Vec<f32>]) -> f32 { nums.iter().fold(-1000.0, |max, curr| { if curr[0] > max { return curr[0]; ...
re: {}", num, fit); num == num_evolve })?; solution.train( &ism.inputs, &ism.answers, 0.00001, Loss::Diff, |epoch, loss| { let loss = loss.abs(); println!("epoch: {:?} loss: {:.5?}", epoch, loss); epoch == num_trai...
random
[ { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let thread_time = Instant::now();\n\n let (top, _) = Population::<Hello, HelloEnv, World>::new()\n\n .size(100)\n\n .populate_base()\n\n .dynamic_distance(true)\n\n .configure(Config {\n\n inbreed_rate: 0.00...
Rust
src/apps/user.rs
nyanpasu64/handlr
94e35e5f30b1ae8926fe038e16bfc316974e18e2
use crate::common::atomic_save::{ AtomicFile, AtomicSaveError, Durability, OverwriteBehavior, }; use crate::common::Handler; use crate::{Error, Result}; use mime::Mime; use once_cell::sync::Lazy; use pest::Parser; use std::collections::{HashMap, VecDeque}; use std::io::Read; use std::path::PathBuf; use std::str::Fr...
use crate::common::atomic_save::{ AtomicFile, AtomicSaveError, Durability, OverwriteBehavior, }; use crate::common::Handler; use crate::{Error, Result}; use mime::Mime; use once_cell::sync::Lazy; use pest::Parser; use std::collections::{HashMap, VecDeque}; use std::io::Read; use std::path::PathBuf; use std::str::Fr...
OverwriteBehavior::AllowOverwrite, Durability::DontSyncDir, ); af.write(|f| -> Result<()> { let mut writer = BufWriter::new(f); #[rustfmt::skip] let mut write_section = | title, items: &HashMap<Mime, VecDeque<Handler>>, ...
match ( Mime::from_str(name), current_section_name.as_str(), ) { (Ok(mime), "Added Associations") => { conf.added_associations.insert(mime, handlers) ...
random
[ { "content": "fn unalias_mime(db: &SharedMimeInfo, mime: &Mime) -> Mime {\n\n // unalias_mime_type() performs a linear scan over the list of aliases.\n\n // It should use a hashmap.\n\n if let Some(canonical) = db.unalias_mime_type(mime) {\n\n return canonical;\n\n } else {\n\n return ...
Rust
liblustreapi-sys/src/bindings.rs
AlexTalker/integrated-manager-for-lustre
251099e5c776f3c1898af50bb7cc77924c7cf7c7
/* automatically generated by rust-bindgen */ #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData, []) } #[inline] pu...
/* automatically generated by rust-bindgen */ #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData, []) } #[inline] pu...
fy!(lov_user_md_v1)) ); } impl Default for lov_user_md_v1 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C, packed)] pub struct lov_user_mds_data_v1 { pub lmd_st: lstat_t, pub lmd_lmm: lov_user_md_v1, } #[test] fn bindgen_test_layout_lov_user_mds_data_v1() { assert_e...
); assert_eq!( ::std::mem::align_of::<lov_user_md_v1>(), 1usize, concat!("Alignment of ", stringi
function_block-random_span
[ { "content": "/// Connect to the rabbitmq instance running on the IML manager\n\n///\n\n/// This fn is useful for production code as it reads in env vars\n\n/// to make a connection.\n\n///\n\npub fn connect_to_rabbit() -> impl TcpClientFuture {\n\n connect(\n\n &iml_manager_env::get_addr(),\n\n ...
Rust
src/errors.rs
Cypher1/Tako
a709df240ce27714fe5474419236049ac979dab5
use crate::ast::{Info, Node, Path}; use crate::primitives::Val; use crate::tokens::Token; use specs::Entity; use thiserror::Error; use derivative::Derivative; #[derive(Error, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Derivative)] #[derivative(Debug)] pub enum TError { #[error("unfinished conversion to cpp, ent...
use crate::ast::{Info, Node, Path}; use crate::primitives::Val; use crate::tokens::Token; use specs::Entity; use thiserror::Error; use derivative::Derivative; #[derive(Error, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Derivative)] #[derivative(Debug)] pub enum TError { #[error("unfinished conversion to cpp, ent...
}
if !first { write!(f, ", ")?; } else { first = false; } write!(f, "{}", v)?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "#[must_use]\n\npub fn path_to_string(path: PathRef) -> String {\n\n path.iter()\n\n .map(|p| format!(\"{}\", p))\n\n .collect::<Vec<String>>()\n\n .join(\".\")\n\n}\n\n\n\n//TODO: Remove the default instance.\n\n#[derive(Debug, Clone, PartialEq, Eq, Default)]\n\npub struct ...
Rust
src/lib.rs
davidkna/shadow-rs
ec6afa791458b8f7a8dc1a17a2376dacf3c561da
mod build; mod channel; mod ci; mod env; mod err; mod git; use build::*; use env::*; use git::*; use crate::ci::CIType; use std::collections::HashMap; use std::env as std_env; use std::fs::File; use std::io::Write; use std::path::Path; pub use channel::BuildRustChannel; use chrono::Local; pub use err::SdResult; ...
mod build; mod channel; mod ci; mod env; mod err; mod git; use build::*; use env::*; use git::*; use crate::ci::CIType; use std::collections::HashMap; use std::env as std_env; use std::fs::File; use std::io::Write; use std::path::Path; pub use channel::BuildRustChannel; use chrono::Local; pub use err::SdResult; ...
Create time by:{}"#, Local::now().format("%Y-%m-%d %H:%M:%S").to_string() ); writeln!(&self.f, "{}\n\n", desc)?; Ok(()) } fn write_const(&mut self, shadow_const: ShadowConst, val: ConstVal) -> SdResult<()> { let desc = format!("/// {}", val.desc); let (t, v...
Self::get_env(); let ci_type = shadow.try_ci(); let src_path = Path::new(src_path.as_str()); let mut map = new_git(&src_path, ci_type, &shadow.std_env); for (k, v) in new_project(&shadow.std_env) { map.insert(k, v); } for (k, v) in new_system_env(&shadow.std...
random
[ { "content": "pub fn new_system_env(std_env: &HashMap<String, String>) -> HashMap<ShadowConst, ConstVal> {\n\n let mut env = SystemEnv::default();\n\n env.map.insert(\n\n BUILD_OS,\n\n ConstVal {\n\n desc: \"display build system os\".to_string(),\n\n v: format!(\"{}-{}\...
Rust
src/lib.rs
PhotonQuantum/cutlass
88d35dc995283faef498e14fae4ac8dfa6b72d2f
extern crate proc_macro; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::punctuated::Punctuated; use syn::{parse_macro_input, Block, FnArg, ItemFn, Pat, ReturnType, Type}; #[proc_macro_attribute] pub fn curry(_attr: TokenStream, item: TokenStream) -> TokenStream { let parsed = parse_macro...
extern crate proc_macro; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::punctuated::Punctuated; use syn::{parse_macro_input, Block, FnArg, ItemFn, Pat, ReturnType, Type}; #[proc_macro_attribute] pub fn curry(_attr: TokenStream, item: TokenStream) -> TokenStream { let parsed = parse_macro...
fn extract_arg_types(fn_args: Punctuated<FnArg, syn::token::Comma>) -> Vec<Box<Type>> { return fn_args.into_iter().map(extract_type).collect::<Vec<_>>(); } fn extract_arg_idents(fn_args: Punctuated<FnArg, syn::token::Comma>) -> Vec<Box<Pat>> { return fn_args.into_iter().map(extract_arg_pat).collect::<Vec<_>>...
fn extract_return_type(a: ReturnType) -> Box<Type> { match a { ReturnType::Type(_, p) => p, _ => panic!("Not supported on functions without return types!"), } }
function_block-full_function
[ { "content": "#[test]\n\nfn add_works() {\n\n let plus_3 = add(1)(2);\n\n let v: Vec<u32> = (1..=3).map(plus_3).collect();\n\n assert_eq!(v, vec![4, 5, 6]);\n\n}\n", "file_path": "tests/smoke.rs", "rank": 9, "score": 18216.26588789376 }, { "content": "#[test]\n\nfn concat_works() {\...
Rust
src/api/private/add_order.rs
Fuzzy-Math/KrakenAPI-Rust
6656c265a743ba18766b19a5704950339557d944
use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use std::fmt::{self, Display}; use crate::auth::KrakenAuth; use super::{EndpointInfo, KAssetPair, KrakenInput, MethodType, OrderFlags, OrderType, TradeType}; use super::{Input, MutateInput, Output, UpdateInput}; pub enum Leverage { Two, ...
use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use std::fmt::{self, Display}; use crate::auth::KrakenAuth; use super::{EndpointInfo, KAssetPair, KrakenInput, MethodType, OrderFlags, OrderType, TradeType}; use super::{Input, MutateInput, Output, UpdateInput}; pub enum Leverage { Two, ...
pub fn with_volume(self, volume: f64) -> Self { self.update_input("volume", volume.to_string()) } pub fn with_leverage(self, leverage: Leverage) -> Self { self.update_input("leverage", format!("{}:{}", leverage.to_string(), 1u8)) } pub fn with_order_flags<T>(m...
fn with_price2(self, ordertype: &OrderType) -> Self { match ordertype.price2() { Some(price) => self.update_input("price2", price), None => self, } }
function_block-full_function
[ { "content": "/// Marker trait for output types that are returned from Kraken. Ensures that\n\n/// [KrakenClient][super::client::KrakenClient]'s [request][super::client::KrakenClient::request]\n\n/// method expects the correct output types\n\npub trait Output {}\n\n\n\n// This trait allows us to get a mutable r...
Rust
src/interfaces/object.rs
msorvig/windows-rs
bf5efbf4933e3e44ff9322735065fa88d64d281c
use crate::foundation::{IReference, IStringable, PropertyValue}; use crate::*; #[repr(transparent)] #[derive(Clone, PartialEq, Eq)] pub struct Object(IUnknown); impl Object { pub fn type_name(&self) -> Result<HString> { unsafe { let mut abi = std::ptr::null_mut(); (self.vtable...
use crate::foundation::{IReference, IStringable, PropertyValue}; use crate::*; #[repr(transparent)] #[derive(Clone, PartialEq, Eq)] pub struct Object(IUnknown); impl Object { pub fn type_name(&self) -> Result<HString> { unsafe { let mut abi = std::ptr::null_mut(); (self.vtable...
write!(f, "{:?} {}", self.0, name) } } macro_rules! primitive_boxed_type { ($(($t:ty, $m:ident)),+) => { $(impl std::convert::TryFrom<$t> for Object { type Error = Error; fn try_from(value: $t) -> Result<Self> { PropertyValue::$m(value) } ...
let name = self .cast::<IStringable>() .and_then(|s| s.to_string()) .or_else(|_| self.type_name()) .unwrap_or_default();
assignment_statement
[ { "content": "type DllGetActivationFactory = extern \"system\" fn(name: RawPtr, factory: *mut RawPtr) -> ErrorCode;\n\n\n\n/// Attempts to load and cache the factory interface for the given WinRT class. This is automatically\n\n// used by the generated bindings and should not generally be used directly.\n\npub ...
Rust
src/types/core.rs
Murgeye/imap-codec
fb7b5fc2358902383fbdbccdbc22bfa408305d91
use crate::{ codec::Encode, parse::core::{is_astring_char, is_atom_char, is_text_char}, utils::escape_quoted, }; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, convert::TryFrom, fmt, io::Write, string::FromUtf8Error}; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct ...
use crate::{ codec::Encode, parse::core::{is_astring_char, is_atom_char, is_text_char}, utils::escape_quoted, }; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, convert::TryFrom, fmt, io::Write, string::FromUtf8Error}; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct ...
for (from, expected) in tests.iter() { let cs = Charset::try_from(*from).unwrap(); println!("{}", cs); let mut out = Vec::new(); cs.encode(&mut out).unwrap(); assert_eq!(String::from_utf8(out).unwrap(), *expected); } assert!(Charset...
let tests = [ ("bengali", "bengali"), ("\"simple\" english", r#""\"simple\" english""#), ("", "\"\""), ("\"", "\"\\\"\""), ("\\", "\"\\\\\""), ];
assignment_statement
[ { "content": "/// Use this parser instead of command when doing authentication.\n\n///\n\n/// ```text\n\n/// Parsed here (because this is not parsed through command,\n\n/// ...
Rust
clippy_lints/src/manual_bits.rs
rsmantini/rust-clippy
6aa3684431e85609eab1168098915afcb4e20d65
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{get_parent_expr, meets_msrv, msrvs}; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind, GenericArg, QPath}; use rustc_lint::{LateContext, Late...
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{get_parent_expr, meets_msrv, msrvs}; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind, GenericArg, QPath}; use rustc_lint::{LateContext, Late...
fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>)> { if_chain! { if let ExprKind::Call(count_func, _func_args) = expr.kind; if let ExprKind::Path(ref count_func_qpath) = count_func.kind; if let QPath::Resolved(_, count_fu...
x>, expr1: &'tcx Expr<'_>, expr2: &'tcx Expr<'_>, ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>, &'tcx Expr<'tcx>)> { match (get_size_of_ty(cx, expr1), get_size_of_ty(cx, expr2)) { (Some((real_ty, resolved_ty)), None) => Some((real_ty, resolved_ty, expr2)), (None, Some((real_ty, resolved_...
function_block-function_prefixed
[ { "content": "#[must_use]\n\npub fn expr_visitor<'tcx>(cx: &LateContext<'tcx>, f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {\n\n struct V<'tcx, F> {\n\n hir: Map<'tcx>,\n\n f: F,\n\n }\n\n impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<'tcx, F> {\n\n...
Rust
src/codex/predictive.rs
edave64/ku
aa968056ae279abcbfeeb2c06c0c4867080772e1
use std::error::Error; use crate::errors::UnsolvableError; use crate::solver::board::Board; use crate::solver::solve::solve; use crate::tools::{BitReader, BitWriter}; struct PredictorBoard { board: [u8; 81], } impl PredictorBoard { fn possibilities(&self, i: u8) -> Vec<u8> { if self.board[i as usize] ...
use std::error::Error; use crate::errors::UnsolvableError; use crate::solver::board::Board; use crate::solver::solve::solve; use crate::tools::{BitReader, BitWriter}; struct PredictorBoard { board: [u8; 81], } impl PredictorBoard {
fn set(&mut self, i: u8, val: u8) { self.board[i as usize] = val; } } pub fn pattern_linear(i: u8) -> u8 { i } pub fn pattern_c2(i: u8) -> u8 { i * 2 % 81 } pub fn pattern_c4(i: u8) -> u8 { i * 4 % 81 } pub fn pattern_c8(i: u8) -> u8 { ((i as u32 * 8) % 81) as u8 } pub fn pattern_...
fn possibilities(&self, i: u8) -> Vec<u8> { if self.board[i as usize] != 0 { return vec![self.board[i as usize]]; } let row = (i / 9) * 9; let col = i % 9; let block = (row / 27) * 27 + col / 3 * 3; fn mask (val: u8) -> u16 { if val == 0 { return...
function_block-full_function
[ { "content": "pub fn solve(board: Board, prove_unique: bool) -> Result<Option<Board>, NonUniqueError> {\n\n let next = board.most_certain();\n\n match next {\n\n None => return Ok(Some(board)),\n\n Some((next_cell, possibilities)) => {\n\n let mut already_found = None;\n\n ...
Rust
treasure/src/valuables.rs
cjstehno/dmtools
5bfedc56ad901db11ac77a5a1a45a998ba979668
use std::collections::HashMap; use crate::treasure_definition::Tables; use crate::dice::DieRoll; #[derive(Debug, Deserialize)] pub struct ValuableObject { pub roll: String, pub description: String, } impl ValuableObject { fn select(table_path: &str, die_roll: u16) -> Option<ValuableObject> { trac...
use std::collections::HashMap; use crate::treasure_definition::Tables; use crate::dice::DieRoll; #[derive(Debug, Deserialize)] pub struct ValuableObject { pub roll: String, pub description: String, } impl ValuableObject { fn select(table_path: &str, die_roll: u16) -> Option<ValuableObject> { trac...
t MagicItem { pub description: String } impl Eq for MagicItem {} impl MagicItem { pub fn roll_magic(count: u16, table: &str, count_2: u16, table_2: &str) -> HashMap<MagicItem, u8> { let mut first_table = MagicItem::roll_magic_table(count, table); let second_table = MagicItem::roll_magic_table(...
None => () } } return gems; } else { HashMap::new() } } } #[derive(Debug, PartialEq, Hash)] pub struct Art { pub value: u16, pub description: String, } impl Eq for Art {} impl Art { pub fn roll_art(count: u16, value: u1...
random
[ { "content": "fn render_single(level: &str, party_size: u8, monsters: &Vec<Monster>, table: &mut Table){\n\n let party_level = level.parse::<u8>().expect(\"Unable to parse party level\");\n\n let rating = calculate_difficulty(party_level, party_size, &monsters);\n\n\n\n render(party_level, &rating, tab...
Rust
examples/profiler.rs
bitslab/compiler-interrupts-rs
1cd65f807f56c6e0d25161c24a0d1d02e0782cb2
#![feature(thread_local)] #[cfg(target_os = "linux")] mod profiler { use std::io::Write; use anyhow::{Context, Result}; use nanorand::{Rng, WyRand}; use nix::libc; use nix::sched::*; use nix::unistd::*; const BASE_VAL: i64 = 1_000_000; const MAX_THREADS: i64 = 2; static mut CI_INT...
#![feature(thread_local)] #[cfg(target_os = "linux")] mod profiler { use std::io::Write; use anyhow::{Context, Result}; use nanorand::{Rng, WyRand}; use nix::libc; use nix::sched::*; use nix::unistd::*; const BASE_VAL: i64 = 1_000_000; const MAX_THREADS: i64 = 2; static mut CI_INT...
fn log_intervals() -> Result<()> { unsafe { compiler_interrupts::deregister(); } let thread = std::thread::current(); let thread_name = thread.name().context("failed to get thread name")?; let filename = format!("{}_intervals.txt", thread_name); let l...
fn interrupt_handler(curr_ic: i64) { unsafe { let ic = curr_ic - prev_ic; if ic < 0 { panic!("IR count was negative: {}", ic); } let mut aux: u32 = 0; let curr_tsc = std::arch::x86_64::__rdtscp(&mut aux); let tsc = curr_tsc...
function_block-function_prefix_line
[ { "content": "fn rand() -> i32 {\n\n let mut rng = WyRand::new();\n\n rng.generate_range(0..i32::MAX)\n\n}\n\n\n", "file_path": "examples/demo.rs", "rank": 1, "score": 50324.606615748446 }, { "content": "fn increment() -> Result<()> {\n\n unsafe {\n\n println!(\"interval: {}\...
Rust
consensus/consensus-types/src/block_info.rs
kevinlewi/libra
d46a63f9ab663a065a5237c493c117abe64b0441
use crate::block::Block; use crypto::hash::HashValue; use failure::prelude::{Error, Result}; use libra_types::transaction::Version; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; pub type Round = u64; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct BlockInfo { epo...
use crate::block::Block; use crypto::hash::HashValue; use failure::prelude::{Error, Result}; use libra_types::transaction::Version; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; pub type Round = u64; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct BlockInfo { epo...
fn try_from(proto: network::proto::BlockInfo) -> Result<Self> { Ok(BlockInfo::new( proto.epoch, proto.round, HashValue::from_slice(&proto.id)?, HashValue::from_slice(&proto.executed_state_id)?, proto.version, proto.timestamp_usecs, ...
64 { self.epoch } pub fn executed_state_id(&self) -> HashValue { self.executed_state_id } pub fn id(&self) -> HashValue { self.id } pub fn round(&self) -> Round { self.round } pub fn timestamp_usecs(&self) -> u64 { self.timestamp_usecs } ...
random
[ { "content": "/// This produces a round that is often higher than the parent, but not\n\n/// too high\n\npub fn some_round(initial_round: Round) -> impl Strategy<Value = Round> {\n\n prop_oneof![\n\n 9 => Just(1 + initial_round),\n\n 1 => bigger_round(initial_round),\n\n ]\n\n}\n\n\n\nprop_c...
Rust
src/test/instruction_tests/instr_vcvttps2uqq.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vcvttps2uqq_1() { run_test( &Instruction { mnemonic: Mnemonic::VCVTTPS2UQQ, ...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vcvttps2uqq_1() { run_test( &Instruction { mnemonic: Mnemonic::VCVTTPS2UQQ, ...
operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 97, 125, 143, 120, 132, 241, 23, 73, 182, 122], ...
irect(XMM24)), operand2: Some(IndirectScaledIndexedDisplaced( RCX, RSI, Eight, 2058766615, Some(OperandSize::Qword), None, )),
random
[ { "content": "fn encode16_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
src/devices/bin/driver-index/src/resolved_driver.rs
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
use { anyhow::{self, Context}, bind::interpreter::{ common::BytecodeError, decode_bind_rules::{DecodedCompositeBindRules, DecodedRules}, match_bind::{match_bind, DeviceProperties, MatchBindData}, }, cm_rust::FidlIntoNative, fidl_fuchsia_component_decl as fdecl, fidl_fuchsia...
use { anyhow::{self, Context}, bind::interpreter::{ common::BytecodeError, decode_bind_rules::{DecodedCompositeBindRules, DecodedRules}, match_bind::{match_bind, DeviceProperties, MatchBindData}, }, cm_rust::FidlIntoNative, fidl_fuchsia_component_decl as fdecl, fidl_fuchsia...
pub fn matches( &self, properties: &DeviceProperties, ) -> Result<Option<fdf::MatchedDriver>, bind::interpreter::common::BytecodeError> { match &self.bind_rules { DecodedRules::Normal(rules) => { let matches = match_bind( MatchBindData { ...
uchsia_zircon::Status::INTERNAL })?; let mut base_url = component_url.clone(); base_url.set_fragment(None); let res = resolver .resolve(&base_url.as_str(), dir_server_end) .map_err(|e| { log::warn!("Resolve call failed: {}", e); ...
function_block-function_prefixed
[]
Rust
src/sync/mod.rs
LaudateCorpus1/ari
b01265230dec54b1608e6277d7be4b1a1957a11b
use parking_lot::{Condvar, Mutex}; use std::num::Wrapping; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; pub trait ResetEvent { fn reset(&self); fn set(&self); fn wait(&self); fn wait_until(&self, instant: Instant) -> bool;...
use parking_lot::{Condvar, Mutex}; use std::num::Wrapping; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; pub trait ResetEvent { fn reset(&self); fn set(&self); fn wait(&self); fn wait_until(&self, instant: Instant) -> bool;...
{ let mut value = self.value.lock(); value.id += Wrapping(1); value.signalled = true; self.condition.notify_all(); } fn wait(&self) { let mut value = self.value.lock(); let id = value.id; while !value.signalled && value.id == id { self.cond...
let mut value = self.value.lock(); while !*value { if self.condition.wait_until(&mut value, instant).timed_out() { return false; } } *value = false; true } } pub struct ManualResetEvent { value: Mutex<ManualResetEventData>, ...
random
[ { "content": "// returns true if the directory at `path` exists, and it is a directory.\n\npub fn directory_exists(path: impl AsRef<Path>) -> bool {\n\n match std::fs::metadata(path) {\n\n Ok(meta) => meta.is_dir(),\n\n Err(_) => false,\n\n }\n\n}\n\n\n\n\n", "file_path": "src/fs/mod.rs"...
Rust
sgx/indexmap-sgx-test/enclave/src/map.rs
mathias-arm/indexmap
7c819fc20e43da92d201d7badc322ef7f654b844
use indexmap::*; use indexmap::map::*; use crate::util::enumerate; use std::prelude::v1::*; pub fn it_works() { let mut map = IndexMap::new(); assert_eq!(map.is_empty(), true); map.insert(1, ()); map.insert(1, ()); assert_eq!(map.len(), 1); assert!(map.get(&1).is_some()); assert_eq!(map.is_...
use indexmap::*; use indexmap::map::*; use crate::util::enumerate; use std::prelude::v1::*; pub fn it_works() { let mut map = IndexMap::new(); assert_eq!(map.is_empty(), true); map.insert(1, ()); map.insert(1, ()); assert_eq!(map.len(), 1); assert!(map.get(&1).is_some()); assert_eq!(map.is_...
ert_eq!(e.index(), 2); let e = e.or_insert("3"); assert_eq!(e, &"3"); } let e = map.entry(2); assert_eq!(e.index(), 1); assert_eq!(e.key(), &2); match e { Entry::Occupied(ref e) => assert_eq!(e.get(), &"2"), Entry::Vacant(_) => panic!() } assert_eq!(e.or_...
i + 1); assert_eq!(map.get(&elt), Some(&elt)); assert_eq!(map[&elt], elt); } println!("{:?}", map); for &elt in &not_present { assert!(map.get(&elt).is_none()); } } pub fn insert_full() { let insert = vec![9, 2, 7, 1, 4, 6, 13]; let present = vec![1, 6, 2]; let mut...
random
[ { "content": "//#[test]\n\npub fn new() {\n\n let set = IndexSet::<String>::new();\n\n println!(\"{:?}\", set);\n\n assert_eq!(set.capacity(), 0);\n\n assert_eq!(set.len(), 0);\n\n assert_eq!(set.is_empty(), true);\n\n}\n\n\n", "file_path": "sgx/indexmap-sgx-test/enclave/src/set.rs", "ran...
Rust
src/consumer.rs
AnickaBurova/rabbit_auto
91b5b564f8c8c565cfa81b8a016f47a1037c4040
use core::pin::Pin; use futures::{ future::Future, stream::Stream, task::{Context, Poll}, }; use lapin::{message::Delivery, Channel, Consumer}; use anyhow::Result; use super::comms::*; pub type ConsumerCreator = Creator<(Channel, Consumer)>; type NextFuture = Pin< Box< dyn Future< ...
use core::pin::Pin; use futures::{ future::Future, stream::Stream, task::{Context, Poll}, }; use lapin::{message::Delivery, Channel, Consumer}; use anyhow::Result; use super::comms::*; pub type ConsumerCreator = Creator<(Channel, Consumer)>; type NextFuture = Pin< Box< dyn Future< ...
log::error!("Failed to consume a message: {}", err); } None => { log::error!("Consumer has finished for some reason!"); } } log::warn!("Recreating the consumer"); let (cr, (chan, cons)) = Self::connect(creator).await...
log::debug!("Got delivery"); return (delivery, consumer, channel, creator); } Some(Err(err)) => {
random
[ { "content": "enum State {\n\n /// Configured, but not connected at least once\n\n Configured {\n\n config: Config,\n\n },\n\n /// Connected and running\n\n Connected {\n\n config: Config,\n\n connection: Connection,\n\n },\n\n}\n\n\n\n/// RabbitMQ connection singleton\n\n...
Rust
src/cocoa_colors.rs
MoAlyousef/cocoa-colors
cdb4e2f6b376dea40e65cd3bf945dcf9728cb939
/* automatically generated by rust-bindgen 0.57.0 */ extern "C" { pub fn get_windowBackgroundColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_labelColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_controlBackgroundColor(r: *mut f64, g: ...
/* automatically generated by rust-bindgen 0.57.0 */ extern "C" { pub fn get_windowBackgroundColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_labelColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_controlBackgroundColor(r: *mut f64, g: ...
b fn get_systemPurpleColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_systemRedColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_systemTealColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_systemYellowC...
erTexturedBackgroundColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_windowFrameTextColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get_underPageBackgroundColor(r: *mut f64, g: *mut f64, b: *mut f64, a: *mut f64); } extern "C" { pub fn get...
random
[ { "content": "#[cfg(target_os = \"macos\")]\n\nfn main() {\n\n let mut build = cc::Build::new();\n\n build.file(\"src/cocoa_colors.m\");\n\n build.compile(\"cocoa_colors\");\n\n}\n\n\n", "file_path": "build.rs", "rank": 0, "score": 31610.874595785204 }, { "content": "#[cfg(not(targe...
Rust
Day20-25/day25.rs
bcongdon/advent_of_code_2019
36400195d6919f3c48f523504275b718304ec99a
use std::collections::VecDeque; use std::fs::File; use std::io::prelude::*; use std::io::{self, Read}; use std::iter; use std::path::Path; #[derive(Debug)] struct VM { state: Vec<i64>, pc: usize, input: Vec<i64>, output: Vec<i64>, halted: bool, relative_base: i64, waiting_for_input: bool, }...
use std::collections::VecDeque; use std::fs::File; use std::io::prelude::*; use std::io::{self, Read}; use std::iter; use std::path::Path; #[derive(Debug)] struct VM { state: Vec<i64>, pc: usize, input: Vec<i64>, output: Vec<i64>, halted: bool, relative_base: i64, waiting_for_input: bool, }...
fn get_write_location(&mut self, code: i64, num_params: i64) -> usize { let mode = (code % 10_i64.pow(2 + num_params as u32)) / (10_i64.pow(1 + num_params as u32)); let p = self.next_value() as usize; let pos = match mode { 0 => p, 2 => ((p...
e]), _ => panic!("Invalid mode: {}", mode), } } params }
function_block-function_prefixed
[ { "content": "fn is_affected(inp: &Vec<i64>, x: i64, y: i64) -> bool {\n\n let mut vm = VM::new(inp.to_vec());\n\n vm.push_input(x);\n\n vm.push_input(y);\n\n vm.run_until_output().unwrap_or(0) == 1\n\n}\n\n\n", "file_path": "Day10-19/day19.rs", "rank": 0, "score": 163580.60983943494 }...
Rust
http/src/request/guild/member/search_guild_members.rs
Learath2/twilight
8791dc606a5d1ab2fa13faef8e668a010e16ac63
use crate::{ client::Client, error::Error as HttpError, request::{validate, Pending, Request}, routing::Route, }; use hyper::body::Bytes; use serde::de::DeserializeSeed; use std::{ error::Error, fmt::{Display, Formatter, Result as FmtResult}, future::Future, pin::Pin, task::{Context,...
use crate::{ client::Client, error::Error as HttpError, request::{validate, Pending, Request}, routing::Route, }; use hyper::body::Bytes; use serde::de::DeserializeSeed; use std::{ error::Error, fmt::{Display, Formatter, Result as FmtResult}, future::Future, pin::Pin, task::{Context,...
}
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { if self.fut.is_none() { self.as_mut().start()?; } let fut = self.fut.as_mut().expect("future is created"); match fut.as_mut().poll(cx) { Poll::Ready(res) => { let byt...
function_block-full_function
[ { "content": "type PendingOption<'a> = Pin<Box<dyn Future<Output = Result<Bytes, Error>> + Send + 'a>>;\n\n\n\n/// Request method.\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\n\n#[non_exhaustive]\n\npub enum Method {\n\n /// DELETE method.\n\n Delete,\n\n /// GET method.\n\n Get,\n\n //...
Rust
src/data.rs
aftershootco/libexif-rs
d65fe4078f62619a03a998cbc6951797c8c7ed4a
use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::slice; use crate::bindings::*; use crate::bits::*; use crate::content::Content; use crate::entry::Entry; use crate::error::ExifError; use crate::internal::*; use crate::loader::Loader; use crate::value::Value; pub const EXIF_HEADER...
use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::slice; use crate::bindings::*; use crate::bits::*; use crate::content::Content; use crate::entry::Entry; use crate::error::ExifError; use crate::internal::*; use crate::loader::Loader; use crate::value::Value; pub const EXIF_HEADER...
pub fn write( &mut self, old_buffer: impl AsRef<[u8]>, to: impl AsRef<Path>, ) -> Result<(), ExifError> { let mut exif_data: *mut u8 = std::ptr::null_mut(); let mut exif_data_len: u32 = 0; unsafe { exif_data_fix(self.inner); exif_data_sav...
from_file( &mut self, from: impl AsRef<Path>, to: impl AsRef<Path>, ) -> Result<(), ExifError> { let old_buffer = std::fs::read(from)?; self.write(old_buffer, to) }
function_block-function_prefixed
[ { "content": "fn extract_text(raw_data: &[u8], components: usize, byte_order: ByteOrder) -> String {\n\n let mut vec = extract_vec::<u8>(raw_data, components, byte_order, get_u8);\n\n\n\n let cstring = unsafe {\n\n let len = libc::strlen(vec.as_ptr() as *const c_char);\n\n vec.set_len(len);\...
Rust
src/k8s_utils.rs
stackabletech/operator-rs
34639c05b842392539036bc2a37f096c9e27d9c8
use crate::pod_utils; use k8s_openapi::api::core::v1::{Node, Pod}; use rand::prelude::SliceRandom; use std::collections::BTreeMap; pub type LabelOptionalValueMap = BTreeMap<String, Option<String>>; pub fn find_excess_pods<'a>( nodes_and_required_labels: &[(Vec<Node>, LabelOptionalValueMap, Option<u16>)], exis...
use crate::pod_utils; use k8s_openapi::api::core::v1::{Node, Pod}; use rand::prelude::SliceRandom; use std::collections::BTreeMap; pub type LabelOptionalValueMap = BTreeMap<String, Option<String>>; pub fn find_excess_pods<'a>( nodes_and_required_labels: &[(Vec<Node>, LabelOptionalValueMap, Option<u16>)], exis...
alid_pods_for_nodes() { let nodes = vec![ builder::NodeBuilder::new().name("foobar").build(), builder::NodeBuilder::new().name("barfoo").build(), ]; let existing_pods = vec![PodBuilder::new() .node_name("foobar") .metadata_default() ...
; } } } used_pods } pub fn find_valid_pods_for_nodes<'a>( candidate_nodes: &[Node], existing_pods: &'a [Pod], required_labels: &LabelOptionalValueMap, ) -> Vec<&'a Pod> { existing_pods .iter() .filter(|pod| pod_utils::pod...
random
[ { "content": "/// This method checks if a Pod contains all required labels including an optional value per label.\n\n///\n\n/// # Arguments\n\n///\n\n/// - `pod` - the Pod to check for labels\n\n/// - `required_labels` - is a BTreeMap of label keys to an optional value\n\n///\n\n/// # Example\n\n///\n\n/// ```\...
Rust
tests/search.rs
regular-pv/automatic-relations
c2d1918bdfae3125b2acf1f0ccad6bebf614429c
#[macro_use] extern crate terms; #[macro_use] extern crate tree_automata as ta; extern crate automatic_relations as automatic; use std::cell::Cell; use std::cmp::Ord; use std::collections::HashSet; use terms::{ Term, Pattern, Var, variable::{ Spawnable, Family, Parented } }; use ta::{ Symbol, State,...
#[macro_use] extern crate terms; #[macro_use] extern crate tree_automata as ta; extern crate automatic_relations as automatic; use std::cell::Cell; use std::cmp::Ord; use std::collections::HashSet; use terms::{ Term, Pattern, Var, variable::{ Spawnable, Family, Parented } }; use ta::{ Symbol, State,...
#[test] fn non_linear1() { let n = Rank("n", 2); let zero = Rank("0", 0); let tree = "tree"; let mut types = automaton! { n(tree, tree) -> tree, zero -> tree, finals tree }; let eq_types = aligned::Convolution::equality(&types, 2); let namespace = Cell::new...
fn linear_impossible1() { let s = Rank("s", 1); let zero = Rank("0", 0); let nat = "nat"; let mut types = automaton! { s(nat) -> nat, zero -> nat, finals nat }; let eq_types = aligned::Convolution::equality(&types, 2); let namespace = Cell::new(0); let x:...
function_block-function_prefix_line
[ { "content": "fn assert_multi_search<F: Ranked + Symbol + Ord, Q: State, X: Family + Ord>(automata: &[&Automaton<Rank<Convoluted<F>>, Q, NoLabel>], mut patterns: Vec<Vec<Pattern<F, X>>>, mut expected_output: Vec<Vec<Term<Rank<Convoluted<F>>>>>) {\n\n\t// prepare the patterns.\n\n\tlet convoluted_patterns = patt...
Rust
codeforces/round-766-d2/src/bin/e.rs
Avanta8/rust-competitive-programming
1c41936e81f4d2a55144818cf326a29ce119b8c2
#![allow( unused_imports, clippy::many_single_char_names, clippy::comparison_chain, clippy::if_same_then_else, clippy::if_not_else, clippy::ifs_same_cond, clippy::type_complexity, clippy::collapsible_if, clippy::collapsible_else_if )] use std::cmp::*; use std::collections::*; pub s...
#![allow( unused_imports, clippy::many_single_char_names, clippy::comparison_chain, clippy::if_same_then_else, clippy::if_not_else, clippy::ifs_same_cond, clippy::type_complexity, clippy::collapsible_if, clippy::collapsible_else_if )] use std::cmp::*; use std::collections::*; pub s...
pub fn main() { let mut sc = IO::new(std::io::stdin(), std::io::stdout()); for _ in 0..sc.read() { let height = sc.read(); let width = sc.read(); let num_ladders = sc.read(); let penalty = sc.vec(height); let ladders = (0..num_ladders) .map(|_| { ...
inue; } for (&sx, map) in room_ladders[row].iter() { let dist = rows[row].get(sx).unwrap(); for &((ex, ey), h) in map { rows[ey].insert(ex, dist - h); } } } rows[height - 1].get(width - 1) }
function_block-function_prefixed
[ { "content": "pub fn gcd(mut a: i64, mut b: i64) -> i64 {\n\n while b != 0 {\n\n a %= b;\n\n std::mem::swap(&mut a, &mut b);\n\n }\n\n a.abs()\n\n}\n\n\n", "file_path": "template/src/math/gcd.rs", "rank": 0, "score": 123218.30787403631 }, { "content": "pub fn pow(mut a...
Rust
devand-web/src/api.rs
vishalsodani/devand
0681fb2dbbca4609a12b94f5b221a38b439246ed
use crate::auth::{AuthData, LoggedUser}; use crate::{CodeNowUsers, Mailer, PgDevandConn, WeekScheduleMatrix}; use chrono::prelude::*; use chrono::Duration; use devand_core::schedule_matcher::AvailabilityMatch; use devand_core::{User, UserAffinity, UserId}; use rocket::http::Status; use rocket::{Route, State}; use rocke...
use crate::auth::{AuthData, LoggedUser}; use crate::{CodeNowUsers, Mailer, PgDevandConn, WeekScheduleMatrix}; use chrono::prelude::*; use chrono::Duration; use devand_core::schedule_matcher::AvailabilityMatch; use devand_core::{User, UserAffinity, UserId}; use rocket::http::Status; use rocket::{Route, State}; use rocke...
#[post("/password-edit", data = "<passwords>")] fn password_edit( auth_data: AuthData, conn: PgDevandConn, passwords: Json<devand_core::PasswordEdit>, ) -> Result<(), Status> { let ok = devand_db::auth::check_password(auth_data.user_id, &passwords.0.old_password, &conn) .map_err(|_| Status::In...
thData, conn: PgDevandConn, passwords: Json<devand_core::PasswordEdit>, ) -> Option<Json<bool>> { let ok = devand_db::auth::check_password(auth_data.user_id, &passwords.0.old_password, &conn) .ok()?; Some(Json(ok)) }
function_block-function_prefixed
[ { "content": "pub fn check_password(user_id: UserId, password: &str, conn: &PgConnection) -> Result<bool, Error> {\n\n let enc_password: String = schema::auth::table\n\n .filter(schema::auth::dsl::user_id.eq(user_id.0))\n\n .select(schema::auth::enc_password)\n\n .first(conn)\n\n ...
Rust
dessin/src/contrib/textbox.rs
daedalus-aero-space/drawing
2d67b74807fbd10f52573f415e91550e79f4d464
use crate::{ shape::Style, shapes::text::{FontWeight, Text, TextAlign}, Drawing, Rect, Shape, }; use algebr::{vec2, Vec2}; use rusttype::{Font, Scale}; #[derive(Debug, Clone, PartialEq)] pub struct TextLayout { pub(crate) text: String, pub(crate) pos: Rect, pub(crate) boxes: Vec<TextBox>, } cra...
use crate::{ shape::Style, shapes::text::{FontWeight, Text, TextAlign}, Drawing, Rect, Shape, }; use algebr::{vec2, Vec2}; use rusttype::{Font, Scale}; #[derive(Debug, Clone, PartialEq)] pub struct TextLayout { pub(crate) text: String, pub(crate) pos: Rect, pub(crate) boxes: Vec<TextBox>, } cra...
text.push(' '); let mut pos = Vec2::zero(); let mut box_idx = 0; let mut acc = String::new(); let mut canvas = Rect::new(); let mut drawing = Drawing::empty(); for line in text.split("\n") { for word in line.split(" ").chain(Some("\n")) { ...
fn length_of(word: &str, font: Font, scale: f32) -> f32 { let scale = Scale::uniform(scale); font.glyphs_for(word.chars()) .scan(None, |last, g| { let pos = if let Some(last) = last { font.pair_kerning(scale, *last, g.clone().id()) ...
function_block-full_function
[ { "content": "fn point(v: Vec2) -> Point {\n\n Point::new(Mm(v.x as f64), Mm(v.y as f64))\n\n}\n\n\n", "file_path": "dessin-pdf/src/shapes.rs", "rank": 0, "score": 91800.58019543756 }, { "content": "pub fn embedded(dessin: Drawing) -> Drawing {\n\n let mut parent = Drawing::empty().wit...
Rust
src/builder/edit_message.rs
mkrasnitski/serenity
5eb6118ff7dfe0d801dab43225a5fedad9dfb913
use std::collections::HashMap; use super::{CreateAllowedMentions, CreateEmbed}; use crate::builder::CreateComponents; use crate::internal::prelude::*; use crate::json::{self, from_number}; use crate::model::channel::{AttachmentType, MessageFlags}; use crate::model::id::AttachmentId; #[derive(Clone, Debug, Default)] p...
use std::collections::HashMap; use super::{CreateAllowedMentions, CreateEmbed}; use crate::builder::CreateComponents; use crate::internal::prelude::*; use crate::json::{self, from_number}; use crate::model::channel::{AttachmentType, MessageFlags}; use crate::model::id::AttachmentId; #[derive(Clone, Debug, Default)] p...
pub fn add_embeds(&mut self, embeds: Vec<CreateEmbed>) -> &mut Self { for embed in embeds { self._add_embed(embed); } self } pub fn embed<F>(&mut self, f: F) -> &mut Self where F: FnOnce(&mut CreateEmbed) -...
teEmbed, { let mut embed = CreateEmbed::default(); f(&mut embed); self._add_embed(embed) }
function_block-function_prefixed
[ { "content": "/// Renames all attributes that have a specific `name` to the `target`.\n\npub fn rename_attributes(attributes: &mut Vec<Attribute>, name: &str, target: &str) {\n\n for attr in attributes {\n\n if attr.path.is_ident(name) {\n\n attr.path = Path::from(PathSegment::from(Ident::n...
Rust
webserver/src/function.rs
kvsari/sammy
f5d2fb77ab32d1fc32bc64d4edf964d916c371a7
use chrono::Utc; use model::TicksRequest; pub fn prepare_folder_requests( folder_url: &str, ticks_request: &TicksRequest, ) -> Vec<String> { let from = *ticks_request.from(); let to = ticks_request .to() .unwrap_or(Utc::now().timestamp() as u64); let span = *ticks_request.span(...
use chrono::Utc; use model::TicksRequest; pub fn prepare_folder_requests( folder_url: &str, ticks_request: &TicksRequest, ) -> Vec<String> { let from = *ticks_request.from(); let to = ticks_request .to() .unwrap_or(Utc::now().timestamp() as u64); let span = *ticks_request.span(...
#[test] fn generate_one_correct_link() { let req = TicksRequest::_new( exchange::Exchange::Binance, asset::BTC_USD, 10, Some(11), 1 ); let params = prepare_folder_requests("host", &req); assert!(params.len() == 1); ...
asset::BTC_USD, 10, Some(11), 0 ); let params = prepare_folder_requests("y", &req); assert!(params.is_empty()); }
function_block-function_prefix_line
[ { "content": "pub fn ticks_last_24h_10_min_spans(\n\n req: &HttpRequest<ServerState>,\n\n) -> Box<Future<Item = HttpResponse, Error = error::Error>> {\n\n let now: DateTime<Utc> = Utc::now();\n\n let mut minutes = 1440;\n\n\n\n let state = req.state();\n\n let folder_url = state.folder_url.clone(...
Rust
src/events.rs
dakom/dominator-helpers
e1ec52fe658dae70c28f1db10dd89ce47b80b607
#[macro_export] macro_rules! temp_make_event { ($name:ident, $type:literal => $event:path) => { pub struct $name { event: $event, } impl dominator::traits::StaticEvent for $name { const EVENT_TYPE: &'static str = $type; #[inline] fn unche...
#[macro_export] macro_rules! temp_make_event { ($name:ident, $type:literal => $event:path) => { pub struct $name { event: $event, } impl dominator::traits::StaticEvent for $name { const EVENT_TYPE: &'static str = $type; #[inline] fn unche...
.unwrap_throw() } } temp_make_event!(Load, "load" => web_sys::Event); #[macro_export] macro_rules! make_custom_event { ($name:ident, $type:literal) => { $crate::temp_make_event!($name, $type => web_sys::CustomEvent); impl $name { pub fn detail(&self) -> JsValue { self.event.detail(...
ub fn dyn_target<A>(&self) -> Option<A> where A: wasm_bindgen::JsCast, { use wasm_bindgen::JsCast; self.target()?.dyn_into().ok() } } }; } temp_make_event!(Message, "message" => web_sys::MessageEvent); impl Message { pu...
random
[ { "content": "/// Helper to create Rc signal-factories (same idea as box_signal_fn but cloneable)\n\npub fn rc_signal_fn<T, S: Signal<Item = T> + 'static>(f: impl Fn() -> S + 'static) -> RcSignalFn<T> {\n\n Rc::new(move || {\n\n Box::pin(f())\n\n })\n\n}\n\n/*\n\n * These all generally solving the ...
Rust
src/driver.rs
Kixiron/cranial-coitus
2f0b158709b23f23a4d84045846829b250779f31
use crate::{ args::Settings, graph::Rvsdg, interpreter::{EvaluationError, ExecutionStats, Machine}, ir::{Block, IrBuilder, Pretty, PrettyConfig}, lower_tokens, parse::{self, Parsed, Token}, passes::{self, PassConfig}, utils::{HashMap, HashSet, PerfEvent}, values::{Cell, Ptr}, }; use ...
use crate::{ args::Settings, graph::Rvsdg, interpreter::{EvaluationError, ExecutionStats, Machine}, ir::{Block, IrBuilder, Pretty, PrettyConfig}, lower_tokens, parse::{self, Parsed, Token}, passes::{self, PassConfig}, utils::{HashMap, HashSet, PerfEvent}, values::{Cell, Ptr}, }; use ...
, ); pretty_printed }; if let Some(dump_dir) = dump_dir { tracing::debug!("dumping sequentialized graph to '{}'", dump_dir.display()); fs::write(dump_dir, &program_ir).with_context(|| { format!( "failed to write sequentialized graph to '{}'", ...
n {:#?}", file, elapsed, ); tokens } #[tracing::instrument(skip(input, output, program))] pub fn execute<I, O>( step_limit: usize, tape_len: u16, input: I, output: O, should_profile: bool, program: &mut Block, ) -> ( Result<(), EvaluationError>, Vec<u8>, Exe...
random
[ { "content": "fn run(settings: &Settings, file: &Path, start_time: Instant) -> Result<()> {\n\n let step_limit = settings.step_limit();\n\n let contents = fs::read_to_string(file).expect(\"failed to read file\");\n\n\n\n let mut graph = {\n\n let span = tracing::info_span!(\"parsing\");\n\n ...
Rust
device-management-service/src/service/mod.rs
jcrossley3/drogue-cloud
d03ef5e1fe515f53f9a50d23e71535bef04d6e86
pub mod admin; mod error; pub mod management; mod utils; mod x509; use crate::{service::error::PostgresManagementServiceError, utils::epoch}; use deadpool_postgres::{Pool, Transaction}; use drogue_client::{registry, Translator}; use drogue_cloud_database_common::{ auth::ensure, error::ServiceError, models:...
pub mod admin; mod error; pub mod management; mod utils; mod x509; use crate::{service::error::PostgresManagementServiceError, utils::epoch}; use deadpool_postgres::{Pool, Transaction}; use drogue_client::{registry, Translator}; use drogue_cloud_database_common::{ auth::ensure, error::ServiceError, models:...
}
events: &[Event], ) -> Result<(), PostgresManagementServiceError<E>> where E: std::error::Error + std::fmt::Debug + 'static, { events .to_vec() .send_with(&PostgresOutboxAccessor::new(client)) .await .map_err(Self::outbox_err) }
function_block-function_prefix_line
[ { "content": "pub trait Key: Clone + Debug + Send + Sync + 'static {\n\n fn to_string(&self) -> String;\n\n fn from_string(s: String) -> Result<Self, ()>;\n\n}\n\n\n\nimpl Key for String {\n\n fn to_string(&self) -> String {\n\n ToString::to_string(self)\n\n }\n\n\n\n fn from_string(s: Str...
Rust
src/cargo_proj.rs
dan-t/cargo-release
47fce48a4c09969df73e71f0b9217f15507255ae
use std::fs; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use toml; use semver::Version; use rr_result::RrResult; use utils::{modify_file, map_file}; #[derive(Debug)] pub struct CargoProj { name: String, version: Version, cargo_toml: PathBuf, changelog: Option<PathBuf> } ...
use std::fs; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use toml; use semver::Version; use rr_result::RrResult; use utils::{modify_file, map_file}; #[derive(Debug)] pub struct CargoProj { name: String, version: Version, cargo_toml: PathBuf, changelog: Option<PathBuf> } ...
to_str).map(str::to_lowercase) { if base_name == "changelog" { return Ok(Some(file)); } } } Ok(None) } fn parse_toml(path: &Path) -> RrResult<toml::Value> { map_file(path, |contents| { let val = contents.parse::<toml::Value>()?; Ok(val) }...
.ok_or(format!("Couldn't get 'version' string from: {:?}", package))?; Version::parse(version_str)? }; let changelog = find_changelog(&cargo_dir)?; Ok(CargoProj { name: name.to_string(), version: version, cargo_toml: cargo_toml, ...
random
[ { "content": "pub fn tag(name: &str) -> RrResult<()> {\n\n let output = Command::new(\"git\")\n\n .arg(\"tag\")\n\n .arg(name)\n\n .output()?;\n\n\n\n check_output(&output)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/git.rs", "rank": 1, "score": 86771.84447472362 }, ...
Rust
day_2/src/main.rs
asaaki/advent-of-code-2019
7f3e166c13595e60cb3a08f1b1b90b4fa6a20430
use clap::{App, Arg}; use std::fs; use std::fs::File; use std::io::Read; static PART1_NOUN_VERB: (usize, usize) = (12, 2); static PART2_ANSWER: usize = 19_690_720; fn main() -> std::io::Result<()> { let clap_app = App::new("AoC day 2") .version("1.0") .about("Fix the computer") .author("...
use clap::{App, Arg}; use std::fs; use std::fs::File; use std::io::Read; static PART1_NOUN_VERB: (usize, usize) = (12, 2); static PART2_ANSWER: usize = 19_690_720; fn main() -> std::io::Result<()> { let clap_app = App::new("AoC day 2") .version("1.0") .about("Fix the computer") .author("...
b): (usize, usize)) -> Vec<usize> { opcodes[1] = noun; opcodes[2] = verb; opcodes } fn run_program(opcodes: Vec<usize>) -> Vec<usize> { let mut prog = Prog { done: false, pc: 0, opcodes, }; prog = prog.execute(); prog.opcodes } #[derive(Debug, Clone)] struct Prog { ...
parse::<usize>().unwrap()) .collect(); opcodes } fn adjust_noun_and_verb(mut opcodes: Vec<usize>, (noun, ver
random
[ { "content": "fn read_data(mut file: File) -> CodeRange {\n\n let mut buffer = String::new();\n\n file.read_to_string(&mut buffer).unwrap();\n\n let data: Vec<Code> = buffer\n\n .trim()\n\n .split('-')\n\n .map(|s| s.parse::<Code>().unwrap())\n\n .collect();\n\n data[0].....
Rust
src/misc.rs
aeshirey/until-rs
db8b903d9149e7a069b6f3800e4d149766e9e886
use std::time::Duration; use std::{cell::RefCell, time::SystemTime}; use url::Url; pub fn parse_duration(duration: &str) -> Result<Duration, ()> { let mut total_delay = 0; let mut acc = 0; for c in duration.chars() { match c { '0'..='9' => { acc *= 10; a...
use std::time::Duration; use std::{cell::RefCell, time::SystemTime}; use url::Url; pub fn parse_duration(duration: &str) -> Result<Duration, ()> { let mut total_delay = 0; let mut acc = 0; for c in duration.chars() { match c { '0'..='9' => { acc *= 10; a...
pub fn parse_http_get(urlarg: &str) -> (u16, String) { let urlbytes = urlarg.chars().collect::<Vec<_>>(); let (status_code, urlarg) = if urlarg.len() > 4 && urlbytes[0..3].iter().all(|c| c.is_numeric()) && urlbytes[3] == ',' { let code = 100 * (urlbytes[0] as u16 - '0' as u16) ...
0; } _ => return Err(()), } } total_delay += acc; let d = Duration::from_secs(total_delay as u64); Ok(d) }
function_block-function_prefixed
[ { "content": "fn main() -> Result<(), ()> {\n\n let matches = get_app().get_matches();\n\n\n\n let mut waitfors = Vec::new();\n\n\n\n let verbose: bool = matches.is_present(\"verbose\");\n\n\n\n if let Some(elapsed) = matches.value_of(\"elapsed\") {\n\n let duration = misc::parse_duration(ela...
Rust
rust/src/lib.rs
TilCreator/rust-esp32-std-hello
d2e1775e7fda2d18cb8d61cb4dcd6976af4afc27
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use std::thread; use std::ffi::{CString}; use esp_idf_sys::*; use tokio::{ join, runtime::Runtime, time::{sleep, Duration}, }; mod wip; #[no_mangle] pub extern "C" fn main() { simple_playground(); threads_playground(...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use std::thread; use std::ffi::{CString}; use esp_idf_sys::*; use tokio::{ join, runtime::Runtime, time::{sleep, Duration}, }; mod wip; #[no_mangle] pub extern "C" fn main() { simple_playground(); threads_playground(...
fn threads_playground() { let mut children = vec![]; println!("Rust main thread: {:?}", thread::current()); for i in 0..5 { children.push(thread::spawn(move || { println!("This is thread number {}, {:?}", i, thread::current()); })); } println!("About to join...
n simple_playground() { println!("Hello, world from Rust!"); let mut children = vec![]; children.push("foo"); children.push("bar"); println!("More complex print {:?}", children); }
function_block-function_prefixed
[ { "content": "extern void main();\n", "file_path": "src/main.c", "rank": 1, "score": 42759.90260905648 }, { "content": "void app_main() {\n\n main();\n", "file_path": "src/main.c", "rank": 5, "score": 28764.225470355428 }, { "content": "// TODO: Figure out which librar...
Rust
src/main_prev.rs
m1el/absurdle-solver
c1a0f27bdb21950054cf4e83b8969be0ae7f6e60
#![feature(iter_intersperse)] use core::cmp::{Ord, PartialOrd, Ordering, Reverse}; use core::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; use std::collections::{BinaryHeap, HashMap}; mod words; pub(crate) type Word = [u8; 5]; #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] enum Letter...
#![feature(iter_intersperse)] use core::cmp::{Ord, PartialOrd, Ordering, Reverse}; use core::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; use std::collections::{BinaryHeap, HashMap}; mod words; pub(crate) type Word = [u8; 5]; #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] enum Letter...
static POSITION: AtomicUsize = AtomicUsize::new(0); fn worker() { loop { let position = POSITION.fetch_add(1, AtomicOrdering::SeqCst); if position >= words::POSSIBLE_WORDS.len() { break; } let needle = words::POSSIBLE_WORDS[position]; let needle_str = core::str::from_utf8(&needle[...
E_WORDS.iter()) { if node.path.iter().any(|&p| p == guess) { continue; } let (_score, words) = get_rigged_response(&node.words, guess); if node.words.len() == words.len() { continue; } ...
function_block-function_prefixed
[ { "content": "/// Given a secret word and a player's guess, calculate the guess score.\n\npub fn guess_score(mut secret: Word, guess: Word) -> GuessScore {\n\n let mut letters = [LetterScore::Miss; WORD_LENGTH];\n\n\n\n // Prioritize finding letters that are in the correct place\n\n let mut correct_pla...
Rust
src/ring_buffer.rs
ollpu/tiralabra
250a91aa3d3e150ee75555745e21e0a3aafb607c
use std::cell::UnsafeCell; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; pub trait Item: Copy + Send + Sync + Default {} impl<T: Copy + Send + Sync + Default> Item for T {} struct RingBuffer<T: Item> { capacity: usize, buffer: Vec<UnsafeCell<T>>, read_index: AtomicUsize, write_in...
use std::cell::UnsafeCell; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; pub trait Item: Copy + Send + Sync + Default {} impl<T: Copy + Send + Sync + Default> Item for T {} struct RingBuffer<T: Item> { capacity: usize, buffer: Vec<UnsafeCell<T>>, read_index: AtomicUsize, write_in...
) -> RingRange { let read_index = self.read_index.load(Ordering::Relaxed); let write_index = self.write_index.load(Ordering::Acquire); RingRange { start: read_index, open_end: write_index, capacity: self.capacity, } } fn comm...
RingRange { start: usize, open_end: usize, capacity: usize, } pub fn with_capacity<T: Item>(capacity: usize) -> (Producer<T>, Consumer<T>) { let capacity = capacity + 1; let ring_buffer = Arc::new(RingBuffer { capacity, buffer: (0..capacity).map(|_| Default::default()).collect(), ...
random
[ { "content": "pub trait Float:\n\n rustfft::FftNum\n\n + num_traits::Float\n\n + num_traits::FloatConst\n\n + num_traits::Num\n\n + num_traits::NumAssignOps\n\n + num_traits::AsPrimitive<i64>\n\n + std::default::Default\n\n + std::iter::Sum\n\n{\n\n fn v(x: f64) -> Self {\n\n S...
Rust
src/paths/tokens.rs
beltram/jsonpath
ca0bcfcdc8c3eb9ae86459aad31a7a59a1f00a9f
use super::str_reader::StrRange; #[derive(Debug, PartialEq, Clone)] pub enum Token { Absolute(StrRange), Dot(StrRange), At(StrRange), OpenArray(StrRange), CloseArray(StrRange), Asterisk(StrRange), Question(StrRange), Comma(StrRange), Split(StrRange), OpenParenthesis(StrRange), ...
use super::str_reader::StrRange; #[derive(Debug, PartialEq, Clone)] pub enum Token { Absolute(StrRange), Dot(StrRange), At(StrRange), OpenArray(StrRange), CloseArray(StrRange), Asterisk(StrRange), Question(StrRange), Comma(StrRange), Split(StrRange), OpenParenthesis(StrRange), ...
Debug, PartialEq, Clone)] pub enum FilterToken { Equal, NotEqual, Little, LittleOrEqual, Greater, GreaterOrEqual, And, Or, }
e), SingleQuoted(StrRange), Equal(StrRange), GreaterOrEqual(StrRange), Greater(StrRange), Little(StrRange), LittleOrEqual(StrRange), NotEqual(StrRange), And(StrRange), Or(StrRange), Whitespace(StrRange), } impl Token { pub fn is_match_token_type(&self, other: Token) -> bool ...
random
[ { "content": "pub trait ParserTokenHandler<'a> {\n\n fn handle<F>(&mut self, token: &ParseToken, parse_value_reader: &F)\n\n where\n\n F: Fn(&StrRange) -> &'a str;\n\n}", "file_path": "src/paths/parser_token_handler.rs", "rank": 0, "score": 94111.38876363792 }, { "conten...
Rust
fathom/src/lang/core.rs
yeslogic/fathom
b9bcb4307563e44802c195fc75ddbbe6306d454a
use num_bigint::BigInt; use std::collections::BTreeMap; use std::fmt; use std::sync::Arc; use crate::ieee754; use crate::lang::{FileId, Located}; use crate::reporting::Message; mod lexer; #[allow(clippy::style, clippy::complexity, clippy::perf)] mod grammar { include!(concat!(env!("OUT_DIR"), "/lang/core/gramm...
use num_bigint::BigInt; use std::collections::BTreeMap; use std::fmt; use std::sync::Arc; use crate::ieee754; use crate::lang::{FileId, Located}; use crate::reporting::Message; mod lexer; #[allow(clippy::style, clippy::complexity, clippy::perf)] mod grammar { include!(concat!(env!("OUT_DIR"), "/lang/core/gramm...
} impl PartialEq for Module { fn eq(&self, other: &Module) -> bool { self.doc == other.doc && self.items == other.items } } pub type Item = Located<ItemData>; #[derive(Debug, Clone, PartialEq)] pub enum ItemData { Constant(Constant), StructType(StructType), StructForm...
pub fn parse(file_id: FileId, source: &str, messages: &mut Vec<Message>) -> Module { let tokens = lexer::tokens(file_id, source); grammar::ModuleParser::new() .parse(file_id, messages, tokens) .unwrap_or_else(|error| { messages.push(Message::from_lalrpop(file_id, ...
function_block-full_function
[ { "content": "/// Type check and elaborate a module\n\npub fn check_module(context: &Context, raw_module: &raw::Module) -> Result<Module, TypeError> {\n\n let mut context = context.clone();\n\n let items = raw_module\n\n .items\n\n .clone()\n\n .unnest()\n\n .into_iter()\n\n ...
Rust
src/config.rs
davidpdrsn/AxumSqlxSessions
e083a38f22f1fcb1a1bd5e63dddb206f7b76b7b3
use chrono::Duration; #[derive(Debug, Clone)] pub struct SqlxSessionConfig { pub(crate) lifespan: Duration, pub(crate) cookie_name: String, pub(crate) cookie_path: String, pub(crate) cookie_len: usize, pub(crate) database: String, pub(crate) username: String, ...
use chrono::Duration; #[derive(Debug, Clone)] pub struct SqlxSessionConfig { pub(crate) lifespan: Duration, pub(crate) cookie_name: String, pub(crate) cookie_path: String, pub(crate) cookie_len: usize, pub(crate) database: String, pub(crate) username: String, ...
.into(), cookie_len: 16, database: "".into(), username: "".into(), password: "".into(), host: "localhost".into(), port: 5432, table_name: "async_sessions".into(), max_connections: 5, memory_lifespan:...
password.into(); self } pub fn with_table_name(mut self, table_name: &str) -> Self { self.table_name = table_name.into(); self } pub fn with_host(mut self, host: &str) -> Self { self.host = host.into(); self } ...
random
[ { "content": "use chrono::{DateTime, Utc};\n\nuse serde::{Deserialize, Serialize};\n\nuse std::collections::HashMap;\n\nuse uuid::Uuid;\n\n\n\n///This Contains all of out Sessions Data including their Hashed Data they access.\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n\npub struct SQLxSessionData {\n\n...
Rust
tests/values/test_number.rs
j2inn/libhaystack
8821d5181f65233a746f7cb27c89d04529fa9b2b
use libhaystack::units::get_unit_or_default; #[cfg(test)] use libhaystack::val::*; #[test] fn test_number_make_value() { let number: Number = Number::make(41.0); let value: Value = number.into(); assert!(value.is_number()); assert!(!value.is_bool()); assert_eq!(Number::try_from(&value), Ok(Num...
use libhaystack::units::get_unit_or_default; #[cfg(test)] use libhaystack::val::*; #[test] fn test_number_make_value() { let number: Number = Number::make(41.0); let value: Value = number.into(); assert!(value.is_number()); assert!(!value.is_bool()); assert_eq!(Number::try_from(&value), O
; let a: Number = Number::make_with_unit(20.0, get_unit_or_default("m")); let b: Number = Number::make_with_unit(20.0, get_unit_or_default("ft")); assert!((a - b).is_err()); } #[test] fn test_number_multiplication() { let a: Number = 10.into(); let b: Number = 2.into(); assert_eq!(a * b, Ok(...
k(Number::make(41.0))); } #[test] fn test_number_make() { let number: Number = Number::make_with_unit(42.0, get_unit_or_default("s")); assert_eq!(number.value, 42.0); assert_eq!(number.unit, Some(get_unit_or_default("s"))); } #[test] fn test_number_from() { let number: Number = 10.into(); assert...
random
[ { "content": "#[test]\n\nfn test_value_dict_value() {\n\n let dict = Value::from(dict! {\n\n \"site\" => Value::make_marker(),\n\n \"name\" => Value::from(\"Foo\")\n\n });\n\n assert!(dict.is_dict());\n\n\n\n // Get the Dict value\n\n let dict_value = Dict::try_from(&dict).unwrap();...
Rust
query-engine/connectors/sql-query-connector/src/database/transaction.rs
tomhoule/prisma-engine
fed0da6a6828108ce51b205436c2e8c26ba675ca
use crate::database::operations::*; use crate::{query_builder::read::ManyRelatedRecordsQueryBuilder, SqlError}; use connector_interface::{ self as connector, filter::Filter, QueryArguments, ReadOperations, Transaction, WriteArgs, WriteOperations, IO, }; use prisma_models::prelude::*; use quaint::prelude::Connection...
use crate::database::operations::*; use crate::{query_builder::read::ManyRelatedRecordsQueryBuilder, SqlError}; use connector_interface::{ self as connector, filter::Filter, QueryArguments, ReadOperations, Transaction, WriteArgs, WriteOperations, IO, }; use prisma_models::prelude::*; use quaint::prelude::Connection...
} } impl<'a, T> Transaction<'a> for SqlConnectorTransaction<'a, T> where T: ManyRelatedRecordsQueryBuilder + Send + Sync + 'static, { fn commit<'b>(&'b self) -> IO<'b, ()> { IO::new(self.catch(async move { Ok(self.inner.commit().await.map_err(SqlError::from)?) })) } fn rollback<'b>(&'b se...
match fut.await { Ok(o) => Ok(o), Err(err) => Err(err.into_connector_error(&self.connection_info)), }
if_condition
[ { "content": "pub fn wrap_as_step<T, F>(steps: Vec<T>, mut wrap_fn: F) -> impl Iterator<Item = SqlMigrationStep>\n\nwhere\n\n F: FnMut(T) -> SqlMigrationStep,\n\n{\n\n steps.into_iter().map(move |x| wrap_fn(x))\n\n}\n", "file_path": "migration-engine/connectors/sql-migration-connector/src/sql_database...
Rust
src/cryptographic_primitives/proofs/sigma_dlog_eq.rs
qhyw99/curv
be8845fb2302ba70f910267d87350e8b16d61973
/* This file is part of Curv library Copyright 2018 by Kzen Networks (https://github.com/KZen-networks/curv) License MIT: https://github.com/KZen-networks/curv/blob/master/LICENSE */ use super::ProofError; use crate::elliptic::curves::traits::*; use crate::cryptographic_primitives::hashing::hash_sha2...
/* This file is part of Curv library Copyright 2018 by Kzen Networks (https://github.com/KZen-networks/curv) License MIT: https://github.com/KZen-networks/curv/blob/master/LICENSE */ use super::ProofError; use crate::elliptic::curves::traits::*; use crate::cryptographic_primitives::hashing::hash_sha2...
pub fn verify(proof: &DLogEqProof<P>) -> Result<(), ProofError> { let challenge = HSha256::create_hash(&[ &proof.pk_t_rand_commitment.0.bytes_compressed_to_big_int(), &proof.pk_t_rand_commitment.1.bytes_compressed_to_big_int(), &proof.generator.0.bytes_compressed_to_big...
r = ECScalar::from(&challenge); let challenge_mul_sk = challenge_fe.mul(&sk.get_element()); let challenge_response = sk_t_rand_commitment.sub(&challenge_mul_sk.get_element()); sk_t_rand_commitment.zeroize(); DLogEqProof { generator: (g0.clone(), g1.clone())...
function_block-function_prefixed
[ { "content": "pub fn secret_sharing_3_out_of_5<P>()\n\nwhere\n\n P: ECPoint + Clone,\n\n P::Scalar: PartialEq + Clone + Debug,\n\n{\n\n use curv::cryptographic_primitives::secret_sharing::feldman_vss::VerifiableSS;\n\n use curv::elliptic::curves::traits::ECScalar;\n\n\n\n let secret: P::Scalar = ...
Rust
crates/fuzzing/src/lib.rs
pventuzelo/wasmtime
d733ebf3abd5fc074e93fd283f0a894e986ecbcb
#![deny(missing_docs, missing_debug_implementations)] pub mod generators; pub mod oracles; use anyhow::Context; use std::fs; use std::path::{Path, PathBuf}; use std::process; use std::sync::{atomic, Once}; #[macro_export] macro_rules! with_log_wasm_test_case { ( $wasm:expr , |$wasm_var:ident| $oracle:expr ) =>...
#![deny(missing_docs, missing_debug_implementations)] pub mod generators; pub mod oracles; use anyhow::Context; use std::fs; use std::path::{Path, PathBuf}; use std::process; use std::sync::{atomic, Once}; #[macro_export] macro_rules! with_log_wasm_test_case { ( $wasm:expr , |$wasm_var:ident| $oracle:expr ) =>...
fn scratch_dir() -> PathBuf { let dir = Path::new(env!("CARGO_MANIFEST_DIR")) .join("target") .join("scratch"); static CREATE: Once = Once::new(); CREATE.call_once(|| { fs::create_dir_all(&dir) .with_context(|| format!("Failed to create {}", dir.display())) ...
pub fn log_wasm_test_case(wasm: &[u8], wasm_var: &'static str, oracle_expr: &'static str) { init_logging(); let wasm_path = wasm_test_case_path(); fs::write(&wasm_path, wasm) .with_context(|| format!("Failed to write wasm to {}", wasm_path.display())) .unwrap(); log::info!("Wrote Wasm t...
function_block-full_function
[ { "content": "/// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected\n\n/// panic or segfault or anything else that can be detected \"passively\".\n\n///\n\n/// Performs initial validation, and returns early if the Wasm is invalid.\n\n///\n\n/// You can control which compiler is used via ...
Rust
headers/src/header_components/disposition.rs
PeterW-LWL/mail
f05836f227b44e7106d1360c7052356cd41ba361
use std::borrow::Cow; #[cfg(feature = "serde")] use std::fmt; use failure::Fail; use media_type::push_params_to_buffer; use media_type::spec::{Ascii, Internationalized, MimeSpec, Modern}; use soft_ascii_string::SoftAsciiStr; #[cfg(feature = "serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; use...
use std::borrow::Cow; #[cfg(feature = "serde")] use std::fmt; use failure::Fail; use media_type::push_params_to_buffer; use media_type::spec::{Ascii, Internationalized, MimeSpec, Modern}; use soft_ascii_string::SoftAsciiStr; #[cfg(feature = "serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; use...
} deserializer.deserialize_str(Visitor) } } impl<'a> HeaderTryFrom<&'a str> for Disposition { fn try_from(text: &'a str) -> Result<Self, ComponentCreationError> { if text.eq_ignore_ascii_case("Inline") { Ok(Disposition::inline()) } else if text.eq_ignore_ascii_case...
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: ::serde::de::Error, { if value.eq_ignore_ascii_case("inline") { Ok(DispositionKind::Inline) } else if value.eq_ignore_ascii_case("attachment") { ...
function_block-full_function
[ { "content": "pub fn deserialize_attachments<'de, D>(deserializer: D) -> Result<Vec<Resource>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n //FIXME[perf] write custom visitor etc.\n\n let vec = <Vec<ResourceDeserializationHelper>>::deserialize(deserializer)?;\n\n\n\n let vec = vec.into_iter...
Rust
tough/tests/http.rs
srgothi92/tough
b4fd7c6d931aa9e5d721f6f279d0c902c248cb4f
mod test_utils; #[cfg(feature = "http")] mod http_happy { use crate::test_utils::{read_to_end, test_data}; use mockito::mock; use std::fs::File; use std::str::FromStr; use tough::{DefaultTransport, HttpTransport, RepositoryLoader, Transport}; use url::Url; fn create_successful_get_moc...
mod test_utils; #[cfg(feature = "http")] mod http_happy { use crate::test_utils::{read_to_end, test_data}; use mockito::mock; use std::fs::File; use std::str::FromStr; use tough::{DefaultTransport, HttpTransport, RepositoryLoader, Transport}; use url::Url; fn create_successful_get_moc...
} #[cfg(feature = "http")] #[cfg(feature = "integ")] mod http_integ { use crate::test_utils::test_data; use std::fs::File; use std::path::PathBuf; use std::process::{Command, Stdio}; use tough::{HttpTransportBuilder, RepositoryLoader}; use url::Url; pub fn integ_dir() -> PathBuf { ...
s .get("file1.txt") .unwrap() .custom .get("file_permissions") .unwrap(), "0644" ); mock_timestamp.assert(); mock_snapshot.assert(); mock_targets.assert(); mock_role1.assert(); mo...
function_block-function_prefixed
[ { "content": "fn sign_root_json(key: &str, root_json: &str) {\n\n Command::cargo_bin(\"tuftool\")\n\n .unwrap()\n\n .args(&[\"root\", \"sign\", root_json, \"-k\", key])\n\n .assert()\n\n .success();\n\n}\n\n\n", "file_path": "tuftool/tests/create_repository_integration.rs", ...
Rust
src/control.rs
uttarayan21/mctl-rs
b3ecde84b629bef453123278e49930873e2e6fba
use crate::cli; use crate::config::Config; use crate::error::{Error, ErrorKind}; use derive_more::Display; use std::{convert::TryFrom, str::FromStr}; #[derive(Debug, Clone, Copy, Display, serde::Deserialize)] pub enum Player { Mpd, Mpris, Both, None, } impl FromStr for Player { type Err = Error; ...
use crate::cli; use crate::config::Config; use crate::error::{Error, ErrorKind}; use derive_more::Display; use std::{convert::TryFrom, str::FromStr}; #[derive(Debug, Clone, Copy, Display, serde::Deserialize)] pub enum Player { Mpd, Mpris, Both, None, } impl FromStr for Player { type Err = Error; ...
if let Some(mpdclient) = &mut self.mpdclient { println!("{}", PlayerInfo::try_from(mpdclient)?); } } _ => (), } Ok(()) } pub fn handle(&mut self, operation: Operation, player: Player) -> Result<(), Error> { println!("...
isclient)?); } } Player::Both => { if let Some(mprisclient) = &mut self.mprisclient { println!("{}", PlayerInfo::try_from(mprisclient)?); }
function_block-random_span
[ { "content": "fn main() -> Result<(), Error> {\n\n let config = config::Config::try_load().unwrap_or_default();\n\n let matches = cli::build_cli().get_matches();\n\n let operation: Operation = matches\n\n .value_of(\"operation\")\n\n .and_then(|op| op.parse::<Operation>().ok())\n\n ...
Rust
src/graphics/texture.rs
BrassLion/rust-pbr
1b406984d27d7477eb4319ac3acbf2916d7ca755
pub struct Texture { _texture: wgpu::Texture, pub dimension: wgpu::TextureViewDimension, pub view: wgpu::TextureView, pub sampler: wgpu::Sampler, } impl Texture { pub fn new_texture_from_data( device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32, ...
pub struct Texture { _texture: wgpu::Texture, pub dimension: wgpu::TextureViewDimension, pub view: wgpu::TextureView, pub sampler: wgpu::Sampler, } impl Texture { pub fn new_texture_from_data( device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32, ...
pub fn new_cubemap_texture( device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32, face_textures: &[Texture], image_format: wgpu::TextureFormat, mip_levels: u32, ) -> Self { let size = wgpu::Extent3d { width: wi...
height: u32, framebuffer: &Texture, image_format: wgpu::TextureFormat, wrap_mode: wgpu::AddressMode, ) -> Self { let size = wgpu::Extent3d { width: width, height: height, depth: 1, }; let _texture = device.create_texture(&w...
function_block-function_prefix_line
[ { "content": "pub fn create_texture_bind_group(\n\n device: &wgpu::Device,\n\n visibility: wgpu::ShaderStage,\n\n textures: &[&Texture],\n\n) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {\n\n let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {\n\n label:...
Rust
src/lib.rs
immykins/oura-rs
a6d7599364376527f745d7087745f5289f7e65ab
use serde::Deserialize; use url::Url; use clap::Clap; pub struct Client { pub token: String, } #[derive(Deserialize, Debug)] struct UserInfo { age: u8, weight: f32, height: u16, gender: String, email: String, } #[derive(Deserialize, Debug)] struct Readiness { readiness: Vec<ReadinessPer...
use serde::Deserialize; use url::Url; use clap::Clap; pub struct Client { pub token: String, } #[derive(Deserialize, Debug)] struct UserInfo { age: u8, weight: f32, height: u16, gender: String, email: String, } #[derive(Deserialize, Debug)] struct Readiness { readiness: Vec<ReadinessPer...
endpoint!(info, UserInfo, "https://api.ouraring.com/v1/userinfo"); endpoint!(sleep, Sleep, "https://api.ouraring.com/v1/sleep"); endpoint!(bedtime, Bedtime, "https://api.ouraring.com/v1/bedtime"); endpoint!( readiness, Readiness, "https://api.ouraring.com/v1/readiness...
pub fn activity(&self, opts: TimeOpts) -> Result<(), Box<dyn std::error::Error>> { let url = Url::parse_with_params( "https://api.ouraring.com/v1/activity", &[("access_token", self.token.clone())], )?; let resp = reqwest::blocking::get(url)?.json::<Activity>()?; p...
function_block-full_function
[ { "content": "#[derive(Clap)]\n\nstruct Bedtime {}\n\n\n", "file_path": "src/main.rs", "rank": 8, "score": 34492.389108462856 }, { "content": "fn main() {\n\n let opts: Opts = Opts::parse();\n\n let client = Client::new(opts.token);\n\n\n\n let result = match opts.subcmd {\n\n ...
Rust
src/lib.rs
jgrosspietsch/nonogram-rs
477e211126c81b247ba112ebc7ba99f051dd1646
mod solution; extern crate crc; extern crate ndarray; extern crate ndarray_rand; extern crate rand; extern crate serde; extern crate serde_json; use crc::crc64::checksum_ecma; use ndarray::{iter::Lanes, ArrayView1, Ix1}; use ndarray_rand::RandomExt; use rand::distributions::Uniform; use serde::{Deserialize, Deseriali...
mod solution; extern crate crc; extern crate ndarray; extern crate ndarray_rand; extern crate rand; extern crate serde; extern crate serde_json; use crc::crc64::checksum_ecma; use ndarray::{iter::Lanes, ArrayView1, Ix1}; use ndarray_rand::RandomExt; use rand::distributions::Uniform; use serde::{Deserialize, Deseriali...
match grid { Ok(grid_array) => Ok(Nonogram { row_segments: arr1(self.row_segments.as_slice()), column_segments: arr1(self.column_segments.as_slice()), completed_grid: grid_array, }), Err(e) => Err(e.to_string()), } ...
let grid = Array2::from_shape_vec( (self.height, self.width), self.completed_grid.iter().flatten().cloned().collect(), );
assignment_statement
[ { "content": "pub fn common_row_indexes(states: &[StateRow]) -> Vec<(usize, CellState)> {\n\n let mut common_empty: Array1<usize> = Array1::zeros(states[0].0.len());\n\n let mut common_filled: Array1<usize> = Array1::zeros(states[0].0.len());\n\n\n\n for state in states {\n\n for i in 0..state.0...
Rust
src/system/timer.rs
Past9/stm32-api-generator
95075fa757faedcec1fdea967939ab94a778215c
use anyhow::{bail, Result}; use svd_expander::{DeviceSpec, PeripheralSpec}; use super::*; #[derive(Clone)] pub struct Timer { pub name: Name, pub peripheral_enable_field: String, pub auto_reload_field: RangedField, pub prescaler_field: RangedField, pub counter_field: RangedField, pub arpe_field: String, ...
use anyhow::{bail, Result}; use svd_expander::{DeviceSpec, PeripheralSpec}; use super::*; #[derive(Clone)] pub struct Timer { pub name: Name, pub peripheral_enable_field: String, pub auto_reload_field: RangedField, pub prescaler_field: RangedField, pub counter_field: RangedField, pub arpe_field: String, ...
edField, pub preload_path: String, pub polarity_path: String, pub complement: Option<OutputComplement>, } impl OutputChannel { pub fn new(peripheral: &PeripheralSpec, channel_number: u32) -> Result<Option<Self>> { Ok(Some(Self { enable_path: match find_field_in_peripheral(peripheral, &f!("cc{channel_n...
{ self.input.is_some() } pub fn as_input(&self) -> &InputChannel { match self.input { Some(ref input) => input, None => panic!("{} is not an input channel", self.name.camel()), } } pub fn as_input_mut(&mut self) -> &mut InputChannel { match self.input { Some(ref mut input) =...
random
[ { "content": "#[allow(dead_code)]\n\nfn try_find_enum_field_in_peripheral(p: &PeripheralSpec, name: &str) -> Result<EnumField> {\n\n find_enum_field_in_peripheral(p, name).ok_or(anyhow!(\n\n \"Could not find field {} in peripheral {}\",\n\n name,\n\n p.name\n\n ))\n\n}\n\n\n", "file_path": "src/s...
Rust
src/subcommands/tui/state.rs
KaoImin/ckb-cli
935c280d06ea26ed5bdf12d3d3c6558d20730796
use std::collections::BTreeMap; use std::sync::Arc; use std::thread; use std::time::Duration; use ckb_types::{core::HeaderView, packed::Script, prelude::*}; use ckb_util::RwLock; use super::util::ts_now; use ckb_sdk::{ rpc::{BlockView, ChainInfo, LocalNode, RemoteNode, TxPoolInfo}, HttpRpcClient, }; const MA...
use std::collections::BTreeMap; use std::sync::Arc; use std::thread; use std::time::Duration; use ckb_types::{core::HeaderView, packed::Script, prelude::*}; use ckb_util::RwLock; use super::util::ts_now; use ckb_sdk::{ rpc::{BlockView, ChainInfo, LocalNode, RemoteNode, TxPoolInfo}, HttpRpcClient, }; const MA...
pub(crate) output_count: usize, pub(crate) cellbase_outputs: Vec<(u64, Script)>, } impl From<BlockView> for BlockInfo { fn from(view: BlockView) -> BlockInfo { let header = view.header.into(); let uncle_count = view.uncles.len(); let commit_tx_count = view.transactions.len(); l...
}); } fn process(state: &Arc<RwLock<State>>, rpc_client: &mut HttpRpcClient) -> Result<(), String> { loop { let chain_info_opt = rpc_client.get_blockchain_info().ok(); let local_node_info = rpc_client.local_node_info()?; let tx_pool_info = rpc_client.tx_pool_info()?; let peers =...
random
[ { "content": "pub fn get_network_type(rpc_client: &mut HttpRpcClient) -> Result<NetworkType, String> {\n\n let chain_info = rpc_client.get_blockchain_info()?;\n\n NetworkType::from_raw_str(chain_info.chain.as_str())\n\n .ok_or_else(|| format!(\"Unexpected network type: {}\", chain_info.chain))\n\n}...
Rust
sept/src/poset.rs
vdods/sept-rs
5cd3d8099f73c4171ad000ad1893d805f52b372b
use crate::{DirectedAcyclicGraph, NodeSet}; use std::{cmp::Eq, fmt::Debug, hash::Hash}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PartialOrder { Equal, LessThan, GreaterThan, Incomparable, } pub type PartialOrderEvalFn<T> = fn(lhs: T, rhs: T) -> PartialOrder; #[derive(Debug)] pub struct P...
use crate::{DirectedAcyclicGraph, NodeSet}; use std::{cmp::Eq, fmt::Debug, hash::Hash}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PartialOrder { Equal, LessThan, GreaterThan, Incomparable, } pub type PartialOrderEvalFn<T> = fn(lhs: T, rhs: T) -> PartialOrder; #[derive(Debug)] pub struct P...
pub fn least_upper_bound_of(&self, x: T) -> NodeSet<T> { let mut retval = NodeSet::new(); for leaf_node in self.dag.leaf_node_s.iter() { self.least_upper_bound_recursive(x, *leaf_node, &mut retval); } retval } fn greatest_lower_bound_recursive(&se...
pub fn greatest_lower_bound_of(&self, x: T) -> NodeSet<T> { let mut retval = NodeSet::new(); for root_node in self.dag.root_node_s.iter() { self.greatest_lower_bound_recursive(x, *root_node, &mut retval); } retval }
function_block-full_function
[ { "content": "struct RegisteredEqualsFn {\n\n eq_fn: BinaryPredicate,\n\n is_transposed: bool,\n\n}\n\n\n\n/// The sept Runtime is what supports the sept data model; it tracks what types are registered\n\n/// and the various inhabitation and subtyping (and other) relationships.\n\n#[derive(Default)]\n\npu...
Rust
gristmill-gui/src/layout.rs
plish-plash/gristmill
9798bb3e027f28062eaa29394c4dea09f8bb6faa
use std::convert::TryFrom; use gristmill::geometry2d::*; use super::LayoutContext; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Side { Left, Right, Top, Bottom } impl Side { pub fn opposite(self) -> Side { match self { Side::Left => Side::Right, Side::Right => Side::...
use std::convert::TryFrom; use gristmill::geometry2d::*; use super::LayoutContext; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Side { Left, Right, Top, Bottom } impl Side { pub fn opposite(self) -> Side { match self { Side::Left => Side::Right, Side::Right => Side::...
}
xt, Side::Top); let mut bottom_edge = self.get_edge(context, Side::Bottom); if left_edge.is_some() && right_edge.is_none() { right_edge = Some(left_edge.unwrap() + self.base_size.width as i32); } else if right_edge.is_some() && left_edge.is_none() { left_edge = So...
function_block-function_prefixed
[ { "content": "pub fn load_fonts(resources: &mut Resources) {\n\n init_logging();\n\n FONTS_INIT.call_once(|| {\n\n let (font_store, font_list) = read_fonts();\n\n resources.insert(\"fonts\", font_list);\n\n unsafe {\n\n FONTS = Some(font_store);\n\n }\n\n });\n\n}...
Rust
vendor/alsa-0.5.0/src/chmap.rs
ritikmishra/babycat
ce21a5d07f3e0ce4d30b7109617ef48f29d350a8
use crate::alsa; use libc; use std::{fmt, mem, ptr, slice}; use super::error::*; alsa_enum!( ChmapType, ALL_CHMAP_TYPES[4], None = SND_CHMAP_TYPE_NONE, Fixed = SND_CHMAP_TYPE_FIXED, Var = SND_CHMAP_TYPE_VAR, Paired = SND_CHMAP_TYPE_PAIRED, ); alsa_enum!( ChmapPosition, ALL_CHMAP_POS...
use crate::alsa; use libc; use std::{fmt, mem, ptr, slice}; use super::error::*; alsa_enum!( ChmapType, ALL_CHMAP_TYPES[4], None = SND_CHMAP_TYPE_NONE, Fixed = SND_CHMAP_TYPE_FIXED, Var = SND_CHMAP_TYPE_VAR, Paired = SND_CHMAP_TYPE_PAIRED, ); alsa_enum!( ChmapPosition, ALL_CHMAP_POS...
tIter::new(None, &*CString::new("pcm").unwrap()).unwrap(); for p in i.map(|n| n.name.unwrap()) { println!("Chmaps for {:?}:", p); match PCM::open(&CString::new(p).unwrap(), Direction::Playback, false) { Ok(a) => for c in a.query_chmaps() { println!(" {:?}, {}", c.0, c.1)...
self, f: &mut fmt::Formatter) -> fmt::Result { let mut buf: Vec<libc::c_char> = vec![0; 512]; acheck!(snd_pcm_chmap_print(self.0, buf.len() as libc::size_t, buf.as_mut_ptr()))?; let s = from_const("snd_pcm_chmap_print", buf.as_mut_ptr())?; write!(f, "{}", s) } } impl<'a> From<&'a [C...
random
[ { "content": "pub fn get<T: Copy>(v: &[T], frame: usize, channel_idx: usize, num_channels: usize) -> T {\n\n v[frame * num_channels + channel_idx]\n\n}\n\n\n", "file_path": "src/backend/resample/common.rs", "rank": 0, "score": 128592.51563315146 }, { "content": "fn resample_benchmark(c: &...
Rust
src/uu/seq/src/seq.rs
sagudev/coreutils
92a1f1422eb12e0f6bd421d173c2402f2201b19d
#[macro_use] extern crate uucore; use clap::{crate_version, App, AppSettings, Arg}; use num_bigint::BigInt; use num_traits::One; use num_traits::Zero; use num_traits::{Num, ToPrimitive}; use std::cmp; use std::io::{stdout, Write}; use std::str::FromStr; use uucore::display::Quotable; static ABOUT: &str = "Display n...
#[macro_use] extern crate uucore; use clap::{crate_version, App, AppSettings, Arg}; use num_bigint::BigInt; use num_traits::One; use num_traits::Zero; use num_traits::{Num, ToPrimitive}; use std::cmp; use std::io::{stdout, Write}; use std::str::FromStr; use uucore::display::Quotable; static ABOUT: &str = "Display n...
t, separator: String, terminator: String, pad: bool, padding: usize, is_first_minus_zero: bool, ) { let (first, increment, last) = range; let mut value = first; let mut is_first_iteration = true; while !done_printing(&value, &increment, &last) { if !is_first_iteration { ...
all numbers by padding with zeros"), ) .arg( Arg::with_name(ARG_NUMBERS) .multiple(true) .takes_value(true) .allow_hyphen_values(true) .max_values(3) .required(true), ) } fn done_printing<T: Num + Partia...
random
[ { "content": "pub fn signal_name_by_value(signal_value: usize) -> Option<&'static str> {\n\n ALL_SIGNALS.get(signal_value).copied()\n\n}\n\n\n", "file_path": "src/uucore/src/lib/features/signals.rs", "rank": 0, "score": 522995.20658111066 }, { "content": "pub fn uumain(mut args: impl uuco...
Rust
tentacle/src/service/helper.rs
chanhsu001/tentacle
9308fd5ae502ef0fd5bf803b6f99a3db4a16731e
use futures::{channel::mpsc, prelude::*}; use log::{debug, error, trace}; use multiaddr::Multiaddr; use secio::handshake::Config; use std::{ io, pin::Pin, task::{Context, Poll}, time::Duration, }; use tokio::io::{AsyncRead, AsyncWrite}; use yamux::session::SessionType as YamuxType; use crate::{ err...
use futures::{channel::mpsc, prelude::*}; use log::{debug, error, trace}; use multiaddr::Multiaddr; use secio::handshake::Config; use std::{ io, pin::Pin, task::{Context, Poll}, time::Duration, }; use tokio::io::{AsyncRead, AsyncWrite}; use yamux::session::SessionType as YamuxType; use crate::{ err...
} } pub(crate) struct HandshakeContext { pub(crate) key_pair: Option<secio::SecioKeyPair>, pub(crate) event_sender: mpsc::Sender<SessionEvent>, pub(crate) max_frame_length: usize, pub(crate) timeout: Duration, pub(crate) ty: SessionType, pub(crate) remote_address: Multiaddr, pub(crate)...
match ty { SessionType::Outbound => YamuxType::Client, SessionType::Inbound => YamuxType::Server, }
if_condition
[ { "content": "/// Check if the ip address is reachable.\n\n/// Copy from std::net::IpAddr::is_global\n\npub fn is_reachable(ip: IpAddr) -> bool {\n\n match ip {\n\n IpAddr::V4(ipv4) => {\n\n !ipv4.is_private()\n\n && !ipv4.is_loopback()\n\n && !ipv4.is_link_loc...
Rust
pallets/accounts/src/lib.rs
N1ghtStorm/cat_dogs_friends
68e7cb3e1ad433283115e480a73fdc29d2e6189e
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::{ ensure, decl_error, decl_module, decl_storage, dispatch::{ DispatchResult, DispatchError, Vec, }, }; use frame_system::{ ensure_signed, }; use frame_support::{ codec::{Decode, Encode}, sp_ru...
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::{ ensure, decl_error, decl_module, decl_storage, dispatch::{ DispatchResult, DispatchError, Vec, }, }; use frame_system::{ ensure_signed, }; use frame_support::{ codec::{Decode, Encode}, sp_ru...
>::insert(account, &data); } pub fn account_is_master(acc: &T::AccountId) -> bool { AccountRegistry::<T>::get(acc).roles & MASTER_ROLE_MASK != 0 } pub fn account_is_cat_owner(acc: &T::AccountId) -> bool { AccountRegistry::<T>::get(acc).roles & CAT_OWNER_RO...
Ok(()) } } } impl<T: Config> Module<T> { fn account_set(who: &T::AccountId, role: u8) { AccountRegistry::<T>::mutate(&who,|acc|{ acc.roles |= role; }); } fn account_add(account: &T::AccountId, data: CarbonCreditAccountStruct) { AccountRegistry::<T
random
[ { "content": "\t#[pallet::config]\n\n\tpub trait Config: frame_system::Config {\n\n\t\t/// Because this pallet emits events, it depends on the runtime's definition of an event.\n\n\t\ttype Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;\n\n\t}\n\n\n\n\t#[pallet::pallet]\n\n\t#[pallet::...
Rust
rs/tests/src/boundary_nodes_integration/boundary_nodes.rs
Deland-Labs/ic
047172b01e0afc0e61448669d4ec98b2425c6853
/* tag::catalog[] Title:: Boundary nodes integration test end::catalog[] */ use crate::driver::boundary_node::{BoundaryNode, BoundaryNodeVm}; use crate::driver::ic::{InternetComputer, Subnet}; use crate::driver::pot_dsl::get_ic_handle_and_ctx; use crate::driver::test_env::{HasIcPrepDir, TestEnv}; use crate::driver::te...
/* tag::catalog[] Title:: Boundary nodes integration test end::catalog[] */ use crate::driver::boundary_node::{BoundaryNode, BoundaryNodeVm}; use crate::driver::ic::{InternetComputer, Subnet}; use crate::driver::pot_dsl::get_ic_handle_and_ctx; use crate::driver::test_env::{HasIcPrepDir, TestEnv}; use crate::driver::te...
} }
unwrap(); info!( logger, "nginx test result = '{}'. Exit status = {}", nginx_result.trim(), channel.exit_status().unwrap() ); if !nginx_result.trim().contains("test is successful") { panic!("NGINX test failed.");
function_block-random_span
[ { "content": "pub fn exec_ssh_command(vm: &dyn SshSession, command: &str) -> Result<(String, i32), Error> {\n\n let mut channel = vm.block_on_ssh_session()?.channel_session()?;\n\n\n\n channel.exec(command)?;\n\n\n\n let mut output = String::new();\n\n channel.read_to_string(&mut output)?;\n\n ch...
Rust
git-odb/src/store_impls/dynamic/mod.rs
Byron/grit
61abb0b006292d2122784b032e198cc716fb7b92
use std::{cell::RefCell, ops::Deref}; use crate::Store; pub struct Handle<S> where S: Deref<Target = Store> + Clone, { pub(crate) store: S, pub refresh: RefreshMode, pub max_recursion_depth: usize, pub ignore_replacements: bool, pub(crate) token: Option<ha...
use std::{cell::RefCell, ops::Deref}; use crate::Store; pub struct Handle<S> where S: Deref<Target = Store> + Clone, { pub(crate) store: S, pub refresh: RefreshMode, pub max_recursion_depth: usize, pub ignore_replacements: bool, pub(crate) token: Option<ha...
} }
r().count(), }) .collect(); for slot in index.slot_indices.iter().map(|idx| &self.files[*idx]) { let files = slot.files.load(); let record = match &**files { Some(index) => { let state = if index.is_...
function_block-function_prefixed
[ { "content": "pub fn verify(path: impl AsRef<Path>, format: OutputFormat, mut out: impl Write) -> anyhow::Result<()> {\n\n if format != OutputFormat::Human {\n\n bail!(\"Only 'human' format is currently supported\");\n\n }\n\n let path = path.as_ref();\n\n let buf = std::fs::read(path).with_c...
Rust
rust/sbp/src/json/ser.rs
Patrick-Luo-THR/libsbp
d42e4a1e3cedf6a82b1d993b82e0da148401f80d
use std::{borrow::Borrow, io}; use bytes::{BufMut, BytesMut}; use dencode::{Encoder, FramedWrite, IterSinkExt}; use serde::Serialize; use serde_json::{ser::Formatter, Serializer}; use super::{JsonError, JsonOutput}; use crate::{ de::Frame, json::{CommonJson, HaskellishFloatFormatter, Json2JsonInput, Json2Jso...
use std::{borrow::Borrow, io}; use bytes::{BufMut, BytesMut}; use dencode::{Encoder, FramedWrite, IterSinkExt}; use serde::Serialize; use serde_json::{ser::Formatter, Serializer}; use super::{JsonError, JsonOutput}; use crate::{ de::Frame, json::{CommonJson, HaskellishFloatFormatter, Json2JsonInput, Json2Jso...
} } #[derive(Debug)] pub struct Json2JsonEncoder<W, F>(FramedWrite<W, Json2JsonEncoderInner<F>>); impl<W, F> Json2JsonEncoder<W, F> where W: io::Write, F: Formatter + Clone, { pub fn new(writer: W, formatter: F) -> Json2JsonEncoder<W, F> { Self(FramedWrite::new( writer, ...
to_buffer( &mut self.frame_buf, &mut self.payload_buf, dst, self.formatter.clone(), msg.borrow(), )
call_expression
[ { "content": "/// Serialize the given message into the IO stream.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use sbp::messages::logging::MsgLog;\n\n///\n\n/// fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// let text = String::from(\"hello\");\n\n/// let msg = MsgLog {\n\n/// s...
Rust
crates/modor/tests/integration/system_params/queries.rs
modor-engine/modor
447ae453030de44ed93a2ab03a66261080304ce4
use crate::system_params::assert_iter; use modor::testing::TestApp; use modor::{App, Built, Entity, EntityBuilder, Query, With}; struct Tester { done_count: u32, } #[singleton] impl Tester { fn build() -> impl Built<Self> { EntityBuilder::new(Self { done_count: 0 }) } #[run] fn iter_with_...
use crate::system_params::assert_iter; use modor::testing::TestApp; use modor::{App, Built, Entity, EntityBuilder, Query, With}; struct Tester { done_count: u32, } #[singleton] impl Tester { fn build() -> impl Built<Self> { EntityBuilder::new(Self { done_count: 0 }) } #[run] fn iter_with_...
} struct Level2; #[entity] impl Level2 { fn build(value1: u32, value2: u32) -> impl Built<Self> { EntityBuilder::new(Self) .with(Value2(value2 + 1)) .with_child(Level3::build(value1, value2)) } } struct Level3; #[entity] impl Level3 { fn build(value1: u32, value2: u32) -...
fn build(value1: u32, value2: u32) -> impl Built<Self> { EntityBuilder::new(Self) .with(Value1(value1 + 2)) .with(Value3(value1 + 2)) .with_child(Level2::build(value1, value2)) }
function_block-full_function
[ { "content": "fn run(c: &mut Criterion) {\n\n c.bench_function(\"entity_creation\", |b| {\n\n b.iter(|| {\n\n let mut app = App::new();\n\n for _ in 0..10_000 {\n\n app = app.with_entity(Object::build());\n\n }\n\n });\n\n });\n\n}\n\n\n\nmod g...
Rust
rype/src/face.rs
SrimantaBarua/bed_low_level
9a0a515b50167ed5883adadee25b779835a8c72c
use std::fmt; use std::rc::Rc; use fnv::FnvHashMap; use geom::{size2, vec2, Size2D}; use super::cmap::Cmap; use super::common::{GlyphInfo, ScaledGlyphInfo}; use super::direction::Direction; use super::error::*; use super::features::*; use super::gasp::Gasp; use super::gdef::Gdef; use super::glyf::Glyf; use super::g...
use std::fmt; use std::rc::Rc; use fnv::FnvHashMap; use geom::{size2, vec2, Size2D}; use super::cmap::Cmap; use super::common::{GlyphInfo, ScaledGlyphInfo}; use super::direction::Direction; use super::error::*; use super::features::*; use super::gasp::Gasp; use super::gdef::Gdef; use super::glyf::Glyf; use super::g...
} pub fn scale(&self, point_size: u16, dpi: Size2D<u16>) -> ScaledFace { let point_size = point_size as f32; let units_per_em = self.0.head.units_per_em as f32; let mult = point_size / (72.0 * units_per_em); let scale = size2(dpi.width as f32 * mult, dpi.height as f32 * mu...
if tag != Tag(0x00010000) && tag != Tag::from(b"OTTO") { Err(Error::Invalid) } else { Self::load_face(&data, 0) }
if_condition
[ { "content": "#[derive(Debug)]\n\nstruct Glyph {\n\n bbox: BBox<i16>,\n\n typ: GlyphTyp,\n\n}\n\n\n\nimpl Glyph {\n\n fn load(data: &[u8]) -> Result<Glyph> {\n\n let num_contours = get_i16(data, 0)?;\n\n let xmin = get_i16(data, 2)?;\n\n let ymin = get_i16(data, 4)?;\n\n let...
Rust
src/graphics/vulkan/device_allocator/suballocator/region.rs
Creative-Coding-The-Hard-Way/2d
0dc8cbe606783cffe504ab4df0c39bbdc40f53a5
use std::ops::{Bound, RangeBounds}; use crate::graphics::vulkan::device_allocator::Allocation; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Region { pub offset: u64, pub size: u64, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum MergeResult { NonContiguous, Contiguo...
use std::ops::{Bound, RangeBounds}; use crate::graphics::vulkan::device_allocator::Allocation; #[derive(Debug, Copy, Clone, Eq,
rt_eq!(Region::new(0, 64), b); assert_eq!(Region::new(64, 192), a); } fn dummy_allocation(offset: u64, size: u64) -> Allocation { let mut allocation = Allocation::null(); allocation.offset = offset; allocation.byte_size = size; allocation } }
PartialEq)] pub struct Region { pub offset: u64, pub size: u64, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum MergeResult { NonContiguous, Contiguous(Region), } impl Region { pub fn new(offset: u64, size: u64) -> Self { Self { offset, size } } pub f...
random
[ { "content": "/// Copy a byte slice into a properly-aligned u32 array.\n\n///\n\n/// This is meant to help functions which use `include_bytes!` to load sprv\n\n/// because Vulkan expects sprv source to be in u32 words but `include_bytes`\n\n/// imports only u8 bytes.\n\n///\n\n/// A full copy is leveraged to ha...
Rust
arnglld/src/main.rs
arngll/arngll-rust
352d59562a451dbe4ea6d1654769d15323db44d0
use anyhow::format_err; use clap::Parser; use cpal::traits::{DeviceTrait, HostTrait}; use futures::executor::{block_on, block_on_stream}; use futures::prelude::*; use hamaddr::HamAddr; use log::info; use quick_dsp::bell202::{Ax25Debug, Bell202Receiver, Bell202Sender}; use quick_dsp::filter::IteratorExt as _; #[deriv...
use anyhow::format_err; use clap::Parser; use cpal::traits::{DeviceTrait, HostTrait}; use futures::executor::{block_on, block_on_stream}; use futures::prelude::*; use hamaddr::HamAddr; use log::info; use quick_dsp::bell202::{Ax25Debug, Bell202Receiver, Bell202Sender}; use quick_dsp::filter::IteratorExt as _; #[deriv...
n")); println!("opt = {:?}", opt); const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC); let frame_string = format!( "\x01\x00de {}: TEST: This is a test frame of ASCII text.", opt.callsign.unwrap() ); let frame = frame_string.bytes().append_crc(&X25); let mu...
function_block-function_prefixed
[ { "content": "/// Bell 202 decoder.\n\n///\n\n/// Feed in samples into the returned filter and it will\n\n/// occasionally spit out a frame. Does not check CRC.\n\n///\n\n/// Theoretical ideal sample rate is between 6800Hz and 7500Hz. 8000Hz\n\n/// works fine, too. Maximum usable sample rate is around 10,000Hz....
Rust
example_generated/example_generated.rs
thomcc/index_vec
9a5deb48ae08fe166d2aac175a24e05c3fe5ec0c
#[repr(transparent)] #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct CoolIndex { _raw: u32, } impl CoolIndex { pub const MAX_INDEX: usize = i32::max_value() as usize; pub const CHECKS_MAX_INDEX: bool = !false; #[inline(always)] pub fn new(valu...
#[repr(transparent)] #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct CoolIndex { _raw: u32, } impl CoolIndex { pub const MAX_INDEX: usize = i32::max_value() as usize; pub const CHECKS_MAX_INDEX: bool = !false; #[inline(always)] pub fn new(valu...
d<usize> for CoolIndex { type Output = Self; #[inline] fn add(self, other: usize) -> Self { Self::new(self.index().wrapping_add(other)) } } impl core::ops::Sub<usize> for CoolIndex { type Output = Self; #[inline] fn sub(self, other: usize) -> Self { Self::new(self.index().wra...
:cmp::Ordering> { self.index().partial_cmp(other) } } impl core::cmp::PartialOrd<CoolIndex> for usize { #[inline] fn partial_cmp(&self, other: &CoolIndex) -> Option<core::cmp::Ordering> { self.partial_cmp(&other.index()) } } impl PartialEq<usize> for CoolIndex { #[inline] fn eq(&...
random
[ { "content": "/// Represents a wrapped value convertable to and from a `usize`.\n\n///\n\n/// Generally you implement this via the [`define_index_type!`] macro, rather\n\n/// than manually implementing it.\n\n///\n\n/// # Overflow\n\n///\n\n/// `Idx` impls are allowed to be smaller than `usize`, which means con...
Rust
src/iter/union_zip.rs
AaronSteel/analytic
6974a4fdc67282651aeeb2e91f5b042d3315ecd7
use std::{ collections::{HashMap, HashSet}, hash::Hash, vec::IntoIter, }; pub trait UnionZip<K, M> { fn union_zip<'a>(&'a self, other: &'a M) -> UnionZipped<'a, K, M>; } pub trait IntoUnionZip<'a, K, M> { fn into_union_zip(self, other: &'a M) -> UnionZipped<'a, K, M>; } pub struct UnionZipped<'a,...
use std::{ collections::{HashMap, HashSet}, hash::Hash, vec::IntoIter, }; pub trait UnionZip<K, M> { fn union_zip<'a>(&'a self, other: &'a M) -> UnionZipped<'a, K, M>; } pub trait IntoUnionZip<'a, K, M> { fn into_union_zip(self, other: &'a M) -> UnionZipped<'a, K, M>; } pub struct UnionZipped<'a,...
}
8)])), iter2.next() ); assert_eq!(Some((9, vec![None, Some(&29), None])), iter2.next()); assert_eq!(Some((12, vec![Some(&6), None, None])), iter2.next()); assert_eq!(Some((14, vec![None, None, Some(&68)])), iter2.next()); assert_eq!(None, iter2.next()); let m...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn standard_deviation<'a, T: Clone + Iterator<Item = &'a A>, A>(\n\n element_iterator: T,\n\n ddof: usize,\n\n) -> f64\n\nwhere\n\n A: Copy + ToPrimitive + 'a,\n\n &'a A: Deref, {\n\n variance(element_iterator, ddof).sqrt()\n\n}\n\n\n", "file_path": "src/stats.r...
Rust
lib_raytracer/src/exercise1/object_file.rs
Therdel/rust_raytracer
01f6070020031b13c5cea7690eed7b0e891b41a5
use std::error::Error; use std::fmt::{self, Debug, Display}; use std::io::{self, BufRead, ErrorKind}; use std::ops::Neg; use std::path::Path; use nalgebra_glm as glm; use tobj::{LoadError, LoadOptions, Model, MTLLoadResult}; use crate::raytracing::{Material, Mesh, Triangle}; use crate::raytracing::bvh::BVH; use crate...
use std::error::Error; use std::fmt::{self, Debug, Display}; use std::io::{self, BufRead, ErrorKind}; use std::ops::Neg; use std::path::Path; use nalgebra_glm as glm; use tobj::{LoadError, LoadOptions, Model, MTLLoadResult}; use crate::raytracing::{Material, Mesh, Triangle}; use crate::raytracing::bvh::BVH; use crate...
fn deflatten_three_vec3s(flattened: &[f32], indices: [usize; 3]) -> [glm::Vec3; 3] { [ deflatten_vec3(flattened, indices[0]), deflatten_vec3(flattened, indices[1]), deflatten_vec3(flattened, indices[2]) ] } fn deflatten_vec3(flattened: &[f32], ...
fn check_and_count_triangles(name: &str, models: &[Model]) -> io::Result<usize> { let mut triangle_count = 0; for model in models { if model.mesh.positions.len() != model.mesh.normals.len() { return ObjLoadError::create_err(name, "Mesh doesn't have exactly one normal per vertex".to_string()...
function_block-full_function
[ { "content": "pub fn take_hitpoint_if_closer<'material>(closest_hitpoint: &mut Option<Hitpoint>,\n\n hitpoint: Option<Hitpoint>) {\n\n if let Some(hitpoint) = hitpoint {\n\n if let Some(ref mut closest_hitpoint) = closest_hitpoint {\n\n if hitpoint.t...
Rust
src/lp_response.rs
Fortunato28/vk2tg_translator
ae63a74dfae1476d1a818d952daff2c5b1ef4c1a
use anyhow::{Context, Result}; use serde_json::Value; use std::any::type_name; use crate::meta_data; pub async fn get_update(meta_data: &meta_data::MetaData) -> Result<Response> { let response = perform_lp_request(meta_data).await; parse_response(&response) } pub async fn perform_lp_request(meta_data: &meta_...
use anyhow::{Context, Result}; use serde_json::Value; use std::any::type_name; use crate::meta_data; pub async fn get_update(meta_data: &meta_data::MetaData) -> Result<Response> { let response = perform_lp_request(meta_data).await; parse_response(&response) } pub async fn perform_lp_request(meta_data: &meta_...
fAHuTPw.jpg", "photo_807":"https:\/\/sun1-21.userapi.com\/uQeCuz0_tZrvx1wx3nMBmWdKBg1mYJzrOaBFRw\/9Q9SBpsB_dM.jpg", "post_id":26, "text":"", "user_id":100, ...
604")); if attach_link.is_none() { continue; } } } if let Some(attach_link) = attach_link.unwrap().as_str() { post.add_attach_link(attach_link); } } posts.pu...
random
[ { "content": "use anyhow::{anyhow, Result};\n\nuse std::env;\n\n\n\n#[derive(Debug)]\n\npub struct Group {\n\n pub link: String,\n\n pub id: String,\n\n pub access_token: String,\n\n}\n\n\n\nimpl Group {\n\n pub fn new(link: &str) -> Group {\n\n let link = link.to_owned();\n\n let id =...
Rust
kernel/h1/src/hil/flash/fake.rs
tjshep/tock-on-titan
fe956de0ce9fa1d4c1859423724490e7abaa6a2b
#[derive(Clone,Copy,Default)] struct LogEntry { value: u32, offset: usize, } pub struct FakeHw { error: core::cell::Cell<u16>, opcode: core::cell::Cell<u32>, transaction_offset: core::cell::Cell<usize>, transaction_size: core::cell::Cell<usize>, write_data: [cor...
#[derive(Clone,Copy,Default)] struct LogEntry { value: u32, offset: usize, } pub struct FakeHw { error: core::cell::Cell<u16>, opcode: core::cell::Cell<u32>, transaction_offset: core::cell::Cell<usize>, transaction_size: core::cell::Cell<usize>, write_data: [cor...
if self.opcode.get() == super::driver::ERASE_OPCODE { core::u32::MAX } else { self.write_data[i].get() }, offset: self.transaction_offset.get() + i, }); self.log_len.set(self.log_len.get() ...
Self { error: Default::default(), opcode: Default::default(), transaction_offset: Default::default(), transaction_size: Default::default(), write_data: Default::default(), log: Default::def...
random
[ { "content": "// Computes the counter value for the given low and high counts.\n\npub fn counter_value(mut high_count: u32, mut low_count: u32) -> u32 {\n\n if high_count & 1 != 0 {\n\n // High count is odd, fast-forward to the state after low_count is\n\n // erased.\n\n high_count += 1;...
Rust
src/tinyinstallj/mod.rs
ThatCoolCoder/tinyinstallj
7f429e339f984e8057c0fbc2c7decd9dc980d00b
use std; use std::path::PathBuf; use webbrowser; use bytes::Bytes; #[cfg(target_family = "unix")] use isatty; mod check_is_admin; mod check_java_installation; mod install; mod config; mod utils; mod get_install_paths; use get_install_paths::InstallPaths; pub fn install(force_install: bool) { ...
use std; use std::path::PathBuf; use webbrowser; use bytes::Bytes; #[cfg(target_family = "unix")] use isatty; mod check_is_admin; mod check_java_installation; mod install; mod config; mod utils; mod get_install_paths; use get_install_paths::InstallPaths; pub fn install(force_install: bool) { ...
#[cfg(target_family = "unix")] fn ask_user_to_run_in_terminal() { match std::process::Command::new("notify-send") .arg("-t") .arg("0") .arg(format!("Error installing {}", config::FULL_PROGRAM_NAME)) .arg("This installer must be run in a terminal as root") .spawn() ...
k() { std::process::exit(0); } break; } } ask_user_to_run_in_terminal(); } }
function_block-function_prefixed
[ { "content": "pub fn create_runner_script(install_paths: &InstallPaths) -> Result<(), String> {\n\n let runner_script_contents = match std::env::consts::OS {\n\n \"windows\" => format!(\"@ECHO OFF\n\n START /B javaw {jvm_arguments} -jar \\\"{jar_path}\\\"\",\n\n jvm_arguments=con...
Rust
src/memory/simple.rs
fzi-forschungszentrum-informatik/firrtl-ast
79cdb65275ce872bd5357ef16be53aede7913aa9
use std::fmt; use std::sync::Arc; #[cfg(test)] use quickcheck::{Arbitrary, Gen}; use crate::expr; use crate::named::Named; use crate::types; use super::common::{PortDir, ReadUnderWrite}; #[derive(Clone, Debug, PartialEq)] pub struct Memory { name: Arc<str>, data_type: types::Type, kind: Kind, } impl ...
use std::fmt; use std::sync::Arc; #[cfg(test)] use quickcheck::{Arbitrary, Gen}; use crate::expr; use crate::named::Named; use crate::types; use super::common::{PortDir, ReadUnderWrite}; #[derive(Clone, Debug, PartialEq)] pub struct Memory { name: Arc<str>, data_type: types::Type, kind: Kind, } impl ...
let d = self.direction().clone(); let a = self.address().clone(); let c = self.clock().clone(); move |m| Self::new(n.clone(), m, d, a.clone(), c.clone()) })) .chain(self.direction().shrink().map({ let n = self.name.clone(); ...
> Box<dyn Iterator<Item = Self>> { use crate::tests::Identifier; let res = Identifier::from(self.name_ref()) .shrink() .map({ let m = self.memory().clone(); let d = self.direction().clone(); let a = self.address().clone(); ...
random
[ { "content": "/// Generate a Flow suitable for a source\n\npub fn source_flow(g: &mut Gen) -> Flow {\n\n g.choose(&[Flow::Source, Flow::Duplex]).unwrap().clone()\n\n}\n\n\n\n\n", "file_path": "src/expr/tests.rs", "rank": 0, "score": 226064.96782765095 }, { "content": "/// Generate a vecto...
Rust
libsplinter/src/mesh/mod.rs
desktophero/splinter-1
6dd88679ec30e18321201e1f5b4617469d433e0b
mod control; mod incoming; #[cfg(feature = "matrix")] mod matrix; mod outgoing; mod pool; mod reactor; use std::collections::HashMap; use std::error::Error; use std::io; use std::sync::{Arc, RwLock}; use std::time::Duration; pub use crate::mesh::control::{AddError, Control, RemoveError}; pub use crate::mesh::incomi...
mod control; mod incoming; #[cfg(feature = "matrix")] mod matrix; mod outgoing; mod pool; mod reactor; use std::collections::HashMap; use std::error::Error; use std::io; use std::sync::{Arc, RwLock}; use std::time::Duration; pub use crate::mesh::control::{AddError, Control, RemoveError}; pub use crate::mesh::incomi...
None => Err(SendError::NotFound), } } pub fn recv(&self) -> Result<Envelope, RecvError> { self.incoming.recv().map_err(|_| RecvError) } pub fn recv_timeout(&self, timeout: Duration) -> Result<Envelope, RecvTimeoutError> { self.incoming .recv_time...
ap!(self.outgoings); let id = envelope.id(); match outgoings.get(&envelope.id()) { Some(ref outgoing) => match outgoing.send(envelope.take_payload()) { Ok(()) => Ok(()), Err(err) => Err(SendError::from_outgoing_send_error(err, id)), },
function_block-random_span
[ { "content": "pub fn into_bytes(payload: web::Payload) -> impl Future<Item = Vec<u8>, Error = ActixError> {\n\n payload\n\n .from_err::<ActixError>()\n\n .fold(web::BytesMut::new(), move |mut body, chunk| {\n\n body.extend_from_slice(&chunk);\n\n Ok::<_, ActixError>(body)\...
Rust
src/bin/trigger_clustering_tool.rs
jaredvann/Timepix-Spidr-Data-Parser
dcff3b0dd59d06bbf48a7743e703fdbf44b07ea5
/* * ARIADNE Experiment, Department of Physics, University of Liverpool * * ------------------------------------ * Timepix Trigger Data Clustering Tool * ------------------------------------ * * timepix-spidr-data-parser/src/bin/trigger_clustering_tool.rs * * Authors: Jared Vann */ extern crate serde_derive;...
/* * ARIADNE Experiment, Department of Physics, University of Liverpool * * ------------------------------------ * Timepix Trigger Data Clustering Tool * ------------------------------------ * * timepix-spidr-data-parser/src/bin/trigger_clustering_tool.rs * * Authors: Jared Vann */ extern crate serde_derive;...
e); } } } i += 1; if cluster.len() < settings.min_cluster_hits as usize { continue; } let sum_tot: u32 = cluster.iter().map(|hit| hit.tot).sum(); if sum_tot < settings.min_cluster_tot { continue; } c...
function_block-function_prefixed
[ { "content": "pub fn write_cluster_to_file(file: &mut File, cluster: &[Hit], toa_adjustment: i64) -> io::Result<()> {\n\n let mut buf = Vec::with_capacity((cluster.len() + 1) * 16);\n\n\n\n for hit in cluster {\n\n let toa = hit.toa as i64 + toa_adjustment;\n\n\n\n if toa < 0 {\n\n ...
Rust
boa_engine/src/object/internal_methods/global.rs
kilotaras/boa
3b4708ce2f7275f607e061e6c5d070f78f246c77
use crate::{ object::{InternalObjectMethods, JsObject, ORDINARY_INTERNAL_METHODS}, property::{DescriptorKind, PropertyDescriptor, PropertyKey}, value::JsValue, Context, JsResult, }; use boa_profiler::Profiler; pub(crate) static GLOBAL_INTERNAL_METHODS: InternalObjectMethods = InternalObjectMethods { ...
use crate::{ object::{InternalObjectMethods, JsObject, ORDINARY_INTERNAL_METHODS}, property::{DescriptorKind, PropertyDescriptor, PropertyKey}, value::JsValue, Context, JsResult, }; use boa_profiler::Profiler; pub(crate) static GLOBAL_INTERNAL_METHODS: InternalObjectMethods = InternalObjectMethods { ...
=> Ok(JsValue::undefined()), }, } } #[inline] #[allow(clippy::needless_pass_by_value)] pub(crate) fn global_set( _obj: &JsObject, key: PropertyKey, value: JsValue, _receiver: JsValue, context: &mut Context, ) -> JsResult<bool> { global_set_no_receiver(&key, value, context) } #[inli...
ue.clone()), DescriptorKind::Accessor { get: Some(get), .. } if !get.is_undefined() => { context.call(get, &receiver, &[]) } _
function_block-random_span
[]
Rust
rust-runtime/aws-smithy-client/src/dvr.rs
matago/smithy-rs
75056c6a780529692e1b44e18402352205f9e1f6
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use std::collections::HashMap; use bytes::Bytes; use serde::{Deserialize, Serialize}; use aws_smithy_types::base64; pub use record::RecordingConnection; pub use replay::ReplayingConnection; mod recor...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use std::collections::HashMap; use bytes::Bytes; use serde::{Deserialize, Serialize}; use aws_smithy_types::base64; pub use record::RecordingConnection; pub use replay::ReplayingConnection; mod recor...
Response { status: u16, version: String, headers: HashMap<String, Vec<String>>, } impl From<&Request> for http::Request<()> { fn from(request: &Request) -> Self { let mut builder = http::Request::builder().uri(request.uri.as_str()); for (k, values) in request.headers.iter() { ...
, } impl NetworkTraffic { pub fn events(&self) -> &Vec<Event> { &self.events } } #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub enum Version { V0, } #[derive(Copy, Clone, Debug, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct ConnectionId(usize); #[de...
random
[ { "content": "/// Parses a semver version number and adds additional error context when parsing fails.\n\npub fn parse_version(manifest_path: &Path, version: &str) -> Result<Version, Error> {\n\n Version::parse(version)\n\n .map_err(|err| Error::InvalidCrateVersion(manifest_path.into(), version.into()...
Rust
src/slots.rs
rustiqtech/solana-exporter
6b72112ab16a3ff7d0cf1d711949b470559f95df
use crate::config::Whitelist; use log::{debug, log_enabled, Level}; use prometheus_exporter::prometheus::{GaugeVec, IntCounterVec}; use solana_client::{client_error::ClientError, rpc_client::RpcClient}; use solana_sdk::epoch_info::EpochInfo; use std::collections::BTreeMap; use std::fmt::{self, Display, Formatter}; c...
use crate::config::Whitelist; use log::{debug, log_enabled, Level}; use prometheus_exporter::prometheus::{GaugeVec, IntCounterVec}; use solana_client::{client_error::ClientError, rpc_client::RpcClient}; use solana_sdk::epoch_info::EpochInfo; use std::collections::BTreeMap; use std::fmt::{self, Display, Formatter}; c...
fn get_slot_leaders(&self, epoch: Option<u64>) -> Result<BTreeMap<usize, String>, ClientError> { let mut slot_leaders = BTreeMap::new(); match self.client.get_leader_schedule(epoch)? { None => (), Some(leader_schedule) => { for (pk, slots) in leade...
s| { self.leader_slots .get_metric_with_label_values(&[leader, &slot_status.to_string()]) .map(|m| m.get()) .unwrap_or_default() }; let skipped_count = get_count(SlotStatus::Skipped); let validated_count = ge...
function_block-function_prefixed
[ { "content": "/// Applies `f` to the first block in `epoch`.\n\npub fn with_first_block<F, A>(client: &RpcClient, epoch: Epoch, f: F) -> anyhow::Result<Option<A>>\n\nwhere\n\n F: Fn(u64) -> anyhow::Result<Option<A>>,\n\n{\n\n let epoch_schedule = client.get_epoch_schedule()?;\n\n let first_slot = epoch...
Rust
src/cli/mod.rs
lmapii/run_clang_format
153a3fd24813ce4ea8846bf38f1263dcb4f044db
use std::{path, process}; mod handlers; mod logging; pub mod utils; use clap::{arg, crate_authors, crate_description, crate_name, crate_version}; #[allow(unused_imports)] use color_eyre::{eyre::eyre, eyre::WrapErr, Help}; use schemars::{schema_for, JsonSchema}; use serde::Deserialize; #[derive(Deserialize, Debug, Js...
use std::{path, process}; mod handlers; mod logging; pub mod utils; use clap::{arg, crate_authors, crate_description, crate_name, crate_version}; #[allow(unused_imports)] use color_eyre::{eyre::eyre, eyre::WrapErr, Help}; use schemars::{schema_for, JsonSchema}; use serde::Deserialize; #[derive(Deserialize, Debug, Js...
pub fn parse(self) -> eyre::Result<Data> { if self.matches.subcommand_matches("schema").is_some() { println!("{}", JsonModel::schema(),); process::exit(0); } let json_path = self.path_for_key("JSON", true)?; let json = JsonModel::load(&json_path).wrap_err("...
pub fn build() -> Builder { let cmd = Builder::app(); let builder = Builder { matches: cmd.get_matches(), }; logging::setup(&builder.matches); builder }
function_block-full_function
[ { "content": "pub fn style_and_root(data: &cli::Data) -> eyre::Result<Option<(path::PathBuf, path::PathBuf)>> {\n\n let style_file = resolve_style_file(data)?;\n\n let style_root = match &data.json.style_root {\n\n None => None,\n\n Some(path) => {\n\n let path = if path.is_absolu...
Rust
src/db.rs
MaxLuchs/databases
cd8151e30b6196f94a775f2f59bcbb1ad1494b17
use crate::utils::{copy_dir_all, list_all_folders}; use eyre::*; use std::env::set_current_dir; use std::fs::{create_dir, remove_dir_all, remove_file, File}; use std::io::{BufRead, BufReader, Write}; use std::path::Path; use std::process::Command; #[derive(Debug, PartialOrd, PartialEq, Copy, Clone)] pub enum DB { ...
use crate::utils::{copy_dir_all, list_all_folders}; use eyre::*; use std::env::set_current_dir; use std::fs::{create_dir, remove_dir_all, remove_file, File}; use std::io::{BufRead, BufReader, Write}; use std::path::Path; use std::process::Command; #[derive(Debug, PartialOrd, PartialEq, Copy, Clone)] pub enum DB { ...
pub fn create_db(root: &Path, name: String, db: DB) -> Result<()> { let target_path = root.join("existing_dbs").join(name); if target_path.exists() { return Err(eyre::eyre!("DB already exists")); } if !root.join("existing_dbs").exists() { create_dir(root.join("existing_dbs"))? } ...
b_password, port ); println!("Env-file : {}", env_content); file.write_all(env_content.as_bytes())?; Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn list_all_folders(path: &Path) -> Result<Vec<Box<Path>>> {\n\n let dirs = read_dir(path)?;\n\n Ok(dirs\n\n .map(|dir| dir.unwrap().path().into_boxed_path())\n\n .collect())\n\n}\n\nuse std::fs;\n\n\n", "file_path": "src/utils.rs", "rank": 9, "score": 106866.97...
Rust
crates/sap-aria/src/state.rs
mc1098/sap
335bef4c49e044a2eb48b089ab77cc58676e0e16
use crate::utils::*; macro_rules! aria_state { ($(#[$enum_comment:meta])+ $enum_name:ident {$( $(#[$var_comment:meta])+ $var_name:ident($var_type:ty) => $implicit: expr ),*$(,)?}) => { $(#[$enum_comment])+ pub enum $enum_name { $( $(#[$var_comment])+ ...
use crate::utils::*; macro_rules! aria_state { ($(#[$enum_comment:meta])+ $enum_name:ident {$( $(#[$var_comment:meta])+ $var_name:ident($var_type:ty) => $implicit: expr ),*$(,)?}) => { $(#[$enum_comment])+ pub enum $enum_name { $( $(#[$var_comment])+ ...
pl! { DuoState { True, False, Undefined, } } enum_to_lowercase_string_impl! { TriState { False, Mixed, True, Undefined, } } enum_to_lowercase_string_impl! { ...
- `radio` - `checkbox` */ Checked(TriState) => state_checked, Current(CurrentToken) => state_default, /** Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. Attribute parity:...
random
[ { "content": "fn element_selection_string(element: &Element) -> String {\n\n let html = format_html(&element.outer_html());\n\n\n\n let (opening_tag, rest) = html.split_at(html.find('>').unwrap());\n\n if rest.starts_with(\">\\n\") {\n\n let mut opening_tag = opening_tag.to_owned();\n\n o...
Rust
src/lib.rs
zgtm/iron-sessionstorage
2c79d9358ff846bd4fccfc80e362e5541f0644a0
extern crate cookie as _cookie; #[macro_use] extern crate error_chain; #[cfg(feature = "redis-backend")] #[macro_use] extern crate iron; #[cfg(not(feature = "redis-backend"))] extern crate iron; extern crate rand; #[cfg(feature = "redis-backend")] extern crate redis; #[cfg(feature = "redis-backend")] extern crate r2d2;...
extern crate cookie as _cookie; #[macro_use] extern crate error_chain; #[cfg(feature = "redis-backend")] #[macro_use] extern crate iron; #[cfg(not(feature = "redis-backend"))] extern crate iron; extern crate rand; #[cfg(feature = "redis-backend")] extern crate redis; #[cfg(feature = "redis-backend")] extern crate r2d2;...
pub mod traits { pub use super::{SessionRequestExt}; } #[cfg(test)] mod tests { #[test] fn it_works() { } }
fn get_default_cookie(key: String, value: String) -> cookie::Cookie { let mut rv = cookie::Cookie::new(key, value); rv.httponly = true; rv.path = Some("/".to_owned()); rv }
function_block-function_prefix_line
[ { "content": "fn handler(req: &mut Request) -> IronResult<Response> {\n\n let mut value = match try!(req.session().get::<Aaa>()) {\n\n Some(aaa) => aaa,\n\n None => Aaa(\"\".to_owned())\n\n };\n\n\n\n let res = Ok(Response::with(\n\n format!(\"Reload this page to add an a: {}\\n\\n...
Rust
tauri/src/webview.rs
nklayman/tauri
4eeacf3ec9a07ad8f27d8fe2390e85bdc62459b5
pub(crate) mod wry; pub use crate::{api::config::WindowConfig, plugin::PluginStore}; pub enum Event { Run(crate::SyncTask), } pub enum Message { EvalScript(String), SetWindowTitle(String), Event(Event), } pub trait WindowBuilderExt: Sized { type Window; fn new() -> Self; fn x(self, x: f6...
pub(crate) mod wry; pub use crate::{api::config::WindowConfig, plugin::PluginStore}; pub enum Event { Run(crate::SyncTask), } pub enum Message { EvalScript(String), SetWindowTitle(String), Event(Event), } pub trait WindowBuilderExt: Sized { type Window; fn new() -> Self; fn x(self, x: f6...
} pub trait WebviewBuilderExt: Sized { type Webview; fn new() -> Self; fn url(self, url: String) -> Self; fn initialization_script(self, init: &str) -> Self; fn finish(self) -> crate::Result<Self::Webview>; } pub struct Callback<D> { pub name: String, pub function: Box<dyn FnMu...
fn from(config: &WindowConfig) -> Self { let mut window = T::new() .title(config.title.to_string()) .width(config.width) .height(config.height) .visible(config.visible) .resizable(config.resizable) .decorations(config.decorations) .maximized(config.maximized) .fullscr...
function_block-full_function
[ { "content": "#[cfg(event)]\n\npub fn listen_fn(event: String, handler: String, once: bool) -> crate::Result<String> {\n\n Ok(format!(\n\n \"if (window['{listeners}'] === void 0) {{\n\n window['{listeners}'] = {{}}\n\n }}\n\n if (window['{listeners}']['{evt}'] === void 0) {{\n\n window['{l...