lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/directory/error.rs
pentlander/tantivy
0e8fcd57274e4276186f8fc32e46f9e9dccdc088
use std::error::Error as StdError; use std::fmt; use std::io; use std::path::PathBuf; #[derive(Debug)] pub struct IOError { path: Option<PathBuf>, err: io::Error, } impl fmt::Display for IOError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.path { Some(ref path) =...
use std::error::Error as StdError; use std::fmt; use std::io; use std::path::PathBuf; #[derive(Debug)] pub struct IOError { path: Option<PathBuf>, err: io::Error, } impl fmt::Display for IOError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.path { Some(ref path) =...
} #[derive(Debug)] pub enum OpenReadError { FileDoesNotExist(PathBuf), IOError(IOError), } impl From<IOError> for OpenReadError { fn from(err: IOError) -> OpenReadError { OpenReadError::IOError(err) } } impl fmt::Display for OpenReadError { fn fmt(&self, f: &mut fmt::Forma...
fn cause(&self) -> Option<&StdError> { match *self { OpenWriteError::FileAlreadyExists(_) => None, OpenWriteError::IOError(ref err) => Some(err), } }
function_block-full_function
[ { "content": "/// Write a `u32` as a vint payload.\n\npub fn write_u32_vint<W: io::Write>(val: u32, writer: &mut W) -> io::Result<()> {\n\n let (val, num_bytes) = serialize_vint_u32(val);\n\n let mut buffer = [0u8; 8];\n\n LittleEndian::write_u64(&mut buffer, val);\n\n writer.write_all(&buffer[..num...
Rust
src/content.rs
silvrwolfboy/hubcaps
f173a3be1e5135b389587afe355b49103a49f8d8
use std::fmt; use std::ops; use serde::Deserialize; use serde::de::{self, Visitor}; use crate::utils::{percent_encode, PATH}; use crate::{Future, Github, Stream}; pub struct Content { github: Github, owner: String, repo: String, } impl Content { #[doc(hidden)] pub fn new<O, R>(github: Github, o...
use std::fmt; use std::ops; use serde::Deserialize; use serde::de::{self, Visitor}; use crate::utils::{percent_encode, PATH}; use crate::{Future, Github, Stream}; pub struct Content { github: Github, owner: String, repo: String, } impl Content { #[doc(hidden)] pub fn new<O, R>(github: Github, o...
}
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct DecodedContentsVisitor; impl<'de> Visitor<'de> for DecodedContentsVisitor { type Value = DecodedContents; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> ...
function_block-full_function
[ { "content": "fn var(name: &str) -> Result<String> {\n\n if let Some(v) = env::var(name).ok() {\n\n Ok(v)\n\n } else {\n\n Err(format!(\"example missing {}\", name).into())\n\n }\n\n}\n\n\n\nconst USER_AGENT: &str = concat!(env!(\"CARGO_PKG_NAME\"), \"/\", env!(\"CARGO_PKG_VERSION\"));\n\...
Rust
lib/engine/src/window/input.rs
OrangeBacon/opengl-rust
842354c929db9d60b73fb54781420d41f8e99f23
use std::collections::HashMap; use super::scancode::Scancode; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum KeyState { None, Down, Hold, Up, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)] pub struct MouseState { ...
use std::collections::HashMap; use super::scancode::Scancode; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum KeyState { None, Down, Hold, Up, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)] pub struct MouseState { ...
pub fn mouse_position(&self) -> (i32, i32) { (self.mouse.x, self.mouse.y) } pub(crate) fn set_mouse_position(&mut self, x: i32, y: i32) { self.mouse.x = x; self.mouse.y = y; } pub fn mouse_delta(&self) -> (i32, i32) { (self.mouse.delta_x, self.mouse...
pub fn is_key_pressed(&self, key: Scancode) -> bool { let key = *self.keys.get(&key).unwrap_or(&KeyState::None); if key == KeyState::Down || key == KeyState::Hold { true } else { false } }
function_block-full_function
[ { "content": "fn default_event_handler(state: &mut EngineState, event: &Event) -> EventResult {\n\n match event {\n\n Event::Quit { .. } => return EventResult::Exit,\n\n Event::KeyDown { key, .. } => {\n\n state.inputs.set_key_state(*key, KeyState::Down);\n\n }\n\n Even...
Rust
delivery-service/ds-lib/src/lib.rs
greydot/openmls
fca1cbd3400d377dae06ef9ceebda5e0392c6c89
use openmls::{framing::VerifiableMlsPlaintext, prelude::*}; use tls_codec::{ Size, TlsByteSliceU16, TlsByteVecU16, TlsByteVecU32, TlsByteVecU8, TlsDeserialize, TlsSerialize, TlsSize, TlsVecU32, }; #[derive(Debug, Default, Clone)] pub struct ClientInfo<'a> { pub client_name: String, pub key_packages: ...
use openmls::{framing::VerifiableMlsPlaintext, prelude::*}; use tls_codec::{ Size, TlsByteSliceU16, TlsByteVecU16, TlsByteVecU32, TlsByteVecU8, TlsDeserialize, TlsSerialize, TlsSize, TlsVecU32, }; #[derive(Debug, Default, Clone)] pub struct ClientInfo<'a> { pub client_name: String, pub key_packages: ...
(bytes)?, )), MessageType::Welcome => Message::Welcome(Welcome::tls_deserialize(bytes)?), }) } } impl<'a> tls_codec::Size for GroupMessage<'a> { fn tls_serialized_len(&self) -> usize { MessageType::MlsCiphertext.tls_serialized_len() + match &self.msg { ...
rialize for ClientInfo<'a> { fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> { let client_name = String::from_utf8_lossy(TlsByteVecU16::tls_deserialize(bytes)?.as_slice()).into(); let mut key_packages: Vec<(TlsByteVecU8, KeyPackage)> = Tl...
random
[ { "content": "pub fn post(url: &Url, msg: &impl Serialize) -> Result<Vec<u8>, String> {\n\n let serialized_msg = msg.tls_serialize_detached().unwrap();\n\n log::debug!(\"Post {:?}\", url);\n\n log::trace!(\"Payload: {:?}\", serialized_msg);\n\n let client = Client::new();\n\n let response = clien...
Rust
compiler/crates/graphql-ir/src/transform.rs
nathalia234/relay
e1435c834383927947d2f38d32948305ed3baed9
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::ir::*; use common::Spanned; use std::sync::Arc; pub trait Transformer { const NAME: &'static str; const VISIT_A...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::ir::*; use common::Spanned; use std::sync::Arc; pub trait Transformer { const NAME: &'static str; const VISIT_A...
fn transform_operation( &mut self, operation: &OperationDefinition, ) -> Transformed<OperationDefinition> { self.default_transform_operation(operation) } fn default_transform_operation( &mut self, operation: &OperationDefinition, ) -> Transformed<Opera...
directives: directives.unwrap_or_else(|| fragment.directives.clone()), selections: selections.unwrap_or_else(|| fragment.selections.clone()), ..fragment.clone() }) }
function_block-function_prefix_line
[ { "content": "pub fn parse(source: &str, file: &str) -> SyntaxResult<Document> {\n\n let parser = Parser::new(source, file);\n\n parser.parse_document()\n\n}\n\n\n", "file_path": "compiler/crates/graphql-syntax/src/lib.rs", "rank": 0, "score": 324088.214504415 }, { "content": "pub fn p...
Rust
crush/src/soc/bdd/differential/post_processing.rs
Simula-UiB/CRHS
8f3dd34c8b99680188d9314c6897e0c790f5358f
use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use vob::Vob; use crate::soc::bdd::Bdd; use crate::soc::system::System; use super::dependency_finder::DepPathFinder; #[allow(unused_variables, dead_code)] pub struct PostProcessing { soc: System, step: usize, active_area: ...
use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use vob::Vob; use crate::soc::bdd::Bdd; use crate::soc::system::System; use super::dependency_finder::DepPathFinder; #[allow(unused_variables, dead_code)] pub struct PostProcessing { soc: System, step: usize, active_area: ...
fn bools_to_u8(bits: &Vec<bool>) -> Vec<u8>{ let b = bits.chunks(8) .map(|v| { v.iter().enumerate() .fold(0u8, |acc, (idx, x)| { acc | ((*x as u8) << idx)} ) }) .collect(); ...
fn u8s_to_hex_separated(bytes: &[u8] ) -> String { let bytes_rev: Vec<u8> = bytes.into_iter().rev().cloned().collect(); let mut s = String::new(); for four_bytes in bytes_rev.chunks(4) { println!("Four bytes: {:?}", four_bytes); for byte in four_bytes.iter(){ ...
function_block-full_function
[ { "content": "/// From a `BddSpec` and a `nvar` build a `Bdd` following the specifications.\n\n/// \n\n/// We create an empty `Bdd`, set its `id` according to the spec then create all the levels\n\n/// (removing the `-1` from the `lhs` beforehand) without connecting the nodes.\n\n/// \n\n/// Once all the level ...
Rust
examples/aes/ta/src/main.rs
mathias-arm/rust-optee-trustzone-sdk
a1954b8a95dd77e396fb86e21dea2dec3fa5d9a4
#![no_main] use optee_utee::{ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, }; use optee_utee::{AlgorithmId, Cipher, OperationMode}; use optee_utee::{AttributeId, AttributeMemref, TransientObject, TransientObjectType}; use optee_utee::{Error, ErrorKind, Parameters, Res...
#![no_main] use optee_utee::{ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, }; use optee_utee::{AlgorithmId, Cipher, OperationMode}; use optee_utee::{AttributeId, AttributeMemref, TransientObject, TransientObjectType}; use optee_utee::{Error, ErrorKind, Parameters, Res...
const TA_FLAGS: u32 = 0; const TA_STACK_SIZE: u32 = 2 * 1024; const TA_DATA_SIZE: u32 = 1 * 1024 * 1024; const TA_VERSION: &[u8] = b"Undefined version\0"; const TA_DESCRIPTION: &[u8] = b"This is an AES example\0"; const EXT_PROP_VALUE_1: &[u8] = b"AES TA\0"; const EXT_PROP_VALUE_2: u32 = 0x0010; const TRACE_LEVEL: i3...
pub fn cipher_buffer(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let mut param0 = unsafe { params.0.as_memref().unwrap() }; let mut param1 = unsafe { params.1.as_memref().unwrap() }; let input = param0.buffer(); let output = param1.buffer(); if output.len() < input.len() { ...
function_block-full_function
[ { "content": "#[ta_invoke_command]\n\nfn invoke_command(sess_ctx: &mut RsaCipher, cmd_id: u32, params: &mut Parameters) -> Result<()> {\n\n trace_println!(\"[+] TA invoke command\");\n\n match Command::from(cmd_id) {\n\n Command::GenKey => gen_key(sess_ctx, params),\n\n Command::GetSize => g...
Rust
crates/prost/tests/src/build.rs
Zha0Chan/crates-sgx
73dc6d9e130757d9e585ee757b3d94d5078512a9
#[macro_use] extern crate cfg_if; cfg_if! { if #[cfg(feature = "edition-2015")] { extern crate env_logger; extern crate prost_build; } } use std::env; use std::fs; use std::path::PathBuf; fn main() { env_logger::init(); let src = PathBuf::from("../tests/src"); let inclu...
#[macro_use] extern crate cfg_if; cfg_if! { if #[cfg(feature = "edition-2015")] { extern crate env_logger; extern crate prost_build; } } use std::env; use std::fs; use std::path::PathBuf;
fn main() { env_logger::init(); let src = PathBuf::from("../tests/src"); let includes = &[src.clone()]; let mut config = prost_build::Config::new(); config.btree_map(&["."]); config.type_attribute("Foo.Bar_Baz.Foo_barBaz", "#[derive(Eq, PartialOrd, Ord)]"); ...
function_block-full_function
[]
Rust
src/double/div.rs
pwnorbitals/qd
2e4b3234d80adc90199bfd6496778e81568318a3
use crate::common::primitive as p; use crate::common::utils as u; use crate::double::Double; use std::ops::{Div, DivAssign}; #[inline] fn mul_f64(a: Double, b: f64) -> Double { let (p, e) = p::two_prod(a.0, b); let (a, b) = u::renorm2(p, e + a.1 * b); Double(a, b) } #[allow(clippy::suspicious_arithmetic...
use crate::common::primitive as p; use crate::common::utils as u; use crate::double::Double; use std::ops::{Div, DivAssign}; #[inline] fn mul_f64(a: Double, b: f64) -> Double { let (p, e) = p::two_prod(a.0, b); let (a, b) = u::renorm2(p, e + a.1 * b); Double(a, b) } #[allow(clippy::suspicious_arithmetic...
} impl Div for &Double { type Output = Double; fn div(self, other: &Double) -> Double { (*self).div(*other) } } impl Div<&Double> for Double { type Output = Double; ...
None => { let q1 = self.0 / other.0; let mut r = self - mul_f64(other, q1); let q2 = r.0 / other.0; r -= mul_f64(other, q2); let q3 = r.0 / other.0; let (a, b) = u::renorm3(q1, q2, q3); Double(a, b) ...
function_block-function_prefix_line
[ { "content": "#[inline]\n\nfn mul_f64(a: Quad, b: f64) -> Quad {\n\n let (h0, l0) = p::two_prod(a.0, b);\n\n let (h1, l1) = p::two_prod(a.1, b);\n\n let (h2, l2) = p::two_prod(a.2, b);\n\n let h3 = a.3 * b;\n\n\n\n let s0 = h0;\n\n let (s1, t0) = p::two_sum(h1, l0);\n\n let (s2, t1, t2) = u...
Rust
rs/orchestrator/src/error.rs
Deland-Labs/ic
047172b01e0afc0e61448669d4ec98b2425c6853
use ic_http_utils::file_downloader::FileDownloadError; use ic_types::replica_version::ReplicaVersionParseError; use ic_types::{registry::RegistryClientError, NodeId, RegistryVersion, ReplicaVersion, SubnetId}; use std::error::Error; use std::fmt; use std::io; use std::path::{Path, PathBuf}; use std::process::Command; ...
use ic_http_utils::file_downloader::FileDownloadError; use ic_types::replica_version::ReplicaVersionParseError; use ic_types::{registry::RegistryClientError, NodeId, RegistryVersion, ReplicaVersion, SubnetId}; use std::error::Error; use std::fmt; use std::io; use std::path::{Path, PathBuf}; use std::process::Command; ...
} impl From<FileDownloadError> for OrchestratorError { fn from(e: FileDownloadError) -> Self { OrchestratorError::FileDownloadError(e) } } impl Error for OrchestratorError {}
OrchestratorError::ReplicaVersionParseError(e) => { write!(f, "Failed to parse replica version: {}", e) } OrchestratorError::MakeRegistryCupError(subnet_id, registry_version) => write!( f, "Failed to construct the genesis/recovery CUP, subnet_id: {...
function_block-function_prefix_line
[ { "content": "fn some_checkpoint_dir(backup_dir: &Path, subnet_id: &SubnetId) -> Option<PathBuf> {\n\n let dir = backup_dir\n\n .join(\"data\")\n\n .join(subnet_id.to_string())\n\n .join(\"ic_state\");\n\n if !dir.exists() {\n\n return None;\n\n }\n\n let lcp = last_check...
Rust
core/src/avm2/object/dictionary_object.rs
threeoh6000/ruffle
7df5370ec1b9519f30df9a67cfafe8b41db6b116
use crate::avm2::activation::Activation; use crate::avm2::object::script_object::ScriptObjectData; use crate::avm2::object::{ClassObject, Object, ObjectPtr, TObject}; use crate::avm2::value::Value; use crate::avm2::Error; use fnv::FnvHashMap; use gc_arena::{Collect, GcCell, MutationContext}; use std::cell::{Ref, RefM...
use crate::avm2::activation::Activation; use crate::avm2::object::script_object::ScriptObjectData; use crate::avm2::object::{ClassObject, Object, ObjectPtr, TObject}; use crate::avm2::value::Value; use crate::avm2::Error; use fnv::FnvHashMap; use gc_arena::{Collect, GcCell, MutationContext}; use std::cell::{Ref, RefM...
pub fn set_property_by_object( self, name: Object<'gc>, value: Value<'gc>, mc: MutationContext<'gc, '_>, ) { self.0.write(mc).object_space.insert(name, value); } pub fn delete_property_by_object(self, name: Object<'gc>, mc: MutationContext<'gc, '_>) {...
0 .read() .object_space .get(&name) .cloned() .unwrap_or(Value::Undefined) }
function_block-function_prefixed
[ { "content": "pub fn root_error_handler<'gc>(activation: &mut Activation<'_, 'gc, '_>, error: Error<'gc>) {\n\n match &error {\n\n Error::ThrownValue(value) => {\n\n let message = value\n\n .coerce_to_string(activation)\n\n .unwrap_or_else(|_| \"undefined\".int...
Rust
src/stage/ast/mod.rs
ncatelli/mossy
25211cc1e871dfe8d06d0a04d23271a321870fdc
macro_rules! generate_type_specifier { (integer, $sign:expr, $width:expr) => { $crate::stage::ast::Type::Integer($sign, $width) }; (char) => { generate_type_specifier!(i8) }; (ptr => $ty:expr) => { $crate::stage::ast::Type::Pointer(Box::new($ty)) }; (i8) => { ...
macro_rules! generate_type_specifier { (integer, $sign:expr, $width:expr) => { $crate::stage::ast::Type::Integer($sign, $width) }; (char) => { generate_type_specifier!(i8) }; (ptr => $ty:expr) => { $crate::stage::ast::Type::Pointer(Box::new($ty)) }; (i8) => { ...
} #[derive(Debug, Clone, PartialEq, Eq)] pub struct FuncProto { pub return_type: Box<Type>, pub args: Vec<Type>, } impl FuncProto { pub fn new(return_type: Box<Type>, args: Vec<Type>) -> Self { Self { return_type, args } } } const POINTER_BYTE_WIDTH: usize = (usize::BITS / 8) as usize; #[de...
fn size(&self) -> usize { match self { Self::Eight => 1, Self::Sixteen => 2, Self::ThirtyTwo => 4, Self::SixtyFour => 8, } }
function_block-full_function
[ { "content": "fn type_declarator<'a>() -> impl parcel::Parser<'a, &'a [(usize, char)], Type> {\n\n whitespace_wrapped(\n\n parcel::join(\n\n type_specifier(),\n\n whitespace_wrapped(expect_character('*').one_or_more()),\n\n )\n\n .map(|(ty, pointer_depth)| {\n\n ...
Rust
src/fileoperation.rs
DrStiev/rs-handlegfa
89c59bb1e6b0b2aad23061ab894b958467a14ae3
use gfa2::gfa1::GFA; use gfa2::gfa2::GFA2; use handlegraph2::hashgraph::HashGraph; use bstr::BString; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn save_as_gfa2_file(graph: &HashGraph, path: Option<String>) -> Result<(), std::io::Error> { use handlegraph2::conversion; let path = ...
use gfa2::gfa1::GFA; use gfa2::gfa2::GFA2; use handlegraph2::hashgraph::HashGraph; use bstr::BString; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn save_as_gfa2_file(graph: &HashGraph, path: Option<String>) -> Result<(), std::io::Error> { use handlegraph2::conversion; let path = ...
#[test] fn can_use_file_gfa2_saved() { use gfa2::{parser_gfa2::GFA2Parser, tag::OptionalFields}; let parser: GFA2Parser<bstr::BString, OptionalFields> = GFA2Parser::new(); let gfa2: GFA2<BString, OptionalFields> = parser .parse_file("./tests/output_files/file_gfa2.gfa2") ...
graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1);...
function_block-function_prefixed
[ { "content": "/// Function that reads a ```GFA1``` files passed as input and return its\n\n/// corresponding ```HandleGraph```\n\npub fn gfa1_to_handlegraph(path: String) -> Result<HashGraph, GraphOperationError> {\n\n use gfa2::{gfa1::GFA, parser_gfa1::GFAParser};\n\n\n\n let parser: GFAParser<usize, ()>...
Rust
rust/src/checkpoints.rs
rdettai/delta-rs
f1f9782196e3f3420399b44377acd153a3d0d7cf
use arrow::datatypes::Schema as ArrowSchema; use arrow::error::ArrowError; use arrow::json::reader::Decoder; use log::*; use parquet::arrow::ArrowWriter; use parquet::errors::ParquetError; use parquet::file::writer::InMemoryWriteableCursor; use std::convert::TryFrom; use super::action; use super::delta_arrow::delta_...
use arrow::datatypes::Schema as ArrowSchema; use arrow::error::ArrowError; use arrow::json::reader::Decoder; use log::*; use parquet::arrow::ArrowWriter; use parquet::errors::ParquetError; use parquet::file::writer::InMemoryWriteableCursor; use std::convert::TryFrom; use super::action; use super::delta_arrow::delta_...
fn parquet_bytes_from_state( &self, state: &DeltaTableState, ) -> Result<Vec<u8>, CheckPointWriterError> { let current_metadata = state .current_metadata() .ok_or(CheckPointWriterError::MissingMetaData)?; let mut jsons = std::iter::once(action::Action::...
pub async fn create_checkpoint_from_state( &self, version: DeltaDataTypeVersion, state: &DeltaTableState, ) -> Result<(), CheckPointWriterError> { info!("Writing parquet bytes to checkpoint buffer."); let parquet_bytes = self.parquet_bytes_from_sta...
function_block-full_function
[ { "content": "#[inline]\n\npub fn get_version() -> Result<Version, String> {\n\n imp::get_version()\n\n}\n", "file_path": "glibc_version/src/lib.rs", "rank": 0, "score": 266271.3643664542 }, { "content": "#[inline]\n\npub fn atomic_rename(from: &str, to: &str) -> Result<(), StorageError> ...
Rust
kernel/src/net/netmapping.rs
lqd/chocolate_milk
ad7fc8f99721d70c06d825a30d8ecfd82263c5fd
use core::ops::{Deref, DerefMut}; use core::alloc::Layout; use core::convert::TryInto; use alloc::boxed::Box; use alloc::borrow::Cow; use noodle::*; use falktp::ServerMessage; use page_table::{VirtAddr, PageType, PhysMem}; use page_table::{PAGE_NX, PAGE_WRITE, PAGE_PRESENT}; use lockcell::LockCell; use crate::core_lo...
use core::ops::{Deref, DerefMut}; use core::alloc::Layout; use core::convert::TryInto; use alloc::boxed::Box; use alloc::borrow::Cow; use noodle::*; use falktp::ServerMessage; use page_table::{VirtAddr, PageType, PhysMem}; use page_table::{PAGE_NX, PAGE_WRITE, PAGE_PRESENT}; use lockcell::LockCell; use crate::core_lo...
} } impl<'a> Deref for NetMapping<'a> { type Target = [u8]; fn deref(&self) -> &Self::Target { self.backing } } impl<'a> DerefMut for NetMapping<'a> { fn deref_mut(&mut self) -> &mut Self::Target { assert!(!self.read_only, "Attempted write access to read-only netwo...
Some(NetMapping { backing: unsafe { core::slice::from_raw_parts_mut(virt_addr.0 as *mut u8, size.try_into().ok()?) }, _fault_reg: register_fault_handler(handler), read_only, })
call_expression
[ { "content": "/// Download a file with the `filename` over TFTP with the PXE 16-bit API\n\npub fn download<P: AsRef<[u8]>>(filename: P) -> Option<Vec<u8>> {\n\n // Lock access to PXE\n\n let _guard = PXE_GUARD.lock();\n\n\n\n // Convert the filename to a slice of bytes\n\n let filename: &[u8] = file...
Rust
roapi-http/tests/helpers.rs
zemelLeong/roapi
3ace6078fa9b31cde12e367caf88ca31938c00cb
use std::path::PathBuf; use columnq::datafusion::arrow; use columnq::table::{KeyValueSource, TableColumn, TableLoadOption, TableSchema, TableSource}; use roapi_http::config::Config; use roapi_http::startup::Application; pub fn test_data_path(relative_path: &str) -> String { let mut d = PathBuf::from(env!("CARGO_M...
use std::path::PathBuf; use columnq::datafusion::arrow; use columnq::table::{KeyValueSource, TableColumn, TableLoadOption, TableSchema, TableSource}; use roapi_http::config::Config; use roapi_http::startup::Application; pub fn test_data_path(relative_path: &str) -> String { let mut d = PathBuf::from(env!("CARGO_M...
pub fn get_spacex_launch_name_kvstore() -> KeyValueSource { KeyValueSource::new( "spacex_launch_name", test_data_path("spacex_launches.json"), "id", "name", ) }
function_block-full_function
[ { "content": "pub fn column_sort_expr_asc(column: impl Into<String>) -> Expr {\n\n Expr::Sort {\n\n expr: Box::new(Expr::Column(Column::from_name(column))),\n\n asc: true,\n\n nulls_first: true,\n\n }\n\n}\n\n\n\npub mod graphql;\n\npub mod rest;\n\npub mod sql;\n", "file_path": "...
Rust
src/testdrive/src/action/verify_timestamp_compaction.rs
ruchirK/materialize
94a022c1bca35726b0b1efa7516200a41d4a12d9
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; use coord::catalog::Catalog; use coord::session::Session; use ore::now::NOW_ZERO; use ore::result::ResultExt; use ore::retry::Retry; use sql::catalog::SessionCatalog; use sql::names::PartialName;...
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; use coord::catalog::Catalog; use coord::session::Session; use ore::now::NOW_ZERO; use ore::result::ResultExt; use ore::retry::Retry; use sql::catalog::SessionCatalog; use sql::names::PartialName;...
cmd.args.done()?; Ok(VerifyTimestampsAction { source, max_size, permit_progress, }) } #[async_trait] impl Action for VerifyTimestampsAction { async fn undo(&self, _: &mut State) -> Result<(), String> { Ok(()) } async fn redo(&self, state: &mut State) -...
let permit_progress = cmd .args .opt_bool("permit-progress") .expect("require valid bool if specified") .unwrap_or(false);
assignment_statement
[ { "content": "pub fn build_compression(cmd: &mut BuiltinCommand) -> Result<Compression, String> {\n\n match cmd.args.opt_string(\"compression\") {\n\n Some(s) => s.parse(),\n\n None => Ok(Compression::None),\n\n }\n\n}\n\n\n", "file_path": "src/testdrive/src/action/file.rs", "rank": ...
Rust
gtk4/src/auto/icon_theme.rs
haecker-felix/gtk4-rs
f225c9f2d1b4f563aafb0c54581b8e8cafd5807c
use crate::IconLookupFlags; use crate::IconPaintable; use crate::TextDirection; use glib::object::Cast; use glib::object::IsA; use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::ToValue; use std::boxed:...
use crate::IconLookupFlags; use crate::IconPaintable; use crate::TextDirection; use glib::object::Cast; use glib::object::IsA; use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::ToValue; use std::boxed:...
b_full(ffi::gtk_icon_theme_lookup_icon( self.to_glib_none().0, icon_name.to_glib_none().0, fallbacks.to_glib_none().0, size, scale, direction.to_glib(), flags.to_glib(), )) } } #[...
_theme_name(self.to_glib_none().0)) } } #[doc(alias = "gtk_icon_theme_has_icon")] pub fn has_icon(&self, icon_name: &str) -> bool { unsafe { from_glib(ffi::gtk_icon_theme_has_icon( self.to_glib_none().0, icon_name.to_glib_none().0, )) ...
random
[]
Rust
src/utils.rs
drahnr/pyroscope-rs
c0a64b7b3d3b9a166bf3648ff3c53534a24d68b1
use crate::error::Result; use crate::PyroscopeError; use std::collections::HashMap; pub fn merge_tags_with_app_name( application_name: String, tags: HashMap<String, String>, ) -> Result<String> { let mut tags_vec = tags .into_iter() .filter(|(k, _)| k != "__name__") .map(|(k, v)| forma...
use crate::error::Result; use crate::PyroscopeError; use std::collections::HashMap; pub fn merge_tags_with_app_name( application_name: String, tags: HashMap<String, String>, ) -> Result<String> { let mut tags_vec = tags .into_iter() .filter(|(k, _)| k != "__name__") .map(|(k, v)| forma...
until: 1644194480, current: 1644194476, rem: 4, } ); } }
current: 1644194470, rem: 10, } ); assert_eq!( get_time_range(1644194476).unwrap(), TimeRange { from: 1644194470,
random
[ { "content": "fn fibonacci(n: u64) -> u64 {\n\n match n {\n\n 0 | 1 => 1,\n\n n => fibonacci(n - 1) + fibonacci(n - 2),\n\n }\n\n}\n\n\n", "file_path": "examples/tags.rs", "rank": 3, "score": 102153.85947132888 }, { "content": "fn fibonacci(n: u64) -> u64 {\n\n match n...
Rust
src/writer/file_writer.rs
cspinetta/jon-listen
89134524b67443d7620b11bb840dfb9dfe04d0f8
use std::fs::File; use std::io::prelude::*; use std::fs::OpenOptions; use std::thread::{self, JoinHandle}; use std::path::PathBuf; use std::fs; use std::time::Duration; use chrono::prelude::*; use std::borrow::BorrowMut; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use ::settings::FileWriterConfig; u...
use std::fs::File; use std::io::prelude::*; use std::fs::OpenOptions; use std::thread::{self, JoinHandle}; use std::path::PathBuf; use std::fs; use std::time::Duration; use chrono::prelude::*; use std::borrow::BorrowMut; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use ::settings::FileWriterConfig; u...
fn rotate(&mut self, new_path: PathBuf) -> Result<(), String> { fs::rename(self.file_path.clone(), new_path.clone()) .map_err(|e| format!("Failed trying to rename the file {:?} to {:?}. Reason: {}", self.file_path.clone(), new_path, e)) .and_then(|_| { let ending_ms...
fn open_file(filepath: &PathBuf, with_starting_msg: bool, keep_content: bool) -> Result<File, String> { let starting_msg = format!("Starting {} at {}\n", filepath.to_string_lossy(), Local::now().to_rfc2822()); info!("Opening file {:?}", filepath); info!("{}", starting_msg); let mut optio...
function_block-full_function
[ { "content": "fn extract_command_arg(args: &mut Vec<String>, names: Vec<String>) -> bool {\n\n match args.iter().position(|a| names.contains(a)) {\n\n Some(i) => {\n\n args.remove(i);\n\n true\n\n }\n\n None => false,\n\n }\n\n}\n\n\n\nmod tcp {\n\n use std::i...
Rust
src/connection/info.rs
bayne/libpq.rs
124f73ac438fd542f933e94499550b1158b8d38e
#[derive(Clone, Debug, PartialEq)] pub struct Info { pub keyword: String, pub envvar: Option<String>, pub compiled: Option<String>, pub val: Option<String>, pub label: Option<String>, pub dispchar: String, pub dispsize: i32, } impl Info { /** * Returns the default connection option...
#[derive(Clone, Debug, PartialEq)] pub struct Info { pub keyword: String, pub envvar: Option<String>, pub compiled: Option<String>, pub val: Option<String>, pub label: Option<String>, pub dispchar: String, pub dispsize: i32, } impl Info { /** * Returns the default connection option...
} impl Default for Info { fn default() -> Self { unsafe { let raw = pq_sys::PQconndefaults(); let info = raw.into(); pq_sys::PQconninfoFree(raw); info } } } #[doc(hidden)] impl From<*mut pq_sys::_PQconninfoOption> for Info { fn from(info: *...
l() { break; } else { let info = raw.offset(x).into(); vec.push(info); } } } vec }
function_block-function_prefixed
[ { "content": "#[deprecated(note = \"Use libpq::Connection::escape_string instead\")]\n\npub fn string(from: &str) -> String {\n\n let c_from = crate::ffi::to_cstr(from);\n\n // @see https://github.com/postgres/postgres/blob/REL_12_2/src/interfaces/libpq/fe-exec.c#L3329\n\n let cstring = crate::ffi::new...
Rust
simulator/src/sim/actions/yin_yang_magic.rs
rainbowbismuth/birb-brains-bot
f168ec06c5c5cc8d41589437c6f91f0d97289167
use crate::sim::actions::{Ability, AbilityImpl, Action, AoE, ALLY_OK, FOE_OK}; use crate::sim::common::{mod_6_formula, AddConditionSpellImpl, ConditionClearSpellImpl}; use crate::sim::{ Combatant, CombatantId, Condition, Element, Event, Simulation, Source, CAN_BE_CALCULATED, CAN_BE_REFLECTED, SILENCEABLE, }; p...
use crate::sim::actions::{Ability, AbilityImpl, Action, AoE, ALLY_OK, FOE_OK}; use crate::sim::common::{mod_6_formula, AddConditionSpellImpl, ConditionClearSpellImpl}; use crate::sim::{ Combatant, CombatantId, Condition, Element, Event, Simulation, Source, CAN_BE_CALCULATED, CAN_BE_REFLECTED, SILENCEABLE, }; p...
tyMissed(user_id, target_id)); return; } if self.hp_not_mp { let absorbed_amount = (target.max_hp() as f32 * self.amount) as i16; sim.change_target_hp(target_id, absorbed_amount, Source::Ability); sim.change_target_hp(user_id, -absorbed_amount, Source::Ab...
cal_evade(user, target, Source::Ability) { return; } let success_chance = mod_6_formula(user, target, Element::None, self.base_chance, false); if !(sim.roll_auto_succeed() < success_chance) { sim.log_event(Event::Abili
function_block-random_span
[ { "content": "pub fn in_range(user: &Combatant, range: u8, target: &Combatant) -> bool {\n\n let dist = user.distance(target);\n\n dist <= range as i16\n\n}\n\n\n", "file_path": "simulator/src/sim/simulation.rs", "rank": 0, "score": 452225.96033337904 }, { "content": "pub fn can_move_i...
Rust
src/kms/gcpkms.rs
stemid/roughenough
7bc4ea5d34fac53d33ff2ed53bb7a70a2c1aca93
#[cfg(feature = "gcpkms")] pub mod inner { extern crate base64; extern crate google_cloudkms1 as cloudkms1; extern crate hyper; extern crate hyper_rustls; extern crate yup_oauth2 as oauth2; use std::default::Default; use std::env; use std::path::Path; use std::result::Result; ...
#[cfg(feature = "gcpkms")] pub mod inner { extern crate base64; extern crate google_cloudkms1 as cloudkms1; extern crate hyper; extern crate hyper_rustls; extern crate yup_oauth2 as oauth2; use std::default::Default; use std::env; use std::path::Path; use std::result::Result; ...
} fn decrypt_dek(&self, encrypted_dek: &EncryptedDEK) -> Result<PlaintextDEK, KmsError> { let mut request = DecryptRequest::default(); request.ciphertext = Some(base64::encode(encrypted_dek)); request.additional_authenticated_data = Some(base64::encode(AD)); ...
match result { Ok((http_resp, enc_resp)) => { if http_resp.status == StatusCode::Ok { let ciphertext = enc_resp.ciphertext.unwrap(); let ct = base64::decode(&ciphertext)?; Ok(ct) } else { ...
if_condition
[ { "content": "/// Factory function to create a `ServerConfig` _trait object_ based on the value\n\n/// of the provided `arg`.\n\n///\n\n/// * `ENV` will return an [`EnvironmentConfig`](struct.EnvironmentConfig.html)\n\n/// * any other value returns a [`FileConfig`](struct.FileConfig.html)\n\n///\n\npub fn m...
Rust
embrs/src/stm32f4/rcc/mod.rs
DCasFer/RustSimpleScheduler
25cda9d5d9601a56296589861556e7c173fbff04
use arm_m; use arm_m::reg::AtomicReg; use super::flash::FLASH; pub mod raw; pub use self::raw::{AhbPrescaler, ApbPrescaler, Cr, Cfgr, Pllcfgr}; pub use self::raw::Pllp as SysPrescaler; use self::raw::ClockDivisor; pub const BOOT_CLOCK_HZ : u32 = 16_000_000; pub struct Rcc; pub struct ClockConfig { ...
use arm_m; use arm_m::reg::AtomicReg; use super::flash::FLASH; pub mod raw; pub use self::raw::{AhbPrescaler, ApbPrescaler, Cr, Cfgr, Pllcfgr}; pub use self::raw::Pllp as SysPrescaler; use self::raw::ClockDivisor; pub const BOOT_CLOCK_HZ : u32 = 16_000_000; pub struct Rcc; pub struct ClockConfig { ...
fn get_clock(self, speeds: &ClockSpeeds) -> f32 { speeds.ahb } } #[derive(Copy, Clone)] pub enum ApbBus { Apb1 = 0, Apb2 = 1, } peripheral_enum! { pub enum ApbPeripheral (ApbBus) { p Tim2 = Apb1 | 0 | 1 | 1 | 1, p Tim3 = Apb1 | 1 | 1 |...
n enable_clock(self, rcc: &Rcc) { if !self.has_enr() { panic!("cannot control clock for AHB{} idx {}", (self.get_bus() as u32) + 1, self.get_bit_index()) } rcc.reg() .ahb_enr[self.get_bus() as usize] .atomic_or(1 << self....
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn set_primask(val: bool) {\n\n unsafe {\n\n asm!(\"msr PRIMASK, $0\"\n\n :: \"r\"(val)\n\n :: \"volatile\")\n\n }\n\n}\n\n\n\n/// Generates an instruction synchronization barrier (`ISB`) instruction.\n", "file_path": "embrs/src/arm_m/mod.r...
Rust
src/lib.rs
jsgf/eventfd-rust
b2db38af64f731ccdd84e10968948ab1ab8d123e
#![cfg(target_os = "linux")] extern crate nix; pub use nix::sys::eventfd::{EventFdFlag, EFD_CLOEXEC, EFD_NONBLOCK, EFD_SEMAPHORE}; use nix::sys::eventfd::eventfd; use nix::unistd::{dup, close, write, read}; use std::io; use std::os::unix::io::{AsRawFd,RawFd}; use std::thread; use std::sync::mpsc; use std::mem; pub ...
#![cfg(target_os = "linux")] extern crate nix; pub use nix::sys::eventfd::{EventFdFlag, EFD_CLOEXEC, EFD_NONBLOCK, EFD_SEMAPHORE}; use nix::sys::eventfd::eventfd; use nix::unistd::{dup, close, write, read}; use std::io; use std::os::unix::io::{AsRawFd,RawFd}; use std::thread; use std::sync::mpsc; use std::mem; pub ...
pub fn write(&self, val: u64) -> io::Result<()> { let buf: [u8; 8] = unsafe { mem::transmute(val) }; try!(write(self.fd, &buf)); Ok(()) } pub fn events(&self) -> mpsc::Receiver<u64> { let (tx, rx) = mpsc::sync_cha...
buf = [0u8; 8]; let _ = try!(read(self.fd, &mut buf)); let val = unsafe { mem::transmute(buf) }; Ok(val) }
function_block-function_prefixed
[ { "content": "Eventfd Binding\n\n===============\n\n\n\n[![Build Status](https://travis-ci.org/jsgf/eventfd-rust.svg?branch=master)](https://travis-ci.org/jsgf/eventfd-rust)\n\n\n\nThis crate implements a binding for eventfd. This isn't especially\n\nuseful on its own; the primary use case is as part of the API...
Rust
src/client/tokens.rs
lann/bindle
ec1513554a4b088d5c9f7b25020be3d05cc58a62
use std::{ path::{Path, PathBuf}, sync::Arc, }; use oauth2::reqwest::async_http_client; use oauth2::{ basic::*, devicecode::DeviceAuthorizationResponse, AuthUrl, Client as Oauth2Client, ClientId, RefreshToken, StandardRevocableToken, StandardTokenResponse, TokenResponse, TokenUrl, }; use reqwest::{ ...
use std::{ path::{Path, PathBuf}, sync::Arc, }; use oauth2::reqwest::async_http_client; use oauth2::{ basic::*, devicecode::DeviceAuthorizationResponse, AuthUrl, Client as Oauth2Client, ClientId, RefreshToken, StandardRevocableToken, StandardTokenResponse, TokenResponse, TokenUrl, }; use reqwest::{ ...
, ) .set_auth_type(oauth2::AuthType::RequestBody); let token_res = { let mut refresh_token = self.refresh_token.write().await; let token_res = match oauth_client .exchange_refresh_token(&refres...
Some(TokenUrl::new(self.token_url.clone()).map_err(|e| { ClientError::TokenError(format!("Invalid token url: {}", e)) })?)
call_expression
[ { "content": "fn parse_basic(auth_data: &str) -> anyhow::Result<(String, String)> {\n\n match auth_data.strip_prefix(HTTP_BASIC_PREFIX) {\n\n None => anyhow::bail!(\"Wrong auth type. Only Basic auth is supported\"),\n\n Some(suffix) => {\n\n // suffix should be base64 string\n\n ...
Rust
primitives/mmr/src/mmr/utils.rs
redmaner/core-rs-albatross
9721dd99e8fef949e7e89a8047f95eaaa8ec9fd7
use crate::error::Error; use crate::hash::Merge; const USIZE_BITS: u32 = 0usize.count_zeros(); #[inline] pub(crate) fn bit_length(v: usize) -> u32 { USIZE_BITS - v.leading_zeros() } pub(crate) fn bagging<H: Merge, I: Iterator<Item = Result<(H, usize), Error>>>( peaks_rev: I, ) -> Result<H, Error> { ...
use crate::error::Error; use crate::hash::Merge; const USIZE_BITS: u32 = 0usize.count_zeros(); #[inline] pub(crate) fn bit_length(v: usize) -> u32 { USIZE_BITS - v.leading_zeros() } pub(crate) fn bagging<H: Merge, I: Iterator<Item = Result<(H, usize), Error>>>( peaks_rev: I, ) -> Result<H, Error> { ...
} pub(crate) fn hash_mmr<H: Merge, T: Hash<H>>(values: &[T]) -> H { let mut peaks = vec![]; let mut i = 0; while i < values.len() { let max_height = bit_length(values.len() - i) as usize - 1; let max_leaves = 1 << max_height; ...
Some(H::merge( &hash_perfect_tree(&values[..mid])?, &hash_perfect_tree(&values[mid..])?, len as u64, ))
call_expression
[]
Rust
vendor/wayland-client/src/globals.rs
nwtnni/icfp-2020
0eeb7851cd70bdec9343d6a4257d7286275fa79f
use std::sync::{Arc, Mutex}; use crate::protocol::wl_display; use crate::protocol::wl_registry; use crate::{Attached, DispatchData, Interface, Main, Proxy}; struct Inner { list: Vec<(u32, String, u32)>, } #[derive(Clone)] pub struct GlobalManager { inner: Arc<Mutex<Inner>>, registry: Main<wl_registry::Wl...
use std::sync::{Arc, Mutex}; use crate::protocol::wl_display; use crate::protocol::wl_registry; use crate::{Attached, DispatchData, Interface, Main, Proxy}; struct Inner { list: Vec<(u32, String, u32)>, } #[derive(Clone)] pub struct GlobalManager { inner: Arc<Mutex<Inner>>, registry: Main<wl_registry::Wl...
}); GlobalManager { inner: inner_clone, registry, } } pub fn new_with_cb<F>(display: &Attached<wl_display::WlDisplay>, mut callback: F) -> GlobalManager where F: FnMut(GlobalEvent, Attached<wl_regist...
match msg { wl_registry::Event::Global { name, interface, version, } => { inner.list.push((name, interface, version)); } wl_registry::Event::GlobalRemove { name } => { ...
if_condition
[ { "content": "pub fn demodulate(list: &str, cache: &mut AtomCache) -> Rc<Exp> {\n\n let (ret, _) = demodulate_list(list, cache);\n\n ret.set_cached(Rc::clone(&ret));\n\n ret\n\n}\n\n\n", "file_path": "src/transport.rs", "rank": 0, "score": 154818.572826611 }, { "content": "pub fn mo...
Rust
jormungandr/src/topology/mod.rs
MitchellTesla/jormungandr-rom_io
2325582d4dced77e2b023b12ffe6d014005078c8
use crate::network::p2p::Address; use jormungandr_lib::{interfaces::Subscription, time::SystemTime}; use serde::{Serialize, Serializer}; use std::{ convert::{TryFrom, TryInto}, fmt, hash::{Hash, Hasher}, }; mod gossip; pub mod layers; mod process; mod quarantine; #[allow(clippy::module_inception)] mod to...
use crate::network::p2p::Address; use jormungandr_lib::{interfaces::Subscription, time::SystemTime}; use serde::{Serialize, Serializer}; use std::{ convert::{TryFrom, TryInto}, fmt, hash::{Hash, Hasher}, }; mod gossip; pub mod layers; mod process; mod quarantine; #[allow(clippy::module_inception)] mod to...
}
fn from(other: Peer) -> Self { let other: poldercast::Gossip = other.into(); Self { id: NodeId(other.id()), address: other.address(), last_update: other.time().to_system_time().into(), quarantined: None, subscriptions: other .su...
function_block-full_function
[ { "content": "pub fn load_block(block_reader: impl BufRead) -> Result<Block, Error> {\n\n Block::deserialize(&mut Codec::new(block_reader)).map_err(Error::BlockFileCorrupted)\n\n}\n\n\n\n#[derive(StructOpt)]\n\npub struct Common {\n\n #[structopt(flatten)]\n\n pub input: Input,\n\n\n\n /// the file ...
Rust
src/dynamics/world.rs
Gohla/rust_box2d
d5431f905a09c0b2670f648c15f6d5120c0693c3
#[path = "world_callbacks.rs"] pub mod callbacks; use std::mem; use std::ptr; use std::marker::PhantomData; use std::cell::{Ref, RefMut}; use wrap::*; use handle::*; use common::{Draw, DrawLink, DrawFlags}; use common::math::Vec2; use collision::AABB; use dynamics::Profile; use user_data::UserDataTypes; use dynamics::...
#[path = "world_callbacks.rs"] pub mod callbacks; use std::mem; use std::ptr; use std::marker::PhantomData; use std::cell::{Ref, RefMut}; use wrap::*; use handle::*; use common::{Draw, DrawLink, DrawFlags}; use common::math::Vec2; use collision::AABB; use dynamics::Profile; use user_data::UserDataTypes; use dynamics::...
(WrappedRef::new(Contact::from_ffi( mem::replace(&mut self.ptr, next) as *mut ffi::Contact ))) } } } } #[doc(hidden)] pub mod ffi { pub use common::ffi::Draw; pub use dynamics::body::ffi::Body; pub use dynamics::joints::ffi::Joint; pub use dynamics::c...
unsafe { let mut link = QueryCallbackLink::new(); let ptr = link.use_with(callback); ffi::World_query_aabb(self.ptr(), ptr, aabb); } } pub fn ray_cast<C: RayCastCallback>(&self, callback: &mut C, p1: &Vec2, p2: &Vec2) { unsafe { let mut link = Ra...
random
[ { "content": "pub fn step<U: UserDataTypes>(data: &mut Data<U>, dt: f32) {\n\n data.world.step(dt, VELOCITY_ITERATIONS, POSITION_ITERATIONS);\n\n}\n\n\n\nimpl<U: UserDataTypes> Test<U> for () {}\n\n\n\nimpl<F, U: UserDataTypes> Test<U> for F\n\n where F: FnMut(&Input, &mut Data<U>)\n\n{\n\n fn process_...
Rust
applications/vote-purge-stress/main.rs
pratikfegade/noria
0460dd90ff8950cf1262bd66b58fd03620221b85
#![allow(clippy::many_single_char_names)] use clap::{value_t_or_exit, App, Arg}; use hdrhistogram::Histogram; use noria::{Builder, DurabilityMode, FrontierStrategy, PersistenceParameters}; use std::time::{Duration, Instant}; const RECIPE: &str = "# base tables CREATE TABLE Article (id int, title varchar(255), PRIMARY...
#![allow(clippy::many_single_char_names)] use clap::{value_t_or_exit, App, Arg}; use hdrhistogram::Histogram; use noria::{Builder, DurabilityMode, FrontierStrategy, PersistenceParameters}; use std::time::{Duration, Instant}; const RECIPE: &str = "# base tables CREATE TABLE Article (id int, title varchar(255), PRIMARY...
s(50)); } } println!("# purge mode: {}", args.value_of("purge").unwrap()); println!( "# replays/s: {:.2}", f64::from(n) / start.elapsed().as_secs_f64() ); println!("# op\tpct\ttime"); println!("replay\t50\t{:.2}\tµs", stats.value_at_qu...
function_block-function_prefixed
[ { "content": "CREATE TABLE Vote (article_id int, user int);\n\n\n", "file_path": "applications/vote/clients/localsoup/graph.rs", "rank": 2, "score": 473892.9226471856 }, { "content": "CREATE VIEW user_stats AS SELECT users.id, user_comments.comments, user_stories.stories FROM users LEFT JOIN...
Rust
src/game.rs
afarinetti/gameoflife-rs
4d664f9122178727d2b3216876aa9409b9b7b97b
use std::fmt; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Cell { Dead, Alive, } impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Cell::Alive => write!(f, "ALIVE"), Cell::Dead => write!(f, "DEAD"), ...
use std::fmt; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Cell { Dead, Alive, } impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Cell::Alive => write!(f, "ALIVE"), Cell::Dead => write!(f, "DEAD"), ...
#[allow(dead_code)] pub fn new_with_grid(grid: Grid) -> ConwaySim { ConwaySim { grid, generation: 0 } } pub fn get_generation(&self) -> u32 { self.generation } pub fn is_cell_alive(&self, row: u32, col: u32) -> bool { self.grid.get(row, col) == Cell::Alive } ...
m_cols: u32) -> ConwaySim { ConwaySim { grid: Grid::new(num_rows, num_cols), generation: 0, } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let mut sim = game::ConwaySim::new(5, 5);\n\n\n\n sim.set_cells(&[\n\n (2, 1),\n\n (2, 2),\n\n (2, 3)\n\n ]);\n\n\n\n for _i in 0..105 {\n\n sim.step();\n\n \n\n println!(\"Generation: {}\", sim.get_generation());\n\n pri...
Rust
fly-query-rs/src/current_search.rs
HeroicosHM/Hackathon2020
1960fded5de849dca6b2eebdfcd4082d8f7c62f7
use crate::BEARER_AUTH; use reqwest::Client; use serde::{de::IgnoredAny, Deserialize, Serialize}; use wasm_bindgen::prelude::*; const AIRPORT_QUERY: &'static str = " query findAirports($query: String!) { airports(query: $query) { edges { node { ...Airport } } } } fragment Airport on Ai...
use crate::BEARER_AUTH; use reqwest::Client; use serde::{de::IgnoredAny, Deserialize, Serialize}; use wasm_bindgen::prelude::*; const AIRPORT_QUERY: &'static str = " query findAirports($query: String!) { airports(query: $query) { edges { node { ...Airport } } } } fragment Airport on Ai...
pub async fn query_current_search(search: String) -> String { console_error_panic_hook::set_once(); let response = match Client::new() .post("http://localhost:3000/api/graphql") .header("authorization", BEARER_AUTH) .header("content-type", "application/json") .body(serde_json::to...
function_block-full_function
[ { "content": "#[derive(Serialize)]\n\nstruct FlightQueryVariables<'a> {\n\n ap_from: &'a str,\n\n ap_to: &'a str,\n\n depart_date: &'a str,\n\n return_date: Option<&'a str>,\n\n round_trip: bool,\n\n}\n\n\n\nimpl<'a> FlightQueryVariables<'a> {\n\n fn new(\n\n ap_from: &'a str,\n\n ...
Rust
src/validation.rs
djc/rpki-validator
a133f7dad930290ad51d65dbecf862d7063099f0
use std::sync::Arc; use std::sync::RwLock; use ipnetwork::IpNetwork; use rpki::asres::AsId; use storage::{RecordStorage, Record}; pub struct RecordValidator { storage: Arc<RwLock<RecordStorage>>, } impl RecordValidator { pub fn new(storage: Arc<RwLock<RecordStorage>>) -> Self { RecordValidator { ...
use std::sync::Arc; use std::sync::RwLock; use ipnetwork::IpNetwork; use rpki::asres::AsId; use storage::{RecordStorage, Record}; pub struct RecordValidator { storage: Arc<RwLock<RecordStorage>>, } impl RecordValidator { pub fn new(storage: Arc<RwLock<RecordStorage>>) -> Self { RecordValidator { ...
pub fn matched(&self) -> &Vec<Record> { &self.matched } pub fn unmatched_origin(&self) -> &Vec<Record> { &self.unmatched_origin } pub fn unmatched_length(&self) -> &Vec<Record> { &self.unmatched_length } } #[derive(Debug, PartialEq)] pub enum ValidationResult { V...
pub fn new(matched: Vec<Record>, unmatched_origin: Vec<Record>, unmatched_length: Vec<Record>) -> Self { ValidationRecords { matched, unmatched_origin, unmatched_length } }
function_block-full_function
[ { "content": "#[derive(Eq, Ord, PartialEq, PartialOrd)]\n\nstruct RecordMetadata {\n\n origin: AsId,\n\n max_length: u8,\n\n path: Arc<PathBuf>,\n\n trust_anchor: Arc<TrustAnchor>,\n\n}\n\n\n\nimpl RecordMetadata {\n\n fn new(origin: AsId,\n\n max_length: u8,\n\n path: Arc<Pat...
Rust
day-12/src/matt.rs
rust-nairobi/aoc-2020
1d39ff72936833c216c89a91f3ba3a4c9c2aac3e
use std::fs::File; use std::io::{self, BufRead}; struct Position { x: isize, y: isize, } struct Ship { dir: f64, pos: Position, waypoint: Position, } impl Ship { fn new() -> Ship { Ship { dir: 0f64, pos: Position { x: 0, y: 0 }, waypoint: Position {...
use std::fs::File; use std::io::{self, BufRead}; struct Position { x: isize, y: isize, } struct Ship { dir: f64, pos: Position, waypoint: Position, } impl Ship { fn new() -> Ship { Ship { dir: 0f64, pos: Position { x: 0, y: 0 }, waypoint: Position {...
#[test] fn test() { let actions = load_input("test.txt").unwrap(); let mut ship = Ship::new(); ship.navigate(&actions); assert_eq!(25, ship.mdist()); }
s() .filter_map(|x| x.ok()) .map(|x| { let val = x[1..].parse::<isize>().unwrap(); match &x[0..1] { "E" => Action::East(val), "F" => Action::Forward(val), "L" => Action::Left(val), "N" => Action::North(val), ...
function_block-function_prefixed
[ { "content": "fn parse_input_line(line: &str) -> GridLine {\n\n let mut grid_line = vec![];\n\n for chr in line.chars() {\n\n match chr {\n\n '#' => grid_line.push(GridPoint::Tree),\n\n '.' => grid_line.push(GridPoint::OpenSquare),\n\n _ => unreachable!(),\n\n ...
Rust
libs/prisma-models/src/record.rs
VanCoding/prisma-engines
bec4da3195df1ce40b2559939510abce2159b635
use crate::{DomainError, ModelProjection, OrderBy, PrismaValue, RecordProjection, ScalarFieldRef, SortOrder}; use itertools::Itertools; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct SingleRecord { pub record: Record, pub field_names: Vec<String>, } impl Into<ManyRecords> for SingleRecord {...
use crate::{DomainError, ModelProjection, OrderBy, PrismaValue, RecordProjection, ScalarFieldRef, SortOrder}; use itertools::Itertools; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct SingleRecord { pub record: Record, pub field_names: Vec<String>, } impl Into<ManyRecords> for SingleRecord {...
}); orderings .next() .map(|first| orderings.fold(first, |acc, ord| acc.then(ord))) .unwrap() }) } pub fn push(&mut self, record: Record) { self.records.push(record); } pub fn projections(&self, model_projection:...
match o.sort_order { SortOrder::Ascending => a.values[index].cmp(&b.values[index]), SortOrder::Descending => b.values[index].cmp(&a.values[index]), }
if_condition
[ { "content": "pub fn replace_field_names(target: &mut Vec<String>, old_name: &str, new_name: &str) {\n\n target\n\n .iter_mut()\n\n .map(|v| {\n\n if v == old_name {\n\n *v = new_name.to_string()\n\n }\n\n })\n\n .for_each(drop);\n\n}\n", "...
Rust
bench-streamer/src/main.rs
YandriHN/solana
456e6711f0c24b13ae5e923ff8cd2af3caab496d
#![allow(clippy::integer_arithmetic)] use { clap::{crate_description, crate_name, Arg, Command}, crossbeam_channel::unbounded, solana_streamer::{ packet::{Packet, PacketBatch, PacketBatchRecycler, PACKET_DATA_SIZE}, streamer::{receiver, PacketBatchReceiver, StreamerReceiveStats}, }, ...
#![allow(clippy::integer_arithmetic)] use { clap::{crate_description, crate_name, Arg, Command}, crossbeam_channel::unbounded, solana_streamer::{ packet::{Packet, PacketBatch, PacketBatchRecycler, PACKET_DATA_SIZE}, streamer::{receiver, PacketBatchReceiver, StreamerReceiveStats}, }, ...
fn main() -> Result<()> { let mut num_sockets = 1usize; let matches = Command::new(crate_name!()) .about(crate_description!()) .version(solana_version::version!()) .arg( Arg::new("num-recv-sockets") .long("num-recv-sockets") .value_name("NUM...
fn sink(exit: Arc<AtomicBool>, rvs: Arc<AtomicUsize>, r: PacketBatchReceiver) -> JoinHandle<()> { spawn(move || loop { if exit.load(Ordering::Relaxed) { return; } let timer = Duration::new(1, 0); if let Ok(packet_batch) = r.recv_timeout(timer) { rvs.fetch_add(...
function_block-full_function
[ { "content": "#[cfg(not(windows))]\n\nfn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> std::io::Result<()> {\n\n std::os::unix::fs::symlink(src, dst)\n\n}\n\n\n", "file_path": "install/src/command.rs", "rank": 0, "score": 301982.69425580115 }, { "content": "#[cfg(target_o...
Rust
src/rate_limiter/src/persist.rs
parampavar/firecracker
a97b3f6c5c048c84a49ee501c48833deb8189c18
use super::*; use snapshot::Persist; use versionize::{VersionMap, Versionize, VersionizeResult}; use versionize_derive::Versionize; #[derive(Versionize)] pub struct TokenBucketState { size: u64, one_time_burst: Option<u64>, refill_time: u64, budget: u64, elapsed_ns: u64, } impl Persist<'_> for T...
use super::*; use snapshot::Persist; use versionize::{VersionMap, Versionize, VersionizeResult}; use versionize_derive::Versionize; #[derive(Versionize)] pub struct TokenBucketState { size: u64, one_time_burst: Option<u64>,
.partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); assert_eq!( restored_rate_limiter.timer_fd.get_state(), TimerState::Disarmed ...
refill_time: u64, budget: u64, elapsed_ns: u64, } impl Persist<'_> for TokenBucket { type State = TokenBucketState; type ConstructorArgs = (); type Error = (); fn save(&self) -> Self::State { TokenBucketState { size: self.size, one_time_burst: self.one_time_...
random
[ { "content": "/// Returns the memory address where the initrd could be loaded.\n\npub fn initrd_load_addr(guest_mem: &GuestMemoryMmap, initrd_size: usize) -> super::Result<u64> {\n\n let round_to_pagesize = |size| (size + (super::PAGE_SIZE - 1)) & !(super::PAGE_SIZE - 1);\n\n match GuestAddress(get_fdt_ad...
Rust
cli/src/run.rs
russellwmy/tract
e53430a65eac501f3145ff7fbaa80d6aac8c9e40
use crate::CliResult; use crate::{Model, Parameters}; use tract_hir::internal::*; #[cfg(feature = "pulse")] use tract_pulse::internal::*; pub fn handle(params: &Parameters, options: &clap::ArgMatches) -> CliResult<()> { let dump = options.is_present("dump"); #[cfg(feature = "pulse")] let outputs = if let S...
use crate::CliResult; use crate::{Model, Parameters}; use tract_hir::internal::*; #[cfg(feature = "pulse")] use tract_pulse::internal::*; pub fn handle(params: &Parameters, options: &clap::ArgMatches) -> CliResult<()> { let dump = options.is_present("dump"); #[cfg(feature = "pulse")] let outputs = if let S...
shape); let input = input.to_array_view::<f32>()?; for ix in 0..input_dim.div_ceil(pulse) { let chunk = input.slice_axis(tract_ndarray::Axis(axis), (ix * pulse..(ix + 1) * pulse).into()); let input = if chunk.shape()[input_fact.axis] < pulse { let mut chunk_shape = chunk....
with(stream_symbol(), input_dim as i64)) .to_usize()?; let mut output_shape = output_fact.shape.to_vec(); output_shape[output_fact.axis] = (output_dim as usize + output_fact.delay + 4 * output_fact.pulse()).to_dim(); let output_shape: TVec<usize> = output_shape.iter().map(|d| d.to_usize().un...
random
[ { "content": "pub fn dump(ast: &mut IntoAst, node: &TypedNode) -> TractResult<Option<Arc<RValue>>> {\n\n let lrn = node.op_as::<Lrn>().unwrap();\n\n let input = ast.mapping[&node.inputs[0]].clone();\n\n Ok(Some(invocation(\n\n \"tract_onnx_lrn\",\n\n &[input],\n\n &[\n\n ...
Rust
dpu-cluster-core/src/pipeline/stages/loader.rs
upmem/dpu_cluster
92f143a9d7757a29e79a863d25afb4e6daeccc56
use std::sync::mpsc::Receiver; use std::sync::mpsc::Sender; use crate::pipeline::transfer::OutputMemoryTransfer; use crate::pipeline::PipelineError; use std::sync::Arc; use std::sync::Mutex; use crate::pipeline::transfer::InputMemoryTransfer; use crate::view::View; use crate::pipeline::stages::DpuGroup; use crate::pipe...
use std::sync::mpsc::Receiver; use std::sync::mpsc::Sender; use crate::pipeline::transfer::OutputMemoryTransfer; use crate::pipeline::PipelineError; use std::sync::Arc; use std::sync::Mutex; use crate::pipeline::transfer::InputMemoryTransfer; use crate::view::View; use crate::pipeline::stages::DpuGroup; use crate::pipe...
} fn load_input_chunk<T>(driver: &Driver, group: &DpuGroup, chunk: Vec<Vec<InputMemoryTransfer>>, output_sender: &SyncSender<OutputResult<T>>) -> bool { match chunk.iter().max_by_key(|t| t.len()).map(|t| t.len()) { None => true, Some(max_len) => match do...
d)); if is_ok { self.job_sender.send((group, outputs)).unwrap(); } } }
function_block-function_prefixed
[ { "content": "pub trait Stage: Sized + Send + 'static {\n\n fn launch(mut self) -> Result<ThreadHandle, PipelineError> {\n\n self.init()?;\n\n\n\n Ok(Some(thread::spawn(|| self.run())))\n\n }\n\n\n\n fn init(&mut self) -> Result<(), PipelineError> { Ok(()) }\n\n fn run(self);\n\n}\n\n\...
Rust
algebra/src/fields/models/fp6_2over3.rs
ZencashOfficial/zexe
deaabb1c47d2a01fbd7514dc4ed4e255ebaec890
use super::quadratic_extension::*; use std::marker::PhantomData; use std::ops::{MulAssign, Neg}; use crate::{ bits::{FromBits, FromCompressedBits, ToBits, ToCompressedBits}, fields::{Field, Fp3, Fp3Parameters, SquareRootField}, BitSerializationError, Error, }; pub trait Fp6Parameters: 'static + Send + Syn...
use super::quadratic_extension::*; use std::marker::PhantomData; use std::ops::{MulAssign, Neg}; use crate::{ bits::{FromBits, FromCompressedBits, ToBits, ToCompressedBits}, fields::{Field, Fp3, Fp3Parameters, SquareRootField}, BitSerializationError, Error, }; pub trait Fp6Parameters: 'static + Send + Syn...
pub fn mul_by_2345(self, other: &Self) -> Self /* Devegili OhEig Scott Dahab --- Multiplication and Squaring on Pairing-Friendly Fields.pdf; Section 3 (Karatsuba) */ { let v0 = { let t = other.c0.c2 * &<P::Fp3Params as Fp3Parameters>::NONRESIDUE; Fp3::<P::Fp3Params>::new(s...
mut self, c0: &<P::Fp3Params as Fp3Parameters>::Fp, c1: &<P::Fp3Params as Fp3Parameters>::Fp, c4: &<P::Fp3Params as Fp3Parameters>::Fp, ) { let z0 = self.c0.c0; let z1 = self.c0.c1; let z2 = self.c0.c2; let z3 = self.c1.c0; let z4 = self.c1.c1; ...
function_block-function_prefix_line
[ { "content": "pub trait Fp3Parameters: 'static + Send + Sync {\n\n type Fp: PrimeField + SquareRootField;\n\n\n\n //alpha\n\n const NONRESIDUE: Self::Fp;\n\n // coefficients of the powers of the Frobenius automorphism as linear map over F\n\n // (pi^0(X), pi^1(X), pi^2(X)) = (C1_0*X, C1_1*X +C1_2...
Rust
cleu-orm/src/crud/utils.rs
c410-f3r/cleu-orm
34d22f1f4bb01ff792262ebb63bdeec36dc0d603
use crate::{ buffer_try_push_str, buffer_write_fmt, crud::{TdEntity, TdError}, write_column_alias, write_select_field, FromRowsSuffix, SelectLimit, SelectOrderBy, SqlWriter, Suffix, Table, TableDefs, }; use sqlx_core::{ postgres::{PgPool, PgRow}, query::query, row::Row, }; #[inline] pub fn seek_related_e...
use crate::{ buffer_try_push_str, buffer_write_fmt, crud::{TdEntity, TdError}, write_column_alias, write_select_field, FromRowsSuffix, SelectLimit, SelectOrderBy, SqlWriter, Suffix, Table, TableDefs, }; use sqlx_core::{ postgres::{PgPool, PgRow}, query::query, row::Row, }; #[inline] pub fn seek_related_e...
ated_entities::<_, _, _, TD>( buffer, actual_rows, table.suffix(), table.suffix(), |entity| { rslt.push(entity); Ok(()) }, )?; counter = counter.wrapping_add(skip); } Ok(rslt) }
r..).unwrap_or_default(); let (skip, entity) = R::from_rows_suffix(curr_rows, buffer, suffix_related, row)?; write_column_alias(buffer, TD::TABLE_NAME, suffix, TD::PRIMARY_KEY_NAME)?; let curr: i64 = row.try_get(buffer.as_ref()).map_err(Into::into)?; buffer.clear(); if previous == curr { cb(e...
random
[]
Rust
awc/src/responses/response.rs
LGU-Web3-0/actix-web
5fd5875d2c72194232cc4356c7093c54e0fc700b
use std::{ cell::{Ref, RefCell, RefMut}, fmt, mem, pin::Pin, task::{Context, Poll}, time::{Duration, Instant}, }; use actix_http::{ error::PayloadError, header::HeaderMap, BoxedPayloadStream, Extensions, HttpMessage, Payload, ResponseHead, StatusCode, Version, }; use actix_rt::time::{sleep,...
use std::{ cell::{Ref, RefCell, RefMut}, fmt, mem, pin::Pin, task::{Context, Poll}, time::{Duration, Instant}, }; use actix_http::{ error::PayloadError, header::HeaderMap, BoxedPayloadStream, Extensions, HttpMessage, Payload, ResponseHead, StatusCode, Version, }; use actix_rt::time::{sleep,...
} impl<S> ClientResponse<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { pub fn body(&mut self) -> ResponseBody<S> { ResponseBody::new(self) } ...
if cookie.name() == name { return Some(cookie.to_owned()); } } } None }
function_block-function_prefix_line
[ { "content": "#[allow(non_snake_case)]\n\npub fn Header(name: &'static str, value: &'static str) -> impl Guard {\n\n HeaderGuard(\n\n header::HeaderName::try_from(name).unwrap(),\n\n header::HeaderValue::from_static(value),\n\n )\n\n}\n\n\n", "file_path": "actix-web/src/guard.rs", "r...
Rust
day16/main2.rs
allonsy/advent2017
644dd55ca9cc4319136123126c40330e9ba52de0
mod util; use std::collections::HashSet; const ARR_SIZE: usize = 16; struct Dance { index_arr: [u8; ARR_SIZE], char_arr: [char; ARR_SIZE], } impl Dance { fn new() -> Dance { Dance { index_arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], char_arr: [ ...
mod util; use std::collections::HashSet; const ARR_SIZE: usize = 16; struct Dance { index_arr: [u8; ARR_SIZE], char_arr: [char; ARR_SIZE], } impl Dance { fn new() -> Dance { Dance { index_arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], char_arr: [ ...
fn swap_char(&mut self, from_char: char, to_char: char) { let from_char_idx: usize = from_char as usize - 97; let to_char_idx: usize = to_char as usize - 97; let temp = self.index_arr[to_char_idx]; self.index_arr[to_char_idx] = self.index_arr[from_char_idx]; self.char_arr[...
fn swap_index(&mut self, from_index: usize, to_index: usize) { let temp = self.char_arr[to_index]; self.char_arr[to_index] = self.char_arr[from_index]; self.index_arr[self.char_arr[to_index] as usize - 97] = to_index as u8; self.char_arr[from_index] = temp; self.index_arr[temp a...
function_block-full_function
[ { "content": "fn rotate(num: usize, arr: [char; ARR_SIZE]) -> [char; ARR_SIZE] {\n\n let mut new_arr = ['\\0'; ARR_SIZE];\n\n for i in 0..ARR_SIZE {\n\n let new_index = (i + num) % ARR_SIZE;\n\n new_arr[new_index] = arr[i];\n\n }\n\n return new_arr;\n\n}\n\n\n", "file_path": "day16...
Rust
src/screen/agent_info.rs
timcryt/zemeroth
7b6b51add0f90e9c85e3a9c3a3cd890c9239b4a6
use std::{collections::HashMap, time::Duration}; use gwg::{ graphics::{self, Color, Image, Point2, Text}, Context, }; use heck::TitleCase; use ui::{self, Gui, Widget}; use crate::{ core::battle::{ ability::{Ability, PassiveAbility}, component::{self, Component, ObjType, Prototypes}, },...
use std::{collections::HashMap, time::Duration}; use gwg::{ graphics::{self, Color, Image, Point2, Text}, Context, }; use heck::TitleCase; use ui::{self, Gui, Widget}; use crate::{ core::battle::{ ability::{Ability, PassiveAbility}, component::{self, Component, ObjType, Prototypes}, },...
pub fn new_upgrade_info( context: &mut Context, prototypes: &Prototypes, from: &ObjType, to: &ObjType, ) -> ZResult<Self> { let font = utils::default_font(context); let mut gui = ui::Gui::new(context); let mut layout = ui::VLayout::new(); let h =...
pub fn new_agent_info( context: &mut Context, prototypes: &Prototypes, typename: &ObjType, ) -> ZResult<Self> { let font = utils::default_font(context); let mut gui = ui::Gui::new(context); let mut layout = ui::VLayout::new(); let h = utils::line_heights().big...
function_block-full_function
[ { "content": "fn label(context: &mut Context, font: Font, text: &str) -> ZResult<Box<dyn ui::Widget>> {\n\n let text = Box::new(Text::new((text, font, FONT_SIZE)));\n\n Ok(Box::new(ui::Label::new(context, text, line_height())?))\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Campaign {\n\n state: State,\n\...
Rust
git-packetline/src/read/async_io.rs
mellowagain/gitoxide
dc58eca510e5a067acdeaad4b595a34b4598a0cd
use std::io; use bstr::ByteSlice; use futures_io::AsyncRead; use futures_lite::AsyncReadExt; use crate::{ decode, read::{ExhaustiveOutcome, WithSidebands}, PacketLine, StreamingPeekableIter, MAX_LINE_LEN, U16_HEX_BYTES, }; impl<T> StreamingPeekableIter<T> where T: AsyncRead + Unpin, { #[allow(cli...
use std::io; use bstr::ByteSlice; use futures_io::AsyncRead; use futures_lite::AsyncReadExt; use crate::{ decode, read::{ExhaustiveOutcome, WithSidebands}, PacketLine, StreamingPeekableIter, MAX_LINE_LEN, U16_HEX_BYTES, }; impl<T> StreamingPeekableIter<T> where T: AsyncRead + Unpin, { #[allow(cli...
if buf_resize { buf.resize(len, 0); } Ok(Ok(crate::decode(buf).expect("only valid data here"))) } Ok(Err(err)) => { buf.clear(); Ok(Err(err)) } ...
let len = line .as_slice() .map(|s| s.len() + U16_HEX_BYTES) .unwrap_or(U16_HEX_BYTES);
assignment_statement
[ { "content": "fn into_io_err(err: Error) -> io::Error {\n\n io::Error::new(io::ErrorKind::Other, err)\n\n}\n\n\n\nimpl<W: AsyncWrite + Unpin> AsyncWrite for LineWriter<'_, W> {\n\n fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, data: &[u8]) -> Poll<io::Result<usize>> {\n\n use futures_li...
Rust
src/dnsmx.rs
oxidizers/drdns
98c1153a09642c2a5d8d2ed77ef7d9429d94995a
use buffer::{Buffer, STDOUT_BUFFER}; use byte; use dns; use libc; use stralloc::StrAlloc; use strerr::{StrErr, STRERR_SYS}; use uint16; use ulong; #[no_mangle] pub unsafe extern "C" fn nomem() { StrErr::die( 111i32, (*b"dnsmx: fatal: \0").as_ptr(), (*b"out of memory\0").as_ptr(), 0i...
use buffer::{Buffer, STDOUT_BUFFER}; use byte; use dns; use libc; use stralloc::StrAlloc; use strerr::{StrErr, STRERR_SYS}; use uint16; use ulong; #[no_mangle]
static mut seed: [u8; 128] = [0u8; 128]; static mut fqdn: StrAlloc = StrAlloc { s: 0 as (*mut u8), len: 0u32, a: 0u32, }; static mut q: *mut u8 = 0 as (*mut u8); static mut out: StrAlloc = StrAlloc { s: 0 as (*mut u8), len: 0u32, a: 0u32, }; #[no_mangle] pub static mut strnum: [u8; 40] = [...
pub unsafe extern "C" fn nomem() { StrErr::die( 111i32, (*b"dnsmx: fatal: \0").as_ptr(), (*b"out of memory\0").as_ptr(), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const StrErr), ); }
function_block-full_function
[ { "content": "//! `uint16.rs`: network byte order (i.e. big endian) conversions\n\n//!\n\n//! This should probably be replaced by the byteorder crate\n\n\n\npub unsafe fn pack(s: *mut u8, u: u16) {\n\n *s.offset(0isize) = (u as (i32) & 255i32) as (u8);\n\n *s.offset(1isize) = (u as (i32) >> 8i32) as (u8);...
Rust
src/lisp_subr.rs
tjshaffer21/rustl
31c786c32b35f364a2b2c282874c2bda81fe01ef
use std::rc::Rc; use lisp_types::{ LispResult, LispParam, sexpr::*, errors::* }; use environment::Env; pub fn atom<'a>(args_ptr: &LispParam<'a>, env: &'a Env<'a>) -> LispResult<'a> { let args = args_ptr.borrow(); let len = args.len(); if len == 0 { Err(LispError::TooFewArguments) } else if len...
use std::rc::Rc; use lisp_types::{ LispResult, LispParam, sexpr::*, errors::* }; use environment::Env; pub fn atom<'a>(args_ptr: &LispParam<'a>, env: &'a Env<'a>) -> LispResult<'a> { let args = args_ptr.borrow(); let len = args.len(); if len == 0 { Err(LispError::TooFewArguments) }
pub fn eq<'a>(args_ptr: &LispParam<'a>, env: &'a Env<'a>) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); if args.len() > 2 { return Err(LispError::TooManyArguments) } if let Some(x) = args.pop_front() { if let Some(y) = args.pop_front() { if x == y { ...
else if len > 1 { Err(LispError::TooManyArguments) } else { match args.front().unwrap() { SExpr::Atom(_) => Ok(env.get(&"t").unwrap()), _ => Ok(env.get(&"nil").unwrap()), } } }
function_block-function_prefix_line
[]
Rust
src/parse/header.rs
MikuroXina/bms-rs
16f5301fe8847a6aa6791dd7e1a3308204172cf4
use std::{collections::HashMap, fmt::Debug, path::PathBuf}; use super::{ParseError, Result}; use crate::lex::{command::*, token::Token}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum LnType { Rdm, Mgq, } impl Default for LnType { fn default() -> Self { Self::Rdm } } ...
use std::{collections::HashMap, fmt::Debug, path::PathBuf}; use super::{ParseError, Result}; use crate::lex::{command::*, token::Token}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum LnType { Rdm, Mgq, } impl Default for LnType { fn default() -> Self { Self::Rdm } } ...
}
else { eprintln!("not number total found: {:?}", total); } } Token::Url(url) => self.url = Some(url.into()), Token::VideoFile(video_file) => self.video_file = Some(video_file.into()), Token::VolWav(volume) => self.volume = volume, ...
function_block-function_prefix_line
[ { "content": "/// Analyzes and converts the BMS format text into [`TokenStream`].\n\npub fn parse(source: &str) -> Result<TokenStream> {\n\n let mut cursor = Cursor::new(source);\n\n\n\n let mut tokens = vec![];\n\n while !cursor.is_end() {\n\n tokens.push(Token::parse(&mut cursor)?);\n\n }\n...
Rust
src/common/core.rs
hbeimf/crust
2cc9414ef5ad57133ad25de2193ba1734798a9de
use crate::common::{CommonError, Result, State}; use maidsafe_utilities::thread::{self, Joiner}; use mio::{Event, Events, Poll, PollOpt, Ready, Token}; use mio_extras::channel::{self, Receiver, Sender}; use mio_extras::timer::{Timeout, Timer}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; us...
use crate::common::{CommonError, Result, State}; use maidsafe_utilities::thread::{self, Joiner}; use mio::{Event, Events, Poll, PollOpt, Ready, Token}; use mio_extras::channel::{self, Receiver, Sender}; use mio_extras::timer::{Timeout, Timer}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; us...
r_id: u8) -> Self { CoreTimer { state_id, timer_id } } }
} } } impl<T> CoreMessage<T> { pub fn new<F: FnOnce(&mut Core<T>, &Poll) + Send + 'static>(f: F) -> Self { let mut f = Some(f); CoreMessage(Some(Box::new(move |core: &mut Core<T>, poll: &Poll| { if let Some(f) = f.take() { f(core, poll) } ...
random
[ { "content": "/// Puts given peer contacts into bootstrap cache which is then written to disk.\n\npub fn cache_peer_info(core: &mut EventLoopCore, peer_info: PeerInfo, config: &CrustConfig) {\n\n let hard_coded_peers = &unwrap!(config.lock()).cfg.hard_coded_contacts;\n\n if hard_coded_peers.contains(&peer...
Rust
src/main.rs
adumbidiot/pikadick-rs
da2610a36f6a137543e6261dfb43d3d6fd288138
#![deny( unused_qualifications, clippy::all, unused_qualifications, unused_import_braces, unreachable_pub, trivial_numeric_casts, rustdoc::all, missing_debug_implementations, missing_copy_implementations, deprecated_in_future, meta_variable_misuse, non_ascii_idents, ...
#![deny( unused_qualifications, clippy::all, unused_qualifications, unused_import_braces, unreachable_pub, trivial_numeric_casts, rustdoc::all, missing_debug_implementations, missing_copy_implementations, deprecated_in_future, meta_variable_misuse, non_ascii_idents, ...
fn setup() -> anyhow::Result<(tokio::runtime::Runtime, Config, bool, WorkerGuard)> { eprintln!("starting tokio runtime..."); let tokio_rt = RuntimeBuilder::new_multi_thread() .enable_all() .thread_name("pikadick-tokio-worker") .build() .context("failed to start tokio runtime")?...
let config_path: &Path = "./config.toml".as_ref(); eprintln!("loading `{}`...", config_path.display()); let mut config = Config::load_from_path(config_path) .with_context(|| format!("failed to load `{}`", config_path.display()))?; eprintln!("validating config..."); let errors = config.validate...
function_block-function_prefix_line
[ { "content": "pub fn vaporwave_str(data: &str) -> String {\n\n data.chars()\n\n .filter_map(|c| {\n\n let c = c as u32;\n\n if (33..=270).contains(&c) {\n\n std::char::from_u32(c + 65248) // unwrap or c ?\n\n } else {\n\n Some(32 as char)\...
Rust
phper/src/functions.rs
erasin/phper
ec1a67cac3e3d101242786e950246f76fd92f921
use std::{mem::zeroed, os::raw::c_char}; use crate::{ alloc::EBox, classes::Visibility, errors::{ArgumentCountError, CallFunctionError, CallMethodError}, objects::Object, strings::ZendString, sys::*, utils::ensure_end_with_zero, values::{ExecuteData, SetVal, Val}, }; use std::{ ma...
use std::{mem::zeroed, os::raw::c_char}; use crate::{ alloc::EBox, classes::Visibility, errors::{ArgumentCountError, CallFunctionError, CallMethodError}, objects::Object, strings::ZendString, sys::*, utils::ensure_end_with_zero, values::{ExecuteData, SetVal, Val}, }; use std::{ ma...
} pub(crate) struct Method<F, R, T> where F: Fn(&mut Object<T>, &mut [Val]) -> R + Send + Sync, R: SetVal, { f: F, _p0: PhantomData<R>, _p1: PhantomData<T>, } impl<F, R, T> Method<F, R, T> where F: Fn(&mut Object<T>, &mut [Val]) -> R + Send + Sync, R: SetVal, { pub(crate) fn new(f: F)...
ta, arguments: &mut [Val], return_value: &mut Val) { let r = (self.0)(arguments); unsafe { r.set_val(return_value); } }
function_block-function_prefixed
[ { "content": "pub fn replace_and_get<T: Default, R>(t: &mut T, f: impl FnOnce(T) -> R) -> R {\n\n f(replace(t, Default::default()))\n\n}\n", "file_path": "examples/http-client/src/utils.rs", "rank": 1, "score": 210667.59407539124 }, { "content": "fn integration_values_return_val(_: &mut [...
Rust
ezgui/src/event_ctx.rs
jinzhong2/abstreet
e1c5edc76d636af4f3e4593efc25055bdd637dd7
use crate::widgets::ContextMenu; use crate::{ Canvas, Color, GfxCtx, HorizontalAlignment, Line, Prerender, Text, UserInput, VerticalAlignment, }; use abstutil::{elapsed_seconds, Timer, TimerSink}; use geom::Angle; use glium_glyph::glyph_brush::rusttype::Font; use glium_glyph::GlyphBrush; use std::collections::VecDe...
use crate::widgets::ContextMenu; use crate::{ Canvas, Color, GfxCtx, HorizontalAlignment, Line, Prerender, Text, UserInput, VerticalAlignment, }; use abstutil::{elapsed_seconds, Timer, TimerSink}; use geom::Angle; use glium_glyph::glyph_brush::rusttype::Font; use glium_glyph::GlyphBrush; use std::collections::VecDe...
pub fn redo_mouseover(&self) -> bool { self.input.window_lost_cursor() || (!self.canvas.is_dragging() && self.input.get_moved_mouse().is_some()) || self.input.get_mouse_scroll().is_some() } pub fn set_textures( &mut self, skip_textures: Vec<(&str, Color)>, ...
me, Box::new(LoadingScreen::new( self.prerender, self.program, self.canvas.window_width, self.canvas.window_height, self.canvas.font_size, timer_name.to_string(), )), ); f(self, &mut t...
function_block-function_prefixed
[ { "content": "fn use_parking_hints(map: &mut RawMap, path: &str, timer: &mut Timer) {\n\n timer.start(\"apply parking hints\");\n\n let shapes: ExtraShapes = abstutil::read_binary(path, timer).expect(\"loading blockface failed\");\n\n\n\n // Match shapes with the nearest road + direction (true for forw...
Rust
vrp-core/src/solver/telemetry.rs
valerivp/vrp
27ee30e5f4c44e051e5cec1248e606305b52fc00
#[cfg(test)] #[path = "../../tests/unit/solver/telemetry_test.rs"] mod telemetry_test; use crate::algorithms::nsga2::Objective; use crate::construction::heuristics::InsertionContext; use crate::solver::population::SelectionPhase; use crate::solver::{RefinementContext, Statistics}; use crate::utils::Timer; use std::f...
#[cfg(test)] #[path = "../../tests/unit/solver/telemetry_test.rs"] mod telemetry_test; use crate::algorithms::nsga2::Objective; use crate::construction::heuristics::InsertionContext; use crate::solver::population::SelectionPhase; use crate::solver::{RefinementContext, Statistics}; use crate::utils::Ti
termination_estimate, }; self.next_generation = Some(generation + 1); let (log_best, log_population, track_population, should_dump_population) = match &self.mode { TelemetryMode::None => return, TelemetryMode::OnlyLogging { log_best, log_population, dump_population...
mer; use std::fmt::Write; use std::ops::Deref; use std::sync::Arc; pub type InfoLogger = Arc<dyn Fn(&str)>; pub struct Metrics { pub duration: usize, pub generations: usize, pub speed: f64, pub evolution: Vec<Generation>, } pub struct Generation { pub number: usize, ...
random
[ { "content": "fn create_file(path: &str, description: &str) -> File {\n\n File::create(path).unwrap_or_else(|err| {\n\n eprintln!(\"Cannot create {} file '{}': '{}'\", description, path, err.to_string());\n\n process::exit(1);\n\n })\n\n}\n\n\n\n// TODO avoid code duplication (macros?)\n\n\n...
Rust
lib/engine-universal/src/unwind/windows_x64.rs
DumbMachine/wasmer
84727032e59bee88a4a5b8860cf593f7cfdd0baf
use loupe::{MemoryUsage, MemoryUsageTracker}; use std::collections::HashMap; use wasmer_compiler::CompiledFunctionUnwindInfo; use winapi::um::winnt; pub struct UnwindRegistry { functions: HashMap<usize, Vec<winnt::RUNTIME_FUNCTION>>, published: bool, } impl UnwindRegistry { pub fn new() -> Sel...
use loupe::{MemoryUsage, MemoryUsageTracker}; use std::collections::HashMap; use wasmer_compiler::CompiledFunctionUnwindInfo; use winapi::um::winnt; pub struct UnwindRegistry { functions: HashMap<usize, Vec<winnt::RUNTIME_FUNCTION>>, published: bool, } impl UnwindRegistry { pub fn new() -> Sel...
}
fn size_of_val(&self, tracker: &mut dyn MemoryUsageTracker) -> usize { self.functions .iter() .map(|(_, _)| std::mem::size_of::<u64>() * 3) .sum::<usize>() + self.published.size_of_va...
function_block-full_function
[ { "content": "pub fn get_emscripten_table_size(module: &Module) -> Result<(u32, Option<u32>), String> {\n\n if let Some(import) = module.imports().tables().next() {\n\n let ty = import.ty();\n\n Ok((ty.minimum, ty.maximum))\n\n } else {\n\n Err(\"Emscripten requires at least one impor...
Rust
gtk/src/flash.rs
system76/muf
a1561b32acad891424da8b6de8ae012f39f83d05
use atomic::Atomic; use dbus::arg::{OwnedFd, RefArg, Variant}; use dbus::blocking::{Connection, Proxy}; use dbus_udisks2::DiskDevice; use futures::executor; use libc; use popsicle::{Progress, Task}; use std::cell::Cell; use std::collections::HashMap; use std::fmt::{self, Debug, Display, Formatter}; use std::fs::File; u...
use atomic::Atomic; use dbus::arg::{OwnedFd, RefArg, Variant}; use dbus::blocking::{Connection, Proxy}; use dbus_udisks2::DiskDevice; use futures::executor; use libc; use popsicle::{Progress, Task}; use std::cell::Cell; use std::collections::HashMap; use std::fmt::{self, Debug, Display, Formatter}; use std::fs::File; u...
} Ok(()) } fn udisks_open(dbus_path: &str) -> anyhow::Result<File> { let connection = Connection::new_system()?; let dbus_path = ::dbus::strings::Path::new(dbus_path).map_err(anyhow::Error::msg)?; let proxy = Proxy::new("org.freedesktop.UDisks2", &dbus_path, Duration::new(25, 0), &conne...
if err.name() != Some("org.freedesktop.UDisks2.Error.NotMounted") { return Err(anyhow::Error::new(err)); }
if_condition
[ { "content": "pub fn init() -> Result<(), glib::Error> {\n\n const GRESOURCE: &[u8] = include_bytes!(concat!(env!(\"OUT_DIR\"), \"/compiled.gresource\"));\n\n\n\n gio::resources_register(&gio::Resource::from_data(&glib::Bytes::from_static(GRESOURCE))?);\n\n\n\n let theme = gtk::IconTheme::default().unw...
Rust
rust/envop/src/main.rs
eagletmt/misc
cb4d3d3d19a00161ad7e87056d007ee043effed7
use std::io::Write as _; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut args = std::env::args(); let me = args.next().unwrap(); let name = args.next().unwrap_or_else(|| { eprintln!("Usage: {} NAME PROG ARGS...", me); std::process::exit(1); }); let prog = args.next().u...
use std::io::Write as _; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut args = std::env::args(); let me = args.next().unwrap(); let name = args.next().unwrap_or_else(|| { eprintln!("Usage: {} NAME PROG ARGS...", me); std::process::exit(1); }); let prog = args.next().u...
tderr().write_all(&output.stderr)?; std::process::exit(output.status.code().unwrap_or(1)); } let item_summaries: Vec<ItemSummary> = serde_json::from_slice(&output.stdout)?; let mut envs = Vec::new(); for item_summary in item_summaries .into_iter() .filter(|item_summary| item_sum...
and::new("op") .arg("list") .arg("items") .arg("--vault") .arg(&vault) .arg("--categories") .arg("Secure Note") .arg("--tags") .arg(&tags) .output()?; if !output.status.success() { eprintln!("`op list items` failed"); std::io::s...
random
[ { "content": "fn main() -> anyhow::Result<()> {\n\n env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(\"info\")).init();\n\n\n\n for arg in std::env::args().skip(1) {\n\n unpack(&arg).with_context(|| format!(\"failed to unpack {}\", arg))?;\n\n }\n\n Ok(())\n\n}\n\n\n...
Rust
src/mbart/encoder.rs
eonm-abes/rust-bert
24fdb2dfb41e7cad6367f77e905570649bb7aefe
use crate::bart::{BartEncoderOutput, _expand_mask}; use crate::common::activations::TensorFunction; use crate::common::dropout::Dropout; use crate::mbart::attention::MBartAttention; use crate::mbart::embeddings::MBartLearnedPositionalEmbedding; use crate::mbart::MBartConfig; use crate::Activation; use std::borrow::{B...
use crate::bart::{BartEncoderOutput, _expand_mask}; use crate::common::activations::TensorFunction; use crate::common::dropout::Dropout; use crate::mbart::attention::MBartAttention; use crate::mbart::embeddings::MBartLearnedPositionalEmbedding; use crate::mbart::MBartConfig; use crate::Activation; use std::borrow::{B...
} pub struct MBartEncoder { dropout: Dropout, layer_norm_embedding: nn::LayerNorm, layer_norm: nn::LayerNorm, layers: Vec<MBartEncoderLayer>, embed_positions: MBartLearnedPositionalEmbedding, output_attentions: bool, output_hidden_states: bool, scale_embedding: f64, } impl MBartEncode...
self.self_attention .forward_t(&output, None, encoder_attention_mask, None, train); let output: Tensor = output.apply_t(&self.dropout, train) + x; let residual = output.copy(); let output = output.apply(&self.final_layer_norm); let output = (self.activation.get_fn())(&ou...
function_block-function_prefix_line
[ { "content": "pub fn _tanh(x: &Tensor) -> Tensor {\n\n x.tanh()\n\n}\n\n\n\npub struct TensorFunction(Box<fn(&Tensor) -> Tensor>);\n\n\n\nimpl TensorFunction {\n\n pub fn new(fun: Box<fn(&Tensor) -> Tensor>) -> Self {\n\n Self(fun)\n\n }\n\n\n\n pub fn get_fn(&self) -> &fn(&Tensor) -> Tensor ...
Rust
crates/rome_console/src/markup.rs
RustPhilly/tools
a5c89104e6623b2eb51e2fc1881ddc551fde34d2
use std::{ fmt::{self, Debug}, io, }; use termcolor::{Color, ColorSpec}; use crate::fmt::{Display, Formatter, MarkupElements, Write}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum MarkupElement { Emphasis, Dim, Italic, Underline, Error, Success, Warn, Info, } impl Mar...
use std::{ fmt::{self, Debug}, io, }; use termcolor::{Color, ColorSpec}; use crate::fmt::{Display, Formatter, MarkupElements, Write}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum MarkupElement { Emphasis, Dim, Italic, Underline, Error, Success, Warn, Info, } impl Mar...
} #[derive(Copy, Clone)] pub struct Markup<'fmt>(pub &'fmt [MarkupNode<'fmt>]); impl<'fmt> Markup<'fmt> { pub fn to_owned(&self) -> MarkupBuf { let mut result = MarkupBuf(Vec::new()); Formatter::new(&mut result).write_markup(*self).unwrap(); result } } #[derive(Clone, Defaul...
write!(fmt, "<{element:?}>")?; } write!(fmt, "{:?}", self.content)?; for element in self.elements.iter().rev() { write!(fmt, "</{element:?}>")?; } if fmt.alternate() && self.content.contains('\n') { writeln!(fmt)?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn prepend_generated_preamble(content: impl Display) -> String {\n\n format!(\"//! {}\\n\\n{}\", PREAMBLE, content)\n\n}\n\n\n", "file_path": "xtask/src/lib.rs", "rank": 0, "score": 448341.5380411264 }, { "content": "pub trait Language: Sized + Clone + Copy + fmt::Debug ...
Rust
lib/shiika_core/src/names.rs
shiika-lang/shiika
1992ad906c4e7354f8eb7000a134898b68651883
use crate::ty; use crate::ty::*; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq)] pub struct ClassFirstname(pub String); impl std::fmt::Display for ClassFirstname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } impl ClassFirstname { p...
use crate::ty; use crate::ty::*; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq)] pub struct ClassFirstname(pub String); impl std::fmt::Display for ClassFirstname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } impl ClassFirstname { p...
pub fn meta_name(&self) -> ClassFullname { metaclass_fullname(&self.0) } pub fn method_fullname(&self, method_firstname: &MethodFirstname) -> MethodFullname { method_fullname(self, &method_firstname.0) } pub fn to_const_fullname(&self) -> ConstFullname { toplevel_const(&s...
et mut name = self.0.clone(); name.replace_range(0..=4, ""); ty::meta(&name) } else { self.instance_ty() } }
function_block-function_prefixed
[ { "content": "pub fn new(base_name_: impl Into<String>, type_args: Vec<TermTy>, is_meta: bool) -> TermTy {\n\n let base_name = base_name_.into();\n\n debug_assert!(!base_name.is_empty());\n\n debug_assert!(!base_name.starts_with(\"Meta:\"));\n\n debug_assert!(!base_name.contains('<'));\n\n let fu...
Rust
client/src/command_receiver.rs
amethyst/naia
791d5c90ce3435c254da1a6048064c2204ff538c
use std::collections::{HashMap, VecDeque}; use naia_shared::{ wrapping_diff, EntityType, ProtocolType, Ref, Replicate, SequenceBuffer, SequenceIterator, WorldMutType, }; use super::{entity_manager::EntityManager, event::OwnedEntity}; const COMMAND_HISTORY_SIZE: u16 = 64; #[derive(Debug)] pub struct CommandR...
use std::collections::{HashMap, VecDeque}; use naia_shared::{ wrapping_diff, EntityType, ProtocolType, Ref, Replicate, SequenceBuffer, SequenceIterator, WorldMutType, }; use super::{entity_manager::EntityManager, event::OwnedEntity}; const COMMAND_HISTORY_SIZE: u16 = 64; #[derive(Debug)] pub struct CommandR...
owned_entity: &K) { self.command_history.insert( *owned_entity, SequenceBuffer::with_capacity(COMMAND_HISTORY_SIZE), ); } pub fn prediction_cleanup(&mut self, owned_entity: &K) { self.command_history.remove(owned_entity); } }
if let Some(command_buffer) = self.command_history.get_mut(owned_entity) { command_buffer.remove_until(history_tick); } } pub fn prediction_init(&mut self,
random
[ { "content": "pub fn before_receive_events(world: &mut World) {\n\n world.resource_scope(|world, mut client: Mut<Client<Entity>>| {\n\n\n\n // Host Component Updates\n\n let mut host_component_event_reader = world\n\n .get_resource_mut::<Events<HostSyncEvent>>()\n\n .unwra...
Rust
packages/moneymarket/src/testing.rs
1Zaitsev/money-market-mocks
d2c5d089e1a34735e9483f9e54afb647bb00c13d
use crate::mock_querier::mock_dependencies; use crate::oracle::PriceResponse; use crate::querier::{compute_tax, deduct_tax, query_price, query_tax_rate, TimeConstraints}; use crate::tokens::{Tokens, TokensHuman, TokensMath, TokensToRaw}; use cosmwasm_bignumber::{Decimal256, Uint256}; use cosmwasm_std::{Addr, Api, Cano...
use crate::mock_querier::mock_dependencies; use crate::oracle::PriceResponse; use crate::querier::{compute_tax, deduct_tax, query_price, query_tax_rate, TimeConstraints}; use crate::tokens::{Tokens, TokensHuman, TokensMath, TokensToRaw}; use cosmwasm_bignumber::{Decimal256, Uint256}; use cosmwasm_std::{Addr, Api, Cano...
fn token_math_invalid_token_2() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), ...
rom_ratio(131, 2), last_updated_base: 123, last_updated_quote: 321, } ); query_price( deps.as_ref(), Addr::unchecked("oracle"), "terra123123".to_string(), "ukrw".to_string(), None, ) .unwrap_err(); let res = query_price( ...
random
[ { "content": "pub fn query_tax_rate_and_cap(deps: Deps, denom: String) -> StdResult<(Decimal256, Uint256)> {\n\n let terra_querier = TerraQuerier::new(&deps.querier);\n\n let rate = terra_querier.query_tax_rate()?.rate;\n\n let cap = terra_querier.query_tax_cap(denom)?.cap;\n\n Ok((rate.into(), cap....
Rust
micro-color-chooser/src/service/game_color_prefs.rs
CoinArcade/BUGOUT
ec01dc3dae54e1e248d540d442caa1731f2822e4
use crate::components::Repos; use crate::repo::*; use api::GameReady; use color_model::*; use core_model::*; pub fn by_session_id(session_id: &SessionId, repos: &Repos) -> Result<GameColorPref, FetchErr> { repos.game_ready.get(session_id).and_then(|sg| match sg { None => Ok(GameColorPref::NotReady), ...
use crate::components::Repos; use crate::repo::*; use api::GameReady; use color_model::*; use core_model::*; pub fn by_session_id(session_id: &SessionId, repos: &Repos) -> Result<GameColorPref, FetchErr> { repos.game_ready.get(session_id).and_then(|sg| match sg { None => Ok(GameColorPref::NotReady), ...
ert_eq!(actual, GameColorPref::NotReady) } }
ref, another_pref) } ) } #[test] fn test_by_session_id_partial() { let sid = SessionId::new(); let cid = ClientId::new(); let gid = GameId::new(); let pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black,...
random
[ { "content": "pub fn fetch(game_id: &GameId, components: &Components) -> Result<Option<GameState>, FetchErr> {\n\n let mut conn = components.client.get_connection().expect(\"fetch conn\");\n\n let key = components.redis_key_provider.game_states(&game_id);\n\n let bin_data: Option<Vec<u8>> = conn.get(&k...
Rust
src/util.rs
rantan/tapyrus-signer
bd8026460860469b15b2fca3ae158c801d15870f
use curv::{BigInt, GE}; use std::convert::TryFrom; use std::os::raw::c_int; use std::sync::atomic::AtomicUsize; use std::sync::Arc; pub fn sum_point(points: &Vec<GE>) -> GE { let mut iter = points.iter(); let head = iter.next().unwrap(); let tail = iter; tail.fold(head.clone(), |acc, x| acc + x) } pub...
use curv::{BigInt, GE}; use std::convert::TryFrom; use std::os::raw::c_int; use std::sync::atomic::AtomicUsize; use std::sync::Arc; pub fn sum_point(points: &Vec<GE>) -> GE { let mut iter = points.iter(); let head = iter.next().unwrap(); let tail = iter; tail.fold(head.clone(), |acc, x| acc + x) } pub...
const STOP_SIGNALS: [usize; 6] = [ signal_hook::SIGABRT as usize, signal_hook::SIGHUP as usize, signal_hook::SIGINT as usize, signal_hook::SIGQUIT as usize, signal_hook::SIGTERM as usize, signal_hook::SIGTRAP as usize, ]; pub fn set_stop_signal_handler() -> Result<Arc<AtomicUsize>, std::io::E...
while a1.is_multiple_of(&BigInt::from(2)) { a1 = a1 >> 1; e += 1; } let mut s: i8 = if e & 1 == 0 || n.modulus(&BigInt::from(8)) == BigInt::from(1) || n.modulus(&BigInt::from(8)) == BigInt::from(7) { 1 } else if n.modulus(&BigInt::from(8)) == BigInt::from(3) ...
function_block-function_prefix_line
[ { "content": "fn compute_e(r: &GE, y: &GE, message: &[u8]) -> FE {\n\n let mut hasher = Sha256::new();\n\n hasher.input(&r.get_element().serialize()[1..33]);\n\n hasher.input(&y.get_element().serialize()[..]);\n\n hasher.input(message);\n\n let e_bn = BigInt::from(&hasher.result()[..]);\n\n\n\n ...
Rust
iml-gui/crate/src/page/login.rs
intel-hpdd/-intel-manager-for-lustre
f8a6f61205b42cc62f4bbcb8d81214ad4f215cd6
use crate::{ auth, components::{ddn_logo, ddn_logo_lettering, whamcloud_logo}, generated::css_classes::C, GMsg, MergeAttrs, }; use core::fmt; use iml_wire_types::Branding; use seed::{browser::service::fetch, prelude::*, *}; #[derive(Clone, Default, serde::Serialize)] struct Form { username: Strin...
use crate::{ auth, components::{ddn_logo, ddn_logo_lettering, whamcloud_logo}, generated::css_classes::C, GMsg, MergeAttrs, }; use core::fmt; use iml_wire_types::Branding; use seed::{browser::service::fetch, prelude::*, *}; #[derive(Clone, Default, serde::Serialize)] struct Form { username: Strin...
] ] }
ord", At::Placeholder => "Password", At::AutoComplete => "current-password" }, ], match errs.password.as_ref() { Some(errs) => { errs.iter().map(|x| err_item(x)).collect() ...
random
[ { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) {\n\n match msg {\n\n Msg::Fetch => {\n\n model.cancel = None;\n\n\n\n let request = fetch_session().controller(|controller| model.request_controller = Some(controller));\n\n\n\n ...
Rust
src/gossip/config.rs
devillove084/HierarchicalCache
0e6f95b758dbb9df274075d550e2b0dc8fd66699
#![allow(dead_code)] #[derive(Clone)] pub struct PeerSamplingConfig { push: bool, pull: bool, sampling_period: u64, sampling_deviation: u64, view_size: usize, healing_factor: usize, swapping_factor: usize, } impl PeerSamplingConfig { pu...
#![allow(dead_code)] #[derive(Clone)] pub struct PeerSamplingConfig { push: bool, pull: bool, sampling_period: u64, sampling_deviation: u64, view_size: usize, healing_factor: usize, swapping_factor: usize, } impl PeerSamplingConfig { pu...
} pub struct GossipConfig { push: bool, pull: bool, gossip_period: u64, gossip_deviation: u64, update_expiration: UpdateExpirationMode, } impl GossipConfig { pub fn new(push: bool, pull: bool, gossip_period: u64, update_expiration: UpdateExpirationMode)...
fn default() -> Self { PeerSamplingConfig { push: true, pull: true, sampling_period: 60000, sampling_deviation: 0, view_size: 30, healing_factor: 3, swapping_factor: 12 } }
function_block-full_function
[ { "content": "pub fn string_object_hash(object: &RobjPtr, seed: u64) -> usize {\n\n match object.borrow().encoding() {\n\n RobjEncoding::Raw =>\n\n murmur_hash64a(object.borrow().string(), seed) as usize,\n\n RobjEncoding::Int =>\n\n murmur_hash64a(object.borrow().integer(...
Rust
src/lib.rs
alec-deason/bevy_contrib_schedules
7029bf35f5c784ff4e8eba11152b072b54afc6d2
use bevy::{ app::stage, core::Time, ecs::{Schedule, ParallelExecutor, World, Resources, System, Entity}, utils::HashMap, }; #[derive(Debug)] pub enum ScheduleType { Always, Fixed(f64, f64), } pub struct PackedSchedule(pub ScheduleType, pub Schedule, ParallelExecutor)...
use bevy::{ app::stage, core::Time, ecs::{Schedule, ParallelExecutor, World, Resources, System, Entity}, utils::HashMap, }; #[derive(Debug)] pub enum ScheduleType { Always, Fixed(f64, f64), } pub struct PackedSchedule(pub ScheduleType, pub Schedule, ParallelExecutor)...
tage::POST_UPDATE) .add_stage(stage::LAST) } pub fn add_stage(mut self, stage_name: &'static str) -> Self { self.0.1.add_stage(stage_name); self } pub fn add_stage_after(mut self, target: &'static str, stage_name: &'static str) -> Self { self.0.1.add_stage_after(tar...
lf) -> Self { self.add_stage(stage::FIRST) .add_stage(stage::PRE_UPDATE) .add_stage(stage::UPDATE) .add_stage(s
function_block-random_span
[ { "content": "fn fixed_sys() {\n\n println!(\"game tick!\");\n\n}", "file_path": "examples/fixed_tick.rs", "rank": 1, "score": 37938.93565220559 }, { "content": "fn build(mut commands: Commands) {\n\n // TODO: Demonstrate how to later remove schedules conditionally\n\n // Spoiler: J...
Rust
crates/model/src/score/snapshots.rs
katandps/beatoraja_play_recommend
c7adf974cdab1b249c86c896aa1ba0a8fdd20819
use crate::score::score::ParamSnap; use crate::*; use chrono::Duration; use std::collections::BTreeSet; #[derive(Deserialize, Serialize, Debug, Clone, Default)] pub struct SnapShots(pub BTreeSet<SnapShot>); impl SnapShots { pub fn create_by_snaps(snapshots: Vec<SnapShot>) -> SnapShots { SnapShots(snapshot...
use crate::score::score::ParamSnap; use crate::*; use chrono::Duration; use std::collections::BTreeSet; #[derive(Deserialize, Serialize, Debug, Clone, Default)] pub struct SnapShots(pub BTreeSet<SnapShot>); impl SnapShots { pub fn create_by_snaps(snapshots: Vec<SnapShot>) -> SnapShots { SnapShots(snapshot...
Some(T::make(last, last_date.clone(), one_day_before)) } None => None, } } } #[cfg(test)] mod test { use super::*; use crate::score::score::ClearTypeSnap; #[test] pub fn test() { let shot1 = SnapShot::from_data(1, 2, 3, 4, 11); let shot2 = Sna...
t mut last_date = &last.updated_at; let mut one_day_before = None; for snap in self.0.iter().rev() { if T::cmp(snap, last) { last_date = &snap.updated_at; } else { one_day_before = self.snap(&(last_da...
random
[ { "content": "pub fn changed_visibility_by_query() -> impl Filter<Extract = (bool,), Error = Rejection> + Clone {\n\n warp::body::json().and_then(get_changed_visibility_query)\n\n}\n\n\n\nasync fn get_changed_name_query(body: HashMap<String, String>) -> Result<String, Rejection> {\n\n let changed_name = b...
Rust
examples/dlint/config.rs
cdaringe/deno_lint
5ca58cd3f230ba95c75e261192414ee0bb9a758f
use anyhow::bail; use anyhow::Error as AnyError; use deno_lint::rules::{get_filtered_rules, LintRule}; use serde::Deserialize; use std::path::Path; use std::path::PathBuf; #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct RulesConfig { pub tags: Vec<String>, pub include: Vec<String>, pub exclu...
use anyhow::bail; use anyhow::Error as AnyError; use deno_lint::rules::{get_filtered_rules, LintRule}; use serde::Deserialize; use std::path::Path; use std::path::PathBuf; #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct RulesConfig { pub tags: Vec<String>, pub include: Vec<String>, pub exclu...
let mut file_paths = Vec::new(); for result in walker.into_iter() { match result { Ok(result) => file_paths.push(result.into_path()), Err(err) => bail!("Error walking files: {}", err), } } Ok(file_paths) } #[cfg(test)] mod tests { use super::*; use deno_lint::rules::get_recommended_r...
let walker = match walker { Ok(walker) => walker, Err(err) => bail!("Error parsing file patterns: {}", err), };
assignment_statement
[ { "content": "fn is_valid_typeof_string(str: &str) -> bool {\n\n matches!(\n\n str,\n\n \"undefined\"\n\n | \"object\"\n\n | \"boolean\"\n\n | \"number\"\n\n | \"string\"\n\n | \"function\"\n\n | \"symbol\"\n\n | \"bigint\"\n\n )\n\n}\n\n\n", "file_path": "src/rule...
Rust
src/config/freqency.rs
ywatanabee/libipt-rs
0efe4ff71d8e3236f4d3f691a16e714eb0c745bb
#[cfg(test)] mod test { use super::*; #[test] fn test_freq_props() { let mut freq = Frequency::new(1, 2, 3, 4); assert_eq!(freq.mtc(), 1); assert_eq!(freq.nom(), 2); assert_eq!(freq.ctc(), 3); assert_eq!(freq.tsc(), 4); freq.set_mtc(5); freq.set_nom(...
#[cfg(test)] mod test { use super::*; #[test] fn test_freq_props() {
} #[derive(Clone, Copy, Default)] pub struct Frequency { pub(super) mtc: u8, pub(super) nom: u8, pub(super) ctc: u32, pub(super) tsc: u32 }...
let mut freq = Frequency::new(1, 2, 3, 4); assert_eq!(freq.mtc(), 1); assert_eq!(freq.nom(), 2); assert_eq!(freq.ctc(), 3); assert_eq!(freq.tsc(), 4); freq.set_mtc(5); freq.set_nom(6); freq.set_ctc(7); freq.set_tsc(8); assert_eq!(freq.mtc(), 5); ...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_encoder_all_packets() {\n\n let mut inp = [0; 132];\n\n let mut cfg = ConfigBuilder::new(&mut inp)\n\n .unwrap()\n\n .cpu(Cpu::intel(1, 2, 3))\n\n .finish();\n\n\n\n let mut enc = Encoder::new(&mut cfg).unwrap();\n\n\n\n let mut size: u32 = 0;\n\...
Rust
client/src/util.rs
fabaff/innernet
fd06b8054d007fcf86144c37c6eaf37f30719450
use crate::{ClientError, Error}; use colored::*; use indoc::eprintdoc; use log::{Level, LevelFilter}; use serde::{de::DeserializeOwned, Serialize}; use shared::{interface_config::ServerInfo, INNERNET_PUBKEY_HEADER}; use std::{io, time::Duration}; use ureq::{Agent, AgentBuilder}; static LOGGER: Logger = Logger; struct ...
use crate::{ClientError, Error}; use colored::*; use indoc::eprintdoc; use log::{Level, LevelFilter}; use serde::{de::DeserializeOwned, Serialize}; use shared::{interface_config::ServerInfo, INNERNET_PUBKEY_HEADER}; use std::{io, time::Duration}; use ureq::{Agent, AgentBuilder}; static LOGGER: Logger = Logger; struct ...
pub fn human_size(bytes: u64) -> String { const KB: u64 = 1024; const MB: u64 = 1024 * KB; const GB: u64 = 1024 * MB; const TB: u64 = 1024 * GB; match bytes { n if n < 2 * KB => format!("{} {}", n, "B".cyan()), n if n < 2 * MB => format!("{:.2} {}", n as f64 / KB as f64, "KiB".cyan...
format!( "{} {}, {} {} ago", hours, if hours == 1 { "hour" } else { "hours" }.cyan(), mins, if mins == 1 { "minute" } else { "minutes" }.cyan(), ) }, } }
function_block-function_prefix_line
[ { "content": "pub fn confirm(prompt: &str) -> Result<bool, io::Error> {\n\n ensure_interactive(prompt)?;\n\n Confirm::with_theme(&*THEME)\n\n .wait_for_newline(true)\n\n .with_prompt(prompt)\n\n .default(false)\n\n .interact()\n\n}\n\n\n", "file_path": "shared/src/prompts.r...
Rust
qor-os/src/trap/context.rs
CarterTS/Qor
046616dc06179c158788c9003371441bc8a919d9
use core::usize; use super::TrapFrame; #[derive(Debug, Clone, Copy)] pub enum InterruptType { UserSoftwareInterrupt, SupervisorSoftwareInterrupt, MachineSoftwareInterrupt, UserTimeInterrupt, SupervisorTimerInterrupt, MachineTimerInterrupt, UserExternalInterrupt, SupervisorExternalInter...
use core::usize; use super::TrapFrame; #[derive(Debug, Clone, Copy)] pub enum InterruptType { UserSoftwareInterrupt, SupervisorSoftwareInterrupt, MachineSoftwareInterrupt, UserTimeInterrupt, SupervisorTimerInterrupt, MachineTimerInterrupt, UserExternalInterrupt, SupervisorExternalInter...
:InstructionAddressMisaligned, (false, 1) => InterruptType::InstructionAccessFault, (false, 2) => InterruptType::IllegalInstruction, (false, 3) => InterruptType::Breakpoint, (false, 4) => InterruptType::LoadAddressMisaligned, (false, 5) => InterruptType::LoadA...
ault, StorePageFault, UnknownSync(usize), UnknownAsync(usize) } pub struct InterruptContext { epc: usize, tval: usize, cause: InterruptType, hart: usize, status: usize, frame: *mut TrapFrame, async_trap: bool } impl InterruptContext { pub fn new(epc: usize, tval: usize...
random
[ { "content": "#[test]\n\npub fn test_path_iterator()\n\n{\n\n use libutils::paths::OwnedPath;\n\n\n\n let path0 = OwnedPath::new(\"/usr/bin/ls\");\n\n let path1 = OwnedPath::new(\"bin/ls\");\n\n let path2 = OwnedPath::new(\"/\");\n\n let path3 = OwnedPath::new(\"./../../home/\");\n\n\n\n asser...
Rust
elasticsearch/src/error.rs
yaanhyy/elasticsearch-rs
740c3ebd41b391f954e9cf008209b39d89a75231
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not u...
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for addition
type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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 * * ...
al information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you 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 * * Un...
random
[ { "content": "pub fn create_default() -> Elasticsearch {\n\n create_for_url(cluster_addr().as_str())\n\n}\n\n\n", "file_path": "elasticsearch/tests/common/client.rs", "rank": 0, "score": 61105.408873425535 }, { "content": "fn create_client() -> Result<Elasticsearch, Error> {\n\n fn clu...
Rust
internal/wasmldr/src/workload.rs
rohankumardubey/enarx
27300ba494f463bf077fb1f8d326057412fa58ae
use log::{debug, info}; use wasmtime_wasi::sync::WasiCtxBuilder; #[allow(clippy::enum_variant_names)] #[derive(Debug)] pub enum Error { ConfigurationError, ExportNotFound, InstantiationFailed, CallFailed, IoError(std::io::Error), WASIError(wasmtime_wasi::Error),...
use log::{debug, info}; use wasmtime_wasi::sync::WasiCtxBuilder; #[allow(clippy::enum_variant_names)] #[derive(Debug)] pub enum Error { ConfigurationError, ExportNotFound, InstantiationFailed, CallFailed, IoError(std::io::Error), WASIError(wasmtime_wasi::Error),...
#[test] fn workload_run_no_export() { let bytes = wat::parse_str(NO_EXPORT_WAT).expect("error parsing wat"); match workload::run(&bytes, empty::<String>(), empty::<(String, String)>()) { Err(workload::Error::ExportNotFound) => {} _ => panic!("unexpected error"), ...
fn workload_run_return_1() { let bytes = wat::parse_str(RETURN_1_WAT).expect("error parsing wat"); let results: Vec<i32> = workload::run(&bytes, empty::<String>(), empty::<(String, String)>()) .unwrap() .iter() .map(|v| v.unwrap_i32()) ...
function_block-full_function
[ { "content": "#[cfg(feature = \"gdb\")]\n\npub fn handle_gdb(block: &mut Block, gdb_fd: &mut Option<std::net::TcpStream>, sockaddr: &str) {\n\n use gdbstub::Connection;\n\n\n\n let req = unsafe { block.msg.req };\n\n match req.num.into() {\n\n sallyport::syscall::SYS_ENARX_GDB_START => {\n\n ...
Rust
infra/src/shader.rs
MrShiposha/apriori-engine
faaf897fb72c093a8bc86498bf6f7e913ebc8f02
use { std::{ fs, io::prelude::*, path::{Path, PathBuf} }, shaderc::{ Compiler, CompileOptions, IncludeType, IncludeCallbackResult, ResolvedInclude }, convert_case::{Case, Casing}, pathdiff::diff_paths, crate::{ Result, ...
use { std::{ fs, io::prelude::*, path::{Path, PathBuf} }, shaderc::{ Compiler, CompileOptions, IncludeType, IncludeCallbackResult, ResolvedInclude }, convert_case::{Case, Casing}, pathdiff::diff_paths, crate::{ Result, ...
shaderc::SourceLanguage::GLSL; } else if ext == "hlsl" { source_language = shaderc::SourceLanguage::HLSL; } else { return Err( Error::ShaderFile( format!( "the shader {} has unknown extension {}", ...
entry.path(); if path.is_file() { continue; } if let Some(dir_name) = path.components().last() { if dir_name.as_os_str().to_string_lossy() == SHADER_DIR_NAME { process_shader_dir(src_path, dir, &path)?; break; } } ...
random
[ { "content": "pub fn process_c_srcs(dir: &Path, include_dirs: &Vec<PathBuf>, cc_build: &mut cc::Build) -> Result<()> {\n\n for entry in fs::read_dir(dir)? {\n\n let entry = entry?;\n\n let path = entry.path();\n\n\n\n if path.is_file() {\n\n continue;\n\n }\n\n\n\n ...
Rust
vendor/sgx_tstd/src/sys/rwlock.rs
mesainner/crates-io
b9e098e801cc7180d2d025cf495add70d9f7e9f5
use sgx_types::{SysError, sgx_thread_t, SGX_THREAD_T_NULL}; use sgx_trts::libc; use crate::thread; use crate::sync::SgxThreadMutex; use crate::sync::SgxThreadCondvar; use crate::sync::SgxThreadSpinlock; use core::cell::UnsafeCell; struct SgxThreadRwLockInner { readers_num: u32, writers_num: u32, busy: u3...
use sgx_types::{SysError, sgx_thread_t, SGX_THREAD_T_NULL}; use sgx_trts::libc; use crate::thread; use crate::sync::SgxThreadMutex; use crate::sync::SgxThreadCondvar; use crate::sync::SgxThreadSpinlock; use core::cell::UnsafeCell; struct SgxThreadRwLockInner { readers_num: u32, writers_num: u32, busy: u3...
unsafe fn deref_busy(&mut self) -> SysError { let ret: SysError; self.spinlock.lock(); { if self.busy == 0 { ret = Err(libc::EAGAIN); } else { self.busy -= 1; ret = Ok(()); } } self.spinlock...
e() { ret = Err(libc::EAGAIN); } else { self.busy += 1; ret = Ok(()); } } self.spinlock.unlock(); ret }
function_block-function_prefixed
[]
Rust
planus-cli/src/util/sorted_map.rs
OliverEvans96/planus
c24182f57eafe15e416d240f805a9d30d652c056
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct SortedMap<K, V>(pub Vec<(K, V)>); pub struct SortedSet<K>(SortedMap<K, ()>); impl<K, V> Default for SortedMap<K, V> { fn default() -> Self { Self::new() } } impl<K> Default for SortedSet<K> { fn default() -> Self { S...
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct SortedMap<K, V>(pub Vec<(K, V)>); pub struct SortedSet<K>(SortedMap<K, ()>); impl<K, V> Default for SortedMap<K, V> { fn default() -> Self { Self::new() } } impl<K> Default for SortedSet<K> { fn default() -> Self { S...
} impl<'a, K: 'a, V: 'a> OccupiedEntry<'a, K, V> { pub fn into_mut(self) -> &'a mut V { &mut self.map.0[self.index].1 } pub fn get_mut(&mut self) -> &mut V { &mut self.map.0[self.index].1 } } impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { ...
pub fn or_default(self) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(Default::default()), } }
function_block-full_function
[ { "content": "pub fn align_up(value: u32, alignment: u32) -> u32 {\n\n ((value + alignment - 1) / alignment) * alignment\n\n}\n", "file_path": "planus-cli/src/util/mod.rs", "rank": 0, "score": 163890.73865225195 }, { "content": "pub fn criterion_benchmark(c: &mut Criterion) {\n\n c.ben...
Rust
tokera/src/api/bag.rs
tokera-com/ate
42c4ce5a0c0aef47aeb4420cc6dc788ef6ee8804
#![allow(unused_imports)] use ate::prelude::*; use error_chain::bail; use fxhash::FxHashSet; use std::ops::Deref; use std::sync::Arc; use tracing::{debug, error, info, trace, warn}; use crate::api::TokApi; use crate::error::*; use crate::model::*; impl TokApi { pub(super) async fn __get_bag( &mut self, ...
#![allow(unused_imports)] use ate::prelude::*; use error_chain::bail; use fxhash::FxHashSet; use std::ops::Deref; use std::sync::Arc; use tracing::{debug, error, info, trace, warn}; use crate::api::TokApi; use crate::error::*; use crate::model::*; impl TokApi {
pub(super) async fn __get_or_create_bag( &mut self, denomination: Denomination, ) -> Result<DaoMut<BagOfCoins>, WalletError> { let ret = self .wallet .as_mut() .bags .get_or_default(denomination) .await?; Ok(ret) }...
pub(super) async fn __get_bag( &mut self, denomination: Denomination, ) -> Result<Option<DaoMut<BagOfCoins>>, WalletError> { let ret = self.wallet.as_mut().bags.get_mut(&denomination).await?; Ok(ret) }
function_block-full_function
[ { "content": "fn conv_err(err: FsError) -> Box<dyn std::error::Error> {\n\n error!(\"{}\", err);\n\n let err: std::io::Error = err.into();\n\n err.into()\n\n}\n", "file_path": "wasm-bus-fuse/examples/find.rs", "rank": 0, "score": 91894.57967854003 }, { "content": "fn main() -> Resul...
Rust
src/kernel/src/log.rs
ariadiamond/twizzler-Rust
5f5d01bac9127ca1d64bb8aa472a04f6634fc3a9
use core::{ fmt::Write, sync::atomic::{AtomicU64, Ordering}, }; use twizzler_abi::syscall::{ KernelConsoleReadBufferError, KernelConsoleReadError, KernelConsoleReadFlags, }; use crate::{interrupt, spinlock::Spinlock}; const KEC_BUFFER_LEN: usize = 4096; const MAX_SINGLE_WRITE: usize = KEC_BUF...
use core::{ fmt::Write, sync::atomic::{AtomicU64, Ordering}, }; use twizzler_abi::syscall::{ KernelConsoleReadBufferError, KernelConsoleReadError, KernelConsoleReadFlags, }; use crate::{interrupt, spinlock::Spinlock}; const KEC_BUFFER_LEN: usize = 4096; const MAX_SINGLE_WRITE: usize = KEC_BUF...
} fn write_head(s: u64) -> u64 { (s >> 32) & 0xffff } fn write_resv(s: u64) -> u64 { (s >> 16) & 0xffff } fn read_head(s: u64) -> u64 { s & 0xffff } fn new_state(rh: u64, wh: u64, wr: u64) -> u64 { ((rh % KEC_BUFFER_LEN as u64) & 0xffff) | (((wh % KEC_BUFFER_LEN as u64) & 0...
fn from(x: twizzler_abi::syscall::KernelConsoleWriteFlags) -> Self { if x.contains(twizzler_abi::syscall::KernelConsoleWriteFlags::DISCARD_ON_FULL) { Self::DISCARD_ON_FULL } else { Self::empty() } }
function_block-function_prefix_line
[]
Rust
src/main.rs
boylede/aoc2020
397cc12bb13b7cefb04a151ce87d992b6b7afb6d
use aoc2020::{Day, RunError, Session, SessionError}; use clap::Clap; #[clap(version = "0.1.0", author = "Daniel Boyle")] #[derive(Debug, Clone, Clap)] pub struct Config { #[clap(short = 'd', long = "day", default_value = "1")] pub day: i32, #[clap(short = 'a', long = "all")] pub all: bool, ...
use aoc2020::{Day, RunError, Session, SessionError}; use clap::Clap; #[clap(version = "0.1.0", author = "Daniel Boyle")] #[derive(Debug, Clone, Clap)] pub struct Config { #[clap(short = 'd', long = "day", default_value = "1")] pub day: i32, #[clap(short = 'a', long = "all")] pub all: bool, ...
fn run_day(day: &Day, config: &Config) { if config.clear { println!("Clearing cache..."); day.clear_cache(); } if config.examples { println!("running examples for day {}...", day.index); match day.run_with_examples() { Ok(_) => (), Err(e) => {print_e...
s { run_day(day, &config); } } else { let index = (config.day - 1) as usize; if index < days.len() { let day = &days[index]; run_day(day, &config); } else { println!("Invalid day selection: {}", config.day); } } }
function_block-function_prefixed
[ { "content": "pub fn cache_input_for_day(day: i32, session: &Session) -> Result<Vec<String>, SessionError> {\n\n let file_path = input_cache_path(day);\n\n let file = fs::OpenOptions::new()\n\n .read(true)\n\n .write(false)\n\n .create(false)\n\n .open(&file_path);\n\n let l...
Rust
src/sdk/metrics/mod.rs
zoidbergwill/opentelemetry-rust
30e65af8942c5c7a635c86bd7a02001b833030d5
use crate::api; use crate::exporter::metrics::prometheus; use std::borrow::Cow; use std::collections::HashMap; pub type LabelSet = HashMap<Cow<'static, str>, Cow<'static, str>>; impl api::LabelSet for LabelSet {} #[allow(missing_debug_implementations)] pub struct Meter { registry: &'static prometheus::Registry,...
use crate::api; use crate::exporter::metrics::prometheus; use std::borrow::Cow; use std::collections::HashMap; pub type LabelSet = HashMap<Cow<'static, str>, Cow<'static, str>>; impl api::LabelSet for LabelSet {} #[allow(missing_debug_implementations)] pub struct Meter { registry: &'static prometheus::Registry,...
fn new_i64_gauge<S: Into<String>>(&self, name: S, opts: api::MetricOptions) -> Self::I64Gauge { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let gauge_opts = self.build_opts(name.into(), des...
fn new_f64_counter<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::F64Counter { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let counter_opts = self.b...
function_block-full_function
[ { "content": "/// Convert from `sdk::LabelSet` to `prometheus`' label format.\n\nfn convert_label_set(label_set: &sdk::LabelSet) -> HashMap<&str, &str> {\n\n label_set\n\n .iter()\n\n .map(|(key, value)| (key.as_ref(), value.as_ref()))\n\n .collect()\n\n}\n\n\n\n/// Convert from list of ...
Rust
examples/swdump.rs
a1ien/jaylink
09de031fb4cc3f76f24e4a361977ec6efb6838bd
use jaylink::{Interface, JayLink, SpeedConfig}; use log::trace; use std::{cmp, fmt}; use structopt::StructOpt; const IDLE_CYCLES_BEFORE_ACCESS: usize = 2; #[derive(StructOpt)] struct Opts { #[structopt(long = "serial")] serial: Option<String>, #[structopt(long = "speed")] speed: Option<u1...
use jaylink::{Interface, JayLink, SpeedConfig}; use log::trace; use std::{cmp, fmt}; use structopt::StructOpt; const IDLE_CYCLES_BEFORE_ACCESS: usize = 2; #[derive(StructOpt)] struct Opts { #[structopt(long = "serial")] serial: Option<String>, #[structopt(long = "speed")] speed: Option<u1...
} trait JayLinkExt { fn swj_seq(&mut self) -> jaylink::Result<()>; fn raw_read(&mut self, port: Port, a: u32) -> Result<u32, SwdError>; fn raw_write(&mut self, port: Port, a: u32, value: u32) -> Result<(), SwdError>; } impl JayLinkExt for JayLink { fn swj_seq(&mut self) -> jaylink::Result<()> { ...
Some(match (sl[0], sl[1], sl[2]) { (true, false, false) => Ack::Ok, (false, true, false) => Ack::Wait, (false, false, true) => Ack::Fault, _ => return None, })
call_expression
[ { "content": "fn to_io_error(error: Error) -> io::Error {\n\n io::Error::new(io::ErrorKind::Other, error)\n\n}\n\n\n\nimpl<'a> Read for SwoStream<'a> {\n\n fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n if self.buf.position() == self.buf.get_ref().len() as u64 {\n\n // At ...
Rust
rust/arrow/benches/buffer_bit_ops.rs
jovany-wang/arrow
1f30466ac7042354de35cc69fd49ced1acd54b38
#[macro_use] extern crate criterion; use criterion::Criterion; extern crate arrow; use arrow::buffer::{Buffer, MutableBuffer}; use arrow::error::ArrowError; use arrow::error::Result; #[cfg(feature = "simd")] use arrow::util::bit_util; use std::borrow::BorrowMut; #[cfg(feature = "simd")] use std::slice::{from_raw_pa...
#[macro_use] extern crate criterion; use criterion::Criterion; extern crate arrow; use arrow::buffer::{Buffer, MutableBuffer}; use arrow::error::ArrowError; use arrow::error::Result; #[cfg(feature = "simd")] use arrow::util::bit_util; use std::borrow::BorrowMut; #[cfg(feature = "simd")] use std::slice::{from_raw_pa...
#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd"))] fn bitwise_bin_op_simd_helper<F>(left: &Buffer, right: &Buffer, op: F) -> Result<Buffer> where F: Fn(packed_simd::u8x64, packed_simd::u8x64) -> packed_simd::u8x64, { if left.len() != right.len() { return Err(ArrowError::Co...
zip(left.data().iter().zip(right.data().iter())) .for_each(|(res, (left, right))| { *res = op(*left, *right); }); Ok(result.freeze()) }
function_block-function_prefix_line
[]
Rust
src/main.rs
MichalGniadek/roguelike-tutorial-2021
69b1b7bac0ed939a25f06cdcaf791fe841a9e197
#![feature(iter_intersperse)] #![feature(option_result_contains)] mod bundles; mod dungeon_crawl; mod world_generation; mod world_map; use bevy::{app::AppExit, prelude::*}; use dungeon_crawl::TurnState; use world_map::Grid; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum AppState { MainMenu, Worl...
#![feature(iter_intersperse)] #![feature(option_result_contains)] mod bundles; mod dungeon_crawl; mod world_generation; mod world_map; use bevy::{app::AppExit, prelude::*}; use dungeon_crawl::TurnState; use world_map::Grid; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum AppState { MainMenu, Worl...
ttf"), font_size: 100.0, color: Color::WHITE, }, TextAlignment::default(), ), ..Default::default() }); }); ...
_2d(); orto.orthographic_projection.scale = 8.0; commands.spawn_bundle(orto); commands .spawn_bundle(UiCameraBundle::default()) .insert(UiCamera); }) .system(), ); #[cfg(target_arch = "wasm32")] app.add_plugin(bevy_webgl2:...
random
[ { "content": "pub fn cleanup_log_and_inventory(mut commands: Commands, inventory: Res<GameData>) {\n\n commands.insert_resource(Logs::default());\n\n for e in inventory.inventory.iter().filter_map(|i| *i) {\n\n commands.entity(e).despawn();\n\n }\n\n commands.insert_resource(GameData::default...
Rust
proxy/tests/discovery.rs
xiaods/conduit
bc16034fd6d3c88f20a4e7a6dc3f0baa0e3ce06f
mod support; use self::support::*; macro_rules! generate_tests { (server: $make_server:path, client: $make_client:path) => { use conduit_proxy_controller_grpc as pb; #[test] fn outbound_asks_controller_api() { let _ = env_logger::try_init(); let srv = $make_server()...
mod support; use self::support::*; macro_rules! generate_tests { (server: $make_server:path, client: $make_client:path) => { use conduit_proxy_controller_grpc as pb; #[test] fn outbound_asks_controller_api() { let _ = env_logger::try_init(); let srv = $make_server()...
let client2 = client::http1(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client2.get("/h1"), "hello h1"); }
function_block-function_prefix_line
[ { "content": "fn run(proxy: Proxy, mut env: config::TestEnv) -> Listening {\n\n use self::conduit_proxy::config;\n\n\n\n let controller = proxy.controller.expect(\"proxy controller missing\");\n\n let inbound = proxy.inbound;\n\n let outbound = proxy.outbound;\n\n let mut mock_orig_dst = DstInner...
Rust
src/rendering.rs
Ipotrick/eisen
fa86495574f3be99213e0ed98f0963db0f43614a
use std::{time::{SystemTime, Instant}}; use async_std::sync::Mutex; use wgpu::{util::{DeviceExt, RenderEncoder}, BindGroupDescriptor, RenderPipelineDescriptor}; use winit::{dpi::PhysicalSize, window::Window}; const QUADS_PER_BATCH: usize = 1024; #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroab...
use std::{time::{SystemTime, Instant}}; use async_std::sync::Mutex; use wgpu::{util::{DeviceExt, RenderEncoder}, BindGroupDescriptor, RenderPipelineDescriptor}; use winit::{dpi::PhysicalSize, window::Window}; const QUADS_PER_BATCH: usize = 1024; #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroab...
pub async fn render(&self) -> Result<(), wgpu::SurfaceError> { let mut state = self.state.lock().await; let state = &mut*state; let output = state.shared_ressources.surface.get_current_texture()?; let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());...
for i in 0..state.last_buffer_index { let slice = bytemuck::cast_slice(&quads[i*QUADS_PER_BATCH..(i+1)*state.last_buffer_index]); state.shared_ressources.main_queue.write_buffer(&state.rect_draw_buffers[i].0, 0, slice); } let slice = bytemuck::cast_slice(&quads[st...
function_block-function_prefix_line
[ { "content": "#[allow(unused)]\n\npub fn block_on<Out>(mut future: impl Future<Output = Out>) -> Out {\n\n LOCAL_BLOCK_ON_DATA.with(\n\n |ref_cell| {\n\n let local_block_data = ref_cell.borrow_mut();\n\n let waker = waker_ref(&local_block_data.waker);\n\n let context =...
Rust
src/state.rs
peterschwarz/sawtooth-pbft
f9b5372fc028d5c47ad4f2a7c6947cbc77272a50
/* * Copyright 2018 Bitwise IO, Inc. * * 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 agree...
/* * Copyright 2018 Bitwise IO, Inc. * * 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 agree...
mary(&self) -> bool { self.role == PbftNodeRole::Primary } pub fn upgrade_role(&mut self) { self.role = PbftNodeRole::Primary; } pub fn downgrade_role(&mut self) { self.role = PbftNodeRole::Secondary; } pub fn switch_phase(&mut self, desired_phase: ...
{ "*" } else { " " }; let mode = match self.mode { PbftMode::Normal => "N", PbftMode::Checkpointing => "C", PbftMode::ViewChanging => "V", }; let phase = match self.phase { PbftPhase::NotStarted => "NS", PbftPhase::PrePreparing => "PP...
random
[ { "content": "#[allow(clippy::ptr_arg)]\n\npub fn commit(\n\n state: &mut PbftState,\n\n service: &mut Service,\n\n message: &ParsedMessage,\n\n) -> Result<(), PbftError> {\n\n info!(\n\n \"{}: Committing block {:?}\",\n\n state,\n\n message.get_block().block_id.clone()\n\n )...
Rust
src/dclic/src/main.rs
alexcpsec/dcli
076a7e21a0bccc453722c9fb69b960d433666736
/* * Copyright 2021 Mike Chambers * https://github.com/mikechambers/dcli * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * us...
/* * Copyright 2021 Mike Chambers * https://github.com/mikechambers/dcli * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * us...
fn print_default(characters: &Characters) { let col_w = 12; let col_id = 24; println!( "{:<0col_w$}{:<0col_id$}{:<0col_w$}", "CLASS", "ID", "STATUS", col_w = col_w, col_id = col_id, ); println!("{}", repeat_str("-", col_w * 2 + col_id)); for p ...
async fn main() { let opt = Opt::from_args(); print_verbose(&format!("{:#?}", opt), opt.verbose); let chars: Characters = match retrieve_characters(opt.member_id, opt.platform, opt.verbose) .await { Ok(e) => match e { Some(e) => e, Non...
function_block-full_function
[ { "content": "/// Command line tool for retrieving and managing the Destiny 2 manifest database.\n\n///\n\n/// Manifest will be stored in the specified local directory with the file name:\n\n/// manifest.sqlite3, along with meta-data with information about the downloaded\n\n/// version. This is used to to deter...
Rust
tezos/context/src/serialize/mod.rs
tezedge/tezedge
b8e20d9886ad8b6876ad62375bacf1f6b7999e3b
use std::{ array::TryFromSliceError, convert::TryInto, io::Write, num::TryFromIntError, str::Utf8Error, string::FromUtf8Error, sync::Arc, }; use modular_bitfield::prelude::*; use tezos_timing::SerializeStats; use thiserror::Error; use crate::{ hash::HashingError, kv_store::HashId, persistent::DB...
use std::{ array::TryFromSliceError, convert::TryInto, io::Write, num::TryFromIntError, str::Utf8Error, string::FromUtf8Error, sync::Arc, }; use modular_bitfield::prelude::*; use tezos_timing::SerializeStats; use thiserror::Error; use crate::{ hash::HashingError, kv_store::HashId, persistent::DB...
pub fn serialize_hash_id_impl( hash_id: Option<HashId>, output: &mut Vec<u8>, repository: &mut ContextKeyValueStore, stats: &mut SerializeStats, ) -> Result<(), SerializationError> { let hash_id = match hash_id { Some(hash_id) => repository.make_hash_id_ready_for_commit(hash_id)?.as_u64(),...
2::from_be_bytes(hash_id.try_into()?); let hash_id = hash_id as u64; let hash_id = hash_id & (COMPACT_HASH_ID_BIT - 1); let hash_id = HashId::new(hash_id); Ok((hash_id, 4)) } else { let hash_id = data.get(0..6).ok_or(UnexpectedEOF)?; let hash_id =...
function_block-function_prefixed
[ { "content": "fn write_object_header(output: &mut Vec<u8>, start: usize, tag: ObjectTag) {\n\n let length = output.len() - start;\n\n\n\n if length <= 0xFF {\n\n let header: [u8; 1] = ObjectHeader::new()\n\n .with_tag(tag)\n\n .with_length(ObjectLength::OneByte)\n\n ...
Rust
vendor/pulldown-cmark/src/simd.rs
47565647456/evtx
fbb2a713d335f5208bb6675f4f158babd6f2f389
use crate::parse::{LookupTable, LoopInstruction, Options}; use core::arch::x86_64::*; pub(crate) const VECTOR_SIZE: usize = std::mem::size_of::<__m128i>(); pub(crate) fn compute_lookup(options: &Options) -> [u8; 16] { let mut lookup = [0u8; 16]; let standard_bytes = [ b'\n', b'\r', b'*', b'_', b'&',...
use crate::parse::{LookupTable, LoopInstruction, Options}; use core::arch::x86_64::*; pub(crate) const VECTOR_SIZE: usize = std::mem::size_of::<__m128i>(); pub(crate) fn compute_lookup(options: &Options) -> [u8; 16] { let mut lookup = [0u8; 16]; let standard_bytes = [ b'\n', b'\r', b'*', b'_', b'&',...
pts = Options::empty(); opts.insert(Options::ENABLE_TABLES); opts.insert(Options::ENABLE_FOOTNOTES); opts.insert(Options::ENABLE_STRIKETHROUGH); opts.insert(Options::ENABLE_TASKLISTS); let lut = crate::parse::create_lut(&opts); let mut indices = vec![]; iterate_...
struction}; use crate::Options; fn check_expected_indices(bytes: &[u8], expected: &[usize], skip: usize) { let mut o
random
[ { "content": "pub fn read_attribute(cursor: &mut Cursor<&[u8]>) -> Result<BinXMLAttribute> {\n\n trace!(\"Offset `0x{:08x}` - Attribute\", cursor.position());\n\n let name = BinXmlNameRef::from_stream(cursor)?;\n\n\n\n Ok(BinXMLAttribute { name })\n\n}\n\n\n", "file_path": "src/binxml/tokens.rs", ...
Rust
src/creeps/lrh.rs
snorrwe/xenos
2b625daf8edea133949a70dcf1579dddc65a3668
use super::{ approach_target_room, gofer, harvester, update_scout_info, upgrader, CreepState, HOME_ROOM, LOADING, TARGET, TASK, }; use crate::prelude::*; use crate::state::RoomIFF; use num::FromPrimitive; use screeps::prelude::*; const HARVEST_TARGET_ROOM: &'static str = "harvest_target_room"; #[derive(Debu...
use super::{ approach_target_room, gofer, harvester, update_scout_info, upgrader, CreepState, HOME_ROOM, LOADING, TARGET, TASK, }; use crate::prelude::*; use crate::state::RoomIFF; use num::FromPrimitive; use screeps::prelude::*; const HARVEST_TARGET_ROOM: &'static str = "harvest_target_room"; #[derive(Debu...
() .enumerate() .filter(|(_, wp)| { scout_intel .get(&wp) .map(|int| match int.iff { RoomIFF::Unknown | RoomIFF::Neutral => true, _ => false, }) .unwrap...
{ &mut *state.mut_game_state() }; let counts: &mut _ = gs .long_range_harvesters .entry(room) .or_insert([0; 4]); let scout_intel = &gs.scout_intel; let (i, target) = neighbours .iter
function_block-random_span
[ { "content": "/// target_key is a memory entry key\n\npub fn approach_target_room(state: &mut CreepState, target_key: &str) -> ExecutionResult {\n\n let target = state.creep_memory_string(target_key).ok_or(\"no target\")?;\n\n\n\n let creep = state.creep();\n\n\n\n let room = creep.room();\n\n let r...
Rust
libeir_ir/src/algo/equality.rs
lumen/eir
37e790f388d13a836991f8a6220eb322269d509e
use std::collections::{BTreeMap, VecDeque}; use snafu::Snafu; use crate::Function; use crate::ValueKind; use crate::{Block, Const, PrimOp, Value}; #[derive(Snafu, Debug, PartialEq, Eq)] pub enum EqualityFail { BlockArity { left: Block, right: Block }, BlockOp { left: Block, right: Block }, BlockReadsLe...
use std::collections::{BTreeMap, VecDeque}; use snafu::Snafu; use crate::Function; use crate::ValueKind; use crate::{Block, Const, PrimOp, Value}; #[derive(Snafu, Debug, PartialEq, Eq)] pub enum EqualityFail { BlockArity { left: Block, right: Block }, BlockOp { left: Block, right: Block }, BlockReadsLe...
Ok(()) } (ValueKind::PrimOp(lp), ValueKind::PrimOp(rp)) => { let l_reads = ctx.lf.primop_reads(lp); let r_reads = ctx.rf.primop_reads(rp); if l_reads.len() != r_reads.len() { return Err(EqualityFail::PrimReadsLength { l...
if !ctx.lf.cons().eq_other(lc, ctx.rf.cons(), rc) { return Err(EqualityFail::MismatchingConst { left: lc, right: rc, }); }
if_condition
[ { "content": "fn lower_function(ctx: &mut LowerCtx, b: &mut FunctionBuilder, fun: &Function) -> IrBlock {\n\n let entry = b.block_insert_with_span(Some(fun.span()));\n\n\n\n match fun {\n\n Function::Named(_named) => unimplemented!(),\n\n Function::Unnamed(lambda) => {\n\n ctx.fun...
Rust
src/firmware/types.rs
tfanelli-rh/sev
e0e17aac9249b00b0cb3e24a2780ca814d229a11
use crate::certs::sev; use crate::Version; use std::marker::PhantomData; pub struct PlatformReset; bitflags::bitflags! { #[derive(Default)] pub struct PlatformStatusFlags: u32 { const OWNED = 1 << 0; const ENCRYPTED_STATE = 1 << 8; } } #[derive(Default...
use crate::certs::sev; use crate::Version; use std::marker::PhantomData; pub struct PlatformReset; bitflags::bitflags! { #[derive(Default)] pub struct PlatformStatusFlags: u32 { const OWNED = 1 << 0; const ENCRYPTED_STATE = 1 << 8; } } #[derive(Default...
*const u8, self.id_len as _) } } } #[derive(Default)] #[repr(C, packed)] pub struct SnpPlatformStatus { pub version: Version, pub state: u8, pub build_id: u32, pub guest_count: u32, pub tcb_version: u64, }
-> Self { Self { addr: cert as *mut _ as _, len: std::mem::size_of_val(cert) as _, _phantom: PhantomData, } } } #[repr(C, packed)] pub struct PekCertImport<'a> { pek_addr: u64, pek_len: u32, oca_addr: u64, oca_len: u32, _phantom: PhantomData<...
random
[]
Rust
apps/fifteen_min/src/bus.rs
lucasccdias/abstreet
cf88a2a13396d1872f5165f54189c753b9686d21
use abstutil::prettyprint_usize; use geom::Duration; use map_gui::tools::{InputWaypoints, WaypointID}; use map_model::connectivity::WalkingOptions; use synthpop::{TripEndpoint, TripMode}; use widgetry::mapspace::{ObjectID, World, WorldOutcome}; use widgetry::{ Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line...
use abstutil::prettyprint_usize; use geom::Duration; use map_gui::tools::{InputWaypoints, WaypointID}; use map_model::connectivity::WalkingOptions; use synthpop::{TripEndpoint, TripMode}; use widgetry::mapspace::{ObjectID, World, WorldOutcome}; use widgetry::{ Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line...
lAlignment::Left, VerticalAlignment::Top) .ignore_initial_events() .build(ctx); } } impl State<App> for BusExperiment { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition<App> { let panel_outcome = self.panel.event(ctx); if let Outcome::Clicked(ref x) = panel_o...
lEq, Eq, Hash)] enum ID { Waypoint(WaypointID), BusRoute(usize), } impl ObjectID for ID {} impl BusExperiment { pub fn new_state(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> { let mut state = BusExperiment { panel: Panel::empty(ctx), waypoints: InputWaypoints::...
random
[ { "content": "pub fn custom_bar(ctx: &mut EventCtx, filled_color: Color, pct_full: f64, txt: Text) -> Widget {\n\n let total_width = 300.0;\n\n let height = 32.0;\n\n let radius = 4.0;\n\n\n\n let mut batch = GeomBatch::new();\n\n // Background\n\n batch.push(\n\n Color::hex(\"#666666\"...
Rust
tests/expectations/tests/issue-648-derive-debug-with-padding.rs
rust-lang-nursery/rust-bindgen
5a01c551993e56d20240ef64d0ec78cd4195855d
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[repr(align(64))] #[derive(Copy, Clone)] pub struct NoDebug { pub c: ::std::os::raw::c_char, } #[test] fn bindgen_test_layout_NoDebug() { assert_eq!( ::std::mem::size_of::<NoDebug>(), ...
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[repr(align(64))] #[derive(Copy, Clone)] pub struct NoDebug { pub c: ::std::os::raw::c_char, } #[test] fn bindgen_test_layout_NoDebug() { assert_eq!( ::std::mem::size_of::<NoDebug>(), ...
} impl ::std::cmp::PartialEq for NoDebug { fn eq(&self, other: &NoDebug) -> bool { self.c == other.c } } #[repr(C)] #[repr(align(64))] #[derive(Copy, Clone)] pub struct ShouldDeriveDebugButDoesNot { pub c: [::std::os::raw::c_char; 32usize], pub d: ::std::os::raw::c_char, } #[test] fn bindgen_t...
et mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn bindgen_test_layout_ShouldImplClone() {\n\n assert_eq!(\n\n ::std::mem::size_of::<ShouldImplClone>(),\n\n 132usize,\n\n concat!(\"Size of: \", stringify!(ShouldImplClone))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<ShouldImplClone>(),\n\n ...
Rust
src/modules/centerdevice/auth.rs
dschneller/ceres
9449011264d17fdd4b03a262930d8fe19ff9dc8f
use clams::prelude::{Config as ClamsConfig}; use clap::{App, Arg, ArgMatches, SubCommand}; use centerdevice::{CenterDevice, Client, ClientCredentials, Token}; use centerdevice::client::AuthorizedClient; use centerdevice::client::auth::{Code, CodeProvider, IntoUrl}; use centerdevice::errors::{Result as CenterDeviceResul...
use clams::prelude::{Config as ClamsConfig}; use clap::{App, Arg, ArgMatches, SubCommand}; use centerdevice::{CenterDevice, Client, ClientCredentials, Token}; use centerdevice::client::AuthorizedClient; use centerdevice::client::auth::{Code, CodeProvider, IntoUrl}; use centerdevice::errors::{Result as CenterDeviceResul...
Ok(()) } fn get_token(centerdevice: &CenterDeviceConfig) -> Result<Token> { let client_credentials = ClientCredentials::new( &centerdevice.client_id, &centerdevice.client_secret, ); let code_provider = CliCodeProvider {}; info!("Authenticating with CenterDevice at {}", centerdevi...
if args.is_present("save") { save_token(run_config, config, &token) .chain_err(|| ErrorKind::FailedToSaveToken)?; }
if_condition
[ { "content": "fn query_health(client: &ReqwestClient, name: &'static str, url: &str) -> impl Future<Item = HealthCheck, Error = Error> {\n\n trace!(\"Quering health for {}\", url);\n\n client\n\n .get(url)\n\n .header(Connection::close())\n\n .send()\n\n .map_err(|e| Error::with_chain(e,...
Rust
src/cli/doc_get.rs
couchbaselabs/couchbase-shell
28498991f17c7383e255cceb05eb71e543ae9d6e
use super::util::convert_json_value_to_nu_value; use crate::state::State; use crate::cli::doc_upsert::{build_batched_kv_items, prime_manifest_if_required}; use crate::cli::util::cluster_identifiers_from; use crate::client::KeyValueRequest; use futures::stream::FuturesUnordered; use futures::StreamExt; use log::debug...
use super::util::convert_json_value_to_nu_value; use crate::state::State; use crate::cli::doc_upsert::{build_batched_kv_items, prime_manifest_if_required}; use crate::cli::util::cluster_identifiers_from; use crate::client::KeyValueRequest; use futures::stream::FuturesUnordered; use futures::StreamExt; use log::debug...
} fn run_get(state: Arc<Mutex<State>>, mut args: CommandArgs) -> Result<OutputStream, ShellError> { let ctrl_c = args.ctrl_c(); let cluster_identifiers = cluster_identifiers_from(&state, &args, true)?; let batch_size: Option<i32> = args.get_flag("batch-size")?; let id_column: String = args.get_flag("...
mand", example: "echo [[id]; [airline_10] [airline_11]] | doc get", result: None, }, ] }
function_block-function_prefixed
[ { "content": "fn buckets_get(state: Arc<Mutex<State>>, args: CommandArgs) -> Result<OutputStream, ShellError> {\n\n let ctrl_c = args.ctrl_c();\n\n\n\n let cluster_identifiers = cluster_identifiers_from(&state, &args, true)?;\n\n let bucket: String = args.req(0)?;\n\n\n\n debug!(\"Running buckets ge...
Rust
crates/interledger-settlement-engines/src/stores/redis_ethereum_ledger/store.rs
pensivej/interledger-rs
f86937f11ee4557887b66c2a7dc935a6475bbd3a
use futures::{ future::{err, ok}, Future, }; use ethereum_tx_sign::web3::types::{Address as EthAddress, H256, U256}; use interledger_service::Account as AccountTrait; use std::collections::HashMap; use crate::engines::ethereum_ledger::{EthereumAccount, EthereumAddresses, EthereumStore}; use redis::{self, cmd,...
use futures::{ future::{err, ok}, Future, }; use ethereum_tx_sign::web3::types::{Address as EthAddress, H256, U256}; use interledger_service::Account as AccountTrait; use std::collections::HashMap; use crate::engines::ethereum_ledger::{EthereumAccount, EthereumAddresses, EthereumStore}; use redis::{self, cmd,...
.unwrap() } #[test] fn saves_and_loads_last_observed_data_properly() { block_on(test_store().and_then(|(store, context)| { let block = U256::from(2); store .save_recently_observed_block(block) .map_err(|err| eprintln!("Redis error: {:...
block_on(test_store().and_then(|(store, context)| { let account_ids = vec![30, 42]; let account_addresses = vec![ EthereumAddresses { own_address: EthAddress::from_str("3cdb3d9e1b74692bb1e3bb5fc81938151ca64b02") .unwrap(), ...
call_expression
[ { "content": "pub fn delay(ms: u64) -> impl Future<Item = (), Error = ()> {\n\n Delay::new(Instant::now() + Duration::from_millis(ms)).map_err(|err| panic!(err))\n\n}\n\n\n", "file_path": "crates/interledger-settlement-engines/tests/redis_helpers.rs", "rank": 0, "score": 401299.29343494965 }, ...
Rust
kernel-hal/src/bare/arch/riscv/vm.rs
SummerVibes/zCore
09c69b2adc920b6edc78a7d45d9237bfd8b43d40
use core::fmt::{Debug, Formatter, Result}; use core::slice; use riscv::{asm, register::satp}; use spin::Mutex; use crate::addr::{align_down, align_up}; use crate::utils::page_table::{GenericPTE, PageTableImpl, PageTableLevel3}; use crate::{mem::phys_to_virt, MMUFlags, PhysAddr, VirtAddr, KCONFIG, PAGE_SIZE}; lazy_st...
use core::fmt::{Debug, Formatter, Result}; use core::slice; use riscv::{asm, register::satp}; use spin::Mutex; use crate::addr::{align_down, align_up}; use crate::utils::page_table::{GenericPTE, PageTableImpl, PageTableLevel3}; use crate::{mem::phys_to_virt, MMUFlags, PhysAddr, VirtAddr, KCONFIG, PAGE_SIZE}; lazy_st...
} impl From<PTF> for MMUFlags { fn from(f: PTF) -> Self { let mut ret = Self::empty(); if f.contains(PTF::READABLE) { ret |= Self::READ; } if f.contains(PTF::WRITABLE) { ret |= Self::WRITE; } if f.contains(PTF::EXECUTABLE) { ret |...
f: MMUFlags) -> Self { if f.is_empty() { return PTF::empty(); } let mut flags = PTF::VALID; if f.contains(MMUFlags::READ) { flags |= PTF::READABLE; } if f.contains(MMUFlags::WRITE) { flags |= PTF::READABLE | PTF::WRITABLE; } ...
function_block-function_prefixed
[]
Rust
build/main.rs
cdecompilador/rust-xcb
d83de0035743766c4503b9e699fb22cc1a6d2986
extern crate quick_xml; mod ast; mod codegen; mod output; mod parse; use std::env; use std::fs; use std::path::{Path, PathBuf}; use ast::{Event, ExtInfo, OpCopy, OpCopyMap}; use codegen::{CodeGen, DepInfo}; use output::Output; use parse::{Parser, Result}; fn xcb_mod_map(name: &str) -> &str { match name { ...
extern crate quick_xml; mod ast; mod codegen; mod output; mod parse; use std::env; use std::fs; use std::path::{Path, PathBuf}; use ast::{Event, ExtInfo, OpCopy, OpCopyMap}; use codegen::{CodeGen, DepInfo}; use output::Output; use parse::{Parser, Result}; fn xcb_mod_map(name: &str) -> &str {
} fn is_always(name: &str) -> bool { matches!(name, "xproto" | "big_requests" | "xc_misc") } fn has_feature(name: &str) -> bool { env::var(format!("CARGO_FEATURE_{}", name.to_ascii_uppercase())).is_ok() } fn main() { let root = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); let ...
match name { "bigreq" => "big_requests", "ge" => "genericevent", "xselinux" => "selinux", "xprint" => "x_print", "xtest" => "test", _ => name, }
if_condition
[ { "content": "fn main() {\n\n let dpy = \":0\";\n\n if let Ok((_, _)) = xcb::Connection::connect(Some(&dpy)) {\n\n println!(\"Connected to X on display \\\"{}\\\"!\", dpy);\n\n } else {\n\n println!(\"Could not connect to X!\");\n\n }\n\n}\n", "file_path": "examples/connect_str.rs"...