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
token-metadata/program/tests/freeze_delegated_account.rs
levicook/metaplex-program-library
5d13c31fec61651937033d26c295b9851da4b62d
#![cfg(feature = "test-bpf")] mod utils; use mpl_token_metadata::error::MetadataError; use num_traits::FromPrimitive; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, transport::TransportError, }; u...
#![cfg(feature = "test-bpf")] mod utils; use mpl_token_metadata::error::MetadataError; use num_traits::FromPrimitive; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, transport::TransportError, }; u...
#[tokio::test] async fn freeze_delegated_no_freeze_authority() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata...
r( &[mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, )], ...
function_block-function_prefixed
[ { "content": "/// Strings need to be appended with `\\0`s in order to have a deterministic length.\n\n/// This supports the `memcmp` filter on get program account calls.\n\n/// NOTE: it is assumed that the metadata fields are never larger than the respective MAX_LENGTH\n\npub fn puff_out_data_fields(metadata: ...
Rust
linkerd/proxy/api-resolve/src/resolve.rs
tegioz/linkerd2-proxy
8b6f9a09968ca844e5c7bcbf924c045d4797541b
use crate::api::destination as api; use crate::core::resolve::{self, Update}; use crate::metadata::Metadata; use crate::pb; use futures::{future, try_ready, Future, Poll, Stream}; use tower::Service; use tower_grpc::{self as grpc, generic::client::GrpcService, Body, BoxBody}; use tracing::{debug, trace}; #[derive(Clon...
use crate::api::destination as api; use crate::core::resolve::{self, Update}; use crate::metadata::Metadata; use crate::pb; use futures::{future, try_ready, Future, Poll, Stream}; use tower::Service; use tower_grpc::{self as grpc, generic::client::GrpcService, Body, BoxBody}; use tracing::{debug, trace}; #[derive(Clon...
}
o()); } None => {} }, None => return Err(grpc::Status::new(grpc::Code::Ok, "end of stream")), }; } }
function_block-function_prefixed
[ { "content": "pub fn layer() -> map_target::Layer<impl Fn(Endpoint) -> Endpoint + Copy> {\n\n map_target::layer(|mut ep: Endpoint| {\n\n debug!(\"rewriting inbound address to loopback; addr={:?}\", ep.addr);\n\n ep.addr = SocketAddr::from(([127, 0, 0, 1], ep.addr.port()));\n\n ep\n\n ...
Rust
src/value.rs
basiliqio/messy_json
aa4f6dfbb5bb2a40ee03e7c1cac0b22c4893db59
use super::*; use serde_json::Value; use std::convert::From; use std::ops::Deref; #[derive(Clone, Debug, Eq, PartialEq, Default)] pub struct MessyJsonObjectValue<'a>(BTreeMap<ArcStr, MessyJsonValue<'a>>); #[derive(Clone, Debug, Eq, PartialEq)] pub enum MessyJsonNullType { Null, Absent, } impl<'a> D...
use super::*; use serde_json::Value; use std::convert::From; use std::ops::Deref; #[derive(Clone, Debug, Eq, PartialEq, Default)] pub struct MessyJsonObjectValue<'a>(BTreeMap<ArcStr, MessyJsonValue<'a>>); #[derive(Clone, Debug, Eq, PartialEq)] pub enum MessyJsonNullType { Null, Absent, } impl<'a> D...
), Value::Object(_)) => mj_obj.eq(other), (MessyJsonValue::String(mj_str), Value::String(v_str)) => mj_str == v_str, (MessyJsonValue::Null(_, _), Value::Null) => true, _ => false, } } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct MessyJsonValueContainer<'a> { v...
sonArrayValue<'a> { pub fn take(self) -> Vec<MessyJsonValue<'a>> { self.0 } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct MessyJsonArrayValue<'a>(Vec<MessyJsonValue<'a>>); impl<'a> Deref for MessyJsonArrayValue<'a> { type Target = Vec<MessyJsonValue<'a>>; fn deref(&self) -> &Self::Targe...
random
[ { "content": "#[cfg(test)]\n\npub fn gen_key(k: &str) -> super::object::KeyType {\n\n ArcStr::from(k)\n\n}\n", "file_path": "src/object.rs", "rank": 0, "score": 154589.97172367276 }, { "content": "#[test]\n\nfn null() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(Mes...
Rust
src/segment/data.rs
iFaceless/tinkv
b7f526ccfea53e82285891929bae177698947658
use crate::error::{Result, TinkvError}; use crate::util::{checksum, parse_file_id, BufReaderWithOffset, FileWithBufWriter}; use serde::{Deserialize, Serialize}; use log::{error, trace}; use std::fmt; use std::fs::{self, File}; use std::io::{copy, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; #[derive...
use crate::error::{Result, TinkvError}; use crate::util::{checksum, parse_file_id, BufReaderWithOffset, FileWithBufWriter}; use serde::{Deserialize, Serialize}; use log::{error, trace}; use std::fmt; use std::fs::{self, File}; use std::io::{copy, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; #[derive...
} #[cfg(test)] mod tests { use super::*; #[test] fn test_new_entry() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.checksum, 494360628); } #[test] fn test_checksum_valid() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_v...
fn next(&mut self) -> Option<Self::Item> { let offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let inner: InnerEntry = bincode::deserialize_from(&self.reader).ok()?; let new_offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let entry = Entry::new(self.file_id, inner, n...
function_block-full_function
[ { "content": "pub fn checksum(data: &[u8]) -> u32 {\n\n crc::crc32::checksum_ieee(data)\n\n}\n\n\n", "file_path": "src/util/misc.rs", "rank": 0, "score": 211904.36433031445 }, { "content": "pub fn parse_file_id(path: &Path) -> Option<u64> {\n\n path.file_name()?\n\n .to_str()?\n...
Rust
artichoke-backend/src/extn/core/random/mruby.rs
Talljoe/artichoke
36ed5eba078a9fbf3cb4d5c8f7407d0a773d2d6e
use crate::extn::core::random::{self, trampoline}; use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { if interp.is_class_defined::<random::Random>() { return Ok(()); } let spec = class::Spec::new("Random", None, Some(def::box_unbox_free::<random::Random>))?; ...
use crate::extn::core::random::{self, trampoline}; use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { if interp.is_class_defined::<random::Random>() { return Ok(()); } let spec = class::Spec::new("Random", None, Some(def::box_unbox_free::<random::Random>))?; ...
#[no_mangle] unsafe extern "C" fn artichoke_random_self_urandom( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let size = Value::from(size); ...
unsafe extern "C" fn artichoke_random_self_srand( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let number = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let number = number.map(Value::from); let...
function_block-full_function
[ { "content": "pub fn seed(interp: &mut Artichoke, mut rand: Value) -> Result<Value, Exception> {\n\n let rand = unsafe { Random::unbox_from_value(&mut rand, interp)? };\n\n let seed = rand.seed(interp)?;\n\n Ok(interp.convert(seed))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/random/...
Rust
src/init.rs
dandyvica/clf
0774f971a973d89688a72f7283e251c7a429e946
use std::fs::OpenOptions; use std::path::PathBuf; use simplelog::*; use crate::configuration::{config::Config, script::Script}; use crate::logfile::snapshot::Snapshot; use crate::misc::extension::Expect; use crate::misc::nagios::Nagios; use crate::{args::CliOptions, configuration::vars::GlobalVars}; pub fn init_con...
use std::fs::OpenOptions; use std::path::PathBuf; use simplelog::*; use crate::configuration::{config::Config, script::Script}; use crate::logfile::snapshot::Snapshot; use crate::misc::extension::Expect; use crate::misc::nagios::Nagios; use crate::{args::CliOptions, configuration::vars::GlobalVars}; pub fn init_con...
ger size is: {} bytes", metadata.len()); if metadata.len() > options.max_logger_size { if let Err(e) = std::fs::remove_file(&logger) { if e.kind() != std::io::ErrorKind::NotFound { error!("unable to delete logger file: {:?}, error: {}", &logger, e); } ...
Err(e) => { Nagios::exit_critical(&format!( "unable to create log file: {}, error: {}", logger.display(), e )); } }; let metadata = std::fs::metadata(&logger) .expect_critical(&format!("error on metadata() API, ...
function_block-random_span
[ { "content": "/// Converts the error to string.\n\npub fn error_to_string<S>(value: &Option<AppError>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n if value.is_none() {\n\n \"None\".to_string().serialize(serializer)\n\n } else {\n\n format!(\"{}\", value....
Rust
src/test/spec/v2_runner/test_file.rs
dtolnay-contrib/mongo-rust-driver
1a096bd0d459c1bf6bc59a6a4dc930476043995f
use std::collections::HashMap; use bson::{doc, from_document}; use futures::TryStreamExt; use semver::VersionReq; use serde::{Deserialize, Deserializer}; use crate::{ bson::Document, options::{FindOptions, ReadPreference, SelectionCriteria, SessionOptions}, test::{spec::deserialize_uri_options_to_uri_stri...
use std::collections::HashMap; use bson::{doc, from_document}; use futures::TryStreamExt; use semver::VersionReq; use serde::{Deserialize, Deserializer}; use crate::{ bson::Document, options::{FindOptions, ReadPreference, SelectionCriteria, SessionOptions}, test::{spec::deserialize_uri_options_to_uri_stri...
} #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum TestData { Single(Vec<Document>), Many(HashMap<String, Vec<Document>>), } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct Test { pub description: String, pub skip_reason: Option<String>, pub use_multiple_mongoses: Op...
fn can_run_on(&self, client: &TestClient) -> bool { if let Some(ref min_version) = self.min_server_version { let req = VersionReq::parse(&format!(">= {}", &min_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if l...
function_block-function_prefixed
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestTopologyDescription {\n\n #[serde(rename = \"type\")]\n\n topology_type: TopologyType,\n\n servers: Vec<TestServerDescription>,\n\n}\n\n\n\nimpl TestTopologyDescription {\n\n fn into_topology_description(\n\n self,\n\n heartbeat...
Rust
src/io.rs
pajamapants3000/red
79292885d1dc6efe7ef98c27a9ec25622cfc12ac
/* * File : io.rs * Purpose: handles input/output functionality * Program: red * About : What does this program do? * Authors: Tommy Lincoln <pajamapants3000@gmail.com> * License: MIT; See LICENSE! * Notes : Notes on successful compilation * Created: 10/26/2016 */ use std::fs::{File, OpenOptions}; use std...
/* * File : io.rs * Purpose: handles input/output functionality * Program: red * About : What does this program do? * Authors: Tommy Lincoln <pajamapants3000@gmail.com> * License: MIT; See LICENSE! * Notes : Notes on successful compilation * Created: 10/26/2016 */ use std::fs::{File, OpenOptions}; use std...
sum in &c_braket { assert!( *sum >= 0, "is_quoted: too many closing brackets" ); } if c_quote == vec!( 0; c_quote.len() ) && c_braket == vec!( 0; c_braket.len() ) { false } else { true } }
use std::ffi::OsStr; use regex::Regex; use error::*; use ::{EditorState, EditorMode}; const PROMPT_CONTINUE: &'static str = ">"; const PROMPT_INSERT: &'static str = "!"; #[derive(Default)] pub struct FileMode { pub f_write: bool, pub f_read: bool, pub f_append: bool, pub f_trunc...
random
[ { "content": "/// Print help, warnings, other output depending on setting\n\n///\n\n/// TODO: Change first arg to just boolean: state.help?\n\npub fn print_help<T: Display>( state: &EditorState, output: T ) {// {{{\n\n if state.show_help {\n\n println!( \"{}\", output );\n\n } else {\n\n pri...
Rust
oracle/src/connection.rs
foundation-rs/backend
cc16dff0879314dd05494581aa580c23c74d282f
#[allow(dead_code)] #[allow(non_snake_case)] #[allow(non_camel_case_types)] use crate::oci; use crate::environment::Environment; use crate::{statement, OracleResult, SQLParams, ParamsProvider, SQLResults}; /* pub struct Connection { env: &'static Environment, srvhp: *mut oci::OCIServer, authp: *mut oci::O...
#[allow(dead_code)] #[allow(non_snake_case)] #[allow(non_camel_case_types)] use crate::oci; use crate::environment::Environment; use crate::{statement, OracleResult, SQLParams, ParamsProvider, SQLResults}; /* pub struct Connection { env: &'static Environment, srvhp: *mut oci::OCIServer, authp: *mut oci::O...
one() } } /* impl Drop for Connection { fn drop(&mut self) { oci::session_end(self.svchp, self.env.errhp, self.authp); oci::server_detach(self.srvhp, self.env.errhp); free_session_handler(self.authp); free_server_handlers(self.srvhp, self.svchp); } } */ fn free_session_han...
= oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SERVER)? as *mut oci::OCIServer; let svchp = oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SVCCTX)? as *mut oci::OCISvcCtx; let errhp = env.errhp; let res = oci::server_attach(srvhp, errhp, db); if let Err(err) = res { free_server_handlers(srvhp, svch...
random
[]
Rust
src/systems/cursor_system.rs
csherratt/everpuzzle
6ac83fa7652d1e2d51f23a6f78ef16e27f11a94d
use amethyst::{ ecs::*, core::Transform, renderer::*, input::* }; use components::{ block::Block, cursor::Cursor, kind_generator::KindGenerator, playfield::stack::Stack, }; use block_states::swap::SWAP_TIME; use block_states::block_state::change_state; use data::block_data::*; use std:...
use amethyst::{ ecs::*, core::Transform, renderer::*, input::* }; use components::{ block::Block, cursor::Cursor, kind_generator::KindGenerator, playfield::stack::Stack, }; use block_states::swap::SWAP_TIME; use block_states::block_state::change_state; use data::block_data::*; use std:...
fn set_swap_variables (b: &mut Block, dir: f32) { b.offset.0 = 16.0 * dir; b.counter = SWAP_TIME as u32; b.move_dir = dir; change_state(b, "SWAP"); }
function_block-full_function
[ { "content": "// checks wether the block below is empty or falling, also checks wether this block is empty\n\npub fn check_for_hang(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) -> bool {\n\n // condition based on another block in a different lifetime\n\n let mut down_condition: bool = fa...
Rust
AoC_2021/Day08_SevenSegmentSearch_Rust/src/main.rs
jgpr-code/AdventOfCode
f529af8d7cb74348405679b76062807827b35a29
use itertools::Itertools; use std::collections::{HashMap, HashSet}; use std::io::{self, Read}; fn main() -> io::Result<()> { let mut stdin = io::stdin(); let mut buffer = String::new(); stdin.read_to_string(&mut buffer)?; part_one(&buffer); part_two(&buffer); Ok(()) } fn parse_input(buffer: &s...
use itertools::Itertools; use std::collections::{HashMap, HashSet}; use std::io::{self, Read}; fn main() -> io::Result<()> { let mut stdin = io::stdin(); let mut buffer = String::new(); stdin.read_to_string(&mut buffer)?; part_one(&buffer); part_two(&buffer); Ok(()) } fn parse_input(buffer: &s...
} if is_valid_mapping(&digit_mapping) { Some(digit_mapping) } else { None } } fn is_valid_mapping(digit_mapping: &HashMap<Vec<char>, i32>) -> bool { let values_set: HashSet<&i32> = digit_mapping.values().collect(); for i in 0..10 { if !values_set.contains(&i) { ...
if let Some(int_digit) = segments_to_digit(&segments) { let mut sorted_chars: Vec<char> = digit.chars().collect(); sorted_chars.sort(); digit_mapping.insert(sorted_chars, int_digit); }
if_condition
[ { "content": "fn parse_input(buffer: &str) -> Vec<LineSegment> {\n\n buffer.lines().map(|line| LineSegment::new(line)).collect()\n\n}\n\n\n", "file_path": "AoC_2021/Day05_HydrothermalVenture_Rust/src/main.rs", "rank": 4, "score": 217899.7567314388 }, { "content": "fn parse_input(buffer: &...
Rust
src/api/boblight.rs
vtavernier/hyperion.rs
18cf772ffb649edff4445361741659760e084393
use std::sync::Arc; use thiserror::Error; use crate::{ global::{InputMessage, InputMessageData, InputSourceHandle, Message, PriorityGuard}, instance::{InstanceHandle, InstanceHandleError}, models::Color, }; pub mod message; use message::{BoblightRequest, BoblightResponse}; #[derive(Debug, Error)] pub en...
use std::sync::Arc; use thiserror::Error; use crate::{ global::{InputMessage, InputMessageData, InputSourceHandle, Message, PriorityGuard}, instance::{InstanceHandle, InstanceHandleError}, models::Color, }; pub mod message; use message::{BoblightRequest, BoblightResponse}; #[derive(Debug, Error)] pub en...
async fn set_priority(&mut self, priority: i32) { let new_priority = if priority < 128 || priority >= 254 { self.instance .current_priorities() .await .map(|priorities| { let mut used_priorities = priorities ...
handle, priority_guard, led_colors: vec![Color::default(); led_count], priority: 128, instance, } }
function_block-function_prefixed
[ { "content": "fn error_response(peer_addr: SocketAddr, error: impl std::fmt::Display) -> message::HyperionReply {\n\n let mut reply = message::HyperionReply::default();\n\n reply.r#type = message::hyperion_reply::Type::Reply.into();\n\n reply.success = Some(false);\n\n reply.error = Some(error.to_st...
Rust
src/proxy/sessions/session_manager.rs
iffyio/quilkin
d5e1024b057c7de11e403c2e942ce51b25ae846d
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this
p.len()); } } }
file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDIT...
random
[ { "content": "# Using Quilkin\n\n\n\nThere are two choices for running Quilkin:\n\n\n\n* Binary\n\n* Container image\n\n\n\nFor each version there is both a release version, which is optimised for production usage, and a debug version that \n\nhas debug level logging enabled.\n\n\n\n## Binary\n\n\n\nThe release...
Rust
nanocurrency-peering/src/lib.rs
tundak/railroad
b18298aab4ad72b045227a94162d9cd1a510ef51
use std::iter::IntoIterator; use std::io; use std::net::{SocketAddr, SocketAddrV6, ToSocketAddrs}; use std::cell::RefCell; use std::rc::Rc; use std::time::{Duration, Instant}; use std::collections::{hash_map, HashMap}; use std::marker::PhantomData; use std::fmt::Debug; #[macro_use] extern crate log; #[macro_use] exte...
use std::iter::IntoIterator; use std::io; use std::net::{SocketAddr, SocketAddrV6, ToSocketAddrs}; use std::cell::RefCell; use std::rc::Rc; use std::time::{Duration, Instant}; use std::collections::{hash_map, HashMap}; use std::marker::PhantomData; use std::fmt::Debug; #[macro_use] extern crate log; #[macro_use] exte...
hash_map::Entry::Vacant(entry) => { entry.insert(Instant::now()); } } if state.peers.contains_key(&new_peer) { return None; } ...
d; const KEEPALIVE_INTERVAL: u64 = 60; const KEEPALIVE_CUTOFF: u64 = KEEPALIVE_INTERVAL * 5; pub fn addr_to_ipv6(addr: SocketAddr) -> SocketAddrV6 { match addr { SocketAddr::V4(addr) => SocketAddrV6::new(addr.ip().to_ipv6_mapped(), addr.port(), 0, 0), SocketAddr::V6(addr) => addr, } } struct ...
random
[ { "content": "mod serde;\n", "file_path": "nanocurrency-types/src/tests/mod.rs", "rank": 2, "score": 26395.1323353986 }, { "content": "mod udp_encode_decode;\n", "file_path": "nanocurrency-protocol/src/tests/mod.rs", "rank": 3, "score": 26394.98531009027 }, { "content": "...
Rust
fltk-derive/src/group.rs
andrrff/fltk-rs
1db0fd4c2341b005cd949ac6a3a7b8ab949ada6c
use crate::utils::get_fl_name; use proc_macro::TokenStream; use quote::*; use syn::*; pub fn impl_group_trait(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let name_str = get_fl_name(name.to_string()); let begin = Ident::new(format!("{}_{}", name_str, "begin").as_str(), name.span()); let ...
use crate::utils::get_fl_name; use proc_macro::TokenStream; use quote::*; use syn::*; pub fn impl_group_trait(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let name_str = get_fl_name(name.to_string()); let begin = Ident::new(format!("{}_{}", name_str, "begin").as_str(), name.span()); let ...
unsafe { crate::app::open_display(); Fl_Group_draw_outside_label(self.inner as _, w.as_widget_ptr() as _) } } fn draw_children(&mut self) { assert!(!self.was_deleted()); unsafe { crate::a...
function_block-function_prefix_line
[ { "content": "/// Sets the callback of a widget\n\npub fn set_callback<F, W>(widget: &mut W, cb: F)\n\nwhere\n\n F: FnMut(&mut dyn WidgetExt),\n\n W: WidgetExt,\n\n{\n\n assert!(!widget.was_deleted());\n\n unsafe {\n\n unsafe extern \"C\" fn shim(wid: *mut fltk_sys::widget::Fl_Widget, data: *...
Rust
render_pi/src/gl_context.rs
j-selby/leaffront
13b15fda0ffa309433e08dc17d4bb0e3f20e9335
use egl; use egl::{EGLConfig, EGLContext, EGLDisplay, EGLNativeDisplayType, EGLSurface}; use videocore::bcm_host; use videocore::dispmanx; use videocore::dispmanx::{ DisplayHandle, ElementHandle, FlagsAlpha, Transform, UpdateHandle, VCAlpha, Window, }; use videocore::image::Rect; use videocore::bcm_host::Graphi...
use egl; use egl::{EGLConfig, EGLContext, EGLDisplay, EGLNativeDisplayType, EGLSurface}; use videocore::bcm_host; use videocore::dispmanx; use videocore::dispmanx::{ DisplayHandle, ElementHandle, FlagsAlpha, Transform, UpdateHandle, VCAlpha, Window, }; use videocore::image::Rect; use videocore::bcm_host::Graphi...
("Display shutdown successful."); } else { println!("Display shutdown failed."); } bcm_host::deinit(); } }
); dispmanx::update_submit_sync(update); let mut window = Box::new(Window { element, width: dimensions.width as i32, height: dimensions.height as i32, }); let context_attr = [egl::EGL_CONTEXT_CLIENT_VERSION, 2, egl::EGL_NO...
random
[ { "content": "/// Loads a configuration file.\n\npub fn load_config(dir: String) -> LeaffrontConfig {\n\n let mut f = File::open(dir).expect(\"Config file not found\");\n\n\n\n let mut config_string = String::new();\n\n f.read_to_string(&mut config_string).unwrap();\n\n\n\n toml::from_str(&config_st...
Rust
src/modules/import_export.rs
lilith645/Maat-Editor3D
bbde60db0555e05bfed2be313d886fa0a3386b35
use csv; use crate::modules::WorldObject; use crate::modules::scenes::GameOptions; use crate::modules::Logs; use crate::cgmath::Vector3; use std::fs::File; use std::fs; pub fn get_models(logs: &mut Logs) -> Vec<(String, String, bool)> { if let Err(e) = fs::create_dir_all("./Models") { logs.add_error(e.to_stri...
use csv; use crate::modules::WorldObject; use crate::modules::scenes::GameOptions; use crate::modules::Logs; use crate::cgmath::Vector3; use std::fs::File; use std::fs; pub fn get_models(logs: &mut Logs) -> Vec<(String, String, bool)> { if let Err(e) = fs::create_dir_all("./Models") { logs.add_error(e.to_stri...
rot_x", "rot_y", "rot_z", "size_x", "size_y", "size_z"]).unwrap(); for object in world_objects { let id = object.id().to_string(); let name = object.name().to_string(); let model = object.model(); let location = object.location(); let instanced = object.instanced_rendered()...
s().rev().collect::<String>(); break; } } else { break; } } known_models.push((name, models[i].to_string(), false)); } } known_models } pub fn export(scene_name: String, world_objects: &Vec<WorldObject>, camera_details: &GameOptions, logs: &...
random
[ { "content": "fn benchmark(draw_calls: &mut Vec<DrawCall>, dimensions: Vector2<f32>) {\n\n draw_calls.push(DrawCall::draw_text_basic(Vector2::new(dimensions.x - 80.0, 15.0), \n\n Vector2::new(64.0, 64.0), \n\n Vector4::new(1.0,...
Rust
src/nodes/item.rs
olefasting/rust_rpg_toolkit
3f82a0fd4175f0b65518ceda1319416d5bf0ae1b
use crate::prelude::*; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ItemKind { OneHandedWeapon, TwoHandedWeapon, Misc, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ItemParams { pub id: String, pub name: String, pub desc...
use crate::prelude::*; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ItemKind { OneHandedWeapon, TwoHandedWeapon, Misc, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ItemParams { pub id: String, pub name: String, pub desc...
pub fn add_node(position: Vec2, amount: u32) -> Handle<Self> { scene::add_node(Self::new(position, amount)) } } impl BufferedDraw for Credits { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } ...
texture_id: "credits".to_string(), tile_size: uvec2(8, 8), ..Default::default() }, } }
function_block-function_prefix_line
[ { "content": "pub fn default_behavior_set() -> String {\n\n DEFAULT_BEHAVIOR_SET_ID.to_string()\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct ActorBehaviorParams {\n\n pub aggression: ActorAggression,\n\n #[serde(\n\n default,\n\n with = \"json::opt_vec2\",\n\n...
Rust
capi/src/session.rs
jws121295/dansible
4c32335b048560352135480ab0216ff5be6bd8fa
use libc::{c_int, c_char}; use std::ffi::CStr; use std::slice::from_raw_parts; use std::sync::mpsc; use std::boxed::FnBox; use std::sync::Mutex; use librespot::session::{Session, Config, Bitrate}; use eventual::{Async, AsyncResult, Future}; use cstring_cache::CStringCache; use types::sp_error; use types::sp_error::*;...
use libc::{c_int, c_char}; use std::ffi::CStr; use std::slice::from_raw_parts; use std::sync::mpsc; use std::boxed::FnBox; use std::sync::Mutex; use librespot::session::{Session, Config, Bitrate}; use eventual::{Async, AsyncResult, Future}; use cstring_cache::CStringCache; use types::sp_error; use types::sp_error::*;...
pub unsafe extern "C" fn sp_session_release(c_session: *mut sp_session) -> sp_error { global_session = None; drop(Box::from_raw(c_session)); SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_login(c_session: *mut sp_session, c_username: *const c_char,...
_session.unwrap().1 }; tx.lock().unwrap().send(Box::new(event)).unwrap(); } pub fn receive<T, E, F>(future: Future<T, E>, handler: F) where T : Send, E: Send, F : FnOnce(&mut SpSession, AsyncResult<T, E>) -> () + Send + 'static { future.receive(move |resu...
random
[ { "content": "pub fn add_session_arguments(opts: &mut getopts::Options) {\n\n opts.optopt(\"c\", \"cache\", \"Path to a directory where files will be cached.\", \"CACHE\")\n\n .reqopt(\"n\", \"name\", \"Device name\", \"NAME\")\n\n .optopt(\"b\", \"bitrate\", \"Bitrate (96, 160 or 320). Default...
Rust
src/main.rs
svenstaro/cargo2junit
8f6555bccd025b794e041b2f6ce46321ec12cb91
extern crate junit_report; extern crate serde; use junit_report::*; use serde::{Deserialize, Serialize}; use std; use std::collections::BTreeSet; use std::io::*; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] struct SuiteResults { passed: usize, failed: usize, } #[derive(Serialize, Deserialize, Debu...
extern crate junit_report; extern crate serde; use junit_report::*; use serde::{Deserialize, Serialize}; use std; use std::collections::BTreeSet; use std::io::*; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] struct SuiteResults { passed: usize, failed: usize, } #[derive(Serialize, Deserialize, Debu...
#[test] fn az_func_regression() { let report = parse_bytes(include_bytes!("test_inputs/azfunc.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/azfunc.json.out")); } #[test] fn float_time() { parse_bytes(incl...
fn cargo_project_failure() { let report = parse_bytes(include_bytes!("test_inputs/cargo_failure.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/cargo_failure.json.out"), ); }
function_block-full_function
[ { "content": "[![Build Status](https://dev.azure.com/cargo2junit/cargo2junit/_apis/build/status/johnterickson.cargo2junit?branchName=master)](https://dev.azure.com/cargo2junit/cargo2junit/_build/latest?definitionId=1&branchName=master)\n\n\n\n# cargo2junit\n\nConverts cargo's json output (from stdin) to JUnit X...
Rust
src/stock.rs
teohhanhui/stocker
ac666f50762620b4e4e0bed39aad150f42aa056c
use crate::{ app::{Indicator, TimeFrame}, reactive::StreamExt, }; use async_compat::Compat; use chrono::{DateTime, Duration, TimeZone, Utc}; use futures::executor; use gcollections::ops::{Bounded, Difference, Union}; use im::{hashmap, ordset, HashMap, OrdSet}; use interval::interval_set::{IntervalSet, ToInterva...
use crate::{ app::{Indicator, TimeFrame}, reactive::StreamExt, }; use async_compat::Compat; use chrono::{DateTime, Duration, TimeZone, Utc}; use futures::executor; use gcollections::ops::{Bounded, Difference, Union}; use im::{hashmap, ordset, HashMap, OrdSet}; use interval::interval_set::{IntervalSet, ToInterva...
covered_date_ranges.union( &vec![( first_bar.timestamp_seconds() as i64, last_bar.timestamp_seconds() as i64, )] .to_interval_set(), ...
history::retrieve_interval(stock_symbol.as_str(), time_frame.interval()) .await })) .expect("historical prices retrieval failed"); let covered_date_ranges = if let (Some(first_bar), Some(last_b...
random
[ { "content": "pub fn to_date_ranges<'a, S, U, R, C>(\n\n chart_events: S,\n\n stock_symbols: U,\n\n init_stock_symbol: String,\n\n time_frames: R,\n\n init_time_frame: TimeFrame,\n\n) -> impl Stream<'a, Item = Option<DateRange>, Context = C>\n\nwhere\n\n S: Stream<'a, Item = ChartEvent, Contex...
Rust
qlib/kernel/fs/fsutil/inode/simple_file_inode.rs
abel-von/Quark
7bbba67ee1105e3b7df751a278cbad9b2af666a1
use alloc::string::String; use crate::qlib::mutex::*; use core::ops::Deref; use alloc::vec::Vec; use core::any::Any; use super::super::super::super::socket::unix::transport::unix::*; use super::super::super::mount::*; use super::super::super::attr::*; use super::super::super::inode::*; use super::super::super::flags...
use alloc::string::String; use crate::qlib::mutex::*; use core::ops::Deref; use alloc::vec::Vec; use core::any::Any; use super::super::super::super::socket::unix::transport::unix::*; use super::super::super::mount::*; use super::super::super::attr::*; use super::super::super::inode::*; use super::super::super::flags...
r::ENOSYS)) } return Ok(FsInfo { Type: self.read().fsType, ..Default::default() }) } fn Mappable(&self) -> Result<HostInodeOp> { return Err(Error::SysError(SysErr::ENODEV)) } } #[derive(Clone, Default, Debug)] pub struct InodeSimpleAttributesInternal { pub fsType: u64, pub...
fn ReadLink(&self, _task: &Task,_dir: &Inode) -> Result<String> { return Err(Error::SysError(SysErr::ENOLINK)) } fn GetLink(&self, _task: &Task, _dir: &Inode) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOLINK)) } fn Truncate(&self, _task: &Task, _dir: &mut Inode, _size: i...
random
[ { "content": "fn InodeIsDirAllocate_Allocate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EISDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 0, "score": 637044.610642917 ...
Rust
lib/src/command/process.rs
abitrolly/watchexec
5bdd87dbf6a67360c78555924e777bd5507d5ec6
use std::process::ExitStatus; use command_group::AsyncGroupChild; use tokio::process::Child; use tracing::{debug, trace}; use crate::error::RuntimeError; #[derive(Debug)] pub enum Process { None, Grouped(AsyncGroupChild), Ungrouped(Child), Done(ExitStatus), } impl Default for Process { fn default(...
use std::process::ExitStatus; use command_group::AsyncGroupChild; use tokio::process::Child; use tracing::{debug, trace}; use crate::error::RuntimeError; #[derive(Debug)] pub enum Process { None, Grouped(AsyncGroupChild), Ungrouped(Child), Done(ExitStatus), } impl Default for Process { fn default(...
.map_err(RuntimeError::Process) } pub async fn kill(&mut self) -> Result<(), RuntimeError> { match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(pgid=?c.id(), "killing process group"); c.kill() } Self::Ungrouped(c) => { debug!(pid=?c.id(), "killing...
match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(signal=%sig, pgid=?c.id(), "sending signal to process group"); c.signal(sig) } Self::Ungrouped(c) => { debug!(signal=%sig, pid=?c.id(), "sending signal to process"); c.signal(sig) } }
if_condition
[ { "content": "/// Convenience function to check a glob pattern from a string.\n\n///\n\n/// This parses the glob and wraps any error with nice [miette] diagnostics.\n\npub fn check_glob(glob: &str) -> Result<(), GlobParseError> {\n\n\tlet mut builder = GitignoreBuilder::new(\"/\");\n\n\tif let Err(err) = builde...
Rust
web_glitz/src/rendering/attachment.rs
RSSchermer/web_glitz.rs
a2e26ef0156705f0b5ac7707c4fc24a4a994d84b
use std::marker; use std::sync::Arc; use web_sys::WebGl2RenderingContext as Gl; use crate::image::format::{ InternalFormat, Multisamplable, Multisample, RenderbufferFormat, TextureFormat, }; use crate::image::renderbuffer::{Renderbuffer, RenderbufferData}; use crate::image::texture_2d::{ Level as Texture2DLev...
use std::marker; use std::sync::Arc; use web_sys::WebGl2RenderingContext as Gl; use crate::image::format::{ InternalFormat, Multisamplable, Multisample, RenderbufferFormat, TextureFormat, }; use crate::image::renderbuffer::{Renderbuffer, RenderbufferData}; use crate::image::texture_2d::{ Level as Texture2DLev...
pub(crate) fn from_texture_2d_array_level_layer(image: &Texture2DArrayLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DA...
pub(crate) fn from_texture_2d_level(image: &Texture2DLevel<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DLevel { d...
function_block-full_function
[ { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if...
Rust
src/ffi/ffi.rs
ives9638/arrow2
b86508e67ca4b08c4544626f7bbe55cf5bd02961
use std::{ptr::NonNull, sync::Arc}; use crate::{ array::{buffers_children_dictionary, Array}, bitmap::{utils::bytes_for, Bitmap}, buffer::{ bytes::{Bytes, Deallocation}, Buffer, }, datatypes::{DataType, Field, PhysicalType}, error::{ArrowError, Result}, ffi::schema::get_fi...
use std::{ptr::NonNull, sync::Arc}; use crate::{ array::{buffers_children_dictionary, Array}, bitmap::{utils::bytes_for, Bitmap}, buffer::{ bytes::{Bytes, Deallocation}, Buffer, }, datatypes::{DataType, Field, PhysicalType}, error::{ArrowError, Result}, ffi::schema::get_fi...
unsafe fn create_bitmap( array: &Ffi_ArrowArray, deallocation: Deallocation, index: usize, ) -> Result<Bitmap> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_string())); } let len = array.length as usize; let buffers = array.buffers as *mu...
g())); } let buffers = array.buffers as *mut *const u8; let len = buffer_len(array, data_type, index)?; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let ptr = NonNull::new(ptr as *mut T); let bytes = ptr .map(|ptr| Bytes::new(ptr, len, deallocation)) ...
function_block-function_prefixed
[ { "content": "/// Shifts array by defined number of items (to left or right)\n\n/// A positive value for `offset` shifts the array to the right\n\n/// a negative value shifts the array to the left.\n\n/// # Examples\n\n/// ```\n\n/// use arrow2::array::Int32Array;\n\n/// use arrow2::compute::window::shift;\n\n/...
Rust
flow-rs/src/node/transform.rs
MegEngine/MegFlow
4bbf15acc21fb1f51e95311e28fb0a10fe4a91d3
/** * \file flow-rs/src/node/transform.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS...
/** * \file flow-rs/src/node/transform.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS...
} node_register!("Transform", Transform); #[inputs(inp)] #[outputs(out:dyn)] #[derive(Node, Default)] struct DynOutTransform {} impl DynOutTransform { fn new(_name: String, _args: &Table) -> DynOutTransform { Default::default() } } impl Actor for DynOutTransform { fn start( mut self: Bo...
async fn exec(&mut self, _: &Context) -> Result<()> { if let Ok(msg) = self.inp.recv_any().await { self.out.send_any(msg).await.ok(); } Ok(()) }
function_block-full_function
[ { "content": "#[pyfunction]\n\nfn version() -> &'static str {\n\n env!(\"CARGO_PKG_VERSION\")\n\n}\n\n\n\n#[pymethods]\n\nimpl Graph {\n\n fn wait(&mut self, py: Python) {\n\n self.inps.clear();\n\n self.outs.clear();\n\n if let Some(graph) = self.graph.take() {\n\n graph.s...
Rust
crates/ruma-events/src/room/encrypted/relation_serde.rs
MTRNord/ruma
653e4c4838fb3e5809573ce0a7e763547d5f20e4
#[cfg(feature = "unstable-pre-spec")] use ruma_identifiers::EventId; use serde::{ser::SerializeStruct as _, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "unstable-pre-spec")] use super::{Annotation, Reference, Replacement}; use super::{InReplyTo, Relation}; #[cfg(feature = "unstable-pre-spec")] u...
#[cfg(feature = "unstable-pre-spec")] use ruma_identifiers::EventId; use serde::{ser::SerializeStruct as _, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "unstable-pre-spec")] use super::{Annotation, Reference, Replacement}; use super::{InReplyTo, Relation}; #[cfg(feature = "unstable-pre-spec")] u...
, #[serde(rename = "m.reference")] Reference(Reference), #[serde(rename = "m.replace")] Replacement(ReplacementJsonRepr), #[serde(other)] Unknown, } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] struct ReplacementJsonRepr { e...
on { #[cfg(feature = "unstable-pre-spec")] Relation::Annotation(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Annotation(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Refe...
random
[ { "content": "pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Relation>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n fn convert_relation(ev: EventWithRelatesToJsonRepr) -> Option<Relation> {\n\n if let Some(in_reply_to) = ev.relates_to.in_reply_to {\n\n return Some...
Rust
meteora-server/src/raft/server.rs
meteora-kvs/meteora
3dc67f72364ba17540970dca43559f12d1a6d929
use std::collections::HashMap; use std::sync::mpsc; use std::sync::mpsc::Sender; use std::time::Duration; use futures::Future; use grpcio::{RpcContext, UnarySink}; use log::*; use raft::eraftpb::{ConfChange, Message}; use meteora_proto::proto::common::{NodeAddress, Null, State}; use meteora_proto::proto::raft::{Addre...
use std::collections::HashMap; use std::sync::mpsc; use std::sync::mpsc::Sender; use std::time::Duration; use futures::Future; use grpcio::{RpcContext, UnarySink}; use log::*; use raft::eraftpb::{ConfChange, Message}; use meteora_proto::proto::common::{NodeAddress, Null, State}; use meteora_proto::proto::raft::{Addre...
self.seq += 1; sender .send(config::Msg::ConfigChange { seq, change: req, cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = ChangeReply::new(); ...
psc::channel(); let sender = self.sender.clone(); let seq = self.seq; let node_id = self.node_id;
random
[ { "content": "type ProposeCallback = Box<dyn Fn(i32, HashMap<u64, NodeAddress>) + Send>;\n\n\n\npub enum Msg {\n\n Propose {\n\n seq: u64,\n\n op: Op,\n\n cb: ProposeCallback,\n\n },\n\n ConfigChange {\n\n seq: u64,\n\n change: ConfChange,\n\n cb: ProposeCallba...
Rust
crates/irust/src/irust/script/mod.rs
i10416/IRust
6faff9bb1fc52597cdd4698e1179932885da375c
use crossterm::event::Event; use irust_api::{Command, GlobalVariables}; use self::script4::ScriptManager4; use super::options::Options; pub mod script4; pub trait Script { fn input_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn get_output_prompt(&mut self, _global_variables: &G...
use crossterm::event::Event; use irust_api::{Command, GlobalVariables}; use self::script4::ScriptManager4; use super::options::Options; pub mod script4; pub trait Script { fn input_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn get_output_prompt(&mut self, _global_variables: &G...
pub fn deactivate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.deactivate(script); } Ok(None) } pub fn choose_script_mg(options: &Options) -> Option<Box<dyn S...
d>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.activate(script); } Ok(None) }
function_block-function_prefixed
[ { "content": "fn _remove_main(script: &str) -> String {\n\n const MAIN_FN: &str = \"fn main() {\";\n\n\n\n let mut script = remove_comments(script);\n\n\n\n let main_start = match script.find(MAIN_FN) {\n\n Some(idx) if _balanced_quotes(&script[..idx]) => idx,\n\n _ => return script,\n\n ...
Rust
src/stage_spec.rs
Isaac-Lozano/sa2_piece_gen
fd99d4cdd8b1f2e5d08072a962b8e686d8462153
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::Path; use serde_derive::{Serialize, Deserialize}; #[cfg(windows)] use process_reader::ProcessHandle; use byteorder::{ReadBytesExt, BE}; use crate::vector::Vector; use crate::rng::Rng; use crate::Platform; #[derive(Clone, Copy, Debug, Serialize, D...
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::Path; use serde_derive::{Serialize, Deserialize}; #[cfg(windows)] use process_reader::ProcessHandle; use byteorder::{ReadBytesExt, BE}; use crate::vector::Vector; use crate::rng::Rng; use crate::Platform; #[derive(Clone, Copy, Debug, Serialize, D...
let mut pieces = Vec::new(); file.seek(SeekFrom::Start(addr)).unwrap(); for _ in 0..num { let id = file.read_u16::<BE>().unwrap(); let _padding = file.read_u16::<BE>().unwrap(); let x = file.read_f32::<BE>().unwrap(); l...
ap() ^ 0x80000000; let en_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; file.seek(SeekFrom::Start(0x003AD6A0)).unwrap(); let rng_state = file.read_u32::<BE>().unwrap(); let mut read_list = |addr, num| {
random
[ { "content": "pub trait Platform {\n\n type SquareRoot: vector::Sqrt;\n\n type Consts: rng::RngConsts;\n\n}\n\n\n\npub struct Gc;\n\n\n\nimpl Platform for Gc {\n\n type SquareRoot = vector::GcFp;\n\n type Consts = rng::GcRng;\n\n}\n\n\n\npub struct Pc;\n\n\n\nimpl Platform for Pc {\n\n type Squar...
Rust
examples/circle_packing.rs
mitchmindtree/nannou_egui
d79939e01e6e170ad1933fc528d2bd36bb03fbe4
use nannou::{color::rgb_u32, rand::thread_rng}; use nannou::{prelude::*, rand::prelude::SliceRandom}; use nannou_egui::{self, egui, EguiBackend}; const WIDTH: f32 = 640.0; const HEIGHT: f32 = 360.0; pub fn main() { nannou::app(model) .update(update) .size(WIDTH as u32, HEIGHT as u32) .run(...
use nannou::{color::rgb_u32, rand::thread_rng}; use nannou::{prelude::*, rand::prelude::SliceRandom}; use nannou_egui::{self, egui, EguiBackend}; const WIDTH: f32 = 640.0; const HEIGHT: f32 = 360.0; pub fn main() { nannou::app(model) .update(update) .size(WIDTH as u32, HEIGHT as u32) .run(...
.into() }
rgba( color.red as f32 / 255.0, color.green as f32 / 255.0, color.blue as f32 / 255.0, 1.0, )
call_expression
[ { "content": "pub fn edit_color(ui: &mut egui::Ui, color: &mut nannou::color::Hsv) {\n\n let mut egui_hsv = egui::color::Hsva::new(\n\n color.hue.to_positive_radians() as f32 / (std::f32::consts::PI * 2.0),\n\n color.saturation,\n\n color.value,\n\n 1.0,\n\n );\n\n\n\n if co...
Rust
src/devices/tools/banjo/src/fidl.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use { lazy_static::lazy_static, regex::Regex, serde::{Deserialize, Deserializer}, serde_derive::{Deserialize, Serialize}, std::collections::BTreeMap, }; lazy_static! { pub static ref IDENTIFIER_RE: Regex = Regex::new(r#"^[A-Za-z]([_A-Za-z0-9]*[A-Za-z0-9])?$"#).unwrap(); pub static...
use { lazy_static::lazy_static, regex::Regex, serde::{Deserialize, Deserializer}, serde_derive::{Deserialize, Serialize}, std::collections::BTreeMap, }; lazy_static! { pub static ref IDENTIFIER_RE: Regex = Regex::new(r#"^[A-Za-z]([_A-Za-z0-9]*[A-Za-z0-9])?$"#).unwrap(); pub static...
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Version(#[serde(deserialize_with = "validate_version")] pub String); fn validate_version<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let version = String::deserialize(deseria...
fn validate_library_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !LIBRARY_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid library identifier: {}", id))); } Ok(i...
function_block-full_function
[]
Rust
src/main.rs
svenstaro/ggj2017
9d2cc2d01e33621096ac6aba20aa2889e4960856
pub mod utils; pub mod block; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics2d; extern crate ggez; extern crate rand; use ggez::conf; use ggez::game::{Game, GameState}; use ggez::{GameResult, Context}; use ggez::graphics; use ggez::timer; use std::time::Duration; use rand::Rand; use std::...
pub mod utils; pub mod block; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics2d; extern crate ggez; extern crate rand; use ggez::conf; use ggez::game::{Game, GameState}; use ggez::{GameResult, Context}; use ggez::graphics; use ggez::timer; use std::time::Duration; use rand::Rand; use std::...
fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.insert(_keycode, true); } } fn key_up_event(&mut self, _keycode: Keycode, ...
ctx, &self.player); graphics::set_color(ctx, graphics::Color::RGB(0, 0, 0)); ctx.renderer.present(); timer::sleep_until_next_frame(ctx, 60); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn draw_rectangle(ctx: &mut Context, block: &Block) {\n\n let body = block.body.borrow();\n\n\n\n if body.shape().is_shape::<Cuboid<Vector2<f32>>>() {\n\n let shape: &Cuboid<Vector2<f32>> = body.shape().as_shape().unwrap();\n\n let extents = shape.half_extents();\n\n ...
Rust
src/drv.rs
kaivol/smartoris-i2c
ce0526e04c95712b9b9c64ca5d6e6598ce65f530
use crate::{ diverged::{DmaChDiverged, I2CDiverged}, I2CMaster, }; use drone_cortexm::{fib, reg::prelude::*, thr::prelude::*}; use drone_stm32_map::periph::{ dma::ch::{traits::*, DmaChMap, DmaChPeriph}, i2c::{traits::*, I2CMap, I2CPeriph}, }; use futures::prelude::*; pub struct I2CSetup< I2C: I2CMa...
use crate::{ diverged::{DmaChDiverged, I2CDiverged}, I2CMaster, }; use drone_cortexm::{fib, reg::prelude::*, thr::prelude::*}; use drone_stm32_map::periph::{ dma::ch::{traits::*, DmaChMap, DmaChPeriph}, i2c::{traits::*, I2CMap, I2CPeriph}, }; use futures::prelude::*; pub struct I2CSetup< I2C: I2CMa...
} })); self.i2c.i2c_cr2.itevten().set_bit(); if !repeated { set_start(); } future } fn init_i2c(&mut self, i2c_freq: u32, i2c_presc: u32, i2c_trise: u32, i2c_mode: I2CMode) { self.i2c.rcc_busenr_i2cen.set_bit(); self.i2c.i2c_cr2.store_...
r.m0a().write(v, buf_rx.as_mut_ptr() as u32); }); self.dma_rx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_rx.len() as u32); }); self.dma_rx.dma_ccr.modify_reg(|r, v| r.en().set(v)); future } fn start(&mut self, addr: u8, ack: bool) -> impl Fu...
random
[ { "content": " unsafe { self.drv.read(addr, buffer).await };\n\n self\n\n }\n\n\n\n /// Returns a reference to the session buffer.\n\n // #[must_use]\n\n // pub fn buf(&self) -> &[u8] {\n\n // &self.buf\n\n // }\n\n\n\n /// Returns a mutable reference to the session buffer...
Rust
examples/echo.rs
sdroege/memfd-rs
923792d71da3cd225eaeeb7517164279aec38817
extern crate nix; extern crate getopts; extern crate memfd; use std::io; use std::os::unix::io::{RawFd, AsRawFd}; use std::path::{Path, PathBuf}; use nix::sys::socket::*; use nix::unistd::*; use nix::sys::uio::*; use getopts::Options; use std::env; use memfd::*; #[derive(Debug)] pub struct UnixDatagram { fd: R...
extern crate nix; extern crate getopts; extern crate memfd; use std::io; use std::os::unix::io::{RawFd, AsRawFd}; use std::path::{Path, PathBuf}; use nix::sys::socket::*; use nix::unistd::*; use nix::sys::uio::*; use getopts::Options; use std::env; use memfd::*; #[derive(Debug)] pub struct UnixDatagram { fd: R...
} None => { sendmsg(self.fd, &iov, &[], MsgFlags::empty(), Some(&SockAddr::Unix(addr))) } }; match res { Ok(_) => Ok(()), Err(nix:...
sendmsg(self.fd, &iov, &[ControlMessage::ScmRights(&[fd.as_raw_fd()])], MSG_CMSG_CLOEXEC, Some(&SockAddr::Unix(addr)))
call_expression
[ { "content": " pub fn as_slice<'a>(&'a self) -> Result<&'a [u8], io::Error> {\n\n let size = try!(self.get_size());\n\n if size == 0 {\n\n return Ok(&[]);\n\n }\n\n\n\n match self.map {\n\n SealedMap::ReadOnly(p, s) => Ok(unsafe { slice::from_raw_parts(p as *...
Rust
src/router/messaging.rs
verkehrsministerium/autobahnkreuz-rs
03d194257709ad9ef1226141b052bf9c0f2408d6
use crate::router::{ConnectionHandler, ConnectionState}; use ws::{CloseCode, Handler, Message as WSMessage, Request, Response, Result as WSResult}; use crate::messages::{ErrorDetails, ErrorType, Message, Reason}; use rmp_serde::Deserializer as RMPDeserializer; use serde_json; use serde::Deserialize; use std::...
use crate::router::{ConnectionHandler, ConnectionState}; use ws::{CloseCode, Handler, Message as WSMessage, Request, Response, Result as WSResult}; use crate::messages::{ErrorDetails, ErrorType, Message, Reason}; use rmp_serde::Deserializer as RMPDeserializer; use serde_json; use serde::Deserialize; use std::...
match self.handle_message(message) { Err(e) => self.on_message_error(e), _ => Ok(()), } } fn on_close(&mut self, code: CloseCode, reason: &str) { log::debug!("connection closed with {:?}: {}", code, reason); if let Ok(conn) = self.router.connection(self....
let message = match self.parse_message(msg) { Err(e) => return self.on_message_error(e), Ok(m) => m, };
assignment_statement
[ { "content": "pub fn send_message_msgpack(sender: &Sender, message: &Message) -> WSResult<()> {\n\n // Send the message\n\n let mut buf: Vec<u8> = Vec::new();\n\n message\n\n .serialize(&mut Serializer::with(&mut buf, StructMapWriter))\n\n .unwrap();\n\n sender.send(WSMessage::Binary(b...
Rust
rust/strprintf/src/traits.rs
Spacewalker2/newsboat
8efc234e7d3ca6df3d0797c131eb917fe4ab18cf
use std::ffi::CString; pub trait Printfable { type Holder: CReprHolder; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder>; } impl Printfable for i32 { type Holder = i32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { ...
use std::ffi::CString; pub trait Printfable { type Holder: CReprHolder; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder>; } impl Printfable for i32 { type Holder = i32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { ...
<Self as CReprHolder>::Output { *self } } impl CReprHolder for CString { type Output = *const libc::c_char; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { self.as_ptr() } } impl CReprHolder for *const libc::c_void { type Output = *const libc::c_void; fn to_c_repr(...
as CReprHolder>::Output; } impl CReprHolder for i32 { type Output = i32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u32 { type Output = u32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder...
random
[ { "content": "pub fn to_u(rs_str: String, default_value: u32) -> u32 {\n\n let mut result = rs_str.parse::<u32>();\n\n\n\n if result.is_err() {\n\n result = Ok(default_value);\n\n }\n\n\n\n result.unwrap()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 0, "scor...
Rust
src/bf.rs
ruslashev/bfga
673f382e2b70a86a5b661f0ffb494579e39afb61
#[derive(Clone)] pub enum BfErr { SyntaxError, InstrLimitExceeded, LogicError, } pub type BfResult = Result<(String, u64), BfErr>; impl std::fmt::Display for BfErr { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { BfErr::SyntaxError => write!(f,...
#[derive(Clone)] pub enum BfErr { SyntaxError, InstrLimitExceeded, LogicError, } pub type BfResult = Result<(String, u64), BfErr>; impl std::fmt::Display for BfErr {
} const TAPE_SIZE: usize = 1_000; fn check_bf_syntax(src: &Vec<char>) -> bool { let mut balance = 0; for instr in src { balance += match instr { '[' => 1, ']' => -1, _ => 0 }; if balance < 0 { return false ...
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { BfErr::SyntaxError => write!(f, "syntax error"), BfErr::InstrLimitExceeded => write!(f, "instruction limit exceeded"), BfErr::LogicError => write!(f, "logic error"), } }
function_block-full_function
[ { "content": "fn fitness(chromosome: &Chromosome, bf_result: &bf::BfResult) -> u64 {\n\n let fitness = match bf_result {\n\n Ok((output, num_instructions)) => {\n\n let diff = string_difference(&output, TARGET);\n\n let length_term =\n\n if diff == 0 {\n\n ...
Rust
meta/src/local.rs
kaiuri/rust-rosetta
67862e06956f955cdf34743a7e5c7c93e4077b64
use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; use anyhow::{anyhow, Context, Error}; use reqwest::Url; use toml::Value; use walkdir::WalkDir; use crate::remote; use crate::TASK_URL_RE; #[derive(Debug, Clone)] pub struct LocalTask { pub package_name: String, pub manif...
use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; use anyhow::{anyhow, Context, Error}; use reqwest::Url; use toml::Value; use walkdir::WalkDir; use crate::remote; use crate::TASK_URL_RE; #[derive(Debug, Clone)] pub struct LocalTask { pub package_name: String, pub manif...
fn find_sources<P>(directory: P) -> Result<HashSet<PathBuf>, Error> where P: AsRef<Path>, { let mut sources = HashSet::new(); for entry in WalkDir::new(directory) { let entry = entry?; if let Some("rs") = entry.path().extension().and_then(|s| s.to_str()) { sources.insert(entr...
fn parse_rosetta_url<P>(manifest_path: P) -> Result<Url, Error> where P: AsRef<Path>, { let manifest: Value = fs::read_to_string(manifest_path)?.parse()?; let url = manifest .get("package") .and_then(|p| p.get("metadata")) .and_then(|m| m.get("rosettacode")) .and_then(|m| m....
function_block-full_function
[]
Rust
src/bin/tui/status.rs
ssneep/grin
b7e29fee55e60c1ec6fa8678b252231855b34816
use cursive::Cursive; use cursive::view::View; use cursive::views::{BoxView, LinearLayout, TextView}; use cursive::direction::Orientation; use cursive::traits::*; use tui::constants::*; use tui::types::*; use servers::ServerStats; pub struct TUIStatusView; impl TUIStatusListener for TUIStatusView { fn create()...
use cursive::Cursive; use cursive::view::View; use cursive::views::{BoxView, LinearLayout, TextView}; use cursive::direction::Orientation; use cursive::traits::*; use tui::constants::*; use tui::types::*; use servers::ServerStats; pub struct TUIStatusView; impl TUIStatusListener for TUIStatusView { fn create()...
fn update(c: &mut Cursive, stats: &ServerStats) { let basic_status = { if stats.is_syncing { if stats.awaiting_peers { "Waiting for peers".to_string() } else { format!("Syncing - Latest header: {}", stats.header_head.height).to_string() } } else { "Running".to_string() } }...
child(TextView::new(" ").with_id("basic_network_info")), ), ); Box::new(basic_status_view.with_id(VIEW_BASIC_STATUS)) }
function_block-function_prefix_line
[ { "content": "pub fn unban_peer(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n\tpeer_addr: &String,\n\n) -> Result<(), Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/peers/{}/unban\",\n\n\t\tbase_addr, api_server_port, peer_addr\n\n\t);\n\n\tapi::client::post(url.as_str(), &\"\").map_err(|e...
Rust
contract/src/lib.rs
Kouprin/contracts-one
8b49f210c379227596a575a141aca7adf282c856
use regex::Regex; use std::cmp::min; use std::convert::TryInto; mod audit; mod certificate; mod contract; mod primitives; mod project; mod user; mod version; pub use crate::audit::*; pub use crate::certificate::*; pub use crate::contract::*; pub use crate::primitives::*; pub use crate::project::*; pub use crate::user...
use regex::Regex; use std::cmp::min; use std::convert::TryInto; mod audit; mod certificate; mod contract; mod primitives; mod project; mod user; mod version; pub use crate::audit::*; pub use crate::certificate::*; pub use crate::contract::*; pub use crate::primitives::*; pub use crate::project::*; pub use crate::user...
} impl Main { pub(crate) fn users() -> LookupMap<UserId, User> { LookupMap::new(b"c".to_vec()) } pub(crate) fn audits() -> LookupMap<AuditId, Audit> { LookupMap::new(b"d".to_vec()) } pub(crate) fn council() -> LookupSet<UserId> { LookupSet::new(b"e".to_vec()) } p...
pub fn new() -> Self { assert!(!env::state_exists(), "Already initialized"); let mut main = Self { projects: UnorderedMap::new(b"a".to_vec()), contracts: TreeMap::new(b"b".to_vec()), }; let mut user = main.extract_user_or_create(&env::signer_account_id()); ...
function_block-full_function
[ { "content": "#[test]\n\nfn register_project_by_not_a_user() {\n\n let mut state = State::new();\n\n state.create_alice();\n\n\n\n let contract = &state.contract;\n\n let alice = state.accounts.get(ALICE).unwrap();\n\n let outcome = call!(\n\n alice,\n\n contract.register_project(\n...
Rust
src/editor.rs
Crosse/raster
f54e52004ef889748caf2322d5bd9e25837615ef
use std::cmp; use error::{RasterError, RasterResult}; use blend::{self, BlendMode}; use Color; use Image; use position::{Position, PositionMode}; use transform; pub fn blend( image1: &Image, image2: &Image, blend_mode: BlendMode, opacity: f32, position: PositionMode, offset_x: i32, offse...
use std::cmp; use error::{RasterError, RasterResult}; use blend::{self, BlendMode}; use Color; use Image; use position::{Position, PositionMode}; use transform; pub fn blend( image1: &Image, image2: &Image, blend_mode: BlendMode, opacity: f32, position: PositionMode, offset_x: i32, offse...
offset_y, opacity, ), BlendMode::Difference => blend::difference( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ),...
h, image1.height, image2.width, image2.height)?; let (w1, h1) = (image1.width, image1.height); let (w2, h2) = (image2.width, image2.height); if (offset_x >= w1) || (offset_x + w2 <= 0) || (offset_y >= h1) || (offset_y + h2 <= 0) { return Err(RasterError::BlendingImageFallsOutsideCanvas); ...
random
[ { "content": "/// Compare two images and returns a hamming distance. A value of 0 indicates a likely similar\n\n/// picture. A value between 1 and 10 is potentially a variation. A value greater than 10 is\n\n/// likely a different image.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::compare;\n\n///\n\n...
Rust
src/draw_buffer.rs
GreatAttractor/projections
95c4217162c5841f1f90160c058b279b5423ba5e
use glium::Surface; use glium::texture::{ depth_texture2d_multisample::DepthTexture2dMultisample, depth_texture2d::DepthTexture2d, texture2d_multisample::Texture2dMultisample, texture2d::Texture2d, }; use std::cell::RefCell; use std::rc::Rc; const INITIAL_DRAW_BUF_SIZE: u32 = 256; const COLOR_FORMAT...
use glium::Surface; use glium::texture::{ depth_texture2d_multisample::DepthTexture2dMultisample, depth_texture2d::DepthTexture2d, texture2d_multisample::Texture2dMultisample, texture2d::Texture2d, }; use std::cell::RefCell; use std::rc::Rc; const INITIAL_DRAW_BUF_SIZE: u32 = 256; const COLOR_FORMAT...
height, NUM_SAMPLES ).unwrap() ) }; let storage_buf = std::rc::Rc::new(Texture2d::empty_with_format( display, glium::texture::UncompressedFloatFormat::U8U8U8, glium::texture::MipmapsOption::NoMipm...
pth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap(), Buffers::MultiSampling(draw_buf, depth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ...
random
[ { "content": "pub fn handle_gui(\n\n ui: &imgui::Ui,\n\n gui_state: &mut GuiState,\n\n program_data: &mut data::ProgramData,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>,\n\n display: &glium::Display\n\n) {\n\n unsafe { imgui::sys::igDockSpaceOverViewport(\n\n imgui::sys::...
Rust
pallets/ai/src/lib.rs
DNFT-Team/dnft-substrate-node
f51822a2b84d4bcfc3dbcb2d1c9829f4c98582a8
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, Get, Randomness, Time}, StorageMap, StorageValue, }; use frame_system::ensure_signed; use pallet_randomness_collective_flip as randomness; use sp_...
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, Get, Randomness, Time}, StorageMap, StorageValue, }; use frame_system::ensure_signed; use pallet_randomness_collective_flip as randomness; use sp_...
fn get_dnonce() -> u64 { let nonce = <DNonce>::get(); <DNonce>::mutate(|n| *n += 1u64); nonce } } impl<T: Config> Module<T> { fn _create_ai_model( title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highl...
fn _bound_ai_data_collection( ai_data_id: AIDataId, collection_id: CollectionId, ) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.collection_id = Some(collection_id.clone()); <AIDatas<T>>::insert(ai_data_i...
function_block-full_function
[ { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n type Token: TokenManager<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as f...
Rust
packages/storage-plus/src/iter_helpers.rs
DragonSBFinance/terra_smartcontract
9cfa31192a1b7d72c1ba95cca76a50befa030623
#![cfg(feature = "iterator")] use serde::de::DeserializeOwned; use cosmwasm_std::Pair; use cosmwasm_std::{from_slice, StdResult}; use crate::helpers::encode_length; pub(crate) fn deserialize_kv<T: DeserializeOwned>(kv: Pair) -> StdResult<Pair<T>> { let (k, v) = kv; let t = from_slice::<T>(&v)?; Ok((k, t...
#![cfg(feature = "iterator")] use serde::de::DeserializeOwned; use cosmwasm_std::Pair; use cosmwasm_std::{from_slice, StdResult}; use crate::helpers::encode_length; pub(crate) fn deserialize_kv<T: DeserializeOwned>(kv: Pair) -> StdResult<Pair<T>> { let (k, v) = kv; let t = from_slice::<T>(&v)?; Ok((k, t...
.collect(); assert_eq!(res.len(), 0); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"ant"), None, Order::Ascending).collect(); assert_eq!(res.len(), 2); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); assert_eq!(res[1], (b"snowy".t...
range_with_prefix( &storage, &prefix, Some(b"bas"), Some(b"sno"), Order::Ascending, )
call_expression
[ { "content": "fn one_byte_higher(limit: &[u8]) -> Vec<u8> {\n\n let mut v = limit.to_vec();\n\n v.push(0);\n\n v\n\n}\n\n\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 0, "score": 360298.9457943783 }, { "content": "/// Returns a new vec of same length and last byte...
Rust
src/base/codec/decode.rs
sergeyboyko0791/redis-asio
8de643fddb2353a68f48b15b20943c9d9fa59d8d
use super::{RedisResult, RedisError, RedisErrorKind, RespInternalValue}; use std::io::Cursor; use std::error::Error; use byteorder::ReadBytesExt; pub struct ParseResult<T> { pub value: T, pub value_src_len: usize, } pub type OptParseResult<T> = Option<ParseResult<T>>; pub fn parse_resp_value(data: &[u8]) -> ...
use super::{RedisResult, RedisError, RedisErrorKind, RespInternalValue}; use std::io::Cursor; use std::error::Error; use byteorder::ReadBytesExt; pub struct ParseResult<T> { pub value: T, pub value_src_len: usize, } pub type OptParseResult<T> = Option<ParseResult<T>>; pub fn parse_resp_value(data: &[u8]) -> ...
fn parse_status(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Status(value); ParseResult { value, va...
fn parse_error(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Error(value); ParseResult { value, value_...
function_block-full_function
[ { "content": "pub fn encode_resp_value(value: RespInternalValue) -> Vec<u8> {\n\n match value {\n\n RespInternalValue::Nil => \"$-1\\r\\n\".as_bytes().to_vec(),\n\n RespInternalValue::Error(x) => format!(\"-{}\\r\\n\", x).into_bytes(),\n\n RespInternalValue::Status(x) => format!(\"+{}\\r...
Rust
src/global/logging.rs
HristoKolev/xdxd-snapshot-rotator
6cc807819d7a1002ab15bc087f90bbb2caa4013b
use std::sync::Mutex; use std::path::{PathBuf, Path}; use std::fs::{File, OpenOptions}; use std::io::{SeekFrom, Write, Seek}; use chrono::Utc; use super::prelude::*; pub struct LoggingConfiguration { pub max_length: u64, pub file_path: PathBuf, } pub struct FileAppenderState { file_handle: File, fil...
use std::sync::Mutex; use std::path::{PathBuf, Path}; use std::fs::{File, OpenOptions}; use std::io::{SeekFrom, Write, Seek}; use chrono::Utc; use super::prelude::*; pub struct LoggingConfiguration { pub max_length: u64, pub file_path: PathBuf, } pub struct FileAppenderState { file_handle: File, fil...
} fn format_message(&self, message: &str) -> Result<String> { let now = Utc::now(); let formatted_date = now.format("%Y-%m-%d %H:%M:%S").to_string(); Ok(format!("{} | {}", formatted_date, message)) } pub fn log(&self, message: &str) -> Result { let formatted_message...
Ok(Logger { console_appender: ConsoleAppender::new(), in_memory_appender: InMemoryAppender::new(), file_appender: FileAppender::new(config)? })
call_expression
[ { "content": "#[allow(unused)]\n\npub fn wait_for_lock(file_path: &str) -> Result<File> {\n\n loop {\n\n if let Some(file) = lock_file(file_path)? {\n\n return Ok(file);\n\n }\n\n\n\n std::thread::sleep(Duration::from_millis(100));\n\n }\n\n}\n", "file_path": "src/globa...
Rust
crates/components/token/erc20/tests/mocks/erc20_mock.rs
zl910627/metis
b38193188614f9bd8391a6afed1a876495d0a771
#![cfg_attr(not(feature = "std"), no_std)] #[metis_lang::contract] pub mod erc20_contract { use super::super::behavior; pub use erc20::{ Error, Result, }; use metis_erc20 as erc20; use metis_lang::{ import, metis, }; #[ink(storage)] #[import(erc20)]...
#![cfg_attr(not(feature = "std"), no_std)] #[metis_lang::contract] pub mod erc20_contract { use super::super::behavior; pub use erc20::{ Error, Result, }; use metis_erc20 as erc20; use metis_lang::{ import, metis, }; #[ink(storage)] #[import(erc20)]...
#[ink(message)] pub fn approve_internal( &mut self, owner: AccountId, spender: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_approve(self, owner, spender, value) } } }
d, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_transfer_from_to(self, from, to, value) }
function_block-function_prefixed
[ { "content": "fn get_storage_mod_type(contract: &Contract, ext_mod: &Ident) -> Result<TokenStream2> {\n\n let storage = contract.module().storage();\n\n let mod_to_get = Some(ext_mod.clone());\n\n\n\n for f in storage.fields() {\n\n if f.ident == mod_to_get {\n\n if let syn::Type::Pat...
Rust
src/pymodule/mod.rs
ripe-tech/pconvert-rust
cf9ffcfc59d5838cf4d74a2c6c666e3f94f7cdc3
pub mod conversions; pub mod utils; use crate::blending::params::{BlendAlgorithmParams, Options}; use crate::blending::{ blend_images, demultiply_image, get_blending_algorithm, is_algorithm_multiplied, BlendAlgorithm, }; use crate::constants; use crate::errors::PConvertError; use crate::parallelism::{ResultMessa...
pub mod conversions; pub mod utils; use crate::blending::params::{BlendAlgorithmParams, Options}; use crate::blending::{ blend_images, demultiply_image, get_blending_algorithm, is_algorithm_multiplied, BlendAlgorithm, }; use crate::constants; use crate::errors::PConvertError; use crate::parallelism::{ResultMessa...
#[pyfn(module, "get_thread_pool_status")] fn get_thread_pool_status(py: Python) -> PyResult<&PyDict> { unsafe { match &mut THREAD_POOL { Some(thread_pool) => { let status_dict = thread_pool.get_status().into_py_dict(py); Ok(status_dic...
img_paths.len(); let algorithms_to_apply: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)> = if let Some(algorithms) = algorithms { build_params(algorithms)? } else if let Some(algorithm) = algorithm { let algorithm = build_algorithm(&algorithm)?; ...
function_block-function_prefixed
[ { "content": "/// Attempts to parse a `&String` to a `BlendAlgorithm`.\n\n/// Returns the enum variant if it succeeds. Otherwise it returns a `PyErr`.\n\npub fn build_algorithm(algorithm: &str) -> Result<BlendAlgorithm, PyErr> {\n\n match BlendAlgorithm::from_str(algorithm) {\n\n Ok(algorithm) => Ok(a...
Rust
src/lib.rs
estchd/passable_guard
0549276b278e11e75c6e8f0b65a689d2eab812e2
use std::marker::PhantomData; use std::ffi::CString; #[derive(Debug, Clone)] pub enum ReconstituteError<PTR, PAS: Passable<PTR>> { PointerMismatch{passed: *mut PTR, reconstituted: *mut PTR}, ReconstituteError{error: PAS::ReconstituteError} } #[derive(Debug, Clone)] pub struct PassableContainer<PTR, PAS: Pas...
use std::marker::PhantomData; use std::ffi::CString; #[derive(Debug, Clone)] pub enum ReconstituteError<PTR, PAS: Passable<PTR>> { PointerMismatch{passed: *mut PTR, reconstituted: *mut PTR}, ReconstituteError{error: PAS::ReconstituteError} } #[derive(Debug, Clone)] pub struct PassableContainer<PTR, PAS: Pas...
; } PAS::reconstitute(ptr) .map(|passable| PassableContainer::new(passable)) .map_err( |err| ReconstituteError::ReconstituteError {error: err} ) } } impl<PTR, PAS: Passable<PTR>> Drop for PassableGuard<PTR, PAS> { fn ...
Err( ReconstituteError::PointerMismatch { passed: self.ptr, reconstituted: ptr } )
call_expression
[ { "content": "# Passable Guard\n\n\n\nThe Passable Guard Crate provides a way to check for FFI memory leaks at runtime.\n\n\n\nThis is achieved by providing a PassableContainer class that encapsulates\n\na Passable Object that can be converted to a raw pointer to pass it over a FFI boundary.\n\n\n\nThis Passabl...
Rust
liblumen_core/src/sys/unix/dynamic_call.rs
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
use crate::sys::dynamic_call::DynamicCallee; extern "C" { #[unwind(allowed)] #[link_name = "__lumen_dynamic_apply"] pub fn apply(f: DynamicCallee, argv: *const usize, argc: usize) -> usize; } #[cfg(all(target_os = "macos", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_ap...
use crate::sys::dynamic_call::DynamicCallee; extern "C" { #[unwind(allowed)] #[link_name = "__lumen_dynamic_apply"] pub fn apply(f: DynamicCallee, argv: *const usize, argc: usize) -> usize; } #[cfg(all(target_os = "macos", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_ap...
extern "C" fn spilled_args_odd( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, ) -> usize { a + b + c + d + e + f + g } }
extern "C" fn spilled_args_even( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, ) -> usize { a + b + c + d + e + f + g + h }
function_block-full_function
[ { "content": "/// Invoke the statically linked `lld` linker with the given arguments.\n\n///\n\n/// NOTE: Assumes that the first value of the argument vector contains the\n\n/// program name which informs lld which flavor of linker is being run.\n\npub fn link(argv: &[CString]) -> Result<(), ()> {\n\n // Acq...
Rust
ipp-util/src/util.rs
simlay/ipp-sys
3b894faf6eb0533663c2d83fea0c9e851ac2d188
use std::{ffi::OsString, io, path::PathBuf}; use futures::{future, Future}; use structopt::StructOpt; use tokio::io::AsyncRead; use ipp_client::{IppClient, IppClientBuilder, IppError}; use ipp_proto::ipp::DelimiterTag; use ipp_proto::{IppAttribute, IppOperationBuilder, IppValue}; fn new_client(uri: &str, params: &...
use std::{ffi::OsString, io, path::PathBuf}; use futures::{future, Future}; use structopt::StructOpt; use tokio::io::AsyncRead; use ipp_client::{IppClient, IppClientBuilder, IppError}; use ipp_proto::ipp::DelimiterTag; use ipp_proto::{IppAttribute, IppOperationBuilder, IppValue}; fn new_client(uri: &str, params: &...
struct JobSource { inner: Box<dyn AsyncRead + Send>, } fn new_source(cmd: &IppPrintCmd) -> Box<dyn Future<Item = JobSource, Error = io::Error> + Send + 'static> { match cmd.file { Some(ref filename) => Box::new( tokio::fs::File::open(filename.to_owned()).and_then(|file| Ok(JobSource { inn...
t) .ca_certs(&params.ca_certs) .verify_hostname(!params.no_verify_hostname) .verify_certificate(!params.no_verify_certificate) .build() }
function_block-function_prefixed
[ { "content": "fn to_device_uri(uri: &str) -> Cow<str> {\n\n match Url::parse(&uri) {\n\n Ok(ref mut url) if !url.username().is_empty() => {\n\n let _ = url.set_username(\"\");\n\n let _ = url.set_password(None);\n\n Cow::Owned(url.to_string())\n\n }\n\n _...
Rust
ovium/src/server.rs
snoir/ovium
357723ee3eb78b46c11ed4ce4b2b6c8e5fedb383
use crate::error::{ConfigError, Error, ErrorKind, OviumError}; use crate::types::*; use crossbeam_channel::unbounded; use crossbeam_utils::thread; use log::{error, info}; use serde::Deserialize; use signal_hook::{iterator::Signals, SIGINT}; use ssh2::Session; use std::collections::HashMap; use std::fs::File; use std::i...
use crate::error::{ConfigError, Error, ErrorKind, OviumError}; use crate::types::*; use crossbeam_channel::unbounded; use crossbeam_utils::thread; use log::{error, info}; use serde::Deserialize; use signal_hook::{iterator::Signals, SIGINT}; use ssh2::Session; use std::collections::HashMap; use std::fs::File; use std::i...
pub fn execute_cmd(node: &Node, cmd: String) -> Result<SshSuccess, Error> { let node_addr = format!("{}:{}", node.ip, node.port); let tcp = TcpStream::connect(node_addr)?; let mut sess = Session::new()?; sess.set_tcp_stream(tcp); sess.handshake()?; sess.userauth_age...
fn handle_client( &self, stream: UnixStream, _signal_receiver: crossbeam_channel::Receiver<i32>, ) -> Result<(), Error> { let mut reader = BufReader::new(&stream); loop { let mut resp = Vec::new(); let read_bytes = reader.read_until(b'\n', &mut resp);...
function_block-full_function
[ { "content": "#[proc_macro_derive(FromParsedResource)]\n\npub fn from_parsed_resource(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let fields_name = match input.data {\n\n Data::Struct(data_struct) => {\n\n let mut fields = Vec::new()...
Rust
tough/tests/target_path_safety.rs
flavio/tough
0ebe90c54d1b993d64c265a2d315cad3ad9a1699
mod test_utils; use chrono::{DateTime, TimeZone, Utc}; use maplit::hashmap; use ring::rand::SystemRandom; use std::collections::HashMap; use std::fs::{self, create_dir_all, File}; use std::num::NonZeroU64; use std::path::Path; use tempfile::TempDir; use test_utils::{dir_url, test_data, DATA_1, DATA_2, DATA_3}; use tou...
mod test_utils; use chrono::{DateTime, TimeZone, Utc}; use maplit::hashmap; use ring::rand::SystemRandom; use std::collections::HashMap; use std::fs::{self, create_dir_all, File}; use std::num::NonZeroU64; use std::path::Path; use tempfile
ap(); editor.add_target(target_name_2.clone(), target_2).unwrap(); editor .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap() .change_delegated_targets("delegated") .unwrap() .add_target...
::TempDir; use test_utils::{dir_url, test_data, DATA_1, DATA_2, DATA_3}; use tough::editor::signed::SignedRole; use tough::editor::RepositoryEditor; use tough::key_source::{KeySource, LocalKeySource}; use tough::schema::{KeyHolder, PathPattern, PathSet, RoleKeys, RoleType, Root, Signed, Target}; use tough::{Prefix, Rep...
random
[ { "content": "fn round_time(time: DateTime<Utc>) -> DateTime<Utc> {\n\n // `Timelike::with_nanosecond` returns None only when passed a value >= 2_000_000_000\n\n time.with_nanosecond(0).unwrap()\n\n}\n\n\n", "file_path": "tuftool/src/root.rs", "rank": 0, "score": 81033.12215003767 }, { ...
Rust
src/core/value.rs
aesedepece/scriptful
37f6ff8361077ac63ab861273ba75b4f0571706d
#[derive(Clone, Debug, PartialOrd)] pub enum Value { Boolean(bool), Float(f64), Integer(i128), String(&'static str), } impl core::ops::Not for Value { type Output = Self; fn not(self) -> Self::Output { use Value::*; match self { Boolean(x) => B...
#[derive(Clone, Debug, PartialOrd)] pub enum Value { Boolean(bool), Float(f64), Integer(i128), String(&'static str), } impl core::ops::Not for Value { type Output = Self; fn not(self) -> Self::Output { use Value::*; match self { Boolean(x) => B...
at(2.2), Float(3.3)); assert_eq!(Float(1.1) + Float(-2.2), Float(-1.1)); assert_eq!(Float(1.1) + Integer(2), Float(3.1)); assert_eq!(Float(1.1) + Integer(-2), Float(-0.9)); assert_eq!(Integer(1) + Integer(2), Integer(3)); assert_eq!(Integer(1) + Integer(-2), Integer(-1)); ...
n(false), Boolean(true)); assert_eq!(Boolean(true) + Boolean(true), Boolean(true)); assert_eq!(Float(1.1) + Flo
function_block-random_span
[ { "content": "/// The main function that tells which creatures evolute and devolute into which other creatures.\n\npub fn pokemon_op_sys(stack: &mut Stack<Creature>, operator: &Command) {\n\n use Creature::*;\n\n let last_creature = stack.pop();\n\n match operator {\n\n Command::Evolute => stack...
Rust
src/emac0/mmctxim.rs
tirust/msp432e4
479d52cb87a757f77406e1f314ea8acfba70f675
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::MMCTXIM { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, ...
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::MMCTXIM { #[doc = r"Modifies the contents of the register"] #[inline(always)]
#[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { ...
pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); }
function_block-full_function
[ { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::BIT {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify...
Rust
src/lib.rs
antialize/sql-parse
37ef1b698af74ab5952f7866512b81e0fbbb9deb
#![no_std] #![forbid(unsafe_code)] extern crate alloc; use alloc::vec::Vec; use lexer::Token; use parser::Parser; mod alter; mod create; mod data_type; mod delete; mod drop; mod expression; mod identifier; mod insert_replace; mod issue; mod keywords; mod lexer; mod parser; mod select; mod span; mod sstring; mod stat...
#![no_std] #![forbid(unsafe_code)] extern crate alloc; use alloc::vec::Vec; use lexer::Token; use parser::Parser; mod alter; mod create; mod data_type; mod delete; mod drop; mod expression; mod identifier; mod insert_replace; mod issue; mod keywords; mod lexer; mod parser; mod select; mod span; mod sstring; mod stat...
if parser.token != Token::Eof { parser.expected_error("Unexpected token after statement") } Some(v) } Ok(None) => { parser.expected_error("Statement"); None } Err(_) => None, } }
function_block-function_prefix_line
[ { "content": "fn parse_width(parser: &mut Parser<'_, '_>) -> Result<Option<(usize, Span)>, ParseError> {\n\n if !matches!(parser.token, Token::LParen) {\n\n return Ok(None);\n\n }\n\n parser.consume_token(Token::LParen)?;\n\n let value = parser.recovered(\")\", &|t| t == &Token::RParen, |pars...
Rust
implementations/rust/ockam/signature_ps/src/signature.rs
psinghal20/ockam
55c2787eb2392c919156c6dded9f31a5249541e1
use crate::{PublicKey, SecretKey}; use blake2::{Blake2b, VarBlake2b}; use bls12_381_plus::{ multi_miller_loop, ExpandMsgXmd, G1Affine, G1Projective, G2Affine, G2Prepared, G2Projective, Scalar, }; use core::convert::TryFrom; use digest::{Update, VariableOutput}; use group::{Curve, Group}; use serde::{ de::{E...
use crate::{PublicKey, SecretKey}; use blake2::{Blake2b, VarBlake2b}; use bls12_381_plus::{ multi_miller_loop, ExpandMsgXmd, G1Affine, G1Projective, G2Affine, G2Prepared, G2Projective, Scalar, }; use core::convert::TryFrom; use digest::{Update, VariableOutput}; use group::{Curve, Group}; use serde::{ de::{E...
} impl<'de> Deserialize<'de> for Signature { fn deserialize<D>(d: D) -> Result<Signature, D::Error> where D: Deserializer<'de>, { struct ArrayVisitor; impl<'de> Visitor<'de> for ArrayVisitor { type Value = Signature; fn expecting(&self, f: &mut fmt::Format...
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { let bytes = self.to_bytes(); let mut seq = s.serialize_tuple(bytes.len())?; for b in &bytes { seq.serialize_element(b)?; } seq.end() }
function_block-full_function
[ { "content": "/// Convert a big endian byte sequence to a Scalar\n\npub fn scalar_from_bytes(bytes: &[u8; 32]) -> CtOption<Scalar> {\n\n let mut t = [0u8; 32];\n\n t.copy_from_slice(bytes);\n\n t.reverse();\n\n Scalar::from_bytes(&t)\n\n}\n\n\n", "file_path": "implementations/rust/ockam/signatur...
Rust
crates/history/src/browser.rs
kolloch/gloo
07e7dfa9c67d74c871f82fca54a1d7b5a0b9fce7
use std::any::Any; use std::borrow::Cow; use std::cell::RefCell; use std::fmt; use std::rc::Rc; use gloo_events::EventListener; use gloo_utils::window; #[cfg(feature = "query")] use serde::Serialize; use wasm_bindgen::{JsValue, UnwrapThrowExt}; use web_sys::Url; #[cfg(feature = "query")] use crate::error::HistoryResu...
use std::any::Any; use std::borrow::Cow; use std::cell::RefCell; use std::fmt; use std::rc::Rc; use gloo_events::EventListener; use gloo_utils::window; #[cfg(feature = "query")] use serde::Serialize; use wasm_bindgen::{JsValue, UnwrapThrowExt}; use web_sys::Url; #[cfg(feature = "query")] use crate::error::HistoryResu...
.into(), hash: loc .hash() .expect_throw("failed to get location hash.") .into(), state: id.and_then(|m| states.get(&m).cloned()), id, } } } impl Default for BrowserHistory { fn default() -> Self { ...
let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace state."); self.notify_callbacks(); } #[cfg(feature = "query")] ...
random
[ { "content": "/// Calls the confirm function.\n\n///\n\n/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)\n\npub fn confirm(message: &str) -> bool {\n\n window().confirm_with_message(message).unwrap_throw()\n\n}\n\n\n", "file_path": "crates/dialogs/src/lib.rs", ...
Rust
src/transformers/dominance.rs
EclecticGriffin/Bril-Toolkit
a72ce7a7d2ca235ec9e544a713638df408d1828c
use super::cfg::{Node, Block}; use crate::serde_structs::structs::{Instr, Label}; use std::rc::{Rc, Weak}; use std::collections::{HashMap, HashSet}; use crate::analysis::dehydrated::{set_intersection, set_union}; use std::collections::VecDeque; fn reverse_post_order(root: &Rc<Node>) -> Vec<Rc<Node>> { let mut pro...
use super::cfg::{Node, Block}; use crate::serde_structs::structs::{Instr, Label}; use std::rc::{Rc, Weak}; use std::collections::{HashMap, HashSet}; use crate::analysis::dehydrated::{set_intersection, set_union}; use std::collections::VecDeque; fn reverse_post_order(root: &Rc<Node>) -> Vec<Rc<Node>> { let mut pro...
pub struct DominanceTree { nodes: HashMap<Label, Rc<Node>>, dominated_map: HashMap<Label, HashSet<Label>>, dom_tree: HashMap<Label, Vec<Label>>, root_label: Label } impl DominanceTree { pub fn new(nodes: &[Rc<Node>]) -> Self { let mut node_map = HashMap::<Label, Rc<Node>>::new(); ...
t ordering = reverse_post_order(&nodes[0]); { let mut dom_set = HashSet::<Label>::new(); for node in ordering.iter() { dom_set.insert(node.label()); } for node in ordering.iter(){ label_map.insert(node.label(), dom_set.clone()); } ...
function_block-function_prefixed
[ { "content": "pub fn connect_basic_blocks(blocks: &mut Vec<Rc<Node>>) {\n\n let map = construct_label_lookup(blocks);\n\n let mut second_iter = blocks.iter();\n\n second_iter.next();\n\n\n\n for (current, node) in blocks.iter().zip(second_iter) {\n\n connect_block(current, node, &map)\n\n ...
Rust
main/src/main.rs
kirch7/shaat
1479561bc3d8329940f693c7708e7cfa71a3fcc9
#[macro_use] extern crate actix; extern crate actix_web; extern crate cookie; extern crate crypto; #[macro_use] extern crate diesel; extern crate env_logger; extern crate futures; #[macro_use] extern crate juniper; #[macro_use] extern crate lazy_static; extern crate listenfd; extern crate messages; extern crate r2d2;...
#[macro_use] extern crate actix; extern crate actix_web; extern crate cookie; extern crate crypto; #[macro_use] extern crate diesel; extern crate env_logger; extern crate futures; #[macro_use] extern crate juniper; #[macro_use] extern crate lazy_static; extern crate listenfd; extern crate messages; extern crate r2d2;...
#[inline] fn get_envvar(key: &str) -> Option<String> { std::env::vars() .find(|(key_, _value)| key_ == key) .map(|(_key, value)| value) } #[inline] fn bad_request() -> HttpResponse { HttpResponse::BadRequest().finish() }
let graphql_state = graphql::AppState { executor: graphql_addr.clone(), }; vec![ App::new() .middleware(Logger::default()) .prefix("/static") .resource("/{filename}", |r| r.f(statiq::handle_static)) .boxed(), ...
function_block-function_prefix_line
[ { "content": "pub fn load(db: &str) -> Result<(), ()> {\n\n let db = SqliteConnection::establish(db).unwrap();\n\n\n\n let mut users = USERS.write().unwrap();\n\n ::db::schema::users::dsl::users\n\n .load::<::db::models::User>(&db)\n\n .map_err(|_| ())?\n\n .iter()\n\n .map(...
Rust
src/test/instruction_tests/instr_vcvtps2uqq.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 vcvtps2uqq_1() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, ...
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 vcvtps2uqq_1() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, ...
nic::VCVTPS2UQQ, operand1: Some(Direct(ZMM25)), operand2: Some(IndirectDisplaced( RDI, 1515537008, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, ...
e, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 241, 125, 143, 121, 52, 141, 108, 38, 160, 46], OperandSize::Dword, ) } #[test] fn v...
random
[ { "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
verify/src/span.rs
tamasfe/verify
5f12650c5aef0edb63961042f7bc7b8da3644cea
use std::ops::{Add, AddAssign}; pub trait Span: core::fmt::Debug + Clone + core::ops::AddAssign {} pub trait SpanExt: Sized + Clone { fn combine(&mut self, span: Self); fn combined(&self, span: Self) -> Self { let mut new = self.clone(); new.combine(span); new ...
use std::ops::{Add, AddAssign}; pub trait Span: core::fmt::Debug + Clone + core::ops::AddAssign {} pub trait SpanExt: Sized + Clone { fn combine(&mut self, span: Self); fn combined(&self, span: Self) -> Self { let mut new = self.clone(); new.combine(span); new ...
} pub trait Spanned { type Span: Span; fn span(&self) -> Option<Self::Span>; } #[cfg(feature = "smallvec")] type KeysSmallVecArray = [String; 10]; #[cfg(feature = "smallvec")] type KeysInner = smallvec_crate::SmallVec<KeysSmallVecArray>; #[cfg(not(feature = "smallv...
fn combine(&mut self, span: Self) { match span { Some(new_span) => match self { Some(s) => *s += new_span, None => *self = Some(new_span), }, None => { *self = None; } } }
function_block-full_function
[ { "content": "/// Spans is used to provide spans for values that implement Serde Serialize.\n\n///\n\n/// Span hierarchy is controlled by the validators, only the new spans are required.\n\npub trait Spans: Clone + Default {\n\n /// The span type that is associated with each value.\n\n type Span: Span;\n\...
Rust
plonky2/src/gates/interpolation.rs
mfaulk/plonky2
2cedd1b02a718d19115560647ba1f741eab83260
use std::marker::PhantomData; use std::ops::Range; use plonky2_field::extension_field::algebra::PolynomialCoeffsAlgebra; use plonky2_field::extension_field::{Extendable, FieldExtension}; use plonky2_field::interpolation::interpolant; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::...
use std::marker::PhantomData; use std::ops::Range; use plonky2_field::extension_field::algebra::PolynomialCoeffsAlgebra; use plonky2_field::extension_field::{Extendable, FieldExtension}; use plonky2_field::interpolation::interpolant; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::...
fn eval_unfiltered_base_one( &self, vars: EvaluationVarsBase<F>, mut yield_constr: StridedConstraintConsumer<F>, ) { let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoe...
let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsAlgebra::new(coeffs); let coset = self.coset_ext(vars.local_wire...
function_block-function_prefix_line
[ { "content": "/// Tests that the constraints imposed by the given gate are low-degree by applying them to random\n\n/// low-degree witness polynomials.\n\npub fn test_low_degree<F: RichField + Extendable<D>, G: Gate<F, D>, const D: usize>(gate: G) {\n\n let rate_bits = log2_ceil(gate.degree() + 1);\n\n\n\n ...
Rust
tests/config_read_tests/configuration_tests.rs
szarykott/miau
a2ad16c2f205a21c1c35ffd91c08163b583c4d29
use miau::{ builder::ConfigurationBuilder, configuration::{Configuration, ConfigurationRead}, error::ErrorCode, format::Json, source::InMemorySource, }; use rstest::rstest; #[test] fn test_arrays_are_subsituted_when_config_is_built() { let json1 = r#"{"array1" : [1,2,3,4]}"#; let json2 = r#...
use miau::{ builder::ConfigurationBuilder, configuration::{Configuration, ConfigurationRead}, error::ErrorCode, format::Json, source::InMemorySource, }; use rstest::rstest; #[test] fn test_arrays_are_subsituted_when_config_is_built() { let json1 = r#"{"array1" : [1,2,3,4]}"#; let json2 = r#...
#[test] fn test_complex_map_config_build_json() { let config_str_1 = r#" { "firstName": "John", "lastName": "Smith", "isAlive": true, "address": { "streetAddress": "21 2nd Street" }, "phoneNumbers": [ { "type": "home", ...
m_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("[0]")); }
function_block-function_prefixed
[ { "content": "fn test_arrays_are_merged_when_substituted(json1: &str, json2: &str, exp: Vec<i32>) {\n\n let mut builder = ConfigurationBuilder::default();\n\n\n\n builder.add(\n\n InMemorySource::from_string_slice(json1.as_ref()),\n\n Json::new(),\n\n );\n\n builder.add(\n\n InM...
Rust
src/logger.rs
dignifiedquire/rust-drand
57cd6bcb459fb3fca1deb11c5a789c413ee308e2
use std::cmp::max; use std::io::{stderr, stdout, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; use ansi_term::{ANSIGenericString, Colour, Style}; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, P...
use std::cmp::max; use std::io::{stderr, stdout, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; use ansi_term::{ANSIGenericString, Colour, Style}; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, P...
, Debug, PartialEq)] pub struct Theme { pub error: Style, pub warn: Style, pub info: Style, pub debug: Style, pub trace: Style, pub module: Style, } impl Theme { pub fn empty() -> Theme { Theme { error: Style::new(), wa...
} } } impl Default for Destination { fn default() -> Destination { Destination::Stderr } } pub struct Logger { destination: Destination, level: LevelFilter, max_module_width: AtomicUsize, max_target_width: AtomicUsize, theme: Theme, } impl Logger { pub fn new(destin...
random
[ { "content": "pub fn group(\n\n key_paths: &[PathBuf],\n\n existing_group: Option<&PathBuf>,\n\n out: Option<&PathBuf>,\n\n period: Option<Duration>,\n\n) -> Result<()> {\n\n ensure!(\n\n existing_group.is_some() || key_paths.len() >= 3,\n\n \"groups must be at least 3 nodes large\"...
Rust
src/jws/envelope.rs
andkononykhin/didcomm-rust
939e13bda8babe9c27bc197bce16c5272fc07637
use askar_crypto::sign::SignatureType; use serde::{Deserialize, Serialize}; use serde_enum_str::{Deserialize_enum_str, Serialize_enum_str}; use crate::error::{err_msg, ErrorKind, Result}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct JWS<'a> { pub signatures: Vec<Signature<'a>>, ...
use askar_crypto::sign::SignatureType; use serde::{Deserialize, Serialize}; use serde_enum_str::{Deserialize_enum_str, Serialize_enum_str}; use crate::error::{err_msg, ErrorKind, Result}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct JWS<'a> { pub signatures: Vec<Signature<'a>>, ...
} #[test] fn algorithm_deserialize_works() { let alg: Algorithm = serde_json::from_str("\"EdDSA\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::EdDSA); let alg: Algorithm = serde_json::from_str("\"ES256\"").expect("Unable deserialize"); assert_eq!(alg, Algorith...
] pub(crate) struct Header<'a> { pub kid: &'a str, } #[derive(Deserialize_enum_str, Serialize_enum_str, Debug, Clone, Eq, PartialEq)] pub(crate) enum Algorithm { #[serde(rename = "EdDSA")] EdDSA, #[serde(rename = "ES256")] Es256, #[serde(rename = "ES256K")] Es256K, #[serde(other...
random
[ { "content": "pub trait ResultContext<T> {\n\n fn context<D>(self, msg: D) -> Result<T>\n\n where\n\n D: fmt::Display + fmt::Debug + Send + Sync + 'static;\n\n}\n\n\n\nimpl<T> ResultContext<T> for Result<T> {\n\n fn context<D>(self, msg: D) -> Result<T>\n\n where\n\n D: fmt::Display + ...
Rust
src/backend/wgpu_impl/shape_vertex_layout.rs
eaglekindoms/LemoGUI
a1499502c2f87cd8919b4de0ac26363b1755bf4a
use wgpu::*; use crate::backend::wgpu_impl::*; use crate::device::GPUContext; use crate::graphic::base::*; use crate::graphic::style::{Bordering, Rounding, Style}; #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CircleVertex { pub position: [f32; 2], pub color: ...
use wgpu::*; use crate::backend::wgpu_impl::*; use crate::device::GPUContext; use crate::graphic::base::*; use crate::graphic::style::{Bordering, Rounding, Style}; #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CircleVertex { pub position: [f32; 2], pub color: ...
::ShaderModuleDescriptor { label: Some("round_rect shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/round_rect.wgsl")), )), }) } } impl RectVertex { pub fn new(rect: &Re...
ertex { pub size: [f32; 2], pub position: [f32; 2], pub border_color: [f32; 4], pub rect_color: [f32; 4], pub is_round_or_border: [u32; 2], } const RECT_ATTRS: [VertexAttribute; 5] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x2, 2 => Float...
random
[ { "content": "/// 描述纹理顶点数据布局,用于着色器识别数据\n\npub fn bind_group(device: &wgpu::Device,\n\n bind_group_layout: &wgpu::BindGroupLayout,\n\n target: &wgpu::TextureView,\n\n sampler: &wgpu::Sampler) -> wgpu::BindGroup\n\n{\n\n device.create_bind_group(\n\n &w...
Rust
src/rustc/middle/trans/impl.rs
mernen/rust
bb5c07922f20559af1e40d63a15b1be0402e5fe4
import libc::c_uint; import base::*; import common::*; import type_of::*; import build::*; import driver::session::session; import syntax::{ast, ast_map}; import ast_map::{path, path_mod, path_name, node_id_to_str}; import driver::session::expect; import syntax::ast_util::local_def; import metadata::csearch; import bac...
import libc::c_uint; import base::*; import common::*; import type_of::*; import build::*; import driver::session::session; import syntax::{ast, ast_map}; import ast_map::{path, path_mod, path_name, node_id_to_str}; import driver::session::expect; import syntax::ast_util::local_def; import metadata::csearch; import bac...
fn trans_self_arg(bcx: block, base: @ast::expr, mentry: typeck::method_map_entry) -> result { let _icx = bcx.insn_ctxt("impl::trans_self_arg"); let basety = expr_ty(bcx, base); let mode = ast::expl(mentry.self_mode); let mut temp_cleanups = ~[]; let result = trans_arg_expr(bcx, {...
fn trans_method(ccx: @crate_ctxt, path: path, method: &ast::method, param_substs: option<param_substs>, llfn: ValueRef) { let self_arg = match method.self_ty.node { ast::sty_static => { no_self } _ => { ...
function_block-full_function
[ { "content": "fn val_ty(v: ValueRef) -> TypeRef { return llvm::LLVMTypeOf(v); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 0, "score": 566159.6927412436 }, { "content": "// LLVM constant constructors.\n\nfn C_null(t: TypeRef) -> ValueRef { return llvm::LLVMConstNull(t);...
Rust
src/dms/font.rs
mnit-rtmc/ntcip
ccc7d59869d4fc406f7f0d0550112e5b3b390bb2
use crate::dms::multi::SyntaxError; use crate::dms::Result; use log::debug; use pix::{rgb::SRgb8, Raster}; use std::collections::HashMap; #[derive(Deserialize, Serialize)] pub struct Character { number: u16, width: u8, #[serde(with = "super::base64")] bitmap: Vec<u8>, } #[derive(Deser...
use crate::dms::multi::SyntaxError; use crate::dms::Result; use log::debug; use pix::{rgb::SRgb8, Raster}; use std::collections::HashMap; #[derive(Deserialize, Serialize)] pub struct Character { number: u16, width: u8, #[serde(with = "super::base64")] bitmap: Vec<u8>, } #[derive(Deser...
pub fn version_id(&self) -> u16 { self.version_id } } impl FontCache { pub fn insert(&mut self, font: Font) { self.fonts.insert(font.number(), font); } pub fn lookup<'a>( &'a self, fnum: u8, version_id: Option<u16>, ) -> Result<&'a Font>...
text: &str, x: i32, y: i32, cs: i32, cf: SRgb8, ) -> Result<()> { let height = i32::from(self.height()); debug!( "render_text: font number {}, name {}", self.number(), self.name() ); debug!("render_text: {} @ {},{} h...
function_block-function_prefix_line
[ { "content": "/// Normalize a MULTI string.\n\npub fn normalize(ms: &str) -> String {\n\n let mut s = String::with_capacity(ms.len());\n\n for t in Parser::new(ms) {\n\n if let Ok(v) = t {\n\n s.push_str(&v.to_string());\n\n }\n\n }\n\n s\n\n}\n\n\n\n#[cfg(test)]\n\nmod test...
Rust
rust/src/methods/reshape/mod.rs
stencila/stencila
bff4faceb1460a84b096e9e45f4a4580a0156295
use super::decode::date::decode_date_maybe; use super::decode::person::decode_person; use super::encode::txt::ToTxt; use defaults::Defaults; use eyre::Result; use once_cell::sync::Lazy; use regex::Regex; use stencila_schema::{ Article, BlockContent, CreativeWorkAuthors, CreativeWorkTitle, Date, InlineContent, Node,...
use super::decode::date::decode_date_maybe; use super::decode::person::decode_person; use super::encode::txt::ToTxt; use defaults::Defaults; use eyre::Result; use once_cell::sync::Lazy; use regex::Regex; use stencila_schema::{ Article, BlockContent, CreativeWorkAuthors, CreativeWorkTitle, Date, InlineContent, Node,...
BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("^(?:D|d)ate\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { if let Some(d...
egex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|(and)|&\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { l...
random
[ { "content": "/// Decode any front matter in a Markdown document into a `Node`\n\n///\n\n/// Any front matter will be coerced into a `Node`, defaulting to the\n\n/// `Node::Article` variant, if `type` is not defined.\n\n/// If there is no front matter detected, will return `None`.\n\npub fn decode_frontmatter(m...
Rust
db/src/models/group.rs
davedray/gatekeeper
0292c33941ec08da2f6e5514b70b9c80fd74ea47
use chrono::{DateTime, Utc}; use diesel::{AsChangeset, Insertable, Queryable}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::models::{Realm, Role, User}; use crate::schema::{groups, groups_roles, users_groups}; #[derive(Insertable, Identifiable, Queryable, Associations, Serialize, Deserialize, Parti...
use chrono::{DateTime, Utc}; use diesel::{AsChangeset, Insertable, Queryable}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::models::{Realm, Role, User}; use crate::schema::{groups, groups_roles, users_groups}; #[derive(Insertable, Identifiable, Queryable, Associations, Serialize, Deserialize, Parti...
} impl From<Group> for domain::Group { fn from(a: Group) -> Self { domain::Group::new( a.id, a.realm_id, a.name, a.description, a.created_at, a.updated_at, ) } } #[derive(AsChangeset)] #[table_name = "groups"] pub struct ...
fn from(a: domain::RemoveRoleFromGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, } }
function_block-full_function
[ { "content": "pub fn ids_by_group(repo: &Postgres, group: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::groups_roles::dsl::*;\n\n groups_roles.filter(group_id.eq(group)).select(role_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 0, "score": 291...
Rust
src/parser/storage.rs
marirs/msg-parser-rs
cd508394d9a98d22e2b7c0d851bfe36ca6a0d464
use std::{ collections::HashMap, u32::MAX, }; use hex::decode; use crate::ole::{Entry, EntryType, Reader}; use super::{ constants::PropIdNameMap, decode::DataType, stream::Stream }; #[derive(Debug, Clone, PartialEq)] pub enum StorageType { Recipient(u32), Attachment(u32), R...
use std::{ collections::HashMap, u32::MAX, }; use hex::decode; use crate::ole::{Entry, EntryType, Reader}; use super::{ constants::PropIdNameMap, decode::DataType, stream::Stream }; #[derive(Debug, Clone, PartialEq)] pub enum StorageType { Recipient(u32), Attachment(u32), R...
#[test] fn test_create_storage_test_email() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); let sender = storages.root.get("SenderEmailAddress"); assert!(sender.is_none()); ...
let mut map_apple: Properties = HashMap::new(); map_apple.insert("A".to_string(), DataType::PtypString("Apple".to_string())); let mut map_bagel: Properties = HashMap::new(); map_bagel.insert("B".to_string(), DataType::PtypString("Bagel".to_string())); let mut basket: HashMap<u32, Proper...
function_block-function_prefix_line
[ { "content": "fn decode_ptypbinary(buff: &Vec<u8>) -> Result<DataType, Error> {\n\n Ok(DataType::PtypBinary(buff.to_vec()))\n\n}\n\n\n", "file_path": "src/parser/decode.rs", "rank": 1, "score": 97399.3281907708 }, { "content": "fn decode_ptypstring(buff: &Vec<u8>) -> Result<DataType, Erro...
Rust
src/librustc_mir/transform/nll/constraint_generation.rs
arshiafaradj/rust
2f47a9eb80bc3474b6e89637269ef1f92cfccb7f
use rustc::hir; use rustc::mir::{Location, Lvalue, Mir, Rvalue}; use rustc::mir::visit::Visitor; use rustc::mir::Lvalue::Projection; use rustc::mir::{LvalueProjection, ProjectionElem}; use rustc::infer::InferCtxt; use rustc::traits::{self, ObligationCause}; use rustc::ty::{self, Ty}; use rustc::ty::fold::TypeFoldable...
use rustc::hir; use rustc::mir::{Location, Lvalue, Mir, Rvalue}; use rustc::mir::visit::Visitor; use rustc::mir::Lvalue::Projection; use rustc::mir::{LvalueProjection, ProjectionElem}; use rustc::infer::InferCtxt; use rustc::traits::{self, ObligationCause}; use rustc::ty::{self, Ty}; use rustc::ty::fold::TypeFoldable...
} impl<'cx, 'gcx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cx, 'gcx, 'tcx> { fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { debug!("visit_rvalue(rvalue={:?}, location={:?})", rvalue, location); ...
let LvalueProjection { ref base, ref elem } = **proj; if let ProjectionElem::Deref = *elem { let tcx = self.infcx.tcx; let base_ty = base.ty(self.mir, tcx).to_ty(tcx); let base_sty = &base_ty.sty; if let ty::TyRef(base_region, ty::TypeAndMut{...
function_block-function_prefixed
[]
Rust
src/xlnet/attention.rs
sftse/rust-bert
5c1c2aa19971a613323fee423c035e0d39d27465
use crate::common::dropout::Dropout; use crate::xlnet::XLNetConfig; use std::borrow::Borrow; use tch::nn::Init; use tch::{nn, Kind, Tensor}; #[derive(Debug)] pub struct LayerState { pub prev_content: Tensor, } impl Clone for LayerState { fn clone(&self) -> Self { LayerState { prev_...
use crate::common::dropout::Dropout; use crate::xlnet::XLNetConfig; use std::borrow::Borrow; use tch::nn::Init; use tch::{nn, Kind, Tensor}; #[derive(Debug)] pub struct LayerState { pub prev_content: Tensor, } impl Clone for LayerState { fn clone(&self) -> Self { LayerState { prev_...
pub fn forward_t( &self, h: &Tensor, g: Option<&Tensor>, attn_mask_h: Option<&Tensor>, attn_mask_g: Option<&Tensor>, r: &Tensor, seg_mat: Option<&Tensor>, layer_state: Option<LayerState>, target_mapping: Option<&Tensor>, train: bool, ...
fn post_attention( &self, h: &Tensor, attention_vector: &Tensor, residual: bool, train: bool, ) -> Tensor { let mut attention_out = Tensor::einsum("ibnd,hnd->ibh", &[attention_vector, &self.output]) .apply_t(&self.dropout, train); if residual { ...
function_block-full_function
[ { "content": "pub fn stable_argsort(input_tensor: &Tensor, dim: i64) -> Tensor {\n\n let scaling_dim = input_tensor.size()[dim as usize];\n\n let scaled_offset = Tensor::arange(scaling_dim, (Kind::Int, input_tensor.device()))\n\n .view([1, 1, -1])\n\n .expand(&input_tensor.size(), true);\n\n...
Rust
src/kernel.rs
Mic92/vmsh
296a09102abece5df0135afb9678261d5a7b6c20
use log::{debug, info}; use nix::sys::mman::ProtFlags; use simple_error::{require_with, try_with, SimpleError}; use std::collections::HashMap; use std::ffi::CStr; use std::mem::{self, size_of}; use std::ops::Range; use vm_memory::remote_mem::process_read_bytes; use crate::guest_mem::{GuestMem, MappedMemory}; use crate...
use log::{debug, info}; use nix::sys::mman::ProtFlags; use simple_error::{require_with, try_with, SimpleError}; use std::collections::HashMap; use std::ffi::CStr; use std::mem::{self, size_of}; use std::ops::Range; use vm_memory::remote_mem::process_read_bytes; use crate::guest_mem::{GuestMem, MappedMemory}; use crate...
end = idx + end_offset + 1; Some(start..end) } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol { pub value_offset: libc::c_int, pub name_offset: libc::c_int, pub namespace_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_5_3 { pub value_offset: libc::c_int, ...
n<Range<usize>> { let idx = find_subsequence(mem, b"init_task")?; let start_offset = mem[..idx] .windows(2) .rev() .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let start = round_up(idx - start_offset, 4); let end_offset = mem[idx..] .wind...
function_block-random_span
[ { "content": "pub fn is_page_aligned(v: usize) -> bool {\n\n v & (page_size() - 1) == 0\n\n}\n\n\n", "file_path": "src/page_math.rs", "rank": 2, "score": 253724.61583958115 }, { "content": "pub fn use_ioregionfd() -> bool {\n\n USE_IOREGIONFD.load(Ordering::Relaxed)\n\n}\n\n\n\npub typ...
Rust
nucleus/src/main.rs
metta-systems/vesper
7d03ea85a2d5ee77b7e8b36e5c9bf1ce41b77084
/* * SPDX-License-Identifier: BlueOak-1.0.0 * Copyright (c) Berkus Decker <berkus+vesper@metta.systems> */ #![no_std] #![no_main] #![feature(decl_macro)] #![feature(allocator_api)] #![feature(ptr_internals)] #![feature(format_args_nl)] #![feature(nonnull_slice_from_raw_parts)] #![feature(custom_test_frameworks)] #!...
/* * SPDX-License-Identifier: BlueOak-1.0.0 * Copyright (c) Berkus Decker <berkus+vesper@metta.systems> */ #![no_std] #![no_main] #![feature(decl_macro)] #![feature(allocator_api)] #![feature(ptr_internals)] #![feature(format_args_nl)] #![feature(nonnull_slice_from_raw_parts)] #![feature(custom_test_frameworks)] #!...
println!("Mailbox call returned error {}", e); println!("Mailbox contents: {:?}", mbox); }) .ok(); } fn reboot() -> ! { cfg_if! { if #[cfg(feature = "qemu")] { println!("Bye, shutting down QEMU"); qemu::semihosting::exit_success() } e...
box.request(); let index = mbox.set_led_on(index, enable); let mbox = mbox.end(index); mbox.call(channel::PropertyTagsArmToVc) .map_err(|e| {
function_block-random_span
[ { "content": "/// Print the kernel memory layout.\n\npub fn print_layout() {\n\n println!(\"[i] Kernel memory layout:\");\n\n\n\n for i in KERNEL_VIRTUAL_LAYOUT.iter() {\n\n println!(\"{}\", i);\n\n }\n\n}\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 0, "score":...
Rust
src/render/pipeline_2d.rs
RomainMazB/bevy_svg
da7acfe562a77151c33e995240d7ef40f803a5ff
use bevy::{ asset::Handle, core::FloatOrd, core_pipeline::Transparent2d, ecs::{entity::Entity, query::With, world::{FromWorld, World}, system::{Query, Res, ResMut},}, log::debug, render::{ mesh::Mesh, render_asset::RenderAssets, render_phase::{DrawFunctions, RenderPhase, ...
use bevy::{ asset::Handle, core::FloatOrd, core_pipeline::Transparent2d, ecs::{entity::Entity, query::With, world::{FromWorld, World}, system::{Query, Res, ResMut},}, log::debug, render::{ mesh::Mesh, render_asset::RenderAssets, render_phase::{DrawFunctions, RenderPhase, ...
, primitive: PrimitiveState { front_face: FrontFace::Cw, cull_mode: None, unclipped_depth: false, polygon_mode: PolygonMode::Fill, conservative: false, topology: key.primitive_topology(), strip_in...
Some(vec![ self.mesh2d_pipeline.view_layout.clone(), self.mesh2d_pipeline.mesh_layout.clone(), ])
call_expression
[ { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn queue_svg_3d(\n\n transparent_draw_functions: Res<DrawFunctions<Transparent3d>>,\n\n svg_3d_pipeline: Res<Svg3dPipeline>,\n\n mut pipelines: ResMut<SpecializedPipelines<Svg3dPipeline>>,\n\n mut pipeline_cache: ResMut<RenderPipelineCache>,\...
Rust
src/cmd/env.rs
wang-q/garr
50c1ecc08e2e4f854fe4186882a738aaa3d3e41d
use clap::*; use garr::*; use std::collections::HashMap; use std::fs; use tera::{Context, Tera}; pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("env") .about("Create a .env file") .after_help( r#" Default values: * REDIS_HOST - localhost * REDIS_PORT - 6379 * R...
use clap::*; use garr::*; use std::collections::HashMap; use std::fs; use tera::{Context, Tera}; pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("env") .about("Create a .env file") .after_help( r#" Default values: * REDIS_HOST - localhost * REDIS_PORT - 6379 * R...
ec![( "t", include_str!("../../templates/ddl/rsw.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_summary(context: &Context) -> std::result::Result<(), std::io::Error> { ...
name = "sqls/ddl/rsw.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(v
function_block-random_span
[ { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // redis connection\n\n let mut conn = connect();\n\n\n\n // processing each file\n\n for infile in args.values_of(\"infiles\").unwrap() {\n\n let reader = reader(infi...
Rust
cita-chain/types/src/receipt.rs
Pencil-Yao/cita
bcd00dc848fd2ca4b1e72d57f5f0e059bb2d3828
use super::Bytes; use std::str::FromStr; use crate::block_number::BlockNumber; use crate::errors::ReceiptError; use crate::log::{LocalizedLog, Log}; use cita_types::traits::LowerHex; use cita_types::{Address, Bloom as LogBloom, H256, U256}; use jsonrpc_types::rpc_types::Receipt as RpcReceipt; use libproto::executor...
use super::Bytes; use std::str::FromStr; use crate::block_number::BlockNumber; use crate::errors::ReceiptError; use crate::log::{LocalizedLog, Log}; use cita_types::traits::LowerHex; use cita_types::{Address, Bloom as LogBloom, H256, U256}; use jsonrpc_types::rpc_types::Receipt as RpcReceipt; use libproto::executor...
} impl From<ProtoReceipt> for Receipt { fn from(receipt: ProtoReceipt) -> Self { let state_root = if receipt.state_root.is_some() { Some(H256::from_slice( receipt.clone().take_state_root().get_state_root(), )) } else { None }; le...
logs .clone() .into_iter() .map(|log_entry| log_entry.protobuf()) .collect(); receipt_proto.set_account_nonce(self.account_nonce.as_u64()); receipt_proto.set_transaction_hash(self.transaction_hash.to_vec()); receipt_proto }
function_block-function_prefix_line
[ { "content": "fn accrue_log(bloom: &mut Bloom, log: &Log) {\n\n bloom.accrue(BloomInput::Raw(&log.address.0));\n\n for topic in &log.topics {\n\n let input = BloomInput::Hash(&topic.0);\n\n bloom.accrue(input);\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs"...
Rust
src/gameboy/cpu/register.rs
Hanaasagi/NGC-224
24a3c439148ffef0930e19c9d88c68a9164a5459
use super::super::Term; #[derive(Default, Debug, Clone)] #[allow(non_snake_case)] pub struct Register { A: u8, B: u8, C: u8, D: u8, E: u8, F: u8, H: u8, L: u8, PC: u16, SP: u16, } impl Register { pub fn new() -> Self { Self::default() } pub fn ne...
use super::super::Term; #[derive(Default, Debug, Clone)] #[allow(non_snake_case)] pub struct Register { A: u8, B: u8, C: u8, D: u8, E: u8, F: u8, H: u8, L: u8, PC: u16, SP: u16, } impl Register { pub fn new() -> Self { Self::default() } pub fn ne...
} #[derive(Clone, Debug)] pub enum Flag { Zero = 0b1000_0000, Sub = 0b0100_0000, HalfCarry = 0b0010_0000, Carry = 0b0001_0000, } impl Flag { pub fn into_value(self) -> u8 { self as u8 } pub fn value(&self) -> u8 { self.clone() as u8...
pub fn reverse_flag(&mut self, flag: Flag) { if self.is_flag_set(flag.clone()) { self.unset_flag(flag); } else { self.set_flag(flag); } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn test_bit(v: u8, b: u8) -> bool {\n\n assert!(b <= 7);\n\n v & (1 << b) != 0\n\n}\n\n\n\n/// modify the bit to 0.\n", "file_path": "src/gameboy/util.rs", "rank": 0, "score": 184909.29057740478 }, { "content": "#[inline]\n\npub fn clear_bit(v: u8, b: u8)...
Rust
contracts/tland-token/src/msg.rs
highwayns/realestate
508db9bc5578ae57050e9bd9e0faacd4f5746cf6
use cosmwasm_std::{StdError, StdResult, Uint128, Binary}; use cw20::{Cw20Coin, Logo}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cw0::Expiration; #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMarketingInfo { pub project: Option<String>, pub...
use cosmwasm_std::{StdError, StdResult, Uint128, Binary}; use cw20::{Cw20Coin, Logo}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cw0::Expiration; #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMarketingInfo { pub project: Option<String>, pub...
} fn is_valid_name(name: &str) -> bool { let bytes = name.as_bytes(); if bytes.len() < 3 || bytes.len() > 50 { return false; } true } fn is_valid_symbol(symbol: &str) -> bool { let bytes = symbol.as_bytes(); if bytes.len() < 3 || bytes.len() > 12 { return false; } for ...
s_valid_symbol(&self.symbol) { return Err(StdError::generic_err( "Ticker symbol is not in expected format [a-zA-Z\\-]{3,12}", )); } if self.decimals > 18 { return Err(StdError::generic_err("Decimals must not exceed 18")); } Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn query_allowance(deps: Deps, owner: String, spender: String) -> StdResult<AllowanceResponse> {\n\n let owner_addr = deps.api.addr_validate(&owner)?;\n\n let spender_addr = deps.api.addr_validate(&spender)?;\n\n let allowance = ALLOWANCES\n\n .may_load(deps.storage, (&owner_ad...
Rust
07-rust/stm32l0x1/stm32l0x1_pac/src/syscfg_comp/comp1_ctrl.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register COMP1_CTRL"] pub type R = crate::R<u32, super::COMP1_CTRL>; #[doc = "Writer for register COMP1_CTRL"] pub type W = crate::W<u32, super::COMP1_CTRL>; #[doc = "Register COMP1_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::COMP1_CTRL { type Type = u32; #[inline(always...
#[doc = "Reader of register COMP1_CTRL"] pub type R = crate::R<u32, super::COMP1_CTRL>; #[doc = "Writer for register COMP1_CTRL"] pub type W = crate::W<u32, super::COMP1_CTRL>; #[doc = "Register COMP1_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::COMP1_CTRL { type Type = u32; #[inline(always...
TY_R { COMP1POLARITY_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&self) -> COMP1VALUE_R { COMP1VALUE_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - COMP1_CSR register lock bit"] ...
= "Write proxy for field `COMP1VALUE`"] pub struct COMP1VALUE_W<'a> { w: &'a mut W, } impl<'a> COMP1VALUE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear...
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
riscv/src/mmu.rs
plorefice/rv6
adb7e28994b08b86596d2bdfbfee0ca5832e3d21
use core::{ fmt, slice::{Iter, IterMut}, }; use bitflags::bitflags; use kmm::{allocator::FrameAllocator, Align}; use crate::{ addr::{PAGE_SHIFT, PAGE_SIZE}, PhysAddr, VirtAddr, }; #[cfg(feature = "sv39")] const PTE_PPN_MASK: u64 = 0x3ff_ffff; #[cfg(feature = "sv48")] const PTE_PPN_MASK: u64 = 0xfff...
use core::{ fmt, slice::{Iter, IterMut}, }; use bitflags::bitflags; use kmm::{allocator::FrameAllocator, Align}; use crate::{ addr::{PAGE_SHIFT, PAGE_SIZE}, PhysAddr, VirtAddr, }; #[cfg(feature = "sv39")] const PTE_PPN_MASK: u64 = 0x3ff_ffff; #[cfg(feature = "sv48")] const PTE_PPN_MASK: u64 = 0xfff...
pub unsafe fn identity_map_range<A>( &mut self, start: PhysAddr, end: PhysAddr, flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { let start = start....
d); } pte.set_flags(flags | EntryFlags::VALID); pte.set_ppn(paddr.page_index()); Ok(()) }
function_block-function_prefixed
[ { "content": "/// A physical memory address representable as an integer of type `U`.\n\npub trait PhysicalAddress<U>: Copy + Clone + Into<U> + AddressOps<U> {}\n\n\n", "file_path": "kmm/src/lib.rs", "rank": 0, "score": 142634.8631566231 }, { "content": "/// A trait for numeric types that can...
Rust
src/bin/test_merge.rs
GuilloteauQ/rayon-adaptive
ad3c82ca5d942df9c052b079e20d0331f840e303
use itertools::{iproduct, Itertools}; use rand::Rng; use rayon_adaptive::adaptive_sort_raw_with_policies_swap_blocks; use rayon_adaptive::Policy; use std::fs::File; use std::io::prelude::*; use std::iter::{once, repeat_with}; use thread_binder::ThreadPoolBuilder; use time::precise_time_ns; fn random_vec_with_range(siz...
use itertools::{iproduct, Itertools}; use rand::Rng; use rayon_adaptive::adaptive_sort_raw_with_policies_swap_blocks; use rayon_adaptive::Policy; use std::fs::File; use std::io::prelude::*; use std::iter::{once, repeat_with}; use thread_binder::ThreadPoolBuilder; use time::precise_time_ns; fn random_vec_with_range(siz...
let sizes = vec![1_000_000]; let threads: Vec<usize> = vec![4]; let policies = vec![Policy::Join(1000), Policy::JoinContext(1000)]; let input_generators = vec![ /* ( Box::new(random_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "random", ), */ ...
lone()); } (va, vb) } fn average_times<INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool>( init_fn: I, timed_fn: F, iterations: usize, ) -> (f64, usize) { let mut ve = Vec::new(); for _ in 0..iterations { ve.push(bench(&init_fn, &timed_fn)); } let v = tuple_to_vec(&ve); ...
random
[ { "content": "/// compute a block size with the given function.\n\n/// this allows us to ensure we enforce important bounds on sizes.\n\nfn compute_size<F: Fn(usize) -> usize>(n: usize, sizing_function: F) -> usize {\n\n let p = current_num_threads();\n\n std::cmp::max(min(n / (2 * p), sizing_function(n))...
Rust
src/main.rs
igoyak/igrepper
6b5b66d4a6b45382d3e8f45571b111c5e0f4b9a4
extern crate clap; extern crate libc; use clap::{App, Arg}; use inotify::{Inotify, WatchMask}; use libc::close; use libc::open; use std::env; use crate::igrepper::igrepper; use file_reading::{SourceInput, SourceProducer}; mod file_reading; mod igrepper; const PARAMETER_ERROR: &str = "Data can only be passed by STDIN...
extern crate clap; extern crate libc; use clap::{App, Arg}; use inotify::{Inotify, WatchMask}; use libc::close; use libc::open; use std::env; use crate::igrepper::igrepper; use file_reading::{SourceInput, SourceProducer}; mod file_reading; mod igrepper; const PARAMETER_ERROR: &str = "Data can only be passed by STDIN...
.requires("file") .help("Reload the file as it changes. Requires [file] to be set."), ) .get_matches(); let file_option = matches.value_of("file"); let is_tty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0; let mut file_path: Option<&str> = None; ...
; fn main() { let matches = App::new("igrepper") .version("1.3.1") .about("The interactive grepper") .arg( Arg::with_name("regex") .short("e") .long("regex") .value_name("REGEX") .help("Regular expression to preload...
random
[ { "content": "fn read_source_from_file(file_path: &str) -> io::Result<Vec<String>> {\n\n let file = File::open(file_path)?;\n\n let reader = BufReader::new(file);\n\n let source: Vec<String> = reader.lines().filter_map(|line| line.ok()).collect();\n\n Ok(source)\n\n}\n\n\n", "file_path": "src/fi...
Rust
src/lib.rs
aymgm/Mirach
c10f00ed06de0b5ab925b54318e7b5c2e2f14352
#![allow(unused)] extern crate symbol; extern crate thiserror; use std::collections::HashMap; use symbol::Symbol; use thiserror::Error; mod llvm_wrapper; use llvm_wrapper as llvm; mod scope_stack; use scope_stack::{ScopeStack, ScopedValue}; mod func_stack; use func_stack::{FuncStackElem, FuncStack}; mod loop_sta...
#![allow(unused)] extern crate symbol; extern crate thiserror; use std::collections::HashMap; use symbol::Symbol; use thiserror::Error; mod llvm_wrapper; use llvm_wrapper as llvm; mod scope_stack; use scope_stack::{ScopeStack, ScopedValue}; mod func_stack; use func_stack::{FuncStackElem, FuncStack}; mod loop_sta...
; llvm::Type::ptr(t) }, _ => unimplemented!() } } fn gen(&mut self, mir: Mir)->Result<Option<llvm::Value>, MirErr> { use llvm::*; match *mir { MirRaw::Unit(_) => panic!("Unit can't be compiled"), MirRaw::Bool(b, _) => Ok(Som...
if ty.args.is_empty() { llvm::Type::void(&self.ctx) } else { self.gen_ty(&ty.args[0]) }
if_condition
[ { "content": "fn run(name: String, mir: Mir)-> String {\n\n use std::process::*;\n\n use llvm_sys::target_machine::*;\n\n use llvm_wrapper::TargetMachine;\n\n let test_data_dir = \"testdata\";\n\n let prefix = if cfg!(target_os = \"windows\") {format!(\"{}\\\\\", test_data_dir)} else {format!(\"{...
Rust
src/textures/render_texture.rs
e0328eric/dioteko
e1f4e017c449d0904ff722f2e3f58ea3a1489b98
use std::cell::Cell; use std::ptr::NonNull; use crate::ffi; pub(crate) struct RenderTextureRc { strong: Cell<usize>, weak: Cell<usize>, } impl RenderTextureRc { fn new() -> Self { Self { strong: Cell::new(1), weak: Cell::new(1), } } } trait RenderTextureRcCont...
use std::cell::Cell; use std::ptr::NonNull; use crate::ffi; pub(crate) struct RenderTextureRc { strong: Cell<usize>, weak: Cell<usize>, } impl RenderTextureRc { fn new() -> Self { Self { strong: Cell::new(1), weak: Cell::new(1), } } } trait RenderTextureRcCont...
render_texture: self.render_texture, rc_count: self.rc_count, } } } impl Drop for WeakRenderTexture { fn drop(&mut self) { self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } ...
#[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, ...
random
[ { "content": "pub fn get_pixel_data_size(width: i32, height: i32, format: i32) -> i32 {\n\n // SAFETY: ffi\n\n unsafe { ffi::GetPixelDataSize(width, height, format) }\n\n}\n", "file_path": "src/textures/pixel.rs", "rank": 0, "score": 176877.2228604159 }, { "content": "pub fn draw_text(...
Rust
rosetta-i18n/src/serde_helpers.rs
baptiste0928/rosetta
039a69493dc5517d7778b9fb4ed0fa57375cc44e
use std::borrow::Cow; use serde::{de, ser}; use crate::LanguageId; impl ser::Serialize for LanguageId<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { serializer.serialize_str(&self.0) } } impl<'de> de::Deserialize<'de> for Language...
use std::borrow::Cow; use serde::{de, ser}; use crate::LanguageId; impl ser::Serialize for LanguageId<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { serializer.serialize_str(&self.0) } } impl<'de> de::Deserialize<'de> for Language...
; } #[test] fn serde_as_language_fallback() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), ...
assert_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("en"), Token::StructEnd, ], )
call_expression
[ { "content": "/// Helper function that return an default [`RosettaBuilder`].\n\npub fn config() -> RosettaBuilder {\n\n RosettaBuilder::default()\n\n}\n\n\n\n/// Builder used to configure Rosetta code generation.\n\n#[derive(Debug, Clone, PartialEq, Eq, Default)]\n\npub struct RosettaBuilder {\n\n files: ...
Rust
src/store/encoding/raw/primitive_enc.rs
meerkatdb/meerkat
26ecee08251401fcb240fa6b8d382df590762eae
use std::convert::TryInto; use std::mem::size_of; use anyhow::Result; use async_trait::async_trait; use crate::store::encoding::bitmap_rle; use crate::store::encoding::{BlockEncoder, BlockSink}; use crate::store::indexing_buffer::PrimitiveBuffer; use crate::store::segment_metadata::column_layout::EncoderLayout; use...
use std::convert::TryInto; use std::mem::size_of; use anyhow::Result; use async_trait::async_trait; use crate::store::encoding::bitmap_rle; use crate::store::encoding::{BlockEncoder, BlockSink}; use crate::store::indexing_buffer::PrimitiveBuffer; use crate::store::segment_metadata::column_layout::EncoderLayout; use...
; self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } fn add_rows(&mut self, num_rows: usize) { self.num_rows = self .num_rows .checked_add((num_rows).try_into().expect("segment over...
encode_primitive_buffer( &self.remaining, 0, self.remaining.len(), 0, &mut self.encoded_data, &mut self.bitmap_encoder, )
call_expression
[ { "content": "#[inline]\n\npub fn encode_varint(mut value: u64, buf: &mut [u8]) -> usize {\n\n let mut i = 0;\n\n while value >= 0x80 {\n\n buf[i] = ((value & 0x7F) | 0x80) as u8;\n\n value >>= 7;\n\n i += 1;\n\n }\n\n buf[i] = value as u8;\n\n i += 1;\n\n i\n\n}\n\n\n\n//...
Rust
src/filters/tests.rs
dsaxton/feroxbuster
45efaa738850f7644683d927cffc5661e97307c4
use super::*; use ::fuzzyhash::FuzzyHash; use ::regex::Regex; #[test] fn wildcard_filter_default() { let wcf = WildcardFilter::default(); assert_eq!(wcf.size, u64::MAX); assert_eq!(wcf.dynamic, u64::MAX); } #[test] fn wildcard_filter_as_any() { let filter = WildcardFilter::default(); let filter2...
use super::*; use ::fuzzyhash::FuzzyHash; use ::regex::Regex; #[test] fn wildcard_filter_default() { let wcf = WildcardFilter::default(); assert_eq!(wcf.size, u64::MAX); assert_eq!(wcf.dynamic, u64::MAX); } #[test] fn wildcard_filter_as_any() { let filter = WildcardFilter::default(); let filter2...
#[test] fn wildcard_should_filter_when_static_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); resp.set_text( "pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus faucibus", ); let filter = W...
y())); assert_eq!(filter.raw_string, r".*\.txt$"); assert_eq!( *filter.as_any().downcast_ref::<RegexFilter>().unwrap(), filter ); }
function_block-function_prefixed
[]
Rust
plan_b/src/map.rs
PoHuit/plan-b
12121a5e9c542b2486a2fd33ba06bcebfeba6b65
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::slice; use libflate::gzip; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SystemId(usize); #[derive(Debug)] pub struct SystemInfo { pub system_id: SystemId, pub name: String, ...
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::slice; use libflate::gzip; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SystemId(usize); #[derive(Debug)] pub struct SystemInfo { pub system_id: SystemId, pub name: String, ...
#[derive(Deserialize)] pub struct Destination { pub stargate_id: usize, pub system_id: usize, } #[derive(Deserialize)] pub struct Point { #[serde(deserialize_with = "de_from_f64")] pub x: f64, #[serde(deserialize_with = "de_from_f64")] pub y: f64, ...
Value::Array(_) => { let ue = de::Unexpected::Seq; Err(de::Error::invalid_value(ue, &e)) } Value::Object(_) => { let ue = de::Unexpected::Map; Err(de::Error::invalid_value(ue, &e)) } } }
function_block-function_prefix_line
[ { "content": "// Look up the given system name in the map, and panic if\n\n// not found. This should be cleaned up.\n\nfn find_system(map: &Map, name: &str) -> SystemId {\n\n map.by_name(name)\n\n .unwrap_or_else(|| panic!(\"could not find {} in map\", name))\n\n .system_id\n\n}\n\n\n", "fi...
Rust
src/keyassignment.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
use crate::config::configuration; use crate::mux::domain::DomainId; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; use term::{KeyCode, KeyModifiers}; #[derive(Debug, Clone, Deserialize, Serialize)] pub enum SpawnTabDomain { DefaultDomain, CurrentTabDomain,...
use crate::config::configuration; use crate::mux::domain::DomainId; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; use term::{KeyCode, KeyModifiers}; #[derive(Debug, Clone, Deserialize, Serialize)] pub enum SpawnTabDomain { DefaultDomain, CurrentTabDomain,...
pub fn lookup(&self, key: KeyCode, mods: KeyModifiers) -> Option<KeyAssignment> { self.0 .get(&(key.normalize_shift_to_upper_case(mods), mods)) .cloned() } }
R, KeyCode::Char('2'), ActivateTab(1)], [KeyModifiers::SUPER, KeyCode::Char('3'), ActivateTab(2)], [KeyModifiers::SUPER, KeyCode::Char('4'), ActivateTab(3)], [KeyModifiers::SUPER, KeyCode::Char('5'), ActivateTab(4)], [KeyModifiers::SUPER, KeyCode::Char('6'), ActivateTab(5...
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn use_default_configuration() {\n\n CONFIG.use_defaults();\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 0, "score": 314081.53445833473 }, { "content": "fn default_term() -> String {\n\n \"xterm-256color\".into()\n\n}\n\n\n", "file...
Rust
src/console.rs
osenft/libtock-rs
55e498a4342ef7a56d1e78ac2d434a0c0e5f410d
use crate::callback::Identity0Consumer; use crate::executor; use crate::futures; use crate::result::TockResult; use crate::syscalls; use core::cell::Cell; use core::fmt; use core::fmt::Write; use core::mem; static mut CONSOLE: Option<Console> = None; const DRIVER_NUMBER: usize = 1; mod command_nr { pub const WRI...
use crate::callback::Identity0Consumer; use crate::executor; use crate::futures; use crate::result::TockResult; use crate::syscalls; use core::cell::Cell; use core::fmt; use core::fmt::Write; use core::mem; static mut CONSOLE: Option<Console> = None; const DRIVER_NUMBER: usize = 1; mod command_nr { pub const WRI...
impl Console { pub fn write<S: AsRef<[u8]>>(&mut self, text: S) -> TockResult<()> { let mut not_written_yet = text.as_ref(); while !not_written_yet.is_empty() { let num_bytes_to_print = self.allow_buffer.len().min(not_written_yet.len()); self.allow_buffer[..num_bytes_to_pri...
b fn get_global_console() -> Option<Console> { unsafe { if let Some(con) = CONSOLE.take() { Some(con) } else { MISSED_PRINT = true; None } } }
function_block-function_prefixed
[ { "content": "fn write_as_hex(buffer: &mut [u8], value: usize) {\n\n write_formatted(buffer, value, 0x10_00_00_00, 0x10);\n\n}\n\n\n", "file_path": "src/debug/mod.rs", "rank": 0, "score": 260874.68899420756 }, { "content": "fn hex(mut n: usize, buf: &mut [u8]) -> usize {\n\n let mut i ...
Rust
src/run/parser/portal2_live_timer.rs
AntyMew/livesplit-core
b59a45ddd85c914121d279df38ad5b0e581bd512
use std::io::{self, BufRead}; use std::result::Result as StdResult; use std::num::ParseFloatError; use {GameTime, Run, Segment, TimeSpan}; quick_error! { #[derive(Debug)] pub enum Error { ExpectedMap {} ExpectedMapName {} ExpectedDifferentMapName {...
use std::io::{self, BufRead}; use std::result::Result as StdResult; use std::num::ParseFloatError; use {GameTime, Run, Segment, TimeSpan}; quick_error! { #[derive(Debug)] pub enum Error { ExpectedMap {} ExpectedMapName {} ExpectedDifferentMapName {...
plits.next().ok_or(Error::ExpectedMapName)?; if map_name != map { return Err(Error::ExpectedDifferentMapName); } let start_ticks: f64 = splits.next().ok_or(Error::ExpectedStartTicks)?.parse()?; let end_ticks: f64 = splits.next().ok_or(Error::ExpectedEndTic...
function_block-function_prefixed
[ { "content": "/// Attempts to parse a ShitSplit splits file.\n\npub fn parse<R: BufRead>(source: R) -> Result<Run> {\n\n let mut run = Run::new();\n\n\n\n let mut lines = source.lines();\n\n\n\n let line = lines.next().ok_or(Error::Empty)??;\n\n let mut splits = line.split('|');\n\n let category_...
Rust
warcio/src/record.rs
tari/warcdedupe
e33747e0804965837223c7bc2bca837bf8710aec
use std::cmp; use std::error::Error as StdError; use std::fmt; use std::io::prelude::*; use std::io::Error as IoError; use std::ops::Drop; use buf_redux::BufReader; pub use buf_redux::Buffer; use thiserror::Error; use crate::compression::{self, Compression}; use crate::header::get_record_header; use crate::{FieldNam...
use std::cmp; use std::error::Error as StdError; use std::fmt; use std::io::prelude::*; use std::io::Error as IoError; use std::ops::Drop; use buf_redux::BufReader; pub use buf_redux::Buffer; use thiserror::Error; use crate::compression::{self, Compression}; use crate::header::get_record_header; use crate::{FieldNam...
; } Some(n) => n, }; let record = Record { content_length: len, bytes_remaining: len, header, input, debug_info: DebugInfo::new(), }; Ok(record) } #[allow(clippy::len_without_is_empty)] ...
Err(InvalidRecord::UnknownLength( header .get_field_bytes("Content-Length") .map(|bytes| bytes.to_vec()), ))
call_expression
[ { "content": "fn run_with_progress<R: std::io::BufRead + std::io::Seek, D, L, W>(\n\n enable: bool,\n\n mut deduplicator: Deduplicator<D, L, W>,\n\n mut input: R,\n\n input_compression: Compression,\n\n) -> Result<(u64, u64), ProcessError>\n\nwhere\n\n R: std::io::BufRead + std::io::Seek,\n\n ...
Rust
contracts/q_native/src/contract/handler/token.rs
quasar-protocol/quasar-cosmwasm
3849c83f2057998637c2c32bcebfe535fd47d4a3
use cosmwasm_std::{ log, Api, Binary, CanonicalAddr, Env, Extern, HandleResponse, HumanAddr, InitResponse, Querier, ReadonlyStorage, StdError, StdResult, Storage, Uint128, }; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use crate::state::{ bytes_to_u128, get_allowance, get_balance, set...
use cosmwasm_std::{ log, Api, Binary, CanonicalAddr, Env, Extern, HandleResponse, HumanAddr, InitResponse, Querier, ReadonlyStorage, StdError, StdResult, Storage, Uint128, }; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use crate::state::{ bytes_to_u128, get_allowance, get_balance, set...
nce.to_be_bytes()); Ok(()) } pub fn mint_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; ...
from: &CanonicalAddr, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut from_balance = to_u128(&balances_store, from.as_slice())?; if from_balance < amount { return Err(StdError::generic_err(format!( ...
function_block-random_span
[ { "content": "fn accrue_interest<S: Storage, A: Api, Q: Querier>(deps: &mut Extern<S, A, Q>, env: Env) -> StdResult<()> {\n\n let prior_state = get_state(&deps.storage)?;\n\n\n\n let borrow_rate = get_borrow_rate(&prior_state.cash, &prior_state.total_borrows, &prior_state.total_reserves);\n\n\n\n if b...
Rust
nfe/src/base/totais.rs
fernandobatels/fiscal-rs
9c5856907dd1c4429dc256a41914676fc0cc5a70
use super::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; #[derive(Debug, PartialEq, Clone)] pub struct Totalizacao { pub valor_base_calculo: f32, pub valor_icms: f32, pub valor_produtos: f32, pub valor_frete: f32, pub valor_s...
use super::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; #[derive(Debug, PartialEq, Clone)] pub struct Totalizacao { pub valor_base_calculo: f32, pub valor_icms: f32, pub valor_produtos: f32, pub valor_frete: f32, pub valor_s...
} impl<'de> Deserialize<'de> for Totalizacao { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let helper = TotalContainer::deserialize(deserializer)?; Ok(Totalizacao { valor_base_calculo: helper.icms.valor_base_calculo, ...
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let icms = IcmsTot { valor_base_calculo: self.valor_base_calculo, valor_icms: self.valor_icms, valor_produtos: self.valor_produtos, valor_frete: self.valor_fret...
function_block-full_function
[ { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = \"<transp><modFrete>9</modFrete></transp>\".to_string();\n\n xml_original.retain(|c| c != '\\n' && c != ' ');\n\n\n\n let transporte = xml_original.parse::<Transporte>()?;\n\n let xml_novo = transporte.to_strin...
Rust
src/exmo/mod.rs
terrybrashaw/ni_ce
cf3c2c71a78a567eab8e387d716a15b913bd92c2
use failure::{Error, ResultExt}; use hex; use hmac::{Hmac, Mac}; use http; use rust_decimal::Decimal as d128; use serde::de::DeserializeOwned; use serde::de::{Deserialize, Deserializer, Visitor}; use serde; use serde_json; use sha2::Sha512; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use st...
use failure::{Error, ResultExt}; use hex; use hmac::{Hmac, Mac}; use http; use rust_decimal::Decimal as d128; use serde::de::DeserializeOwned; use serde::de::{Deserialize, Deserializer, Visitor}; use serde; use serde_json; use sha2::Sha512; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use st...
pub fn place_limit_order<Client>( client: &mut Client, host: &str, credential: &Credential, product: &CurrencyPair, price: d128, quantity: d128, side: Side, ) -> Result<(), Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(5); que...
pub fn get_user_info<Client>( client: &mut Client, host: &str, credential: &Credential, ) -> Result<UserInfo, Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(2); query.append_param("nonce", credential.nonce.to_string()); query.to_string()...
function_block-full_function
[ { "content": "fn private_signature(credential: &Credential, query: &str) -> Result<String, Error> {\n\n let mut mac =\n\n Hmac::<Sha256>::new(credential.secret.as_bytes()).map_err(|e| format_err!(\"{:?}\", e))?;\n\n mac.input(query.as_bytes());\n\n Ok(hex::encode(mac.result().code().to_vec()))\n...
Rust
src/utils.rs
ripe-tech/pconvert-rust
cf9ffcfc59d5838cf4d74a2c6c666e3f94f7cdc3
use crate::blending::demultiply_image; use crate::errors::PConvertError; use image::codecs::png::{CompressionType, FilterType, PngDecoder, PngEncoder}; use image::ImageDecoder; use image::{ColorType, ImageBuffer, Rgba}; use std::fs::File; use std::io::{BufWriter, Read, Write}; pub fn decode_png( readable_stream:...
use crate::blending::demultiply_image; use crate::errors::PConvertError; use image::codecs::png::{CompressionType, FilterType, PngDecoder, PngEncoder}; use image::ImageDecoder; use image::{ColorType, ImageBuffer, Rgba}; use std::fs::File; use std::io::{BufWriter, Read, Write}; pub fn decode_png( readable_stream:...
pub fn image_compression_from(compression: String) -> CompressionType { match compression.trim().to_lowercase().as_str() { "best" => CompressionType::Best, "default" => CompressionType::Default, "fast" => CompressionType::Fast, "huffman" => CompressionType::Huffman, "rle" =...
pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { write_png_to_file(file_out, png, compression, filter) }
function_block-full_function
[ { "content": "/// Demultiplies an image buffer, by applying the demultiply operation over the\n\n/// complete set of pixels in the provided image buffer.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `img` - The image buffer to demultiply.\n\npub fn demultiply_image(img: &mut ImageBuffer<Rgba<u8>, Vec<u8>>) {\n\n ...