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
common/cros_asyncv2/src/file.rs
riscv-android-src/platform-external-crosvm
8f02969ec4253395cac80c7571d5a3ad6d0e566a
use std::{ convert::{TryFrom, TryInto}, fs::File as StdFile, io, path::Path, }; use sys_util::AsRawDescriptor; use crate::{sys, AsIoBufs}; static DOWNCAST_ERROR: &str = "inner error not downcastable to `io::Error`"; #[derive(Debug)] pub struct File { inner: sys::File, } impl File { ...
use std::{ convert::{TryFrom, TryInto}, fs::File as StdFile, io, path::Path, }; use sys_util::AsRawDescriptor; use crate::{sys, AsIoBufs}; static DOWNCAST_ERROR: &str = "inner error not downcastable to `io::Error`"; #[derive(Debug)] pub struct File { inner: sys::File, } impl File { ...
offset).await { Ok(0) => return Err(io::Error::from(io::ErrorKind::WriteZero).into()), Ok(n) => { buf = &buf[n..]; if let Some(off) = offset { offset = Some(off + n as u64); } } ...
, buf: B, offset: Option<u64>, ) -> (anyhow::Result<usize>, B) { self.inner.read_iobuf(buf, offset).await } pub async fn write(&self, buf: &[u8], offset: Option<u64>) -> anyhow::Result<usize> { self.inner.write(buf,...
random
[ { "content": "/// Write a protective MBR for a disk of the given total size (in bytes).\n\n///\n\n/// This should be written at the start of the disk, before the GPT header. It is one `SECTOR_SIZE`\n\n/// long.\n\npub fn write_protective_mbr(file: &mut impl Write, disk_size: u64) -> Result<(), Error> {\n\n /...
Rust
tests/affine_transforms_test.rs
AlexandruIca/verg
adcdac98f57492e8b7576e06a92491934d2e0fa1
use verg::{ canvas::{Canvas, CanvasDescription, ViewBox}, color::{Color, FillRule, FillStyle}, geometry::{PathOps, Point}, math::{rotate_around, scale_around, skew_around, translate, Angle}, }; mod common; const WIDTH: usize = 1000; const HEIGHT: usize = 1000; fn canvas_description() -> CanvasDescr...
use verg::{ canvas::{Canvas, CanvasDescription, ViewBox}, color::{Color, FillRule, FillStyle}, geometry::{PathOps, Point}, math::{rotate_around, scale_around, skew_around, translate, Angle}, }; mod common; const WIDTH: usize = 1000; const HEIGHT: usize = 1000; fn canvas_description() -> CanvasDescr...
; rotate_around(&p, &center, Angle::from_degrees(rotate)) }; }; canvas.draw_shape( &PATH, blue, FILL_RULE, transform(20, 0.8, 0.5, 10.0, 10.0, 36.0), ); canvas.draw_shape( &PATH, crimson...
skew_around( &p, &center, Angle::from_degrees(skew_x), Angle::from_degrees(skew_y), )
call_expression
[ { "content": "pub fn scale_around(point: &Point, around: &Point, sx: f64, sy: f64) -> Point {\n\n let p = translate(point, -around.x, -around.y);\n\n let p = scale(&p, sx, sy);\n\n\n\n translate(&p, around.x, around.y)\n\n}\n\n\n", "file_path": "src/math.rs", "rank": 0, "score": 276355.7809...
Rust
src/gamemodes/gameplay.rs
Rocketman21/claw-machine
2980f1125d9fa84a8c656da829cbecab6e2bf4f1
use bevy::prelude::*; use bevy_kira_audio::AudioChannel; use iyes_loopless::prelude::*; use crate::{ claw::{ClawController, ClawControllerState}, GameState, assets::audio::{UiAudioChannel, AudioHandleStorage, AudioCollection, BackgroundAudioChannel}, ui::controls::Controls, constants::PURPLE_COLOR, helpers...
use bevy::prelude::*; use bevy_kira_audio::AudioChannel; use iyes_loopless::prelude::*; use crate::{ claw::{ClawController, ClawControllerState}, GameState, assets::audio::{UiAudioChannel, AudioHandleStorage, AudioCollection, BackgroundAudioChannel}, ui::controls::Controls, constants::PURPLE_COLOR, helpers...
ntity, &mut Countdown)>, mut query_text: Query<&mut Text, With<CountdownText>>, mut query_claw: Query<&mut ClawController>, mut commands: Commands, ) { if let Ok((entity, mut countdown)) = query_countdown.get_single_mut() { if countdown.0.tick(time.delta()).just_finished() { if let O...
yle: Style { margin: Rect { top: Val::Percent(10.0), left: Val::Percent(50.0), ..default() }, ..default() }, ..default() }) .with_children(|parent| { for index in 0..=1 { parent.spawn() ...
random
[ { "content": "fn setup_system(mut commands: Commands) {\n\n let translation = Vec3::new(-2.0, 2.5, 5.0);\n\n let radius = translation.length();\n\n\n\n commands.spawn_bundle(PerspectiveCameraBundle {\n\n transform: Transform::from_translation(translation)\n\n .looking_at(Vec3::new(0.0...
Rust
sylt-std/src/network.rs
th3tard1sparadox/sylt-lang
89a59c618cc41c6c106c328bcf02ddc00d743f7e
use crate as sylt_std; use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io::Write; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::ops::DerefMut; use std::rc::Rc; use std::str::FromStr; use std::sync::{Arc, Mutex}; use std::thread; use sylt_c...
use crate as sylt_std; use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io::Write; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::ops::DerefMut; use std::rc::Rc; use std::str::FromStr; use std::sync::{Arc, Mutex}; use std::thread; use sylt_c...
(Value::Bool(false)); } }; let serialized = match bincode::serialize(&get_rpc_args(ctx, 1, "n_rpc_client_ip")?) { Ok(serialized) => serialized, Err(e) => { eprintln!("Error serializing values: {:?}", e); return Ok(Value::Bool(false)); } }; ...
match stream.try_clone() { Ok(stream) => { if let Some(handles) = handles.lock().unwrap().as_mut() { handles.insert(addr, (stream, true)); } else { eprintln!("Server has been shutdown, ignoring connection from...
random
[ { "content": "fn simplify_type(ty: Type) -> Type {\n\n fn remove_duplicates(ty: Type, mut seen: Vec<Type>) -> Vec<Type> {\n\n match ty.kind {\n\n TypeKind::Union(ty, rest) => {\n\n if seen.iter().find(|a| **a == *ty).is_none() {\n\n seen.push(*ty);\n\n ...
Rust
dolby_vision/src/rpu/extension_metadata/blocks/level9.rs
amsokol/dovi_tool
458aadecf266575f199814a0479deb2dbe0fc95c
use anyhow::{ensure, Result}; use bitvec_helpers::{bitvec_reader::BitVecReader, bitvec_writer::BitVecWriter}; #[cfg(feature = "serde_feature")] use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; use crate::rpu::extension_metadata::MasteringDisplayPrimaries; use super::{ColorPrimaries, ExtMetadata...
use anyhow::{ensure, Result}; use bitvec_helpers::{bitvec_reader::BitVecReader, bitvec_writer::BitVecWriter}; #[cfg(feature = "serde_feature")] use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; use crate::rpu::extension_metadata::MasteringDisplayPrimaries; use super::{ColorPrimaries, ExtMetadata...
}
lf, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let name = "ExtMetadataBlockLevel9"; let fields_count = match self.length { 1 => 2, 17 => 10, _ => unreachable!(), }; let mut state = serializer.serialize_struct(name...
function_block-function_prefixed
[ { "content": "/// Assumes a list of size 8, otherwise panics\n\npub fn f64_to_integer_primaries(primaries: &[f64]) -> [u16; 8] {\n\n const SCALE: f64 = 1.0 / 32767.0;\n\n\n\n primaries\n\n .iter()\n\n .map(|v| (v / SCALE).round() as u16)\n\n .collect::<Vec<u16>>()\n\n .try_into...
Rust
src/lib.rs
spcan/common-regex
3238bc8ee85e0e000ea20913f09db6477edb2922
#[macro_use] extern crate lazy_static; extern crate regex; pub mod common; pub mod capture; #[cfg(test)] pub mod numbers_test { #[test] fn int_test() { use common::numbers::*; assert!( ALL.is_match("09876")); assert!( ALL.is_match("-345")); assert!( ALL.is_match("+876")); assert!( ALL.is_match("0")); ...
#[macro_use] extern crate lazy_static; extern crate regex; pub mod common; pub mod capture; #[cfg(test)] pub mod numbers_test { #[test] fn int_test() { use common::numbers::*; assert!( ALL.is_match("09876")); assert!( ALL.is_match("-345")); assert!( ALL.is_match("+876")); assert!( ALL.is_match("0")); ...
_WITH_SEPARATORS.is_match("987_")); } #[test] fn float_test() { use common::numbers::*; assert!( ALL.is_match("0.0")); assert!( ALL.is_match(".9")); assert!( ALL.is_match("9.")); assert!( ALL.is_match("1000.1000")); assert!( FLOAT.is_match("0.0")); assert!( FLOAT.is_match(".9")); assert!( FLOAT.is...
( INT_WITH_SEPARATORS.is_match("987_2")); assert!( INT_WITH_SEPARATORS.is_match("987_")); assert!( ALL_WITH_SEPARATORS.is_match("1_000_000")); assert!( ALL
function_block-random_span
[ { "content": "# common-regex\n\n\n\nSome of the most common regex used in applications. The aim of this project is to be expanded in time to provide coverage of a wide variety of topics.\n\n\n\n## Usage\n\n\n\nTo use, add to your Cargo.toml\n\n```\n\n[dependencies]\n\ncommon-regex = \"0.1\"\n\n```\n\n\n\nTo che...
Rust
src/simple_pong.rs
RichoDemus/webpong
38026ab122b35e7fb0385c752b73606be29151a3
use crate::network::message::{GameState, PaddleState}; #[cfg(not(target_arch = "wasm32"))] use log::*; use nalgebra::{Isometry2, Point2, Vector2}; use ncollide2d::query::Proximity; use ncollide2d::shape::Cuboid; use ncollide2d::{query, shape}; #[cfg(target_arch = "wasm32")] use quicksilver::log::*; #[derive(Debug)] pu...
use crate::network::message::{GameState, PaddleState}; #[cfg(not(target_arch = "wasm32"))] use log::*; use nalgebra::{Isometry2, Point2, Vector2}; use ncollide2d::query::Proximity; use ncollide2d::shape::Cuboid; use ncollide2d::{query, shape}; #[cfg(target_arch = "wasm32")] use quicksilver::log::*; #[derive(Debug)] pu...
mity = query::proximity( &ball_isometry, &self.ball.shape, &right_paddle_isometry, &self.right_paddle.shape, 0., ); if let Proximity::Intersecting = proximity { self.ball.velocity.x *= -1.; } } pub fn update_state(&...
let ball_isometry = Isometry2::new(self.ball.position.clone().coords, nalgebra::zero()); let left_paddle_isometry = Isometry2::new(self.left_paddle.position.clone().coords, nalgebra::zero()); let right_paddle_isometry = Isomet...
random
[ { "content": "pub fn draw(\n\n gfx: &mut Graphics,\n\n font: &mut FontRenderer,\n\n paused: bool,\n\n left_paddle: Paddle,\n\n right_paddle: Paddle,\n\n ball: Point2<f64>,\n\n server_ball: Point2<f64>,\n\n) -> std::result::Result<(), Box<dyn std::error::Error>> {\n\n let left_paddle_vec ...
Rust
src/config.rs
oasislabs/oasis-cli
6978247e51c6985136ec10c9338a68f9e1e5d0e9
use std::{ fmt, fs, os::unix::fs::PermissionsExt as _, path::{Path, PathBuf}, str::FromStr, }; use reqwest::Url; use crate::{ dialogue, emit, errors::{CliError, Error, ProfileError, ProfileErrorKind, Result}, }; pub struct Config { doc: toml_edit::Document, dirty: bool, } macro_rules...
use std::{ fmt, fs, os::unix::fs::PermissionsExt as _, path::{Path, PathBuf}, str::FromStr, }; use reqwest::Url; use crate::{ dialogue, emit, errors::{CliError, Error, ProfileError, ProfileErrorKind, Result}, }; pub struct Config { doc: toml_edit::Document, dirty: bool, } macro_rules...
fn write_to_file(&self, path: impl AsRef<Path>) -> Result<()> { fs::write(&path, self.doc.to_string_in_original_order())?; let mut perms = fs::metadata(&path)?.permissions(); perms.set_mode(0o600 /* o+rw */); fs::set_permissions(&path, perms)?; Ok(()) } fn skip_g...
fn read_from_file(path: &Path) -> Result<Self> { let config_string = fs::read_to_string(path) .map_err(|err| CliError::ReadFile(path.display().to_string(), err.to_string()))?; let doc = toml_edit::Document::from_str(&config_string) .map_err(|err| CliError::ConfigParse(path.displa...
function_block-function_prefix_line
[ { "content": "pub fn prompt_telemetry(telemetry_path: &std::path::Path) -> Result<bool, Error> {\n\n println!(\"{}\", \"1. Telemetry\\n\".bold().white());\n\n println!(\n\n \"Would you like to help build a better developer experience by enabling telemetry?\\n\\\n\n This tool will collect an...
Rust
src/step/transformer.rs
jmfiaschi/chewdata
58eb814ca749da682de57b82ac17bccdbebc8e4c
use super::DataResult; use crate::step::reader::Reader; use crate::step::Step; use crate::updater::{Action, UpdaterType}; use async_trait::async_trait; use crossbeam::channel::{Receiver, Sender}; use serde::Deserialize; use serde_json::Value; use std::{collections::HashMap, fmt, io}; use uuid::Uuid; #[derive(Debug, De...
use super::DataResult; use crate::step::reader::Reader; use crate::step::Step; use crate::updater::{Action, UpdaterType}; use async_trait::async_trait; use crossbeam::channel::{Receiver, Sender}; use serde::Deserialize; use serde_json::Value; use std::{collections::HashMap, fmt, io}; use uuid::Uuid; #[derive(Debug, De...
output_name: "output".to_string(), } } } impl fmt::Display for Transformer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Transformer {{'{}','{}' }}", self.alias .to_owned() .unwrap_or_else(||...
ault(), referentials: None, alias: Some(uuid.to_simple().to_string()), description: None, data_type: DataResult::OK.to_string(), wait_in_millisecond: 10, thread_number: 1, actions: Vec::default(), input_name: "input".to_stri...
random
[ { "content": "fn default_eof() -> String {\n\n \"\".to_string()\n\n}\n\n\n\nimpl fmt::Display for Io {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(\n\n f,\n\n \"{}\",\n\n String::from_utf8(self.inner.clone().into_inner()).unwrap_or_defa...
Rust
src/network_bridge.rs
placefortea/teatree
7a56755a428fe63ee753df67a7c71d8f668e17ec
use std::collections::HashMap; use std::marker::Send; use crate::actor::prelude::*; use crate::p2p::P2PActor; use crate::primitives::functions::{try_resend_times, DEFAULT_TIMES}; use crate::primitives::types::GroupID; use crate::rpc::RPCActor; use crate::traits::actor::{BridgeActor, P2PBridgeActor, RPCBridgeActor}; us...
use std::collections::HashMap; use std::marker::Send; use crate::actor::prelude::*; use crate::p2p::P2PActor; use crate::primitives::functions::{try_resend_times, DEFAULT_TIMES}; use crate::primitives::types::GroupID; use crate::rpc::RPCActor; use crate::traits::actor::{BridgeActor, P2PBridgeActor, RPCBridgeActor}; us...
} impl Handler<ReceiveLowerResponseMessage> for NetworkBridgeActor { type Result = (); fn handle( &mut self, msg: ReceiveLowerResponseMessage, _ctx: &mut Self::Context, ) -> Self::Result { self.bridges.get(&msg.0).and_then(|group| { Some( group ...
fn handle( &mut self, msg: ReceiveUpperResponseMessage, _ctx: &mut Self::Context, ) -> Self::Result { self.bridges.get(&msg.0).and_then(|group| { Some( group .recipient_upper_response .do_send(UpperResponseMessage(ms...
function_block-full_function
[ { "content": "pub trait BridgeActor<R = Context<Self>>\n\nwhere\n\n Self: Actor<Context = R>\n\n + Handler<EventMessage>\n\n + Handler<PeerJoinMessage>\n\n + Handler<PeerJoinResultMessage>\n\n + Handler<PeerLeaveMessage>\n\n + Handler<LocalMessage>\n\n + Handler<Uppe...
Rust
src/widgets/textbox.rs
ManevilleF/ui4
8ddcea8d4c6ff1f1d5fa1f6fb36de2754cec0586
use bevy::ecs::system::SystemState; use bevy::prelude::*; use std::sync::Arc; use std::time::Duration; use super::Focused; #[derive(Component)] pub struct TextBox(pub usize); #[derive(Component, Clone)] pub struct TextBoxFunc(Arc<dyn Fn(&mut World) -> &mut String + Send + Sync>); impl TextBoxFunc { pub fn new(f:...
use bevy::ecs::system::SystemState; use bevy::prelude::*; use std::sync::Arc; use std::time::Duration; use super::Focused; #[derive(Component)] pub struct TextBox(pub usize); #[derive(Component, Clone)] pub struct TextBoxFunc(Arc<dyn Fn(&mut World) -> &mut String + Send + Sync>); impl TextBoxFunc { pub fn new(f:...
} impl TextBoxSystemState { pub(crate) fn run(&mut self, world: &mut World) { let (mut reader, mut q, inp, time) = self.state.get_mut(world); self.tmp_chars.extend(reader.iter().map(|rc| rc.char)); if let Ok((tbf, cursor)) = q.get_single_mut() { let pl = inp.pressed(KeyCode::Le...
e: SystemState::new(world), tmp_chars: Vec::new(), timer: Timer::new(Duration::from_millis(100), true), } }
function_block-function_prefixed
[ { "content": "/// Initialize a new ui tree\n\npub fn init_ui(world: &mut World, root: impl FnOnce(Ctx) -> Ctx) {\n\n (Ctx {\n\n current_entity: world\n\n .spawn()\n\n .insert_bundle(NodeBundle::default())\n\n .insert(crate::prelude::Width(crate::prelude::Units::Auto))\...
Rust
crates/holochain/src/core/ribosome/guest_callback/validation_package.rs
guillemcordoba/holochain
fa4acd2067176757327328446368b1e09bfa2a34
use crate::core::ribosome::FnComponents; use crate::core::ribosome::HostContext; use crate::core::ribosome::Invocation; use crate::core::ribosome::InvocationAuth; use crate::core::ribosome::ZomesToInvoke; use derive_more::Constructor; use holo_hash::AnyDhtHash; use holochain_p2p::HolochainP2pDna; use holochain_serializ...
use crate::core::ribosome::FnComponents; use crate::core::ribosome::HostContext; use crate::core::ribosome::Invocation; use crate::core::ribosome::InvocationAuth; use crate::core::ribosome::ZomesToInvoke; use derive_more::Constructor; use holo_hash::AnyDhtHash; use holochain_p2p::HolochainP2pDna; use holochain_serializ...
#[tokio::test(flavor = "multi_thread")] async fn validation_package_invocation_fn_components() { let validation_package_invocation = ValidationPackageInvocationFixturator::new(::fixt::Unpredictable) .next() .unwrap(); let mut expected = vec![ ...
async fn validation_package_invocation_zomes() { let validation_package_invocation = ValidationPackageInvocationFixturator::new(::fixt::Unpredictable) .next() .unwrap(); let zome = validation_package_invocation.zome.clone(); assert_eq!( Zom...
function_block-full_function
[ { "content": "fn global_type(t: impl TryInto<GlobalZomeTypeId, Error = WasmError>) -> GlobalZomeTypeId {\n\n match t.try_into() {\n\n Ok(t) => t,\n\n Err(e) => panic!(\"Failed to convert to global zome type id: {:?}\", e),\n\n }\n\n}\n\n\n", "file_path": "crates/holochain_deterministic_i...
Rust
src/server/handler.rs
rustyhorde/libdeadmock
839e665be5597b1dacc4aa2c3d1351c68b70414f
use crate::config; use crate::error::Error; use crate::matcher::{Enabled, Matcher}; use crate::server::codec; use crate::server::header; use crate::util::{self, FutResponse}; use cached::{cached_key_result, UnboundCache}; use futures::{future, Future, Sink, Stream}; use http::{Request, Response, StatusCode}; use hype...
use crate::config; use crate::error::Error; use crate::matcher::{Enabled, Matcher}; use crate::server::codec; use crate::server::header; use crate::util::{self, FutResponse}; use cached::{cached_key_result, UnboundCache}; use futures::{future, Future, Sink, Stream}; use http::{Request, Response, StatusCode}; use hype...
#[allow(box_pointers)] fn http_response( handler: Handler, request: &Request<()>, response_config: &config::Response, ) -> FutResponse { if let Some(proxy_base_url) = response_config.proxy_base_url() { let full_url = format!("{}{}", proxy_base_url, request.uri()); let (tx, rx) = future...
Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), }; if let Ok(mapping) = matcher.get_match(&request, &locked_dynamic_mappings) { try_trace!(handler.stdout, ""); try_trace!( handler.stdout, "{:#^1$}", format!(...
function_block-function_prefix_line
[]
Rust
crates/tweet-fetch/src/search.rs
tirr-c/tweet-broadcast
2a0caf5e1f5c6a620b69d52aa2896b41714982de
use tweet_model as model; use crate::{ util, concat_param, Error, TwitterClient, }; fn create_endpoint_url( term: &str, max_results: u32, since_id: Option<&str>, next_token: Option<&str>, ) -> reqwest::Url { let mut url = reqwest::Url::parse("https://api.twitter.com/2/tweets...
use tweet_model as model; use crate::{ util, concat_param, Error, TwitterClient, }; fn create_endpoint_url( term: &str, max_results: u32, since_id: Option<&str>, next_token: Option<&str>, ) -> reqwest::Url { let mut url = reqwest::Url::parse("https://api.twitter.com/2/tweets...
pub async fn load_all( mut self, client: &TwitterClient, ) -> Result<model::ResponseItem<Vec<model::Tweet>>, Error> { if self.is_unbound() { let ret = self.next(client, 20).await?; self.apply_head(); return Ok(if let Some(ret) = ret { ...
pub async fn next( &mut self, client: &TwitterClient, max_results: u32, ) -> Result<Option<model::ResponseItem<Vec<model::Tweet>>>, Error> { let next_token = if let Some(token) = &self.next_token { token.as_deref() } else { return Ok(None); }; ...
function_block-full_function
[ { "content": "fn create_endpoint_url(id: &str, max_results: u32, pagination_token: Option<&str>) -> reqwest::Url {\n\n let mut url =\n\n reqwest::Url::parse(&format!(\"https://api.twitter.com/2/lists/{}/tweets\", id)).unwrap();\n\n url.query_pairs_mut()\n\n .append_pair(\"max_results\", &max...
Rust
necsim/impls/no-std/src/cogs/emigration_exit/independent/mod.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
use core::marker::PhantomData; use necsim_core::{ cogs::{Backup, CoalescenceRngSample, EmigrationExit, Habitat, RngCore}, landscape::{IndexedLocation, Location}, lineage::{GlobalLineageReference, MigratingLineage}, simulation::partial::emigration_exit::PartialSimulation, }; use necsim_core_bond::{NonNe...
use core::marker::PhantomData; use necsim_core::{ cogs::{Backup, CoalescenceRngSample, EmigrationExit, Habitat, RngCore}, landscape::{IndexedLocation, Location}, lineage::{GlobalLineageReference, MigratingLineage}, simulation::partial::emigration_exit::PartialSimulation, }; use necsim_core_bond::{NonNe...
if (target_subdomain == self.decomposition.get_subdomain_rank()) || !self.choice.should_lineage_emigrate( &dispersal_origin, event_time, &simulation.habitat, ) { return Some(( lineage_reference, ...
let target_subdomain = self .decomposition .map_location_to_subdomain_rank(&dispersal_target, &simulation.habitat);
assignment_statement
[ { "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/models/r5/ResearchStudy_ComparisonGroup.rs
itsbalamurali/rust-fhir
be43a387214586b6d8c5c5bf1d1f082a15c362b0
#![allow(unused_imports, non_camel_case_types)] use crate::models::r5::CodeableConcept::CodeableConcept; use crate::models::r5::Element::Element; use crate::models::r5::Extension::Extension; use crate::models::r5::Identifier::Identifier; use crate::models::r5::Reference::Reference; use serde_json::json; use serde_json...
#![allow(unused_imports, non_camel_case_types)] use crate::models::r5::CodeableConcept::CodeableConcept; use crate::models::r5::Element::Element; use crate::models::r5::Extension::Extension; use crate::models::r5::Identifier::Identifier; use crate::models::r5::Reference::Reference; use serde_json::json; use serde_json...
pub fn intended_exposure(&self) -> Option<Vec<Reference>> { if let Some(Value::Array(val)) = self.value.get("intendedExposure") { return Some( val.into_iter() .map(|e| Reference { value: Cow::Borrowed(e), }) ...
pub fn identifier_uri(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("identifierUri") { return Some(string); } return None; }
function_block-full_function
[ { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Definition {\n\n pattern: Option<String>,\n\n #[serde(rename = \"type\")]\n\n fhir_type: Option<String>,\n\n description: Option<String>,\n\n properties: Option<BTreeMap<String, Property>>,\n\...
Rust
src/analysis/cost_language.rs
simon-perriard/saft
844eeb900fb125e1c32193a23512b5160f2e9f52
use core::fmt; use rustc_middle::ty::TyCtxt; #[derive(Eq, PartialEq, Clone, Debug)] pub(crate) enum Cost { Concrete(u64), Symbolic(Symbolic), Add(Box<Cost>, Box<Cost>), ConcreteMul(u64, Box<Cost>), SymbolicMul(Symbolic, Box<Cost>), Max(Box<Cost>, Box<Cost>), } #[derive(Eq, PartialEq, Clone, De...
use core::fmt; use rustc_middle::ty::TyCtxt; #[derive(Eq, PartialEq, Clone, Debug)] pub(crate) enum Cost { Concrete(u64), Symbolic(Symbolic), Add(Box<Cost>, Box<Cost>), ConcreteMul(u64, Box<Cost>), SymbolicMul(Symbolic, Box<Cost>), Max(Box<Cost>, Box<Cost>), } #[derive(Eq, PartialEq, Clone, De...
Self::Concrete(x) => write!(f, "{}", x), Self::Symbolic(symbolic) => write!(f, "{}", symbolic), Self::Add(a, b) => write!(f, "{} + {}", a, b), Self::SymbolicMul(a, b) => { if b.pretty_print_need_parenthesis() { write!(f, "{} * ({})", a, b)...
flat.append(&mut b.flatten_add_chain()); } _ => flat.push(self.clone()), } flat } fn cmp_add_chain(&self, other: &Self) -> Option<Self> { let mut chain_1 = self.flatten_add_chain(); let mut chain_2 = other.flatten_add_chain(); c...
random
[ { "content": "pub fn set_if_missing(args: &mut Vec<String>) {\n\n if !args\n\n .iter()\n\n .any(|arg| arg == \"--sysroot\" || arg.starts_with(\"--sysroot=\"))\n\n {\n\n match get() {\n\n Some(sysroot) => {\n\n info!(\"sysroot={}\", sysroot);\n\n ...
Rust
google-cloud/src/vision/client.rs
dalloriam/google-cloud-rs
e9cbbd2c021b09a7a16c3463a2b409031cb7223b
use std::convert::TryFrom; use std::env; use std::fs::File; use std::sync::Arc; use tokio::sync::Mutex; use tonic::transport::{Certificate, Channel, ClientTlsConfig}; use tonic::{IntoRequest, Request}; use crate::authorize::{ApplicationCredentials, TokenManager, TLS_CERTS}; use crate::vision::api; use crate::vision::...
use std::convert::TryFrom; use std::env; use std::fs::File; use std::sync::Arc; use tokio::sync::Mutex; use tonic::transport::{Certificate, Channel, ClientTlsConfig}; use tonic::{IntoRequest, Request}; use crate::authorize::{ApplicationCredentials, TokenManager, TLS_CERTS}; use crate::vision::api; use crate::vision::...
pub async fn detect_faces( &mut self, image: Image, config: FaceDetectionConfig, ) -> Result<Vec<FaceAnnotation>, Error> { let request = api::AnnotateImageRequest { image: Some(image.into()), features: vec![api::Feature { r#type: api...
pub async fn detect_document_text( &mut self, image: Image, config: TextDetectionConfig, ) -> Result<Vec<TextAnnotation>, Error> { let request = api::AnnotateImageRequest { image: Some(image.into()), features: vec![api::Feature { r#type: api::f...
function_block-full_function
[ { "content": "#[proc_macro_derive(IntoValue, attributes(datastore))]\n\npub fn derive_into_value(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as syn::DeriveInput);\n\n let container = Container::from_derive_input(&input).unwrap();\n\n\n\n let ident = container.ident;\n\...
Rust
genesis-programs/src/lib.rs
t-nelson/solana
53aa4ea2e4d5c4aa3a3a09d8c6dc043338276bf4
#[macro_use] extern crate solana_bpf_loader_program; #[macro_use] extern crate solana_budget_program; #[macro_use] extern crate solana_exchange_program; #[macro_use] extern crate solana_vest_program; use log::*; use solana_runtime::bank::{Bank, EnteredEpochCallback}; use solana_sdk::{ clock::Epoch, entrypoint_nati...
#[macro_use] extern crate solana_bpf_loader_program; #[macro_use] extern crate solana_budget_program; #[macro_use] extern crate solana_exchange_program; #[macro_use] extern crate solana_vest_program; use log::*; use solana_runtime::bank::{Bank, EnteredEpochCallback}; use solana_sdk::{ clock::Epoch, entrypoint_nati...
} } if OperatingMode::Stable == operating_mode { bank.set_cross_program_support(bank.epoch() >= 63); } else { bank.set_cross_program_support(true); } }) } #[cfg(test)] mod tests { use super::*; use std::collections::HashSet; #[test] ...
match program { Program::Native((name, program_id)) => { bank.add_native_program(&name, &program_id); } Program::BuiltinLoader(( name, program_id, process_instructi...
if_condition
[ { "content": "fn deposit_many(bank: &Bank, pubkeys: &mut Vec<Pubkey>, num: usize) {\n\n for t in 0..num {\n\n let pubkey = Pubkey::new_rand();\n\n let account = Account::new((t + 1) as u64, 0, &Account::default().owner);\n\n pubkeys.push(pubkey);\n\n assert!(bank.get_account(&pubk...
Rust
src/lib.rs
whmountains/binary_prefix
66608bd1842f04b7e7ff1825297d952ccca60978
pub fn pad(size: usize, input: &[bool]) -> Vec<bool> { let input_len = input.len(); let mut out: Vec<bool> = Vec::new(); for _ in input_len..size { out.push(false); } for item in input.iter() { out.push(item.clone()); } out } fn find_seq(initial: bool, collect...
pub fn pad(size: usize, input: &[bool]) -> Vec<bool> { let input_len = input.len(); let mut out: Vec<bool> = Vec::new(); for _ in input_len..size { out.push(false); } for item in input.iter() { out.push(item.clone()); } out } fn find_seq(initial: bool, collect...
#[test] fn no_pad() { let expected = [false, true, false]; let result = pad(3, &vec![false, true, false]); assert_vec_equal(&result, &expected); } }
let expected = [false, false, false]; let input: Vec<bool> = Vec::new(); let result = pad(3, &input); assert_vec_equal(&result, &expected); }
function_block-function_prefix_line
[]
Rust
2017/18/src/lib.rs
PsypherPunk/advent-of-code
5da9cea793d0dd326d01ccaa307bfbb13ab8c06f
use std::collections::{HashMap, VecDeque}; use std::str::FromStr; #[derive(Clone)] enum Instruction { Snd(Value), Set(Value, Value), Add(Value, Value), Mul(Value, Value), Mod(Value, Value), Rcv(Value), Jgz(Value, Value), } pub struct Program { registers: HashMap<char, isize>, instr...
use std::collections::{HashMap, VecDeque}; use std::str::FromStr; #[derive(Clone)] enum Instruction { Snd(Value), Set(Value, Value), Add(Value, Value), Mul(Value, Value), Mod(Value, Value), Rcv(Value), Jgz(Value, Value), } pub struct Program { registers: HashMap<char, isize>, instr...
}
fn test_part_two() { let input = r#"snd 1 snd 2 snd p rcv a rcv b rcv c rcv d"#; let mut zero = Program::new(&input, 0); let mut one = Program::new(&input, 1); Program::duet(&mut zero, &mut one); assert_eq!(3, one.sent_count); }
function_block-full_function
[ { "content": "pub fn get_part_one(input: &str, display: bool) -> usize {\n\n let mut octopodes = get_octopodes(input);\n\n let mut flash_count = 0;\n\n\n\n let height = octopodes.len();\n\n let width = octopodes[0].len();\n\n\n\n for _ in 1..=100 {\n\n octopodes.iter_mut().for_each(|row| {...
Rust
src/text_domain.rs
Mangmasta/gettext-rs
333d2ff974e959e8c805b164da0de3bdb80a9507
use locale_config::{LanguageRange, Locale}; use std::default::Default; use std::env; use std::fmt; use std::fs; use std::path::PathBuf; use super::{bind_textdomain_codeset, bindtextdomain, setlocale, textdomain, LocaleCategory}; #[derive(Debug, PartialEq)] pub enum TextDomainError { InvalidLocale(String), ...
use locale_config::{LanguageRange, Locale}; use std::default::Default; use std::env; use std::fmt; use std::fs; use std::path::PathBuf; use super::{bind_textdomain_codeset, bindtextdomain, setlocale, textdomain, LocaleCategory}; #[derive(Debug, PartialEq)] pub enum TextDomainError { InvalidLocale(String), ...
text_domain.locale_category ); let text_domain = text_domain.codeset("UTF-8"); assert_eq!(Some("UTF-8".to_owned()), text_domain.codeset); let text_domain = text_domain.prepend("pre"); assert!(!text_domain.pre_paths.is_empty()); let text_domain = text_domain.pu...
ter) -> fmt::Result { let mut debug_struct = fmt.debug_struct("TextDomain"); debug_struct .field("name", &self.name.as_ref().unwrap()) .field( "locale", &match self.locale.as_ref() { Some(locale) => locale.to_owned(), ...
random
[ { "content": "fn posix_path(path: &Path) -> String {\n\n let path = path\n\n .to_str()\n\n .unwrap_or_else(|| fail(&format!(\"Couldn't convert path {:?} to string\", path)));\n\n if env::var(\"HOST\").unwrap().contains(\"windows\") {\n\n let path = path.replace(\"\\\\\", \"/\");\n\n ...
Rust
server/src/api/v1/handlers/demo.rs
zachmeyner/portal2-cm-boards-v2
aa43cf2d7f87fdd0ec25db9d272cec2d6630f903
use crate::models::models::{ Changelog, ChangelogInsert, DemoInsert, DemoOptions, Demos, Maps, SubmissionChangelog, }; use crate::tools::cache::CacheState; use crate::tools::config::Config; use crate::tools::helpers::check_for_valid_score; use actix_multipart::Multipart; use actix_web::{delete, get, post, web, Http...
use crate::models::models::{ Changelog, ChangelogInsert, DemoInsert, DemoOptions, Demos, Maps, SubmissionChangelog, }; use crate::tools::cache::CacheState; use crate::tools::config::Config; use crate::tools::helpers::check_for_valid_score; use actix_multipart::Multipart; use actix_web::{delete, get, post, web, Http...
#[delete("/demos")] pub async fn delete_demo( query: web::Query<DemoOptions>, config: web::Data<Config>, pool: web::Data<PgPool>, ) -> impl Responder { let query = query.into_inner(); let (cl, demo_id) = match get_changelog_and_demo_id(query, pool.get_ref()).await { Ok((cl, demo_id)) => (c...
log_insert.post_rank = details.post_rank; changelog_insert.pre_rank = details.pre_rank; changelog_insert.score_delta = details.score_delta; } else { eprintln!("USER IS BANNED, DO NOT ADD A TIME FOR THEM"); return HttpResponse::NotFound().body("...
function_block-function_prefixed
[ { "content": "/// Mounts the routes to /api/..\n\npub fn init(cfg: &mut web::ServiceConfig) {\n\n cfg.service(\n\n web::scope(\"/api/v1\")\n\n .service(get_singleplayer_maps) // SP\n\n .service(get_singleplayer_preview)\n\n .service(get_banned_scores_sp)\n\n ...
Rust
cli/ast/source_file_info.rs
Patil2099/deno
4ae57d185ea94f0217cf6234e4875cc84b4db8e8
use super::Location; use swc_common::BytePos; pub struct SourceFileInfo { pub specifier: String, pub text: String, line_start_byte_positions: Vec<BytePos>, } impl SourceFileInfo { pub fn new(specifier: &str, text: &str) -> SourceFileInfo { SourceFileInfo { line_start_byte_positions: get_line_star...
use super::Location; use swc_common::BytePos; pub struct SourceFileInfo { pub specifier: String, pub text: String, line_start_byte_positions: Vec<BytePos>, } impl SourceFileInfo { pub fn new(specifier: &str, text: &str) -> SourceFileInfo { SourceFileInfo { line_start_byte_positions: get_line_star...
fn get_column_on_line_index_at_pos( &self, line_index: usize, pos: BytePos, ) -> usize { assert!(line_index < self.line_start_byte_positions.len()); let pos = pos.0 as usize; let line_start_pos = self.line_start_byte_positions[line_index].0 as usize; let line_end_pos = self .line...
fn get_line_index_at_pos(&self, pos: BytePos) -> usize { match self.line_start_byte_positions.binary_search(&pos) { Ok(index) => index, Err(insert_index) => insert_index - 1, } }
function_block-full_function
[ { "content": "/// Print diff of the same file_path, before and after formatting.\n\n///\n\n/// Diff format is loosely based on Github diff formatting.\n\npub fn diff(orig_text: &str, edit_text: &str) -> String {\n\n if orig_text == edit_text {\n\n return String::new();\n\n }\n\n\n\n // normalize newlines ...
Rust
src/primes.rs
getreu/play-rsa
5da39b5c5b4f4d7314a466dfd1076402fb11a7e7
extern crate num; extern crate num_bigint as bigint; extern crate primal; extern crate rand; extern crate rustc_serialize; use bigint::{BigInt, BigUint, RandBigInt, ToBigInt, ToBigUint}; use num::{Integer, One, Zero}; fn small_primes(bound: usize) -> Vec<usize> { primal::Primes::all().take(bound).collect::<Vec<us...
extern crate num; extern crate num_bigint as bigint; extern crate primal; extern crate rand; extern crate rustc_serialize; use bigint::{BigInt, BigUint, RandBigInt, ToBigInt, ToBigUint}; use num::{Integer, One, Zero}; fn small_primes(bound: usize) -> Vec<usize> { primal::Primes::all().take(bound).collect::<Vec<us...
idate; if x == candidate - &one { break 'witness_loop; } else if x == one { return false; } s = s - &one; } return false; } true } pub fn is_prime(candidate: &BigUint) -> bool { for p in small_primes(100).iter()...
if candidate == &two { return true; } if candidate == &three { return true; } if candidate.is_even() { return false; } let (mut s, d) = rewrite(&(candidate - &one)); 'witness_loop: for _ in 0..K { let mut rng = rand::thread_rng(); let...
function_block-random_span
[ { "content": "/// Generate RSA key-pair with given size and exponent.\n\npub fn gen_keys(key_size: KeySizeT, e: PublicExponentT) -> (PublicKey, PrivateKey) {\n\n let key_size = match key_size {\n\n KeySizeT::KeySize(key_size) => key_size,\n\n _ => 1024, // This is the default key size!\n\n }...
Rust
src/trust_region.rs
tversteeg/levenberg-marquardt
ddcb61877ef940f40789e984d04213dc455543f4
#![allow(clippy::excessive_precision)] use crate::qr::LinearLeastSquaresDiagonalProblem; use crate::utils::{dwarf, enorm}; use nalgebra::{ allocator::Allocator, convert, DefaultAllocator, Dim, DimMax, DimMaximum, DimMin, OVector, RealField, }; use num_traits::Float; pub struct LMParameter<F: RealField, N: Di...
#![allow(clippy::excessive_precision)] use crate::qr::LinearLeastSquaresDiagonalProblem; use crate::utils::{dwarf, enorm}; use nalgebra::{ allocator::Allocator, convert, DefaultAllocator, Dim, DimMax, DimMaximum, DimMin, OVector, RealField, }; use num_traits::Float; pub struct LMParameter<F: RealField, N: Di...
#[test] fn test_case4() { let j = Matrix4x3::from_column_slice(&[ 14., -12., 20., -11., 19., 38., -4., -11., -14., 12., -20., 11., ]); let residual = Vector4::new(-5., 3., -2., 7.); let qr = PivotedQR::new(j); let mut lls = qr.into_least_squares_diagonal_pr...
7.); let qr = PivotedQR::new(j); let mut lls = qr.into_least_squares_diagonal_problem(residual); let diag = Vector3::new(4.2, 8.2, 11.2); let param = determine_lambda_and_parameter_update(&mut lls, &diag, 0.5, 0.2); assert_relative_eq!(param.lambda, 0.017646940861467262f64, eps...
function_block-function_prefixed
[ { "content": "/// Compute the derivative using an adaptive central difference quotient.\n\n///\n\n/// The algorithm is based on the Python package `numdifftools`. The approach\n\n/// used is:\n\n///\n\n/// - Use a heuristic to compute an initial step size `h`\n\n/// - Compute a second order central finite diffe...
Rust
src/message/header.rs
r-bk/rsdns
bd6a1750ead61984c23a6b3f97eb4193fe04a9e6
use crate::{ bytes::{Cursor, Reader}, constants::HEADER_LENGTH, message::Flags, Error, Result, }; #[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Header { pub id: u16, pub flags: Flags, pub qd_count: u16, pub an_count: u16,...
use crate::{ bytes::{Cursor, Reader}, constants::HEADER_LENGTH, message::Flags, Error, Result, }; #[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Header { pub id: u16, pub flags: Flags, pub qd_count: u16, pub an_count: u16,...
} } else { Err(Error::EndOfBuffer) } } } #[cfg(test)] mod tests { use super::*; use crate::{ bytes::{WCursor, Writer}, constants::{OpCode, RCode}, }; use rand::seq::IteratorRandom; #[test] fn test_serialization() { let mut rn...
Ok(Header { id: self.u16_be_unchecked(), flags: Flags::from(self.u16_be_unchecked()), qd_count: self.u16_be_unchecked(), an_count: self.u16_be_unchecked(), ns_count: self.u16_be_unchecked(), ar_count:...
call_expression
[ { "content": "#[inline(always)]\n\npub fn check_label(label: &str) -> Result<()> {\n\n check_label_bytes(label.as_bytes())\n\n}\n\n\n", "file_path": "src/names/utils.rs", "rank": 0, "score": 143020.07638758392 }, { "content": "#[inline(always)]\n\npub fn check_name(name: &str) -> Result<(...
Rust
src/db/update/span.rs
ikrelln/ikrelln
939c33aaaa58c373cfde985f997f7e2adf1a3151
use actix::prelude::Message; use actix::{Handler, MessageResult}; use chrono; use diesel; use diesel::prelude::*; use uuid; use crate::db::schema::span; #[derive(Debug, Insertable, Queryable)] #[table_name = "span"] pub struct SpanDb { pub trace_id: String, pub id: String, parent_id: Option<String>, na...
use actix::prelude::Message; use actix::{Handler, MessageResult}; use chrono; use diesel; use diesel::prelude::*; use uuid; use crate::db::schema::span; #[derive(Debug, Insertable, Queryable)] #[table_name = "span"] pub struct SpanDb { pub trace_id: String, pub id: String, parent_id: Option<String>, na...
impl Message for crate::opentracing::Span { type Result = crate::opentracing::Span; } impl super::DbExecutor { fn find_endpoint(&mut self, ep: &EndpointDb) -> Option<EndpointDb> { use super::super::schema::endpoint::dsl::*; let mut query = endpoint.into_boxed(); if let Some(query_ser...
trace_id: trace_id.clone(), id: span_id.clone(), parent_id: span.parent_id.clone(), name: span.name.clone().map(|s| s.to_lowercase()), kind: span.kind.clone().map(|k| k.to_string()), duration: span.duration, ts: span.timestamp.map(|ts| { chrono::N...
function_block-function_prefix_line
[ { "content": "CREATE UNIQUE INDEX UC_Endpoint_name_ipv4 ON endpoint (service_name, ipv4) WHERE (ipv4 is not null AND ipv6 is null and port is null);\n", "file_path": "migrations/2018-01-23-220231_span/up.sql", "rank": 0, "score": 207876.43678878507 }, { "content": "CREATE UNIQUE INDEX UC_End...
Rust
src/commands/mod.rs
iburinoc/spass
acdbbf8633839fa6311d51df89496aa7634c415a
extern crate clap; use clap::ArgMatches; use rusqlite::params; use crypto; use crypto::Key; use database; use database::Connection; use types::{Password, User}; use super::prompt_passw; mod generate; fn update_verify(user: &User, key: &Key, conn: &mut Connection) { let nuser = User { hash: user.hash, ...
extern crate clap; use clap::ArgMatches; use rusqlite::params; use crypto; use crypto::Key; use database; use database::Connection; use types::{Password, User}; use super::prompt_passw; mod generate; fn update_verify(user: &User, key: &Key, conn: &mut Connection) { let nuser = User { hash: user.hash, ...
pub fn gen(args: &ArgMatches, user: &User, key: &Key, conn: &mut Connection) -> Result<(), String> { let (ikey, nkey, pkey) = get_keys(key); let name = args.value_of("name").unwrap(); let id = crypto::password_id(&ikey, name.as_ref()); if database::password_by_id(conn, &id).is_some() { retu...
let (nikey, nnkey, npkey) = get_keys(&newkey); let passwords = database::get_passwords(conn); database::reset(conn); for passw in passwords { use std::str; let name = crypto::decrypt_blob(&nkey, passw.name.as_ref()).unwrap(); let pw = crypto::decrypt_blob(&pkey, passw.password.as_re...
function_block-function_prefix_line
[ { "content": "pub fn get_key(user: &User, pw: &str) -> Result<Key, String> {\n\n let mut k: Key = Default::default();\n\n let mut h: Hash = Default::default();\n\n\n\n derive_key(&mut k, &mut h, pw, &user.salt);\n\n if utils::memcmp(&h, &user.hash) {\n\n Ok(k)\n\n } else {\n\n Err(\...
Rust
src/lib.rs
17cupsofcoffee/lonely-star
f6e0808fd750e282b8ded5e01b66d371078db862
mod assets; mod audio; mod objects; use tetra::audio::Sound; use tetra::graphics::scaling::{ScalingMode, ScreenScaler}; use tetra::graphics::text::{Font, Text}; use tetra::graphics::{self, Color}; use tetra::math::Vec2; use tetra::time; use tetra::{Context, Event, State}; use rand::SeedableRng; use rand_pcg::Pcg64Mcg...
mod assets; mod audio; mod objects; use tetra::audio::Sound; use tetra::graphics::scaling::{ScalingMode, ScreenScaler}; use tetra::graphics::text::{Font, Text}; use tetra::graphics::{self, Color}; use tetra::math::Vec2; use tetra::time; use tetra::{Context, Event, State}; use rand::SeedableRng; use rand_pcg::Pcg64Mcg...
fn event(&mut self, _: &mut Context, event: Event) -> tetra::Result { if let Event::Resized { width, height } = event { self.scaler.set_outer_size(width, height); } Ok(()) } }
fn draw(&mut self, ctx: &mut Context) -> tetra::Result { graphics::set_canvas(ctx, self.scaler.canvas()); graphics::clear(ctx, Color::WHITE); let blend = time::get_blend_factor(ctx); self.backdrop.draw(ctx, &self.assets, self.speed, blend); for gate in &self.gates { ...
function_block-full_function
[ { "content": "use tetra::math::Vec2;\n\nuse tetra::Context;\n\n\n\nuse crate::assets::Assets;\n\n\n\npub struct Backdrop {\n\n position: Vec2<f32>,\n\n}\n\n\n\nimpl Backdrop {\n\n pub fn new() -> Backdrop {\n\n Backdrop {\n\n position: Vec2::zero(),\n\n }\n\n }\n\n\n\n pub f...
Rust
src/commands/tags.rs
nitros12/lolibot-rs
2ca207e7566f15e0a849411308e1bff79297aaac
use serenity::{ prelude::*, model::{ channel::Message, permissions::Permissions, }, framework::standard::{ StandardFramework, CommandError, }, utils::{ with_cache, MessageBuilder, }, }; use diesel::prelude::*; use diesel; use ::PgConnectionMana...
use serenity::{ prelude::*, model::{ channel::Message, permissions::Permissions, }, framework::standard::{ StandardFramework, CommandError, }, utils::{ with_cache, MessageBuilder, }, }; use diesel::prelude::*; use diesel; use ::PgConnectionMana...
fn list_tags(ctx: &Context, g_id: i64, page: i64) -> PaginationResult<Tag> { use schema::tag::dsl::*; let pool = extract_pool!(&ctx); tag.filter(guild_id.eq(&g_id)) .order(key.asc()) .paginate(page) .load_and_count_pages(pool) .unwrap() } fn set_auto_tags(ctx: &Context, g_id...
fn delete_tag_do(ctx: &Context, tag_id: i64) { use schema::tag::dsl::*; let pool = extract_pool!(&ctx); diesel::delete(tag.filter(id.eq(tag_id))) .execute(pool) .unwrap(); }
function_block-full_function
[ { "content": "/// Process possible tag activations\n\nfn process_tag(ctx: &mut Context, msg: &Message, cmd_name: &str) {\n\n use schema::guild::dsl::*;\n\n use schema::tag::dsl::*;\n\n\n\n let g_id = match msg.guild_id {\n\n Some(x) => x.0 as i64,\n\n None => return,\n\n };\n\n\n\n ...
Rust
rust/pyapi/src/prog_gen/flow_options.rs
Origen-SDK/o2
5b0f9a6d113ddebc73c7ee224931e8b2d0301794
use crate::utility::caller::src_caller_meta; use origen::prog_gen::{flow_api, FlowCondition, FlowID}; use origen::Result; use pyo3::types::PyDict; pub fn is_flow_option(key: &str) -> bool { match key { "id" => true, "bin" => true, "softbin" => true, "soft_bin" => true, "if...
use crate::utility::caller::src_caller_meta; use origen::prog_gen::{flow_api, FlowCondition, FlowID}; use origen::Result; use pyo3::types::PyDict; pub fn is_flow_option(key: &str) -> bool { match key { "id" => true, "bin" => true, "softbin" => true, "soft_bin" => true, "if...
pub fn get_softbin(kwargs: Option<&PyDict>) -> Result<Option<usize>> { if let Some(kwargs) = kwargs { if let Some(bin) = kwargs.get_item("softbin") { if let Ok(v) = bin.extract::<usize>() { return Ok(Some(v)); } else { return error!( ...
eturn Ok(Some(v)); } else { return error!("Illegal 'bin' value, expected an Integer, got: '{}'", bin); } } } Ok(None) }
function_block-function_prefixed
[ { "content": "/// Sanitizes the given target/env name and returns it, but will exit the process if it does\n\n/// not uniquely identify a single target/env file.\n\n/// Set the last arg to true to return the path to the matching target instead.\n\npub fn clean_name(name: &str, dir: &str, return_file: bool) -> S...
Rust
src/client.rs
peperunas/bitfinex-rs
846feb058e3d7be4361f494d78f36ab0f6158c20
use reqwest; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_TYPE, USER_AGENT}; use reqwest::{Response, StatusCode}; use serde::Serialize; use crate::auth; use crate::endpoints::{AuthenticatedEndpoint, PublicEndpoint}; use crate::errors::BoxError; static NO_PARAMS: &'static [(); 0] = &[]; #[derive(...
use reqwest; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_TYPE, USER_AGENT}; use reqwest::{Response, StatusCode}; use serde::Serialize; use crate::auth; use crate::endpoints::{AuthenticatedEndpoint, PublicEndpoint}; use crate::errors::BoxError; static NO_PARAMS: &'static [(); 0] = &[]; #[derive(...
let signature_path = format!("/api{}{}{}", path, nonce, payload); let signature = auth::sign_payload(self.secret_key.as_bytes(), signature_path.as_bytes())?; let mut headers = HeaderMap::new(); headers.insert(USER_AGENT, HeaderValue::from_static("bitfinex-rs")); headers.insert...
let path = endpoint .to_string() .strip_prefix(AuthenticatedEndpoint::HOST) .ok_or("Invalid endpoint")? .to_owned();
assignment_statement
[ { "content": "pub fn sign_payload(secret: &[u8], payload: &[u8]) -> Result<String, BoxError> {\n\n let signed_key = hmac::Key::new(hmac::HMAC_SHA384, secret);\n\n let signature = encode(hmac::sign(&signed_key, payload).as_ref());\n\n\n\n Ok(signature)\n\n}\n\n\n\npub async fn generate_nonce() -> Result...
Rust
src/file_system.rs
dan-t/rust-confsolve
df9415c82f26802fb69f94486c04c455011c2d61
use std::iter::Iterator; use std::path::{Path, PathBuf}; use std::vec::Vec; use app_result::{AppResult, AppError}; use appdirs; use std::fs::{ read_dir, create_dir_all, remove_file, copy }; pub fn walk_files(start_dir: &Path) -> AppResult<Files> { match read_dir(start_dir) { Ok(contents) => { ...
use std::iter::Iterator; use std::path::{Path, PathBuf}; use std::vec::Vec; use app_result::{AppResult, AppError}; use appdirs; use std::fs::{ read_dir, create_dir_all, remove_file, copy }; pub fn walk_files(start_dir: &Path) -> AppResult<Files> { match read_dir(start_dir) { Ok(contents) => { ...
} impl Iterator for Files { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { loop { match self.stack.pop() { None => break, Some(path) => { if path.is_file() { return Some(path); } if path.is_dir() { match r...
fn new(paths: Vec<PathBuf>) -> Files { let mut files = Files {stack: Vec::with_capacity(10_000)}; files.stack.extend(paths.into_iter()); files }
function_block-full_function
[ { "content": "/// OS specific path for caches.\n\npub fn cache_home() -> Option<PathBuf>\n\n{\n\n #[cfg(unix)]\n\n fn _cache_home() -> Option<PathBuf>\n\n {\n\n dirs::home_dir().map(|mut dir| { dir.push(\".cache\"); dir })\n\n }\n\n\n\n #[cfg(windows)]\n\n fn _cache_home() -> Option<PathBuf>\n\...
Rust
cubism-core-piston2d-renderer/examples/animate.rs
3c1u/cubism-rs
d5e216538c61f4ecbdc88f56f2470e6e097fd963
use cubism::{expression::Expression, motion::Motion}; use cubism_core as core; use cubism_core_piston2d_renderer::*; use glium::backend::Facade; use glium_graphics::{Flip, Glium2d, GliumWindow, OpenGL, Texture, TextureSettings}; use piston::{input::*, window::WindowSettings}; use sdl2_window::*; fn load_textures<F: Fa...
use cubism::{expression::Expression, motion::Motion}; use cubism_core as core; use cubism_core_piston2d_renderer::*; use glium::backend::Facade; use glium_graphics::{Flip, Glium2d, GliumWindow, OpenGL, Texture, TextureSettings}; use piston::{input::*, window::WindowSettings}; use sdl2_window::*; fn load_textures<F: Fa...
ply(&mut haru, 1.0); haru.update(); g2d.draw(&mut target, v.viewport(), |c, g| { let t = c .transform .trans(viewport[0] as f64 * 0.5, viewport[1] as f64 * 0.5) .scale(0.2, 0.2); clear([1.0, 1.0, 1.0, 1...
n", "Haru/expressions/F07.exp3.json", "Haru/expressions/F08.exp3.json", ]; let mut motions_index: usize = 0; let mut motion = Motion::from_motion3_json(&res_path.join(motions_path[motions_index])) .expect("Failed to load motion."); let mut exp_index: usize = 0; let mut expre...
function_block-random_span
[ { "content": "fn load_textures<F: Facade>(window: &mut F) -> [Texture; 2] {\n\n use std::{iter::FromIterator, path::PathBuf};\n\n\n\n let res_path = PathBuf::from_iter(&[env!(\"CUBISM_CORE\"), \"Samples/Res\"]);\n\n\n\n let tex0 = Texture::from_path(\n\n window,\n\n &res_path.join(\"Haru/...
Rust
awint_macro_internals/src/lower_fields.rs
AaronKutch/awint
9b9b18bfe98b914a256dba9f655f6a8abc0645ee
use std::collections::{HashMap, HashSet}; use awint_ext::ExtAwi; use crate::*; fn field_to_awi( used_values: &mut HashSet<String>, used_widths: &mut HashSet<Width>, used_ref_refs: &mut HashSet<String>, literal_to_id: &HashMap<ExtAwi, usize>, value_to_id: &HashMap<String, usize>, width_to_id...
use std::collections::{HashMap, HashSet}; use awint_ext::ExtAwi; use crate::*; fn field_to_awi( used_values: &mut HashSet<String>, used_widths: &mut HashSet<Width>, used_ref_refs: &mut HashSet<String>, literal_to_id: &HashMap<ExtAwi, usize>, value_to_id: &HashMap<String, usize>, width_to_id...
; lsb_i += 1; } let mut msb_i = concat.concatenation.len() - 1; if msb_i > lsb_i { fielding += &format!("let mut {}: usize = {};\n", SHL, BW); } while msb_i > lsb_i { let comp = &concat.concatenation[msb_i]; let width = lower_width(Some(literal_to_id), comp).unwrap();...
if let Some(width) = lower_width(Some(literal_to_id), comp) { fielding += &field_to_awi( used_values, used_widths, used_ref_refs, literal_to_id, value_to_id, width_to_id, ref_to_id, ...
if_condition
[ { "content": "fn rand_bool(rng: &mut Xoshiro128StarStar) -> bool {\n\n (rng.next_u32() & 1) == 0\n\n}\n\n\n", "file_path": "testcrate/tests/fuzz/fp_string.rs", "rank": 0, "score": 209957.32603089 }, { "content": "fn rand_bool(rng: &mut Xoshiro128StarStar) -> bool {\n\n (rng.next_u32() ...
Rust
src/r3_test_runner/src/main.rs
r3-os/r3
46f460a031ad518fd4c3582ab9c87e31e9cc8806
#![feature(exhaustive_patterns)] #![feature(must_not_suspend)] #![feature(decl_macro)] #![feature(let_else)] #![warn(must_not_suspend)] use anyhow::Context; use clap::Parser; use std::{env, path::Path}; use thiserror::Error; mod driverinterface; mod selection; mod subprocess; mod targets; mod utils; #[tokio::main(...
#![feature(exhaustive_patterns)] #![feature(must_not_suspend)] #![feature(decl_macro)] #![feature(let_else)] #![warn(must_not_suspend)] use anyhow::Context; use clap::Parser; use std::{env, path::Path}; use thiserror::Error; mod driverinterface; mod selection; mod subprocess; mod targets; mod utils; #[tokio::main(...
async fn main_inner() -> anyhow::Result<()> { let opt = Opt::parse(); if opt.help_targets { println!("Supported targets:"); for (name, target) in targets::TARGETS { println!(" {name:30}{}", target.target_arch()); } return Ok(()); } ...
fn try_parse_target(arg_target: &str) -> Result<&'static dyn targets::Target, &'static str> { targets::TARGETS .iter() .find(|x| x.0 == arg_target) .ok_or("no such target") .map(|x| x.1) }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n println!(\"cargo:rerun-if-env-changed=R3_TEST_DRIVER_LINK_SEARCH\");\n\n if let Ok(link_search) = env::var(\"R3_TEST_DRIVER_LINK_SEARCH\") {\n\n println!(\"cargo:rustc-link-search={link_search}\");\n\n }\n\n\n\n // Use the linker script `device.x` at the crate ro...
Rust
src/gpio/gpio_pin23.rs
ducktec/esp32c3
64b9547e200a3ee7e6587d81178be8732e99bee9
#[doc = "Reader of register GPIO_PIN23"] pub type R = crate::R<u32, super::GPIO_PIN23>; #[doc = "Writer for register GPIO_PIN23"] pub type W = crate::W<u32, super::GPIO_PIN23>; #[doc = "Register GPIO_PIN23 `reset()`'s with value 0"] impl crate::ResetValue for super::GPIO_PIN23 { type Type = u32; #[inline(always...
#[doc = "Reader of register GPIO_PIN23"] pub type R = crate::R<u32, super::GPIO_PIN23>; #[doc = "Writer for register GPIO_PIN23"] pub type W = crate::W<u32, super::GPIO_PIN23>; #[doc = "Register GPIO_PIN23 `reset()`'s with value 0"] impl crate::ResetValue for super::GPIO_PIN23 { type Type = u32; #[inline(always...
(self.bits >> 3) & 0x03) as u8) } #[doc = "Bit 2"] #[inline(always)] pub fn gpio_pin23_pad_driver(&self) -> GPIO_PIN23_PAD_DRIVER_R { GPIO_PIN23_PAD_DRIVER_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bits 0:1"] #[inline(always)] pub fn gpio_pin23_sync2_bypass(&self) -> GPIO...
N23_WAKEUP_ENABLE_R { GPIO_PIN23_WAKEUP_ENABLE_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bits 7:9"] #[inline(always)] pub fn gpio_pin23_int_type(&self) -> GPIO_PIN23_INT_TYPE_R { GPIO_PIN23_INT_TYPE_R::new(((self.bits >> 7) & 0x07) as u8) } #[doc = "Bits 3:4"] #[inli...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/lib.rs
zshipko/halide-build
8770a81d0f3865124ddf3ba89818ac8ece719aaa
use std::env; use std::fs::remove_file; use std::io; use std::path::PathBuf; use std::process::Command; static CARGO_LINK_SEARCH: &'static str = "cargo:rustc-link-search=native="; static CARGO_LINK_LIB: &'static str = "cargo:rustc-link-lib="; pub fn link_lib(path: Option<&str>, name: &str) { if let Some(path) =...
use std::env; use std::fs::remove_file; use std::io; use std::path::PathBuf; use std::process::Command; static CARGO_LINK_SEARCH: &'static str = "cargo:rustc-link-search=native="; static CARGO_LINK_LIB: &'static str = "cargo:rustc-link-lib="; pub fn link_lib(path: Option<&str>, name: &str) { if let Some(path) =...
} pub struct Source { pub halide_path: PathBuf, pub repo: String, pub branch: String, pub make: String, pub make_flags: Vec<String>, } impl Source { pub fn download(&self) -> io::Result<bool> { Command::new("git") .arg("clone") .args(&["-b", self.branch.as...
env("LD_LIBRARY_PATH", self.halide_path.join("lib")) .status() .map(|status| status.success()); if !self.keep { let _ = remove_file(&self.output); } res }
function_block-function_prefix_line
[ { "content": "# halide-build\n\n\n\n<a href=\"https://crates.io/crates/halide-build\">\n\n <img src=\"https://img.shields.io/crates/v/halide-build.svg\">\n\n</a>\n\n\n\nA build tool for [Halide](https://github.com/halide/halide) filters.\n\n\n\nIt can be used from within Rust code or from the command-line.\n...
Rust
src/nib/src/writer.rs
grauwoelfchen/beta
20d351c0d570d5b168acfd43abb88d6c63952e09
use std::fs; use std::io::{Error, ErrorKind, Write}; use std::path::Path; use handlebars::Handlebars; use rst_parser::parse_only; use document_tree::{Document, HasChildren}; use document_tree::element_categories::{ BodyElement as BE, StructuralSubElement as SSE, SubStructure as SS, TextOrInlineElement as TOIE...
use std::fs; use std::io::{Error, ErrorKind, Write}; use std::path::Path; use handlebars::Handlebars; use rst_parser::parse_only; use document_tree::{Document, HasChildren}; use document_tree::element_categories::{ BodyElement as BE, StructuralSubElement as SSE, SubStructure as SS, TextOrInlineElement as TOIE...
fn extract_heading_tree(doc: &mut Document) -> Vec<Heading> { let md: &mut MyDocument = unsafe { &mut *(doc as *mut Document as *mut MyDocument) }; lazy_static! { static ref RE: Regex = Regex::new(r"^<(h[1-6])>(.*)</h[1-6]>$").unwrap(); } let mut tree: Vec<Heading> = vec!...
fn merge_authors<'a>(meta: &'a mut Value, c: &Config) -> &'a mut Value { *meta.pointer_mut("/website/metadata/authors").unwrap() = json!(c.website.metadata.as_ref().map_or( c.authors.as_ref().map_or(vec![], |a| { a.iter().map(|n| Author::new(n)).collect() ...
function_block-full_function
[ { "content": "enum HeadingTag {\n\n H1,\n\n H2,\n\n H3,\n\n H4,\n\n H5,\n\n H6,\n\n Unknown,\n\n}\n\n\n\nimpl Serialize for HeadingTag {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n let s: String = self.in...
Rust
src/math/vector.rs
NiklasJonsson/rusterizer
e5d715a91bdfa5b6f572266521e7693ebb056277
use core::ops::{Add, Div, Mul, Neg, Sub}; use core::marker::PhantomData; use crate::math::*; #[derive(Copy, Clone)] pub struct Vector<CS: CoordinateSystem, const N: usize> { arr: [f32; N], coordinate_system: PhantomData<CS>, } impl<CS, const N: usize> Vector<CS, { N }> where CS: CoordinateSystem, { ...
use core::ops::{Add, Div, Mul, Neg, Sub}; use core::marker::PhantomData; use crate::math::*; #[derive(Copy, Clone)] pub struct Vector<CS: CoordinateSystem, const N: usize> { arr: [f32; N], coordinate_system: PhantomData<CS>, } impl<CS, const N: usize> Vector<CS, { N }> where CS: CoordinateSystem, { ...
ze> Neg for Vector<CS, { N }> where CS: CoordinateSystem, { type Output = Self; fn neg(mut self) -> Self { for v in self.arr.iter_mut() { *v *= -1.0; } self } } impl<CS, const N: usize> Mul<f32> for Vector<CS, { N }> where CS: CoordinateSystem, { type Output...
self / self.len() } } impl<CS, const N: usize> std::cmp::PartialEq for Vector<CS, { N }> where CS: CoordinateSystem, { fn eq(&self, other: &Self) -> bool { self.arr .iter() .zip(other.arr.iter()) .fold(true, |acc, (a, b)| acc && a == b) } } impl<CS, ...
random
[ { "content": "pub fn triangle_2x_area<CS: CoordinateSystem, const N: usize>(\n\n vertices: &[Point<CS, { N }>],\n\n) -> f32 {\n\n let v10 = vertices[1].xy() - vertices[0].xy();\n\n let v20 = vertices[2].xy() - vertices[0].xy();\n\n v10.cross(v20)\n\n}\n\n\n\nconst N_MSAA_SAMPLES: u8 = 4;\n\n\n\n#[de...
Rust
test.rs
aheui/rsaheui
ea9207b625a8c7f68fda2dcf501a14ad4956942f
#![license="BSD simplified"] #![feature(macro_rules)] extern crate hangeul; extern crate aheui; macro_rules! check_final_draw_counts( ($final:expr, $count:expr) => ( assert_eq!(aheui::final_draw_counts[$final as uint], $count); ) ) #[cfg(test)] mod tests { use hangeul; use aheui; use aheu...
#![license="BSD simplified"] #![feature(macro_rules)] extern crate hangeul; extern crate aheui; macro_rules! check_final_draw_counts( ($final:expr, $count:expr) => ( assert_eq!(aheui::final_draw_counts[$final as uint], $count); ) ) #[cfg(test)] mod tests { use hangeul; use aheui; use aheu...
#[test] pub fn test_helloworld() { let source = Source::from_str("밤밣따빠밣밟따뿌\n빠맣파빨받밤뚜뭏\n돋밬탕빠맣붏두붇\n볻뫃박발뚷투뭏붖\n뫃도뫃희멓뭏뭏붘\n뫃봌토범더벌뿌뚜\n뽑뽀멓멓더벓뻐뚠\n뽀덩벐멓뻐덕더벅"); let mut it = Interpreter::new(source); assert_eq!(it.counter(), (0, 0)); assert_eq!(it.storage().len(), 0); assert!(!it.st...
assert_eq!(it.storage().peek().unwrap(), 5); it.instruct(&Instruction::from_char('덧')); assert_eq!(it.storage().peek().unwrap(), 9); it.instruct(&Instruction::from_char('멍')); assert_eq!(it.storage().peek().unwrap(), 7); }
function_block-function_prefix_line
[ { "content": "#[test]\n\npub fn test_interpreter() {\n\n let mut interpreter = Interpreter::new(Source::new(\"\"));\n\n assert_eq!(interpreter.counter, (0, 0));\n\n interpreter.instruct(&InstructionData::from_char('아'));\n\n assert_eq!(interpreter.counter, (0, 1));\n\n interpreter.instruct(&Instr...
Rust
librebmc/src/redfish/computer_system.rs
AmateurECE/edtwardy-bmc
aecbd5e5a91d29928076bcb86d450f0323df08d9
use std::collections::HashMap; use std::convert::{From, Infallible}; use std::error; use std::{default::Default, path::{Path, PathBuf}, sync::Arc}; use hyper::{Body, Request, Response}; use routerify::prelude::*; use serde_json; use serde::{Serialize, Serializer, ser::SerializeStruct}; use derive_builder::Builder; u...
use std::collections::HashMap; use std::convert::{From, Infallible}; use std::error; use std::{default::Default, path::{Path, PathBuf}, sync::Arc}; use hyper::{Body, Request, Response}; use routerify::prelude::*; use serde_json; use serde::{Serialize, Serializer, ser::SerializeStruct}; use derive_builder::Builder; u...
} pub trait ResetHandler { fn get_allowable_reset_types(&self) -> Vec<String>; fn reset(&mut self, reset_type: String) -> Result<(), Infallible>; } pub mod actions { use std::path::PathBuf; use serde::{Serialize, Serializer, ser::SerializeStruct}; pub struct Reset { pub target: PathBuf, ...
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let mut state = serializer.serialize_struct("ComputerSystem", 8)?; state.serialize_field("State", &self.state)?; state.serialize_field("Health", &self.health)?; state.serialize_field("HealthRollup"...
function_block-full_function
[ { "content": "// Must be implemented by traits that can be wrapped with Resource<>\n\npub trait ResourceMetadata { const ODATA_TYPE: &'static str; }\n", "file_path": "odata/src/lib.rs", "rank": 0, "score": 94949.52776498339 }, { "content": "pub trait Serialize {\n\n const CARDINALITY: usi...
Rust
tests/fields.rs
roy-ganz/toql
09104e16e921173d03f4a10410d311c939df1581
use toql::{ mock_db::MockDb, prelude::{ query, sql_expr, Cache, FieldFilter, FieldHandler, ParameterMap, SqlArg, SqlBuilderError, SqlExpr, Toql, ToqlApi, }, row, }; use tracing_test::traced_test; #[derive(Debug, Default, Toql)] #[toql(handler = "get_field_handler")] pub struct Level1 {...
use toql::{ mock_db::MockDb, prelude::{ query, sql_expr, Cache, FieldFilter, FieldHandler, ParameterMap, SqlArg, SqlBuilderError, SqlExpr, Toql, ToqlApi, }, row, }; use tracing_test::traced_test; #[derive(Debug, Default, Toql)] #[toql(handler = "get_field_handler")] pub struct Level1 {...
#[tokio::test] #[traced_test("info")] async fn filter() { let cache = Cache::new(); let mut toql = MockDb::from(&cache); let q = query!(Level1, "text1 FN LK 'ABC'"); assert!(toql.load_many(q).await.is_ok()); assert_eq!( toql.take_unsafe_sql(), "SELECT level1.id, level1.text1 F...
let q = query!(Level1, "*"); assert!(toql.load_many(q).await.is_ok()); assert_eq!( toql.take_unsafe_sql(), "SELECT level1.id, level1.text1 FROM Level1 level1" ); let q = query!(Level1, "text2"); assert!(toql.load_many(q).await.is_ok()); assert_eq!( toql.take_unsafe_sql(),...
function_block-function_prefix_line
[]
Rust
main/src/devices/ext_int_pin.rs
Alexander89/Stepper-Feedback-Driver
4e698750d75d79ec77b9845374cc9ebf741c4422
use core::marker::PhantomData; use core::sync::atomic::AtomicBool; use core::{cell::RefCell, sync::atomic::Ordering}; use core::borrow::BorrowMut; use cortex_m::interrupt::{CriticalSection, Mutex}; use embedded_hal::digital::v2::PinState; use hal::clock::GClock; use hal::{ clock::{ClockGenId, GenericClockControlle...
use core::marker::PhantomData; use core::sync::atomic::AtomicBool; use core::{cell::RefCell, sync::atomic::Ordering}; use core::borrow::BorrowMut; use cortex_m::interrupt::{CriticalSection, Mutex}; use embedded_hal::digital::v2::PinState; use hal::clock::GClock; use hal::{ clock::{ClockGenId, GenericClockControlle...
fn get_pin_state(in0: bool, shift: u8) -> bool { let p = unsafe { &*pac::PORT::ptr() }; if in0 { (p.in0.read().in_().bits() & (1 << shift)) != 0 } else { (p.in1.read().in_().bits() & (1 << shift)) != 0 } } macro_rules! eip { ( $Pad:ident, $num:expr, $is_in...
pub fn init( cs: &CriticalSection, clocks: &mut GenericClockController, nvic: &mut NVIC, pm: &mut pac::PM, eic: pac::EIC, ) { let is_configured = cortex_m::interrupt::free(|_| { let is_configured = EIC_SETUP.load(Ordering::SeqCst); EIC_SETUP.store(true, Ordering::...
function_block-full_function
[ { "content": "fn step_changed(state: bool) {\n\n unsafe { HARDWARE.as_mut() }.map(|hw| {\n\n hw.stepper_step();\n\n if state {\n\n hw.led2.on()\n\n } else {\n\n hw.led2.off()\n\n }\n\n });\n\n}\n\n\n", "file_path": "main/src/main.rs", "rank": 1, ...
Rust
src/bin/climate.rs
ckauhaus/esera-mq
1855338e2515856218d9829b9e3aefca10431505
use anyhow::{Context, Result}; use serde::Deserialize; use slog::{debug, error, info, o, warn, Drain, Logger}; use std::collections::HashMap; use std::fs; use std::path::Path; use std::process; use structopt::StructOpt; use esera_mqtt::climate::{Climate, Conf, BASE}; use esera_mqtt::{MqttMsg, Routes, Token}; #[derive...
use anyhow::{Context, Result}; use serde::Deserialize; use slog::{debug, error, info, o, warn, Drain, Logger}; use std::collections::HashMap; use std::fs; use std::path::Path; use std::process; use structopt::StructOpt; use esera_mqtt::climate::{Climate, Conf, BASE}; use esera_mqtt::{MqttMsg, Routes, Token}; #[derive...
} fn run(opt: Opt, log: &Logger) -> Result<()> { let configs = Configs::read(&opt.config) .with_context(|| format!("Failed to read config file {}", opt.config))?; let (mut mqtt, recv) = esera_mqtt::MqttConnection::new( &opt.mqtt_host, &opt.mqtt_cred, &format!("{}/status", BASE)...
fn process( &mut self, idx: usize, tok: Token, topic: &str, payload: &str, log: &Logger, ) -> Box<dyn Iterator<Item = MqttMsg>> { match self.ctrl[idx].process(tok, topic, payload) { Ok(resp) => Box::new(resp.into_iter()), Err(e) => { ...
function_block-full_function
[]
Rust
program/src/processor.rs
Zoints/treasury
013c3a56720f3ad70b4fbe9b280cb9d80ff5e6ca
use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ account_info::{next_account_info, AccountInfo}, clock::Clock, entrypoint::ProgramResult, msg, program::{invoke, invoke_signed}, program_pack::Pack, pubkey::Pubkey, system_instruction::{self}, sysvar::{rent::Rent, Sy...
use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ account_info::{next_account_info, AccountInfo}, clock::Clock, entrypoint::ProgramResult, msg, program::{invoke, invoke_signed}, program_pack::Pack, pubkey::Pubkey, system_instruction::{self}, sysvar::{rent::Rent, Sy...
?; treasury_info.data.borrow_mut().copy_from_slice(&data); Ok(()) } pub fn process_withdraw_simple( program_id: &Pubkey, accounts: &[AccountInfo], amount: u64, ) -> ProgramResult { let iter = &mut accounts.iter(); let _funder_info = next_account_inf...
invoke( &system_instruction::create_account( funder_info.key, treasury_info.key, lamports, space, program_id, ), &[funder_info.clone(), treasury_info.clone()], )
call_expression
[ { "content": "fn process_instruction(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n instruction_data: &[u8],\n\n) -> ProgramResult {\n\n if let Err(error) = Processor::process(program_id, accounts, instruction_data) {\n\n error.print::<TreasuryError>();\n\n return Err(erro...
Rust
headers/src/header_components/unstructured.rs
PeterW-LWL/mail
f05836f227b44e7106d1360c7052356cd41ba361
use std::fmt::{self, Display}; use std::ops::{Deref, DerefMut}; use failure::Fail; use soft_ascii_string::SoftAsciiChar; use data::Input; use error::ComponentCreationError; use internals::bind::encoded_word::{EncodedWordEncoding, WriterWrapper}; use internals::encoder::{EncodableInHeader, EncodingWriter}; use interna...
use std::fmt::{self, Display}; use std::ops::{Deref, DerefMut}; use failure::Fail; use soft_ascii_string::SoftAsciiChar; use data::Input; use error::ComponentCreationError; use internals::bind::encoded_word::{EncodedWordEncoding, WriterWrapper}; use internals::encoder::{EncodableInHeader, EncodingWriter}; use interna...
} } } Ok(()) } fn boxed_clone(&self) -> Box<dyn EncodableInHeader> { Box::new(self.clone()) } } #[cfg(test)] mod test { use super::*; ec_test! { simple_encoding, { Unstructured::try_from( "this simple case" )? } => ascii => [ ...
if !had_fws { handle.write_fws(); }
if_condition
[ { "content": "#[inline(always)]\n\npub fn encoded_word_encode<O, R: AsRef<str>>(input: R, out: &mut O)\n\nwhere\n\n O: EncodedWordWriter,\n\n{\n\n _encoded_word_encode(input.as_ref(), out)\n\n}\n\n\n", "file_path": "internals/src/bind/base64.rs", "rank": 0, "score": 392749.4739850229 }, { ...
Rust
springline-explorer/src/settings.rs
dmrolfs/springline-rs
1548e84ac1b02099bfb3d66e10dcbb8b3667a080
use config::builder::DefaultState; use config::ConfigBuilder; use dialoguer::console::style; use dialoguer::{Confirm, Editor, FuzzySelect}; use settings_loader::{Environment, LoadingOptions, SettingsLoader}; use springline::settings::Settings; use crate::{ExplorerState, MenuAction, Result, THEME}; #[derive(Debug)] pu...
use config::builder::DefaultState; use config::ConfigBuilder; use dialoguer::console::style; use dialoguer::{Confirm, Editor, FuzzySelect}; use settings_loader::{Environment, LoadingOptions, SettingsLoader}; use springline::settings::Settings; use crate::{ExplorerState, MenuAction, Result, THEME}; #[derive(Debug)] pu...
::make_environment_variables_source()); eprintln!( "\n\tAdding overrides from CLI options:\n\t{:?}", style(&state.options).dim().green() ); eprintln!(); builder = state.options.load_overrides(builder)?; let config = builder.build()?; let settings...
s::change_environment))), ("Edit Settings", Some(Box::new(ReviseSettings::edit_settings))), ("return", None), ]; let selections: Vec<&str> = menu_actions.iter().map(|s| s.0).collect(); loop { ...
random
[ { "content": "#[tracing::instrument(level = \"info\")]\n\npub fn register_metrics(registry: &Registry) -> Result<()> {\n\n proctor::metrics::register_proctor_metrics(registry)?;\n\n\n\n registry.register(Box::new(metric_catalog::METRIC_CATALOG_TIMESTAMP.clone()))?;\n\n\n\n registry.register(Box::new(me...
Rust
src/crypto/mod.rs
oniproject/tto
4336c525ac39b1706e7ded9b28e4c5d55929268f
pub mod aead; mod chacha20; mod poly1305; mod hchacha20; #[inline(always)] fn memzero_slice(p: &mut [u8]) { for i in 0..p.len() { unsafe { p.as_mut_ptr().add(i).write_volatile(0) } } } pub const KEY: usize = 32; pub const HMAC: usize = 16; pub const NONCE: usize = 12; pub const XNONCE: usize = 24; ...
pub mod aead; mod chacha20; mod poly1305; mod hchacha20; #[inline(always)] fn memzero_slice(p: &mut [u8]) { for i in 0..p.len() { unsafe { p.as_mut_ptr().add(i).write_volatile(0) } } } pub const KEY: usize = 32; pub const HMAC: usize = 16; pub const NONCE: usize = 12; pub const XNONCE: usize = 24; ...
} #[cfg(feature = "sodium")] pub use self::sodium::{open, xopen, seal, xseal}; #[cfg(feature = "sodium")] mod sodium { use std::os::raw::{c_int, c_uchar, c_ulonglong}; use super::{HMAC, KEY, NONCE, XNONCE}; #[link(name = "sodium")] extern "C" { fn crypto_aead_xchacha20poly1305_ietf_encrypt_d...
2]; input[..].copy_from_slice(&self.0[..16]); npub[4..].copy_from_slice(&self.0[16..]); (npub, hchacha20(&input, key, None)) }
function_block-function_prefixed
[ { "content": "fn xopen(c: &mut [u8], ad: &[u8], t: [u8; TAG], n: &[u8; NPUB], k: &[u8; KEY]) -> Result<(), ()> {\n\n let (n, k) = AutoNonce(*n).split(k);\n\n open(c, Some(ad), &t, &n, &k)\n\n}\n\n\n", "file_path": "tests/xchacha20poly1305.rs", "rank": 4, "score": 433732.05028815207 }, { ...
Rust
protos/src/encoder/lit.rs
xpepermint/httlib-rs
90b8b8f1587e425137d08487d70dd0640fcd4d91
#[derive(Debug)] pub enum EncoderLit<'a> { Bytes(&'a Vec<u8>), Bool(&'a bool), BoolVec(&'a Vec<bool>), Int32(&'a i32), Int32Vec(&'a Vec<i32>), Int64(&'a i64), Int64Vec(&'a Vec<i64>), UInt32(&'a u32), UInt32Vec(&'a Vec<u32>), ...
#[derive(Debug)] pub enum EncoderLit<'a> { Bytes(&'a Vec<u8>), Bool(&'a bool), BoolVec(&'a Vec<bool>), Int32(&'a i32), Int32Vec(&'a Vec<i32>), Int64(&'a i64), Int64Vec(&'a Vec<i64>), UInt32(&'a u32), UInt32Vec(&'a Vec<u32>), ...
Int32Vec(v) } } impl<'a> From<&'a u64> for EncoderLit<'a> { fn from(v: &'a u64) -> Self { Self::UInt64(v) } } impl<'a> From<&'a Vec<u64>> for EncoderLit<'a> { fn from(v: &'a Vec<u64>) -> Self { Self::UInt64Vec(v) } } impl<'a> From<&'a f32> for EncoderLit<'a> { fn from(v: &'a f...
Fixed32Vec(&'a Vec<u32>), Fixed64(&'a u64), Fixed64Vec(&'a Vec<u64>), SFixed32(&'a i32), SFixed32Vec(&'a Vec<i32>), SFixed64(&'a i64), SFixed64Vec(&'a Vec<i64>), } impl<'a> From<&'a bool> for EncoderLit<'a> { fn from(v: &'a bool) -> Self { ...
random
[ { "content": "/// Parses the HPACK's static Huffman table. The function expects data to be in\n\n/// format as provided by the spec (7.2).\n\n/// \n\n/// **Example:**\n\n/// \n\n/// ```rust\n\n/// use std::fs;\n\n/// use std::path::Path;\n\n/// use httlib_huffman::parser::parse;\n\n/// \n\n/// let path = Path::...
Rust
src/main.rs
Traverse-Research/android-sdk-manager-rs
e0b156bd578f2006c35856f21592ce3144cd7806
use android_sdkmanager::{download_and_extract_packages, HostOs, MatchType}; use anyhow::Result; const HELP: &str = "\ android-sdkmanager-rs is a lightweight android sdk and ndk package installer. USAGE: cargo android-sdkmanager [OPTIONS] [INPUT] FLAGS: -h, --help Prints help information OPTIONS: --sd...
use android_sdkmanager::{download_and_extract_packages, HostOs, MatchType}; use anyhow::Result; const HELP: &str = "\ android-sdkmanager-rs is a lightweight android sdk and ndk package installer. USAGE: cargo android-sdkmanager [OPTIONS] [INPUT] FLAGS: -h, --help Prints help information OPTIONS: --sd...
fn main() -> Result<()> { let args = parse_args()?; let full = true; let install_dir = &args.sdk_path; let _ = std::fs::remove_dir_all(install_dir); let _ = std::fs::create_dir_all(install_dir); let packages_borrowed = args.packages.iter().map(|s| s.as_str()).collect::<Vec<_>>(); let pa...
fn parse_args() -> Result<AppArgs, pico_args::Error> { let mut args: Vec<_> = std::env::args_os().collect(); args.remove(0); if args[0] == "android-sdkmanager" { args.remove(0); } let mut pargs = pico_args::Arguments::from_vec(args); if pargs.contains(["-h", "--help"]) { ...
function_block-full_function
[ { "content": "fn is_allowed(path: &Path, allow_list: Option<&[MatchType]>) -> bool {\n\n if let Some(allow_list) = allow_list {\n\n for check in allow_list {\n\n match check {\n\n MatchType::Partial(check) => {\n\n if let Some(file_stem) = path.file_stem() ...
Rust
src/main.rs
suisei-cn/stargazer-rs
6645924370b08f4f9c2857ee097a97f2bec6e9c9
use std::path::PathBuf; use std::sync::Arc; use actix::fut::ready; use actix::Actor; use actix_web::web::Data; use actix_web::{get, web, Responder}; use clap::Parser; use itertools::Itertools; use mongodb::bson::doc; use mongodb::options::IndexOptions; use mongodb::IndexModel; use stargazer_lib::collector::amqp::AMQP...
use std::path::PathBuf; use std::sync::Arc; use actix::fut::ready; use actix::Actor; use actix_web::web::Data; use actix_web::{get, web, Responder}; use clap::Parser; use itertools::Itertools; use mongodb::bson::doc; use mongodb::options::IndexOptions; use mongodb::IndexModel; use stargazer_lib::collector::amqp::AMQP...
async fn main() { tracing_subscriber::fmt::init(); let opts = Opts::parse(); let config = Config::new(opts.config.as_deref()).unwrap(); let collector_config = config.collector.clone(); let sched_config = ScheduleConfig::default(); let source_config = config.source.clone(); let twitter_conf...
function_block-full_function
[ { "content": "pub fn deserialize_maybe_hashmap<'de, D, K, V>(deserializer: D) -> Result<HashMap<K, V>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n HashMap<K, V>: Deserialize<'de>,\n\n{\n\n let maybe = Option::deserialize(deserializer)?;\n\n Ok(maybe.unwrap_or_default())\n\n}\n", "file_path"...
Rust
libbit/src/refs.rs
andyyu2004/bit
4041637b56445b3857a256c8f552a79cdac307d2
mod ref_decorations; mod refdb; mod reflog; use crate::error::{BitGenericError, BitResult}; use crate::obj::{BitObjKind, Oid, Tree, Treeish}; use crate::path::BitPath; use crate::repo::BitRepo; use crate::serialize::{Deserialize, Serialize}; use lazy_static::lazy_static; use regex::Regex; use std::cmp::Ordering; use s...
mod ref_decorations; mod refdb; mod reflog; use crate::error::{BitGenericError, BitResult}; use crate::obj::{BitObjKind, Oid, Tree, Treeish}; use crate::path::BitPath; use crate::repo::BitRepo; use crate::serialize::{Deserialize, Serialize}; use lazy_static::lazy_static; use regex::Regex; use std::cmp::Ordering; use s...
s = self.path.as_path(); if f.alternate() { write!(f, "{}", s.strip_prefix("refs/heads/").unwrap_or(s).display()) } else { write!(f, "{}", s.display()) } } } impl FromStr for SymbolicRef { type Err = BitGenericError; fn from_str(s: &str) -> Result<Self, Sel...
branch(name: &str) -> Self { Self::intern_valid(&format!("refs/heads/{}", name)) .expect("we just set the prefix, must be valid") } pub fn short(&self) -> &'static str { const PREFIXES: &[BitPath] = &[BitPath::REFS_HEADS, BitPath::REFS_TAGS, BitPath::REFS_REMOTES]; ...
random
[ { "content": "fn parse_ref_line(s: &str) -> BitResult<(Oid, SymbolicRef)> {\n\n let (oid, sym) = s.split_once(' ').ok_or_else(|| anyhow!(\"malformed ref line\"))?;\n\n Ok((oid.parse()?, sym.parse()?))\n\n}\n", "file_path": "libbit/src/transport.rs", "rank": 0, "score": 364430.33340971766 }, ...
Rust
src/state_muxer.rs
guanqun/ethers-forked-evm-provider
90d1b429124aae76bfbb70f7d94c4c49cbf2ef0a
use crate::akula::interface::State; use crate::akula::types::{Account, Incarnation, PartialHeader}; use crate::forked_backend::Web3RemoteState; use crate::sqlite_backend::{SqliteBackend, SqliteDumper}; use async_trait::async_trait; use bytes::Bytes; use ethers::abi::ethereum_types::{Address, H256}; use std::path::PathB...
use crate::akula::interface::State; use crate::akula::types::{Account, Incarnation, PartialHeader}; use crate::forked_backend::Web3RemoteState; use crate::sqlite_backend::{SqliteBackend, SqliteDumper}; use async_trait::async_trait; use bytes::Bytes; use ethers::abi::ethereum_types::{Address, H256}; use std::path::PathB...
async fn read_block_header(&self, block_number: u64) -> anyhow::Result<Option<PartialHeader>> { if let Some(db) = &self.db { let lock = db.lock().await; return lock.read_block_header(block_number); } let web3 = self.web3.as_ref().unwrap(); let ret = web3.re...
async fn read_storage( &self, address: Address, incarnation: Incarnation, location: H256, ) -> anyhow::Result<H256> { if let Some(db) = &self.db { let lock = db.lock().await; return lock.read_storage(address, incarnation, location); } ...
function_block-full_function
[ { "content": "pub fn create2_address(caller: Address, salt: H256, code_hash: H256) -> Address {\n\n let mut buf = [0_u8; 1 + ADDRESS_LENGTH + KECCAK_LENGTH + KECCAK_LENGTH];\n\n buf[0] = 0xff;\n\n buf[1..1 + ADDRESS_LENGTH].copy_from_slice(&caller.0);\n\n buf[1 + ADDRESS_LENGTH..1 + ADDRESS_LENGTH +...
Rust
src/main.rs
syohex/hj
4b1d68febff9b1463eaa9110ed9514483d2772e9
use lazy_static::lazy_static; use std::error::Error; use std::io::Write; use clap::Parser; use regex::Regex; use tinyjson::JsonValue; #[macro_use(defer)] extern crate scopeguard; mod reader; use reader::LineBufferedStdin; #[derive(Parser, Debug)] #[clap(about = "Converts HTTP/1 style HTTP responses into JSON. This ...
use lazy_static::lazy_static; use std::error::Error; use std::io::Write; use clap::Parser; use regex::Regex; use tinyjson::JsonValue; #[macro_use(defer)] extern crate scopeguard; mod reader; use reader::LineBufferedStdin; #[derive(Parser, Debug)] #[clap(about = "Converts HTTP/1 style HTTP responses into JSON. This ...
} else { return Err(Box::new(std::io::Error::new( std::io::ErrorKind::InvalidData, std::format!("Invalid header field: {}", str_to_json_string(&line)), ))); } } Err(e) => { ...
if raw_name.eq_ignore_ascii_case("content-length") { if let Ok(len) = raw_value.parse::<usize>() { *content_length = Some(len); } }
if_condition
[ { "content": "#[test]\n\nfn parse_curl_sv_as_raw() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut cmd = Command::cargo_bin(\"hj\")?;\n\n\n\n // curl -sv https://httpbin.org/get > tests/response-curl-sv-httpbin.txt 2>&1\n\n cmd.timeout(Duration::from_secs(1))\n\n .arg(\"--raw\")\n\n ...
Rust
src/py_iface.rs
litchipi/Petridish
972288135673e8cf9771aadef93042e7b06ee921
#[macro_export] macro_rules! generate_py_ifaces { [$petridish:ident, $([$name:ident] $celltype:tt => ($($algoname:ident => $algotype:ty),+)),* $(,)?] => { use $petridish::*; use $petridish::paste::paste; use $petridish::pyo3::prelude::*; use $petridish::pyo3::{wrap_pymodule...
#[macro_export] macro_rules! generate_py_ifaces { [$petridish:ident, $([$name:ident] $celltype:tt => ($($algoname:ident => $algotype:ty),+)),* $(,)?] => { use $petridish::*; use $petridish::paste::paste; use $petridish::pyo3::prelude::*; use $petridish::pyo3::{wrap_pymodule...
default().to_json()) } #[pyfunction] pub fn get_algo_default() -> JsonData{ py_err_if_fail!(AlgoConfiguration::default().to_json()) } #[pyfunction] pub fn create_labmap_assistant(mapformat: String) -> LabMapAssistant { LabMapAssistant::new(mapfor...
} } )* #[pyfunction] pub fn get_lab_default() -> JsonData{ py_err_if_fail!(LabConfig::
random
[ { "content": "pub fn random_genome(ngens: usize) -> Genome {\n\n let mut rng = rand::thread_rng();\n\n let mut res = vec![];\n\n for _ in 0..ngens {\n\n res.push(rng.gen());\n\n }\n\n res\n\n}\n\n\n", "file_path": "src/cell.rs", "rank": 0, "score": 113281.99912020915 }, { ...
Rust
bandersnatch/src/constraints/glv.rs
tanzhanwen/CSC2125-Project-Verkle
25915579be47ad89f6acf8a4a0f95c41c45b26c6
use crate::{ constraints::{EdwardsAffineVar, FqVar}, *, }; use ark_ec::ProjectiveCurve; use ark_ff::{field_new, BigInteger, FpParameters, PrimeField, Zero}; use ark_r1cs_std::{ alloc::AllocVar, boolean::Boolean, fields::FieldVar, groups::CurveVar, prelude::EqGadget, R1CSVar, }; use ark_relations::r1cs...
use crate::{ constraints::{EdwardsAffineVar, FqVar}, *, }; use ark_ec::ProjectiveCurve; use ark_ff::{field_new, BigInteger, FpParameters, PrimeField, Zero}; use ark_r1cs_std::{ alloc::AllocVar, boolean::Boolean, fields::FieldVar, groups::CurveVar, prelude::EqGadget, R1CSVar, }; use ark_relations::r1cs...
et f_y_var = coeff_c_var - coeff_c_var * &y_square_var; let g_y_var = coeff_b_var * &y_square_var + coeff_b_square_var; let h_y_var = y_square_var - coeff_b_var; f_y_var.enforce_equal(&(&xy_var * &new_x_var))?; g_y_var.enforce_equal(&(&h_y_var * &new_y_var))?; Ok(EdwardsAffineV...
stant( <BandersnatchParameters as GLVParameters>::COEFF_B * <BandersnatchParameters as GLVParameters>::COEFF_B, ); let x_var = &point_var.x; let y_var = &point_var.y; let xy_var = x_var * y_var; let y_square_var = y_var * y_var; l
function_block-random_span
[ { "content": "fn bench_endomorphism(c: &mut Criterion) {\n\n let mut bench_group = c.benchmark_group(\"micro benchmark\");\n\n\n\n let base_point = bandersnatch::EdwardsAffine::prime_subgroup_generator();\n\n\n\n let bench_str = format!(\"endomorphism\");\n\n bench_group.bench_function(bench_str, mo...
Rust
src/client.rs
adumbidiot/shift-client-rs
b1143c1ec4d53b6b615287e2a589913269723d44
use crate::{ error::{ ShiftError, ShiftResult, }, types::{ rewards::{ CodeRedemptionJson, CodeRedemptionPage, RewardForm, RewardsPage, }, AccountPage, HomePage, }, }; use scraper::Html; use std::{ sync::{...
use crate::{ error::{ ShiftError, ShiftResult, }, types::{ rewards::{ CodeRedemptionJson, CodeRedemptionPage, RewardForm, RewardsPage, }, AccountPage, HomePage, }, }; use scraper::Html; use std::{ sync::{...
pub async fn get_rewards_page(&self) -> ShiftResult<RewardsPage> { let res = self.client.get(REWARDS_URL).send().await?; let page = res_to_html_transform(res, |html| Ok(RewardsPage::from_html(&html)?)).await?; Ok(page) } pub async fn get_reward_forms( &self, r...
pub async fn login(&self) -> ShiftResult<AccountPage> { let home_page = self.get_home_page().await?; let lock = self.client_data.read().expect("client data poisoned"); let res = self .client .post(SESSIONS_URL) .form(&[ ("utf8", "✓"), ...
function_block-full_function
[ { "content": "fn get_text_by_id<'a>(html: &'a Html, id: &str) -> Option<&'a str> {\n\n let selector = Selector::parse(&format!(\"#{}\", id)).ok()?;\n\n let element = html.select(&selector).next()?;\n\n element.text().next()\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n const SA...
Rust
src/response/snapshot/item.rs
juliarose/backpacktf-api
cebbd04e8eac3f1ac1118acd5549bd86e89672f0
use serde::{Serialize, Deserialize}; use crate::SteamID; use crate::response::attributes::{Attributes, Value as AttributeValue}; use crate::response::deserializers::{ deserialize_attributes, from_optional_number_or_string }; use tf2_enum::{ Wear, Quality, KillstreakTier, Paint, StrangePart, Killstreaker, Sh...
use serde::{Serialize, Deserialize}; use crate::SteamID; use crate::response::attributes::{Attributes, Value as AttributeValue}; use crate::response::deserializers::{ deserialize_attributes, from_optional_number_or_string }; use tf2_enum::{ Wear, Quality, KillstreakTier, Paint, StrangePart, Killstreaker, Sh...
pub fn is_craftable(&self) -> bool { !self.flag_cannot_craft } pub fn is_australium(&self) -> bool { self.attributes.contains_key(&2027) } pub fn is_festivized(&self) -> bool { self.attributes.contains_key(&2053) } pub fn is_strange(&self) -> bool...
2)) { if let Some(float_value) = attribute.float_value { if let Some(float_value) = convert_float_u32(float_value) { if let Ok(sheen) = Sheen::try_from(float_value) { return Some(sheen); } } } ...
function_block-function_prefixed
[ { "content": "pub fn bool_from_int<'de, D>(deserializer: D) -> Result<bool, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n match u8::deserialize(deserializer)? {\n\n 0 => Ok(false),\n\n 1 => Ok(true),\n\n other => Err(de::Error::invalid_value(\n\n Unexpected::Unsigne...
Rust
src/elf.rs
laurmaedje/symslice
5e650353099e46b35a2b614b64f4eee7d0307bac
use std::ffi::CStr; use std::fmt::{self, Display, Formatter}; use std::fs::File; use std::io::{self, Cursor, Read, Seek, SeekFrom}; use std::path::Path; use byteorder::{ReadBytesExt, LE}; #[derive(Debug)] pub struct ElfFile<R> where R: Read + Seek { target: R, pub header: Header, pub section_headers: Vec...
use std::ffi::CStr; use std::fmt::{self, Display, Formatter}; use std::fs::File; use std::io::{self, Cursor, Read, Seek, SeekFrom}; use std::path::Path; use byteorder::{ReadBytesExt, LE}; #[derive(Debug)] pub struct ElfFile<R> where R: Read + Seek { target: R, pub header: Header, pub section_headers: Vec...
fn parse_string(strings: &[u8], offset: u32) -> String { let mut zero = offset as usize; while strings[zero] != 0 { zero += 1; } CStr::from_bytes_with_nul(&strings[offset as usize .. zero + 1]) .expect("invalid C string in elf string table") .to_string_lossy() .into_ow...
size: target.read_u64::<LE>()?, link: target.read_u32::<LE>()?, info: target.read_u32::<LE>()?, addr_align: target.read_u64::<LE>()?, entry_size: target.read_u64::<LE>()?, }; headers.push(header); } let string_index = header.section_name_str...
function_block-function_prefix_line
[ { "content": "/// Write the preamble of the graphviz file.\n\npub fn write_header<W: Write>(mut f: W, title: &str, fontsize: u32) -> Result<()> {\n\n writeln!(f, \"digraph Flow {{\")?;\n\n write!(f, \"graph [label=\\\"{}\\\", labelloc=\\\"t\\\", fontsize={}, \", title, fontsize)?;\n\n writeln!(f, \"fon...
Rust
tempest/src/metric/backend/prometheus.rs
grippy/tempest
0c8f50f9fc04da21af5c0a1ed5055b6db665c825
use crate::metric::backend::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; #[allow(dead_code)] pub(crate) struct Prometheus { uri: String, prefix: Option<String>, target: MetricTarget, name_delimiter: Format, label_separator: Format, label_delimiter: Format, } impl Prometheus { pub(c...
use crate::metric::backend::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; #[allow(dead_code)] pub(crate) struct Prometheus { uri: String, prefix: Option<String>, target: MetricTarget, name_delimiter: Format, label_separator: Format, label_delimiter: Format, } impl Prometheus { pub(c...
} fn push_gateway(&self, uri: &str, metrics: &str) { match minreq::post(uri).with_body(metrics).send() { Ok(http_result) => { trace!( "pushgateway ok: {} {}", http_result.status_code, http_result.reason_ph...
Ok(Prometheus { uri: _uri, prefix: _prefix, target: target, name_delimiter: UNDERSCORE, label_separator: EQUAL, label_delimiter: COMMA, })
call_expression
[ { "content": "/// Merge Labels into Map\n\npub fn merge_labels(map: &mut HashMap<String, String>, labels: Labels) {\n\n if labels.is_some() {\n\n for el in &labels.unwrap() {\n\n map.insert(el.0.clone(), el.1.clone());\n\n }\n\n }\n\n}\n\n\n\n/// MetricsAggregateActor collects met...
Rust
src/diagnostics/archivist/src/logs/message.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
use super::buffer::Accounted; use super::error::StreamError; use byteorder::{ByteOrder, LittleEndian}; use fidl_fuchsia_logger::LogMessage; use fuchsia_zircon as zx; use libc::{c_char, c_int}; use std::{mem, str}; pub const METADATA_SIZE: usize = mem::size_of::<fx_log_metadata_t>(); pub const MIN_PACKET_SIZE: usize ...
use super::buffer::Accounted; use super::error::StreamError; use byteorder::{ByteOrder, LittleEndian}; use fidl_fuchsia_logger::LogMessage; use fuchsia_zircon as zx; use libc::{c_char, c_int}; use std::{mem, str}; pub const METADATA_SIZE: usize = mem::size_of::<fx_log_metadata_t>(); pub const MIN_PACKET_SIZE: usize ...
fn unterminated() { let mut packet = test_packet(); let end = 9; packet.data[end] = 1; let buffer = &packet.as_bytes()[..MIN_PACKET_SIZE + end]; let parsed = Message::from_logger(buffer); assert_eq!(parsed, Err(StreamError::NotNullTerminated { terminator: 1 })); ...
])?.to_owned(); return Ok(Self { size: cursor + contents.len() + 1, tags, contents, pid, tid, time, severity, dropped_logs, });...
random
[]
Rust
crates/utils/settings/src/apps/data_router.rs
epiphany-platform/cdl-temporary
daa704f379c05d7b733c382058ff88a2549d33d7
use std::{collections::HashMap, net::SocketAddrV4}; use communication_utils::{ parallel_consumer::{ParallelCommonConsumer, ParallelCommonConsumerConfig}, publisher::CommonPublisher, }; use serde::{Deserialize, Serialize}; use task_utils::task_limiter::TaskLimiter; use crate::apps::{ default_async_task_lim...
use std::{collections::HashMap, net::SocketAddrV4}; use communication_utils::{ parallel_consumer::{ParallelCommonConsumer, ParallelCommonConsumerConfig}, publisher::CommonPublisher, }; use serde::{Deserialize, Serialize}; use task_utils::task_limiter::TaskLimiter; use crate::apps::{ default_async_task_lim...
} pub async fn producer(&self) -> anyhow::Result<CommonPublisher> { Ok( match ( &self.kafka, &self.amqp, &self.grpc, &self.communication_method, ) { (Some(kafka), _, _, CommunicationMethod::Kafka) =...
match ( &self.kafka, &self.amqp, &self.grpc, &self.communication_method, ) { (Some(kafka), _, _, CommunicationMethod::Kafka) => { kafka .parallel_consumer(TaskLimiter::new(self.async_task_limit)) ...
if_condition
[]
Rust
xrpl_binary_codec/src/serializer.rs
gmosx/xrpl_sdk_rust
f45f61da1d059c4db90a52fb947740a8e9b67d84
use super::util::internal_number_from_string; use xrpl_types::{Amount, Memo, Transaction}; pub const HASH_PREFIX_TRANSACTION: [u8; 4] = [0x53, 0x4E, 0x44, 0x00]; pub const HASH_PREFIX_UNSIGNED_TRANSACTION_SINGLE: [u8; 4] = [0x53, 0x54, 0x58, 0x00]; #[derive(Default)] pub struct Serializer { pub buf: Vec<u8>, } i...
use super::util::internal_number_from_string; use xrpl_types::{Amount, Memo, Transaction}; pub const HASH_PREFIX_TRANSACTION: [u8; 4] = [0x53, 0x4E, 0x44, 0x00]; pub const HASH_PREFIX_UNSIGNED_TRANSACTION_SINGLE: [u8; 4] = [0x53, 0x54, 0x58, 0x00]; #[derive(Default)] pub struct Serializer { pub buf: Vec<u8>, } i...
pub fn push_field_id(&mut self, type_code: u8, field_code: u8) { if type_code < 16 { if field_code < 16 { self.push(type_code << 4 | field_code); } else { self.push(type_code << 4); self.push(field_code); } ...
pub fn push_u64(&mut self, value: u64) { self.push((value >> 56) as u8); self.push(((value >> 48) & 0xff) as u8); self.push(((value >> 40) & 0xff) as u8); self.push(((value >> 32) & 0xff) as u8); self.push(((value >> 24) & 0xff) as u8); self.push(((value >> 16) & 0xff) as...
function_block-full_function
[ { "content": "pub fn serialize_transaction(tx: &Transaction) -> Vec<u8> {\n\n let mut s = Serializer::new();\n\n s.push_transaction(tx, None);\n\n s.to_vec()\n\n}\n\n\n", "file_path": "xrpl_binary_codec/src/util.rs", "rank": 0, "score": 157952.45744905237 }, { "content": "pub fn sig...
Rust
cozy-chess/src/board/movegen/mod.rs
analog-hors/cozy-chess
44225c97fcddb080b96920fd81f9c355c67206a4
use crate::*; use super::*; mod piece_moves; pub use piece_moves::*; #[cfg(test)] mod tests; mod slider { use super::*; pub trait SlidingPiece { const PIECE: Piece; fn pseudo_legals(square: Square, blockers: BitBoard) -> BitBoard; } macro_rules! impl_sliding_piece { ($squ...
use crate::*; use super::*; mod piece_moves; pub use piece_moves::*; #[cfg(test)] mod tests; mod slider { use super::*; pub trait SlidingPiece { const PIECE: Piece; fn pseudo_legals(square: Square, blockers: BitBoard) -> BitBoard; } macro_rules! impl_sliding_piece { ($squ...
#[inline(always)] fn king_safe_on(&self, square: Square) -> bool { macro_rules! short_circuit { ($($attackers:expr),*) => { $(if !$attackers.is_empty() { return false; })* true } } let color = ...
fn add_pawn_legals< F: FnMut(PieceMoves) -> bool, const IN_CHECK: bool >(&self, mask: BitBoard, listener: &mut F) -> bool { const PIECE: Piece = Piece::Pawn; let color = self.side_to_move(); let our_king = self.king(color); let pieces = self.pieces(PIECE) & self.colors(color...
function_block-full_function
[ { "content": "fn write_moves(table: &mut [BitBoard; 87988], magics: &[BlackMagicEntry; Square::NUM], index_bits: usize, deltas: &[(i8, i8); 4]) {\n\n for &square in &Square::ALL {\n\n let magic = &magics[square as usize];\n\n let mask = !magic.mask;\n\n\n\n let mut blockers = BitBoard::E...
Rust
src/macros.rs
narfit66/ncursesw-win-rs
629b36fd2d7be4027d3c6328bf90d2cc6c7403af
/* src/macros.rs Copyright (c) 2019-2021 Stephen Whittle All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitatio...
/* src/macros.rs Copyright (c) 2019-2021 Stephen Whittle All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitatio...
}; if result.is_ok() { self.set_timeout(orig_timeout)?; } result } } }
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #![macro_use] macro_rules! result { ($t: ty) => { R...
random
[ { "content": "/// Use the specialifed colors (foreground and background) as the default colors for defining color pair 0.\n\npub fn assume_default_colors<S, C, T>(colors: S) -> result!(())\n\n where S: ColorsType<C, T>,\n\n C: ColorType<T>,\n\n T: ColorAttributeTypes\n\n{\n\n check_inits...
Rust
src/lib.rs
koizr/esa-cli
d8d27dc54ccd8c7e1c015056956458df85ce1ff8
use std::env; use std::io::{self, Write}; use std::path::PathBuf; use anyhow::{bail, Context, Result}; use clap::Parser; use esa::{self, Esa}; mod config; mod tmp_file; use config::{Config, Env}; use tmp_file::Editor; #[derive(Parser, Debug)] #[clap( name = "esa-cli", version = "0.0.0", author = "koizr...
use std::env; use std::io::{self, Write}; use std::path::PathBuf; use anyhow::{bail, Context, Result}; use clap::Parser; use esa::{self, Esa}; mod config; mod tmp_file; use config::{Config, Env}; use tmp_file::Editor; #[derive(Parser, Debug)] #[clap( name = "esa-cli", version = "0.0.0", author = "koizr...
} }, } Ok(()) } async fn print_team(esa: &Esa) -> Result<()> { let team = esa.team().await?; println!("team: {:?}", team); Ok(()) } async fn print_post(esa: &Esa, id: i32) -> Result<()> { let post = esa.post(id).await?; println!("{}", post.url); println!("{}", pos...
if list { print_posts(&esa, query, include, sort, order).await?; } else if new { create_post(&esa, &esa_env).await?; } else { bail!("Post ID argument or --list option are required."); }
if_condition
[ { "content": "pub fn parse_post(content: &str) -> Result<esa::post::PostContent> {\n\n let mut lines = content.lines();\n\n if lines.next().is_none() {\n\n return Err(anyhow!(\"failed to parse content\"));\n\n }\n\n let title = lines\n\n .next()\n\n .ok_or(anyhow!(\"failed to pa...
Rust
program/src/tests/collection.rs
SpicyRicecaker/gc-representation-rs
a7f33deab3d3005a6336271227a5d9b4ab444151
use std::env; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; use rand::prelude::*; use rand_pcg::Pcg64; use crate::{init_log, recursively_add_children, seed_root}; use super::*; use std::time::Instant; fn random_garbage_collection<T: MemoryManager>(stack: &mut Stack, heap: &mut T) -> Result<(...
use std::env; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; use rand::prelude::*; use rand_pcg::Pcg64; use crate::{init_log, recursively_add_children, seed_root}; use super::*; use std::time::Instant; fn random_garbage_collection<T: MemoryManager>(stack: &mut Stack, heap: &mut T) -> Result<(...
p_size); random_garbage_collection(&mut stack, &mut heap).unwrap(); } fn sum_garbage_collection<T: MemoryManager>( stack: &mut Stack, heap: &mut T, heap_size: usize, ) -> Result<()> { let node_pointer = heap.alloc(Node::default(), stack).unwrap(); stack.roots[0].children.push(node_pointer); ...
CK_SIZE); let mut heap = MarkCompactHeap::init(heap_size); random_garbage_collection(&mut stack, &mut heap).unwrap(); } #[test] fn stop_and_copy_random() { const STACK_SIZE: usize = 1; let heap_size: usize = env::var("HEAP_SIZE").unwrap().parse::<usize>().unwrap() * 2; let mut stack = St...
random
[ { "content": "/// takes in a mutable reference to stack and heap, linking them to a ratio of\n\n/// around 2 edges to : 1 node?\n\npub fn link_heap<T: MemoryManager>(stack: &mut Stack, heap: &mut T, rng: &mut Pcg64) -> Result<()> {\n\n // get number of powers of two (so we can know how many layers of binary\...
Rust
sway-core/src/semantic_analysis/ast_node/expression/intrinsic_function.rs
FuelLabs/sway
0190b5dac4735fd2a34528e48cc2e0c9606b5ce8
use std::fmt; use sway_types::Span; use crate::{ error::{err, ok}, semantic_analysis::{EnforceTypeArguments, Mode, TCOpts, TypeCheckArguments}, type_engine::*, types::DeterministicallyAborts, CompileError, CompileResult, IntrinsicFunctionKind, Namespace, }; use super::TypedExpression; #[derive(D...
use std::fmt; use sway_types::Span; use crate::{ error::{err, ok}, semantic_analysis::{EnforceTypeArguments, Mode, TCOpts, TypeCheckArguments}, type_engine::*, types::DeterministicallyAborts, CompileError, CompileResult, IntrinsicFunctionKind, Namespace, }; use super::TypedExpression; #[derive(D...
} impl DeterministicallyAborts for TypedIntrinsicFunctionKind { fn deterministically_aborts(&self) -> bool { use TypedIntrinsicFunctionKind::*; match self { SizeOfVal { exp } => exp.deterministically_aborts(), SizeOfType { .. } | GetStorageKey | IsRefType { .. } => false, ...
tter) -> fmt::Result { use TypedIntrinsicFunctionKind::*; let s = match self { SizeOfVal { exp } => format!("size_of_val({})", exp), SizeOfType { type_id, .. } => format!("size_of({})", look_up_type_id(*type_id)), IsRefType { type_id, .. } => format!("is_ref_type({})"...
function_block-function_prefixed
[ { "content": "fn run_tests<F: Fn(&mut sway_ir::Context) -> bool>(sub_dir: &str, opt_fn: F) {\n\n let manifest_dir = env!(\"CARGO_MANIFEST_DIR\");\n\n let dir: PathBuf = format!(\"{}/tests/{}\", manifest_dir, sub_dir).into();\n\n for entry in std::fs::read_dir(dir).unwrap() {\n\n let path = entry...
Rust
src/results/db.rs
bofh69/crater
29d2aebfa4723bba8e64889e728953d223418447
use base64; use crates::{Crate, GitHubRepo}; use db::{Database, QueryUtils}; use errors::*; use experiments::Experiment; use results::{DeleteResults, ReadResults, TestResult, WriteResults}; use serde_json; use std::collections::HashMap; use std::io::Read; use toolchain::Toolchain; #[derive(Deserialize)] pub struct Tas...
use base64; use crates::{Crate, GitHubRepo}; use db::{Database, QueryUtils}; use errors::*; use experiments::Experiment; use results::{DeleteResults, ReadResults, TestResult, WriteResults}; use serde_json; use std::collections::HashMap; use std::io::Read; use toolchain::Toolchain; #[derive(Deserialize)] pub struct Tas...
&results .load_log(&ex, &MAIN_TOOLCHAIN, &krate) .unwrap() .unwrap() ).contains("hello world") ); assert!( results .load_test_result(&ex, &TEST_TOOLCHAIN, &krate) .unwrap(...
ent, toolchain: &Toolchain, krate: &Crate, ) -> Result<Option<TestResult>> { self.load_test_result(ex, toolchain, krate) } fn record_sha(&self, ex: &Experiment, repo: &GitHubRepo, sha: &str) -> Result<()> { self.db.execute( "INSERT INTO shas (experiment, org, nam...
random
[ { "content": "pub fn capture_shas<DB: WriteResults>(ex: &Experiment, crates: &[Crate], db: &DB) -> Result<()> {\n\n for krate in crates {\n\n if let Crate::GitHub(ref repo) = *krate {\n\n let dir = repo.mirror_dir();\n\n let r = RunCommand::new(\"git\", &[\"rev-parse\", \"HEAD\"]...
Rust
REE/deps/jsonrpc/host/src/lib.rs
Zondax/tee-substrate-service
fe5c54ad1bd5858e38bc24c3ee7cb635a9096cb1
use std::net::ToSocketAddrs; #[macro_use] extern crate log; use futures::{ stream::{Stream, StreamExt}, Future, FutureExt, SinkExt, }; use jsonrpc_http_server::jsonrpc_core::{BoxFuture, IoHandler, Result as RpcResult}; use host_common::{ channel::{self, mpsc::UnboundedReceiver as Receiver, mpsc::Unboun...
use std::net::ToSocketAddrs; #[macro_use] extern crate log; use futures::{ stream::{Stream, StreamExt}, Future, FutureExt, SinkExt, }; use jsonrpc_http_server::jsonrpc_core::{BoxFuture, IoHandler, Result as RpcResult}; use host_common::{ channel::{self, mpsc::UnboundedReceiver as Receiver, mpsc::Unboun...
BoxFuture<RpcResult<Vec<ZKMSPublicKey>>> { info!("get public keys requested"); Box::pin(self.get_public_keys_impl().map(|r| { r.map(|ks| ks.into_iter().map(|k| k.to_bytes()).collect()) .map_err(Into::into) .map_err(Into::into) })) } f...
ture), _ => panic!("expected signmessage response"), } } } } impl<E> ZKMS for RpcHandler<E> where E: Into<RpcError> + Send + 'static, { fn generate_new(&self, seed: Option<String>) -> BoxFuture<RpcResult<ZKMSPublicKey>> { info!("generate new requested"); ...
random
[ { "content": "/// Reads an u64 from the slice, advancing it\n\npub fn read_and_advance_u64(slice: &mut &[u8]) -> Result<u64, Error> {\n\n if slice.len() < U64_SIZE {\n\n return Err(Error::OutOfMemory);\n\n }\n\n\n\n //read and advance slice\n\n let mut tmp = [0; U64_SIZE];\n\n tmp.copy_fro...
Rust
benches/lib.rs
letheed/divrem
d17f429aa2b47e6f4af5d8e5a0235418415b1741
#![warn(rust_2018_idioms)] #![warn(clippy::pedantic)] #![warn(clippy::cargo)] #![warn(clippy::nursery)] #![allow(clippy::missing_const_for_fn)] #![feature(test)] extern crate test; use divrem::DivRem; use divrem::{DivCeil, DivRemCeil, RemCeil}; use divrem::{DivEuclid, DivRemEuclid, RemEuclid}; use divrem::{DivFloor, ...
#![warn(rust_2018_idioms)] #![warn(clippy::pedantic)] #![warn(clippy::cargo)] #![warn(clippy::nursery)] #![allow(clippy::missing_const_for_fn)] #![feature(test)] extern crate test; use divrem::DivRem; use divrem::{DivCeil, DivRemCeil, RemCeil}; use divrem::{DivEuclid, DivRemEuclid, RemEuclid}; use divrem::{DivFloor, ...
#[inline] fn rem_ceil3(self_: i32, other: i32) -> i32 { let r = self_ % other; if r.signum() == other.signum() { r - other } else { r } } #[inline] fn div_rem_ceil1(self_: i32, other: i32) -> (i32, i32) { DivRemCeil::div_rem_ceil(self_, other) } #[inline] fn div_rem_ceil2(self_: ...
fn rem_ceil2(self_: i32, other: i32) -> i32 { let r = self_ % other; if (r > 0 && other > 0) || (r < 0 && other < 0) { r - other } else { r } }
function_block-full_function
[ { "content": " test!(test_rem_floor, RemFloor, rem_floor);\n\n test!(test_div_rem_floor, DivRemFloor, div_rem_floor);\n\n test!(test_div_euclid, DivEuclid, div_euclid);\n\n test!(test_rem_euclid, RemEuclid, rem_euclid);\n\n test!(test_div_rem_euclid, DivRemEuclid, div_rem_euclid);\n\n test!(te...
Rust
examples/fonts.rs
alexschrod/bevy_doryen
20aa1512944b7174de7ed967175e017eb0077bfa
use bevy_app::{App, EventWriter}; use bevy_doryen::doryen::{AppOptions, TextAlign}; use bevy_doryen::{ DoryenPlugin, DoryenPluginSettings, Input, RenderSystemExtensions, RootConsole, SetFontPath, }; use bevy_ecs::system::{IntoSystem, Res, ResMut}; const CONSOLE_WIDTH: u32 = 40; const CONSOLE_HEIGHT: u32 = 25; con...
use bevy_app::{App, EventWriter}; use bevy_doryen::doryen::{AppOptions, TextAlign}; use bevy_doryen::{ DoryenPlugin, DoryenPluginSettings, Input, RenderSystemExtensions, RootConsole, SetFontPath, }; use bevy_ecs::system::{IntoSystem, Res, ResMut}; const CONSOLE_WIDTH: u32 = 40; const CONSOLE_HEIGHT: u32 = 25; con...
r(mut root_console: ResMut<RootConsole>, font: Res<Font>) { root_console.rectangle( 0, 0, CONSOLE_WIDTH, CONSOLE_HEIGHT, Some((128, 128, 128, 255)), None, Some('.' as u16), ); root_console.area( 10, 10, 5, 5, Som...
function_block-function_prefixed
[ { "content": "fn update(input: Res<Input>, mut text_input: ResMut<TextInput>) {\n\n // input.text returns the characters typed by the player since last update\n\n let text = input.text();\n\n if !text.is_empty() {\n\n text_input.text.push_str(text);\n\n }\n\n // handle backspace\n\n if ...
Rust
src/blockchain/mod.rs
Jimmy-0/BTC-Clients
c88651b6d470da5739fc2fc40a6c24e618022e69
#![allow(unused)] use serde::{Serialize, Deserialize}; use crate::types::block::{Block, generate_genesis_block}; use crate::types::hash::{H256, Hashable}; use std::collections::HashMap; use crate::types::transaction::{Transaction, SignedTransaction, generate_random_transaction}; use crate::types::address::Address; use ...
#![allow(unused)] use serde::{Serialize, Deserialize}; use crate::types::block::{Block, generate_genesis_block}; use crate::types::hash::{H256, Hashable}; use std::collections::HashMap; use crate::types::transaction::{Transaction, SignedTransaction, generate_random_transaction}; use crate::types::address::Address; use ...
pub fn get_random_addr(&self) -> Option<&Address> { let len = self.ledger.len(); if len==0 { return None; } else { let index = rand::thread_rng().gen_range(0..len); return self.ledger.keys().skip(index).next(); } } pub fn get_balance(&self, addr: Address) -> Result<(u32, u32), &'static str> {...
if !state.ledger.contains_key(&receiver_addr) { state.ledger.insert(receiver_addr, (0, val)); } else { tuple = state.ledger[ &receiver_addr ]; let (nonce, bal) = tuple; state.ledger.insert(receiver_addr, (nonce, bal+val)); } } return Ok(state); }
function_block-function_prefix_line
[ { "content": "//#[cfg(any(test, test_utilities))]\n\npub fn generate_random_transaction() -> Transaction {\n\n\tlet r = generate_random_string(30);\n\n\tlet rb = r.as_bytes();\n\n\n\n\tlet mut rng = rand::thread_rng();\n\n\tlet val: u32 = rng.gen();\n\n\tlet ac_nonce: u32 = rng.gen(); // maintain last account_n...
Rust
crates/ra_prof/src/lib.rs
Robbepop/rust-analyzer
8887782c4ab97d22f3d5c10e142407e4371c5c61
use std::cell::RefCell; use std::time::{Duration, Instant}; use std::mem; use std::io::{stderr, Write}; use std::iter::repeat; use std::collections::{HashSet}; use std::default::Default; use std::iter::FromIterator; use std::sync::RwLock; use lazy_static::lazy_static; pub fn set_filter(f: Filter) { let set = HashS...
use std::cell::RefCell; use std::time::{Duration, Instant}; use std::mem; use std::io::{stderr, Write}; use std::iter::repeat; use std::collections::{HashSet}; use std::default::Default; use std::iter::FromIterator; use std::sync::RwLock; use lazy_static::lazy_static;
pub fn profile(desc: &str) -> Profiler { PROFILE_STACK.with(|stack| { let mut stack = stack.borrow_mut(); if stack.starts.len() == 0 { match FILTER.try_read() { Ok(f) => { if f.version > stack.filter_data.version { stack.filte...
pub fn set_filter(f: Filter) { let set = HashSet::from_iter(f.allowed.iter().cloned()); let mut old = FILTER.write().unwrap(); let filter_data = FilterData { depth: f.depth, allowed: set, version: old.version + 1 }; *old = filter_data; }
function_block-function_prefix_line
[ { "content": "fn write() {\n\n match something_unknown {\n\n Maybe::Real(ref mut something) => (),\n\n }\n\n}\n\n\"#),\n\n @r###\"\n\n[54; 139) '{ ... } }': ()\n\n[60; 137) 'match ... }': ()\n\n[66; 83) 'someth...nknown': Maybe<{unknown}>\n\n[94; 124) 'Maybe:...thing)': Maybe<{unkn...
Rust
src/test/instruction_tests/instr_vblendvpd.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 vblendvpd_1() { run_test( &Instruction { mnemonic: Mnemonic::VBLENDVPD, ...
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 vblendvpd_1() { run_test( &Instruction { mnemonic: Mnemonic::VBLENDVPD, ...
e: false, mask: None, broadcast: None, }, &[196, 227, 93, 75, 201, 80], OperandSize::Dword, ) } #[test] fn vblendvpd_6() { run_test( &Instruction { mnemonic: Mnemonic::VBLENDVPD, operand1: Some(Direct(YMM3)), operand2: ...
nic::VBLENDVPD, operand1: Some(Direct(YMM1)), operand2: Some(Direct(YMM4)), operand3: Some(Direct(YMM1)), operand4: Some(Direct(YMM5)), lock: false, rounding_mode: None, merge_mode: None, sa
function_block-random_span
[ { "content": "fn encode64_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
worker/src/backends/bigquery/probe.rs
openquery-io/parallax
0ddcdd82ba21f3b1e6b41ff0d07fcb567a637147
use crate::common::*; use crate::backends::{LastUpdated, Probe}; use crate::gcp::bigquery::{JobBuilder, TableRef}; use crate::opt::{ Context, ContextError, ContextKey, DataType, Domain, ExprMeta, MaximumFrequency, Mode, RowCount, TableMeta, }; use crate::Result; use super::{table_ref_to_context_key, BigQuery}...
use crate::common::*; use crate::backends::{LastUpdated, Probe}; use crate::gcp::bigquery::{JobBuilder, TableRef}; use crate::opt::{ Context, ContextError, ContextKey, DataType, Domain, ExprMeta, MaximumFrequency, Mode, RowCount, TableMeta, }; use crate::Result; use super::{table_ref_to_context_key, BigQuery}...
async fn row_count(&self) -> Result<RowCount> { let query_str = format!("SELECT COUNT(*) FROM {}", self.table_ref); let results = self.inner.lite_query(&query_str).await?; results .rows .and_then(|mut rows| { let mut cells = rows.pop()?.f?; ...
async fn maximum_frequency(&self, key: &ContextKey) -> Result<MaximumFrequency> { let query_str = format!( "SELECT MAX(freq) \ FROM (\ SELECT {key} as key, \ COUNT(*) as freq \ FROM {table_ref} \ GROUP BY {key} \ ...
function_block-full_function
[ { "content": "fn table_ref_to_context_key(table_ref: &TableRef) -> ContextKey {\n\n let (project_id, dataset_id, table_id) = table_ref.unwrap();\n\n ContextKey::with_name(table_id)\n\n .and_prefix(dataset_id)\n\n .and_prefix(project_id)\n\n}\n\n\n\npub struct BigQueryRelT<'a> {\n\n root: ...
Rust
src/atsame70q21b/isi/isi_r2y_set1.rs
tstellanova/atsame7x-pac
f7e24c71181651c141d0727379147c388661ce0e
#[doc = "Reader of register ISI_R2Y_SET1"] pub type R = crate::R<u32, super::ISI_R2Y_SET1>; #[doc = "Writer for register ISI_R2Y_SET1"] pub type W = crate::W<u32, super::ISI_R2Y_SET1>; #[doc = "Register ISI_R2Y_SET1 `reset()`'s with value 0"] impl crate::ResetValue for super::ISI_R2Y_SET1 { type Type = u32; #[i...
#[doc = "Reader of register ISI_R2Y_SET1"] pub type R = crate::R<u32, super::ISI_R2Y_SET1>; #[doc = "Writer for register ISI_R2Y_SET1"] pub type W = crate::W<u32, super::ISI_R2Y_SET1>; #[doc = "Register ISI_R2Y_SET1 `reset()`'s with value 0"] impl crate::ResetValue for super::ISI_R2Y_SET1 { type Type = u32; #[i...
> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w....
C5_R = crate::R<u8, u8>; #[doc = "Write proxy for field `C5`"] pub struct C5_W<'a> { w: &'a mut W, } impl<'a> C5_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x7f << 16)) | (((value as u32) &...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/day5.rs
taurr/advent_of_code_2021
b06be6c9100ab907df88eda9fba86bfda1dee96d
use anyhow::Result; use derive_more::{Add, Constructor, Sub}; use image::{Rgb, RgbImage}; use itertools::Itertools; use regex::Regex; use std::path::Path; use std::str::FromStr; pub fn solve_puzzle(input_path: &Path) -> Result<()> { let input = std::fs::read_to_string(input_path)?; let input = parse_input(&inp...
use anyhow::Result; use derive_more::{Add, Constructor, Sub}; use image::{Rgb, RgbImage}; use itertools::Itertools; use regex::Regex; use std::path::Path; use std::str::FromStr; pub fn solve_puzzle(input_path: &Path) -> Result<()> { let input = std::fs::read_to_string(input_path)?; let input = parse_input(&inp...
}
fn example_part2() { let input = example_input(); let input = parse_input(&input); let result = part2(&input); assert_eq!(12, result); }
function_block-function_prefix_line
[ { "content": "fn part1(mut input: ParsedInput) -> Result<usize> {\n\n follow_instructions(input.instructions.into_iter().take(1), &mut input.dots);\n\n\n\n // finalize\n\n Ok(input.dots.into_iter().unique().count())\n\n}\n\n\n", "file_path": "src/day13.rs", "rank": 0, "score": 248115.826833...
Rust
src/storage/request.rs
jeffreybolle/ironcast
d750893f6c9da5eb3964037025b003585c643ad8
use crate::net::utils::*; #[derive(PartialEq, Clone, Debug)] pub enum RequestType { GET, PUT, } impl RequestType { pub fn to_byte(&self) -> u8 { match self { RequestType::GET => 0x0, RequestType::PUT => 0x1 } } } #[derive(Clone, Debug)] pub struct Request { ...
use crate::net::utils::*; #[derive(PartialEq, Clone, Debug)] pub enum RequestType { GET, PUT, } impl RequestType { pub fn to_byte(&self) -> u8 { match self { RequestType::GET => 0x0, RequestType::PUT => 0x1 } } } #[derive(Clone, Debug)] pub struct Request { ...
match discriminator & 0x2 { 0x0 => { Request { request_type, storage_key, value: None, } } 0x2 => { if msg.len() < 33 + 4 { panic!("invalid messag...
let request_type = match discriminator & 0x1 { 0x0 => RequestType::GET, 0x1 => RequestType::PUT, _ => { panic!("invalid discriminator: {}", discriminator); } };
assignment_statement
[ { "content": "pub fn write_u32(msg: &mut Vec<u8>, value: u32) {\n\n msg.push(((value >> 24) & 0xff) as u8);\n\n msg.push(((value >> 16) & 0xff) as u8);\n\n msg.push(((value >> 8) & 0xff) as u8);\n\n msg.push((value & 0xff) as u8);\n\n}\n\n\n", "file_path": "src/net/utils.rs", "rank": 0, ...
Rust
game-of-life/src/main.rs
Luminoth/nature-of-code
289ac411b78c586efbfebf0c189f074b67f0ffc0
use std::cell::RefCell; use std::rc::Rc; use processing::errors::ProcessingErr; use processing::Screen; use rand::Rng; #[derive(Debug, Default, Copy, Clone)] struct LifeCell { state: i8, previous_state: i8, } impl LifeCell { fn new() -> Self { let mut rng = rand::thread_rng(); let state ...
use std::cell::RefCell; use std::rc::Rc; use processing::errors::ProcessingErr; use processing::Screen; use rand::Rng; #[derive(Debug, Default, Copy, Clone)] struct LifeCell { state: i8, previous_state: i8, } impl LifeCell { fn new() -> Self { let mut rng = rand::thread_rng(); let state ...
fn draw(&self, screen: &mut Screen) -> Result<(), ProcessingErr> { for x in 0..self.columns { for y in 0..self.rows { if self.board[x][y].was_born() { core::fill_rgb(screen, 0.0, 0.0, 255.0); } else if self.board[x][y].is_alive() { ...
for x in 1..self.columns - 1 { for y in 1..self.rows - 1 { let mut neighbors = 0; for i in 0..=2 { for j in 0..=2 { neighbors += self.board[x + i - 1][y + j - 1].previous_state; ...
function_block-function_prefix_line
[ { "content": "fn draw(screen: &mut Screen, dots: impl AsRef<[(f64, f64)]>) -> Result<(), ProcessingErr> {\n\n core::background_grayscale(screen, 255.0);\n\n\n\n screen.stroke_off();\n\n core::fill_rgba(screen, 255.0, 0.0, 0.0, 50.0);\n\n for dot in dots.as_ref() {\n\n core::shapes::ellipse(sc...
Rust
octo/src/parser.rs
redmannequin/octo
3d61fcd1a6c0a6369697b06ae7811b9fffb11462
use std::result; use crate::ast; use crate::errors::ParseError; use crate::lexer::Lexer; use crate::token::{Token, TokenType}; pub type Result<T> = result::Result<T, ParseError>; #[derive(Debug, Clone, Copy)] pub struct Parser<'a> { lexer: Lexer<'a>, curr_token: Token<'a>, peek_token: Token<'a>, } impl<...
use std::result; use crate::ast; use crate::errors::ParseError; use crate::lexer::Lexer; use crate::token::{Token, TokenType}; pub type Result<T> = result::Result<T, ParseError>; #[derive(Debug, Clone, Copy)] pub struct Parser<'a> { lexer: Lexer<'a>, curr_token: Token<'a>, peek_token: Token<'a>, } impl<...
fn parse_ident(&mut self) -> Result<ast::Ident<'a>> { let ident_token = self.expected_bump(TokenType::Identifier)?; Ok(ast::Ident::new(ident_token)) } fn parse_mutability(&mut self) -> Result<bool> { if self.peek_token.token_type == TokenType::Mut { self.bump(); ...
st::Operator, ) -> Result<ast::Expression<'a>> { let token = self.bump(); let right_expr = self.parse_expr(op.into())?; Ok(ast::Expression::Infix(ast::Infix::new( token, op, left_expr, right_expr, ))) }
function_block-function_prefixed
[ { "content": "pub fn eval(program: &[ast::Statement], env: &mut Environment) -> Object {\n\n let mut result = Object::Null;\n\n for stmt in program {\n\n result = match stmt {\n\n ast::Statement::LetStmt(let_stmt) => eval_let_stmt(let_stmt, env),\n\n ast::Statement::ExprStmt(e...
Rust
src/sprite_sheet.rs
PsHegger/rust-game-dev-experiments
a8970d2747524547b2a80fe2bde916e66639d70a
extern crate piston; extern crate piston_window; extern crate quick_xml; extern crate rand; extern crate serde; mod utils; use piston::WindowSettings; use piston_window::*; use utils::game_window::GameWindow; use utils::input::InputHandler; use utils::scene::Scene; use utils::sprite_sheet::SpriteSheet; const WIDTH: ...
extern crate piston; extern crate piston_window; extern crate quick_xml; extern crate rand; extern crate serde; mod utils; use piston::WindowSettings; use piston_window::*; use utils::game_window::GameWindow; use utils::input::InputHandler; use utils::scene::Scene; use utils::sprite_sheet::SpriteSheet; const WIDTH: ...
pub fn coords(&self, height: f64, tile_size: f64) -> [f64; 2] { [ tile_size * self.x as f64, height - (1.0 + self.y as f64) * tile_size, ] } } #[derive(Clone)] pub struct SpriteSheetApp { width: u32, height: u32, sprite_sheet: SpriteSheet, tiles: Vec<Ti...
pub fn new(sprite_name: &str, x: u32, y: u32) -> Tile { Tile { sprite_name: sprite_name.to_string(), x, y, } }
function_block-full_function
[ { "content": "#[derive(Debug, Deserialize, PartialEq, Clone)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct SubTexture {\n\n pub name: String,\n\n pub x: f64,\n\n pub y: f64,\n\n pub width: f64,\n\n pub height: f64,\n\n pub frame_x: f64,\n\n pub frame_y: f64,\n\n pub frame_width: f64...
Rust
src/asn1.rs
citronneur/kerlab
a68f548d23cd88c16f0276af14b5da9c129cb335
use yasna::{Tag as YasnaTag, DERWriter, BERReader, ASN1Error, ASN1ErrorKind}; use error::{KerlabResult}; use yasna::tags::{TAG_GENERALSTRING, TAG_GENERALIZEDTIME}; use ascii::AsciiString; use bit_vec::BitVec; use chrono::{Utc, DateTime, NaiveDateTime}; use std::ops::{Deref, DerefMut}; pub trait ASN1 { fn writ...
use yasna::{Tag as YasnaTag, DERWriter, BERReader, ASN1Error, ASN1ErrorKind}; use error::{KerlabResult}; use yasna::tags::{TAG_GENERALSTRING,
Ok(()) } fn read_asn1(&mut self, reader: BERReader) -> KerlabResult<()> { *self = reader.read_tagged_implicit(TAG_GENERALIZEDTIME, |reader| { let bytes = reader.read_bytes()?; match NaiveDateTime::parse_from_str(AsciiString::from_ascii(bytes).unwrap().as_str(), "%Y...
TAG_GENERALIZEDTIME}; use ascii::AsciiString; use bit_vec::BitVec; use chrono::{Utc, DateTime, NaiveDateTime}; use std::ops::{Deref, DerefMut}; pub trait ASN1 { fn write_asn1(&self, writer: DERWriter) -> KerlabResult<()>; fn read_asn1(&mut self, reader: BERReader) -> KerlabResult<()>; } pub type Se...
random
[ { "content": "use error::{KerlabResult, Error, KerlabErrorKind};\n\nuse encryption::{EType, KeyUsage};\n\nuse rnd::random;\n\nuse md5::Md5;\n\nuse hmac::{Hmac, Mac};\n\n\n", "file_path": "src/rc4hmac.rs", "rank": 0, "score": 4.178296527974096 }, { "content": "use std::io::{Read, Write, Curso...
Rust
src/main.rs
infi/infi-minesweeper
9c551d5de61551381da23545af0a12a691120e64
mod algo; mod data; mod textures; use std::time::Duration; use crate::data::{constants, Board, GameState, Tile}; use image::EncodableLayout; use macroquad::prelude::*; fn window_conf() -> Conf { Conf { window_width: 598, window_height: 650, window_title: "Minesweeper".to_owned(), ...
mod algo; mod data; mod textures; use std::time::Duration; use crate::data::{constants, Board, GameState, Tile}; use image::EncodableLayout; use macroquad::prelude::*; fn window_conf() -> Conf { Conf { window_width: 598, window_height: 650, window_title: "Minesweeper".to_owned(), ...
draw_text_ex( format!("Score: {}", state.score).as_str(), 10.0, y_start_coord, TextParams { font: font, font_size: 32, color: WHITE, ..TextParams::default() }, ); draw_text_ex( format!("Flags: {}", state.flags_...
let flag_dimensions = measure_text( format!("Flags: {}", state.flags_left).as_str(), Some(font), 32, 1.0, );
assignment_statement
[ { "content": "// Messy. Refactor.\n\n// Flood fill algorithm.\n\npub fn flood_fill(board: &mut Board, x: usize, y: usize) {\n\n let mut tile = &mut board.itself[y][x];\n\n\n\n if tile.is_opened || tile.is_flagged || tile.is_mine {\n\n return;\n\n }\n\n\n\n tile.is_opened = true;\n\n\n\n if...
Rust
src/args.rs
cassaundra/sgf-render
2306c3ede7dba495157fe96950afdec818937892
use crate::lib::{GobanRange, GobanStyle, MakeSvgOptions}; use std::path::PathBuf; const DEFAULT_NODE_NUM: u64 = 1; const DEFAULT_FIRST_MOVE_NUM: u64 = 1; const DEFAULT_WIDTH: u32 = 800; pub fn parse(opts: &getopts::Options, args: &[String]) -> Result<SgfRenderArgs, UsageError> { let matches = opts .parse(...
use crate::lib::{GobanRange, GobanStyle, MakeSvgOptions}; use std::path::PathBuf; const DEFAULT_NODE_NUM: u64 = 1; const DEFAULT_FIRST_MOVE_NUM: u64 = 1; const DEFAULT_WIDTH: u32 = 800; pub fn parse(opts: &getopts::Options, args: &[String]) -> Result<SgfRenderArgs, UsageError> { let matches = opts .parse(...
} impl ::std::error::Error for UsageError {} fn parse_point_pair(s: &str) -> Result<GobanRange, UsageError> { let parse_byte = |b: u8| match b { b'a'..=b'z' => Ok(b - b'a'), _ => Err(UsageError::InvalidRange), }; let s = s.as_bytes(); if s.len() != 5 || s[2] != b'-' { return ...
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { UsageError::FailedToParse => write!(f, "Failed to parse arguments."), UsageError::TooManyArguments => write!(f, "Too many arguments."), UsageError::InvalidNodeNumber => write!(f, "Invalid node numbe...
function_block-full_function
[ { "content": "fn draw_stone(stone: Stone, style: GobanStyle) -> impl svg::node::Node {\n\n match style {\n\n GobanStyle::Fancy => {\n\n let shadow = element::Circle::new()\n\n .set(\"cx\", f64::from(stone.x) + 0.025)\n\n .set(\"cy\", f64::from(stone.y) + 0.025)...
Rust
src/problem/p0341_flatten_nested_list_iterator.rs
RUAN0007/leetcode-rust
9d8a05c7e8b5bb9112ea4e46a6ff64cc6902d728
/** * [341] Flatten Nested List Iterator * * You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. * Implement the NestedIterator class: * * NestedIterator(List<NestedInteger> neste...
/** * [341] Flatten Nested List Iterator * * You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. * Implement the NestedIterator class: * * NestedIterator(List<NestedInteger> neste...
fn expand(&mut self) { while let Some(first_nested_int) = self.nested_list.get(0) { match(first_nested_int) { NestedInteger::Int(_)=>{break;} NestedInteger::List(_) => { if let Some(NestedInteger::List(first_nested_list)) = self.nest...
n 0;} if let Some(NestedInteger::Int(val)) = self.nested_list.pop_front() { val } else { panic!("The front must be an int due to the previous expand..."); } }
function_block-function_prefixed
[ { "content": "// helper function for test\n\npub fn to_list(vec: Vec<i32>) -> Option<Box<ListNode>> {\n\n let mut current = None;\n\n for &v in vec.iter().rev() {\n\n let mut node = ListNode::new(v);\n\n node.next = current;\n\n current = Some(Box::new(node));\n\n }\n\n current\...
Rust
src/devtool/src/ci.rs
MikailBag/jjs
bf00423f70f8a6ed508bbcb8b38840225e43cc73
use std::env::var; #[derive(PartialEq, Eq, Clone, Debug)] enum CheckJobType { EndToEnd, __Other, } impl CheckJobType { fn detect() -> Option<CheckJobType> { std::env::var("JOB") .ok() .and_then(|name| match name.as_str() { "e2e" => Some(CheckJobType::EndToEn...
use std::env::var; #[derive(PartialEq, Eq, Clone, Debug)] enum CheckJobType { EndToEnd, __Other, } impl CheckJobType { fn detect() -> Option<CheckJobType> { std::env::var("JOB") .ok() .and_then(|name| match name.as_str() { "e2e" => Some(CheckJobType::EndToEn...
branch_name("refs/null/xxx"), None); } #[test] fn test_strips_prefix_only_once() { assert_eq!( extract_branch_name("refs/heads/refs/heads/m"), Some("refs/heads/m") ); assert_eq!( extract_branch_name("refs/pull/refs/pull/n"), Some("refs...
eploy" => Workflow::Deploy, "ci" => Workflow::Pr, other => panic!("Unknown workflow name: {}", other), } } } #[derive(Clone)] pub struct BuildInfo { ty: BuildType, } impl BuildInfo { pub fn is_deploy(&self) -> bool { matches!(self.ty, BuildType::Deploy(_)) } ...
random
[ { "content": "pub fn check_password_hash(password: &str, expected_hash: &str) -> bool {\n\n let actual_hash = get_password_hash(password);\n\n constant_time_eq::constant_time_eq(expected_hash.as_bytes(), actual_hash.as_bytes())\n\n}\n", "file_path": "src/apiserver_old/engine/src/password.rs", "ran...
Rust
src/scenes/game_selection.rs
chrishulbert/rusty-lemmings
124f012acae5bbddcce069501811cccf8ca974d2
extern crate quicksilver; use quicksilver::{ Result, geom::{Rectangle, Transform}, graphics::{Background::Img, Background::Col, Color, Image as QSImage}, lifecycle::{Event, Window}, input::MouseButton, }; use lemmings::{loader, models::*}; use Scene; use super::EventAction; use super::skill_selecti...
extern crate quicksilver; use quicksilver::{ Result, geom::{Rectangle, Transform}, graphics::{Background::Img, Background::Col, Color, Image as QSImage}, lifecycle::{Event, Window}, input::MouseButton, }; use lemmings::{loader, models::*}; use Scene; use super::EventAction; use super::skill_selecti...
}
lected_game, self.background.clone())?; Ok(Some(Box::new(skill_selection))) } else { Ok(None) } }
function_block-function_prefixed
[ { "content": "pub fn qs_font_from_lemmings_menu_font_with_scale(menu_font: &MenuFont, scale: u8) -> Result<QSMenuFont> {\n\n let mut characters: Vec<QSImage> = Vec::with_capacity(menu_font.characters.len());\n\n for character in menu_font.characters.iter() {\n\n let scaled = xbrz::scale(scale, &cha...
Rust
src/lib.rs
schneiderfelipe/welford
62735fbd9e6ec8c57f7f2d5dae90c1768d4b3254
use num_traits::{cast, Num, NumAssign, NumCast, Zero}; pub struct Welford<T, W = usize> { mean: Option<T>, total: W, msq: T, } impl<T> Welford<T> where T: Zero, { pub fn new() -> Self { Self { mean: None, total: 0, msq:...
use num_traits::{cast, Num, NumAssign, NumCast, Zero}; pub struct Welford<T, W = usize> { mean: Option<T>, total: W, msq: T, } impl<T> Welford<T> where T: Zero, { pub fn new() -> Self { Self { mean: None, total: 0, msq:...
mean(), Some(3.5)); assert_eq!(w1.var(), Some(4.473684210526316)); } }
me(3.0)); assert_eq!(w.var(), Some(4.0)); } #[test] fn test_weighted_welford() { let mut w = Welford::with_weights(); assert_eq!(w.mean(), None); assert_eq!(w.var(), None); w.push_weighted(1.0, 3.0); assert_eq!(w.mean(), Some(1.0)); assert_eq!(w.var(...
random
[ { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let mut w = Welford::<f32>::new();\n\n\n\n while let Ok(value) = {\n\n print!(\"Please enter a real number (anything else to quit): \");\n\n stdout().flush()?;\n\n\n\n let mut buffer = String::new();\n\n stdin().read_l...
Rust
ninja/src/lib.rs
nikhilm/ninja-rs
c87f0f522d60bfd60d27d51ea836554c05d09cf6
/* * Copyright 2020 Nikhil Marathe <nsm.nikhil@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
/* * Copyright 2020 Nikhil Marathe <nsm.nikhil@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
src_path.with_file_name(req_path) } } else { Path::new(OsStr::from_bytes(request)).to_owned() }; std::fs::read(path) } } pub fn run(config: Config) -> anyhow::Result<()> { if let Some(dir) = &config.execution_dir { std::env::set_current_dir(&d...
Debug)] #[error("Unknown debug setting '{0}'")] pub struct DebugModeError(String); impl std::str::FromStr for DebugMode { type Err = DebugModeError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "stats" => Ok(DebugMode::Stats), "list" => Ok(DebugMode::List), ...
random
[ { "content": "pub trait Loader {\n\n fn load(&mut self, from: Option<&[u8]>, request: &[u8]) -> Result<Vec<u8>, std::io::Error>;\n\n}\n\n\n\nmod ast;\n\nmod env;\n\nmod lexer;\n\nmod parser;\n\npub mod repr;\n\n\n\nuse env::Env;\n\nuse parser::{ParseError, Parser};\n\npub use repr::*;\n\n\n\n#[derive(Error, ...
Rust
src/lib.rs
federicomenaquintero/xdg-mime-rs
4d4482d6e7bc2ca4170daa8a2810a787523a20aa
#![cfg(any(unix, target_os = "redox"))] #![allow(dead_code)] use std::env; use std::path::{Path, PathBuf}; extern crate dirs; #[macro_use] extern crate nom; mod alias; mod glob; mod icon; mod magic; mod parent; pub static UNKNOWN_TYPE: &str = "application/octet-stream"; pub static EMPTY_TYPE: &str = "application/...
#![cfg(any(unix, target_os = "redox"))] #![allow(dead_code)] use std::env; use std::path::{Path, PathBuf}; extern crate dirs; #[macro_use] extern crate nom; mod alias; mod glob; mod icon; mod magic; mod parent; pub static UNKNOWN_TYPE: &str = "application/octet-stream"; pub static EMPTY_TYPE: &str = "application/...
_type_equal("application/x-wordperfect", "audio/x-midi"), false ); assert_eq!(mime_db.mime_type_equal("/", "vnd/vnd"), false); assert_eq!( mime_db.mime_type_equal("application/octet-stream", "text/plain"), false ); assert_eq!(mime_db.mime_type_...
mime_db = load_test_data(); assert_eq!( mime_db.unalias_mime_type("application/ics"), Some("text/calendar".to_string()) ); assert_eq!(mime_db.unalias_mime_type("text/plain"), None); } #[test] fn mime_type_equal() { let mime_db = load_test_data(); ...
random
[ { "content": "pub fn read_aliases_from_dir<P: AsRef<Path>>(dir: P) -> Vec<Alias> {\n\n let mut alias_file = PathBuf::new();\n\n alias_file.push(dir);\n\n alias_file.push(\"aliases\");\n\n\n\n read_aliases_from_file(alias_file)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #...
Rust
src/config.rs
hpwxf/rusty-boids
81c8214c4a920c43b4455f4fcf6893e534d729f7
use std::{fmt, fs::File, io, io::prelude::*, process}; use crate::boids::{SimulationConfig, WindowSize}; use clap::{ self, App, Arg, ArgMatches, ErrorKind::{HelpDisplayed, VersionDisplayed}, }; use toml; const CONFIG_ARG: &str = "config"; const WINDOW_SIZE_ARG: &str = "size"; const FULLSCREEN_ARG: &str = "fu...
use std::{fmt, fs::File, io, io::prelude::*, process}; use crate::boids::{SimulationConfig, WindowSize}; use clap::{ self, App, Arg, ArgMatches, ErrorKind::{HelpDisplayed, VersionDisplayed}, }; use toml; const CONFIG_ARG: &str = "config"; const WINDOW_SIZE_ARG: &str = "size"; const FULLSCREEN_ARG: &str = "fu...
#[derive(Debug)] pub enum ConfigError { Io(io::Error), Clap(clap::Error), Toml(toml::de::Error), } impl From<io::Error> for ConfigError { fn from(err: io::Error) -> ConfigError { ConfigError::Io(err) } } impl From<clap::Error> for ConfigError { fn from(err: clap::Error) -> ConfigErro...
arg( Arg::with_name(CONFIG_ARG) .short("c") .long("config") .value_name("FILE") .help("Sets the config file to read simulation parameters from"), ) .arg( Arg::with_name(WINDOW_SIZE_ARG) .short("s") ...
function_block-function_prefix_line
[ { "content": "pub fn run_simulation(config: SimulationConfig) -> Result<(), SimulatorError> {\n\n let mut events_loop = EventsLoop::new();\n\n let window = build_window(&events_loop, &config.window_size)?;\n\n gl_init(&window, config.debug)?;\n\n let window_size = get_window_size_info(&window)?;\n\n...
Rust
src/unit_tests.rs
U007D/parser_combinator
3f8520ef4360882d1b966c9e4ba9d931916a6050
use super::*; #[test] fn literal_parser() { let parse_joe = match_literal("Hello Joe!"); assert_eq!(Ok(("", ())), parse_joe.parse("Hello Joe!")); assert_eq!(Ok((" Hello Robert!", ())), parse_joe.parse("Hello Joe! Hello Robert!")); assert_eq!( Err(Error::ParseGrammarViolation(String::from("Hello...
use super::*; #[test] fn literal_parser() { let parse_joe = match_literal("Hello Joe!"); assert_eq!(Ok(("", ())), parse_joe.parse("Hello Joe!")); assert_eq!(Ok((" Hello Robert!", ())), parse_joe.parse("Hello Joe! Hello Robert!")); assert_eq!( Err(Error::ParseGrammarViolation(String::from("Hello...
al(tag1_open), identifier); assert_eq!(Ok((tag1_close, String::from(tag1_attr))), right.parse(&tag1)); assert_eq!( Err(Error::ParseGrammarViolation(String::from(tag2_attr))), right.parse(tag2_attr) ); assert_eq!( Err(Error::ParseGrammarViolation(String::from(tag3_attr))), ...
); } #[test] fn pair_combinator() { let tag1_open = "<"; let tag1_attr = "my-first-element"; let tag1_close = "/>"; let tag1 = String::from(tag1_open) + tag1_attr + tag1_close; let tag2_attr = "oops!"; let tag3_attr = "!oops"; let tag3_incomplete = String::from(tag1_open) + tag3_attr; ...
random
[ { "content": "#[test]\n\nfn xml_parser() {\n\n let doc = r###\"\n\n <top label=\"Top\">\n\n <semi-bottom label=\"Bottom\"/>\n\n <middle>\n\n <bottom label=\"Another bottom\"/>\n\n </middle>\n\n </top>\"###;\n\n let parsed_doc = Element {\n\n ...
Rust
pgs/pgs/src/codegen/context.rs
wnnrd/pragmatic_script
d5cc8c6d0cf576840c548c702d12c8efd097e2e4
use crate::{ codegen::{ def::{ ContainerDef, FunctionDef }, register::{ Register, RegisterAllocator }, compiler::{ CompilerResult, CompilerError, Compiler } }, parser::{ ...
use crate::{ codegen::{ def::{ ContainerDef, FunctionDef }, register::{ Register, RegisterAllocator }, compiler::{ CompilerResult, CompilerError, Compiler } }, parser::{ ...
pub fn get_var_pos(&self, var_name: &String) -> CompilerResult<i64> { self.variable_positions.get(var_name) .cloned() .ok_or(CompilerError::UnknownVariable(var_name.clone())) } pub fn get_ret_type(&self) -> CompilerResult<Type> { let fn_def = self.def.as_ref() ...
pub fn get_var_loc(&self, var_name: &String) -> CompilerResult<VariableLocation> { /*let reg_res = self.register_allocator.get_permanent(var_name); if reg_res.is_ok() { return Ok(VariableLocation::Register(reg_res.unwrap())); }*/ let position = self.variable_positions.get(var...
function_block-full_function
[ { "content": "fn register_std_print(engine: &mut Engine) -> EngineResult<()> {\n\n let printi_function = Function::new(\"printi\")\n\n .with_arg(Type::Int)\n\n .with_ret_type(Type::Void)\n\n .with_closure(Box::new(|adapter: &mut Adapter| {\n\n //println!(\"Calling printi!\");\...
Rust
src/apiserver_old/src/main.rs
MikailBag/jjs
bf00423f70f8a6ed508bbcb8b38840225e43cc73
use anyhow::Context; use apiserver_engine::ApiserverParams; use futures::stream::StreamExt; use log::info; use std::sync::Arc; async fn launch_api( frcfg: Arc<ApiserverParams>, entity_loader: entity::Loader, problem_loader: problem_loader::Loader, data_dir: &std::path::Path, cancel_token: tokio::sy...
use anyhow::Context; use apiserver_engine::ApiserverParams; use futures::stream::StreamExt; use log::info; use std::sync::Arc; async fn launch_api( frcfg: Arc<ApiserverParams>, entity_loader: entity::Loader, problem_loader: problem_loader::Loader, data_dir: &std::path::Path, cancel_token: tokio::sy...
#[tokio::main] async fn main() -> anyhow::Result<()> { dotenv::dotenv().ok(); util::log::setup(); util::wait::wait(); match std::env::var("__JJS_SPEC").ok().as_deref() { Some("config-schema") => { let schema = schemars::schema_for!(apiserver_engine::config::ApiserverConfi...
let mut joined = futures::stream::select(sigint, sigterm); if joined.next().await.is_none() { loop { tokio::task::yield_now().await; } } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn print_error(err: &dyn std::error::Error) {\n\n eprintln!(\"error: {}\", err);\n\n let mut iter = err.source();\n\n while let Some(cause) = iter {\n\n eprintln!(\"caused by: {}\", cause);\n\n iter = cause.source();\n\n }\n\n}\n", "file_path": "src/util/src/lib.r...
Rust
src/mmu.rs
mehcode/lintel-nes
fbc2385fdf8ebd3a6a31bbd8f7dd044b307f6dd3
use cpu; use ppu; use cartridge::Cartridge; use controller; macro_rules! make_controller {() => { pub trait Controller { fn try_read(&mut self, address: u16, ptr: &mut u8) -> bool; fn read(&mut self, address: u16) -> u8 { let mut value: u8 = 0xFF; if self....
use cpu; use ppu; use cartridge::Cartridge; use controller; macro_rules! make_controller {() => { pub trait Controller { fn try_read(&mut self, address: u16, ptr: &mut u8) -> bool; fn read(&mut self, address: u16) -> u8 { let mut value: u8 = 0xFF; if self....
} false } }
elf) { self.cpu_ram.clear(); self.ppu_ram.clear(); self.ppu_palette.clear(); self.cpu_ram.resize(1024 * 2, 0); self.ppu_ram.resize(1024 * 2, 0); self.ppu_palette.resize(32, 0); if let Some(ref mut controller) = self.controller { ...
random
[ { "content": "/// Read\n\npub fn read(c: &mut Context, b: &mut Bus, mode: AddressingMode) -> u8 {\n\n // Determine _effective_ address\n\n let address = match mode {\n\n Immediate => {\n\n // Immediate addressing fetches value from PC; so just make address = PC\n\n let address...
Rust
rradio/src/pipeline/ping/mod.rs
sammhicks/internet-radio-rs
64687b19a18b74d790f0cd09107fc68acf405fce
use std::{ net::{Ipv4Addr, SocketAddr}, time::Duration, }; use tokio::sync::mpsc; use rradio_messages::{ArcStr, PingError, PingTarget, PingTimes}; mod ipv4; const PING_INTERVAL: Duration = Duration::from_secs(1); #[derive(Debug)] enum Never {} #[derive(Debug)] enum PingInterruption { Finished, Sus...
use std::{ net::{Ipv4Addr, SocketAddr}, time::Duration, }; use tokio::sync::mpsc; use rradio_messages::{ArcStr, PingError, PingTarget, PingTimes}; mod ipv4; const PING_INTERVAL: Duration = Duration::from_secs(1); #[derive(Debug)] enum Never {} #[derive(Debug)] enum PingInterruption { Finished, Sus...
pub fn run( config: crate::config::ping::Config, ) -> Result< ( impl std::future::Future<Output = ()>, mpsc::UnboundedSender<Option<ArcStr>>, mpsc::UnboundedReceiver<PingTimes>, ), ipv4::PermissionsError, > { let ipv4_pinger = ipv4::Pinger::new()?; let (track_url_tx, tra...
function_block-full_function
[ { "content": "fn display_entry(f: &mut Formatter, label: &str, entry: impl Debug) -> std::fmt::Result {\n\n use crossterm::terminal::{Clear, ClearType};\n\n write!(\n\n f,\n\n \"{}: {:?}{}\\r\\n\",\n\n label,\n\n entry,\n\n Clear(ClearType::UntilNewLine)\n\n )\n\n}\n\...
Rust
src/main.rs
GyrosOfWar/s3-proxy
86b052641e22cdf037b50d837558fcea73b26f7e
extern crate actix_web; extern crate bytes; extern crate failure; extern crate futures; #[macro_use] extern crate log; extern crate log4rs; extern crate rusoto_core as aws; extern crate rusoto_s3 as s3; extern crate serde; #[macro_use] extern crate serde_derive; extern crate mime_guess; extern crate num_cpus; extern cr...
extern crate actix_web; extern crate bytes; extern crate failure; extern crate futures; #[macro_use] extern crate log; extern crate log4rs; extern crate rusoto_core as aws; extern crate rusoto_s3 as s3; extern crate serde; #[macro_use] extern crate serde_derive; extern crate mime_guess; extern crate num_cpus; extern cr...
fn run() -> Result<()> { use actix_web::middleware; use std::env; configure_logger(); let mut config = read_config()?; if let Ok(bucket) = env::var("S3_BUCKET") { config.bucket = bucket; } if let Some(port) = env::var("S3_PROXY_PORT").ok().and_then(|p| p.parse().ok()) { ...
y() { return Box::new(future::ok(HttpResponse::NotFound().body("404 - Not found"))); } debug!("Request headers: {:?}", req.headers()); let resp = client .get_object(s3::GetObjectRequest { bucket, key: key.clone(), range, ..Default::default() ...
function_block-function_prefixed
[ { "content": "# s3-proxy\n\nTiny Rust proxy meant to proxy requests to a configured S3 bucket. \n\nUses actix-web for HTTP and rusoto for AWS. \n\n\n\n## Configuration\n\nRequires a configuration file called `s3-proxy.toml`. Example:\n\n```toml\n\nhost = \"localhost\"\n\nport = 3221\n\n# Optional\n\nbucket = \"...