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
odbc-api/src/handles/connection.rs
grovesNL/odbc-api
cfab96c2cff187200b5f2b903ab9227d3e70b1db
use super::{ as_handle::AsHandle, buffer::buf_ptr, drop_handle, error::Error, error::IntoResult, statement::StatementImpl, }; use odbc_sys::{ CompletionType, ConnectionAttribute, DriverConnectOption, HDbc, HEnv, HStmt, Handle, HandleType, Pointer, SQLAllocHandle, SQLConnectW, SQLDisconnect, SQLDriverCon...
use super::{ as_handle::AsHandle, buffer::buf_ptr, drop_handle, error::Error, error::IntoResult, statement::StatementImpl, }; use odbc_sys::{ CompletionType, ConnectionAttribute, DriverConnectOption, HDbc, HEnv, HStmt, Handle, HandleType, Pointer, SQLAllocHandle, SQLConnectW, SQLDisconnect, SQLDriverCon...
pub fn commit(&self) -> Result<(), Error> { unsafe { SQLEndTran(HandleType::Dbc, self.as_handle(), CompletionType::Commit).into_result(self) } } pub fn rollback(&self) -> Result<(), Error> { unsafe { SQLEndTran(HandleType::Dbc, self.as_handle(), C...
pub fn set_autocommit(&self, enabled: bool) -> Result<(), Error> { let val = if enabled { 1u32 } else { 0u32 }; unsafe { SQLSetConnectAttrW( self.handle, ConnectionAttribute::AutoCommit, val as Pointer, 0, ) ...
function_block-full_function
[ { "content": "/// Returns a pointer suitable to be passed as an output buffer to ODBC functions. Most notably it\n\n/// will return NULL for empty buffers.\n\npub fn mut_buf_ptr<T>(buffer: &mut [T]) -> *mut T {\n\n if buffer.is_empty() {\n\n null_mut()\n\n } else {\n\n buffer.as_mut_ptr()\n\...
Rust
agency_client/src/update_connection.rs
bosch-io/aries-vcx
ab5bf5efe701d9a21c32aa68c82e5a52d9bb25ed
use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; use crate::{A2AMessage, A2AMessageKinds, A2AMessageV2, delete_connection, GeneralMessage, parse_response_from_agency, prepare_message_for_agent}; use crate::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}; u...
use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; use crate::{A2AMessage, A2AMessageKinds, A2AMessageV2, delete_connection, GeneralMessage, parse_response_from_agency, prepare_message_for_agent}; use crate::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult}; u...
} #[cfg(test)] mod tests { use super::*; use crate::utils::test_constants::DELETE_CONNECTION_DECRYPTED_RESPONSE; #[test] #[cfg(feature = "general_test")] fn test_deserialize_delete_connection_payload() { let delete_connection_payload: UpdateConnectionResponse = serde_json::from_str(DELET...
fn prepare_request(&mut self) -> AgencyClientResult<Vec<u8>> { let message = A2AMessage::Version2( A2AMessageV2::UpdateConnection( UpdateConnection { msg_type: MessageTypes::build(A2AMessageKinds::UpdateConnectionStatus), status_code: self.stat...
function_block-full_function
[ { "content": "pub fn parse_message_type(message_type: &str) -> AgencyClientResult<(String, String, String, String)> {\n\n lazy_static! {\n\n static ref RE: Regex = Regex::new(r\"(?x)\n\n (?P<did>[\\d\\w:]*);\n\n (?P<spec>.*)/\n\n (?P<family>.*)/\n\n (?P<vers...
Rust
src/vulkan/physical_device/mod.rs
JHorace/ForgeEngine
6b3ab772c89c412a028cfd0f85bf969b83fa45c2
use ash::vk; use std::ffi::CStr; use std::os::raw::c_char; use super::utility::tools; use crate::vulkan::utility::tools::truncate_optional_usize_to_optional_u32; use ash::version::InstanceV1_0; use std::ptr; pub struct QueueFamilyIndices { pub graphics_: Option<u32>, pub graphics_compute_: Option<u32>, pu...
use ash::vk; use std::ffi::CStr; use std::os::raw::c_char; use super::utility::tools; use crate::vulkan::utility::tools::truncate_optional_usize_to_optional_u32; use ash::version::InstanceV1_0; use std::ptr; pub struct QueueFamilyIndices { pub graphics_: Option<u32>, pub graphics_compute_: Option<u32>, pu...
} suitable_devices } fn is_gpu(instance: &ash::Instance, physical_device: vk::PhysicalDevice) -> bool { let device_properties = unsafe { instance.get_physical_device_properties(physical_device) }; match device_properties.device_type { vk::PhysicalDeviceType::DISCRETE_GPU | vk::Physic...
if is_suitable(instance, device, num_device_extensions, device_extensions) { suitable_devices.push(PhysicalDevice::new(instance, device)); }
if_condition
[]
Rust
src/config.rs
rishabh-vasudevan/drg
61ebc05afbdb5dcbe82f61982f4789c5310c82f3
use anyhow::{anyhow, Context as AnyhowContext, Result}; use serde::{Deserialize, Serialize}; use std::{env, fs::create_dir_all, fs::write, fs::File, path::Path}; use chrono::{DateTime, Utc}; use oauth2::basic::BasicTokenResponse; use read_input::prelude::*; use url::Url; use crate::AppId; type ContextId = String; #...
use anyhow::{anyhow, Context as AnyhowContext, Result}; use serde::{Deserialize, Serialize}; use std::{env, fs::create_dir_all, fs::write, fs::File, path::Path}; use chrono::{DateTime, Utc}; use oauth2::basic::BasicTokenResponse; use read_input::prelude::*; use url::Url; use crate::AppId; type ContextId = String; #...
pub fn delete_context(&mut self, name: &str) -> Result<()> { if self.contains_context(&name) { self.contexts.retain(|c| c.name != name); if self.active_context == name { if !self.contexts.is_empty() { self.active_context = self.contexts[0].name....
pub fn write(&self, path: Option<&str>) -> Result<()> { let path = eval_config_path(path); if let Some(parent) = Path::new(&path).parent() { create_dir_all(parent).context("Failed to create parent directory of configuration")?; } log::info!("Saving config file: {}", &path); ...
function_block-full_function
[ { "content": "pub fn verify_token_validity(context: &mut Context) -> Result<bool> {\n\n log::debug!(\"Token expires at : {}\", context.token_exp_date);\n\n // 30 seconds should be enough\n\n if context.token_exp_date - Utc::now() > Duration::seconds(30) {\n\n Ok(false)\n\n } else {\n\n ...
Rust
src/sdk/resource.rs
bnjjj/opentelemetry-rust
8a828a81b3c9750ce4ccebe47d104e69929e8ee6
use crate::api; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use std::collections::{btree_map, btree_map::Entry, BTreeMap}; #[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Default, PartialEq)] pub struct Resource { attrs: BTreeMap<api::Key, api::Val...
use crate::api; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use std::collections::{btree_map, btree_map::Entry, BTreeMap}; #[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Default, PartialEq)] pub struct Resource { a
]; let mut expected_attrs = BTreeMap::new(); expected_attrs.insert(api::Key::new("a"), api::Value::from("final")); assert_eq!( Resource::new(args_with_dupe_keys), Resource { attrs: expected_attrs } ); } #[test] fn merge...
ttrs: BTreeMap<api::Key, api::Value>, } impl Resource { pub fn new<T: IntoIterator<Item = api::KeyValue>>(kvs: T) -> Self { let mut resource = Resource::default(); for kv in kvs.into_iter() { resource.insert(kv); } resource } ...
random
[ { "content": "/// Allows a specific [`Provider`] to be used generically by the\n\n/// [`GlobalProvider`] by mirroring the interface and boxing the return types.\n\n///\n\n/// [`Provider`]: ../api/trace/provider/trait.Provider.html\n\n/// [`GlobalProvider`]: struct.GlobalProvider.html\n\npub trait GenericProvide...
Rust
src/main.rs
actuday6418/spotify-tui
2cffc2e3c4e3da208b35c1113d2bb5e77d6dfddb
mod app; mod cli_app; mod config; mod network; mod redirect_uri; mod user_config; use cli_app::CliApp; use config::ClientConfig; use redirect_uri::redirect_uri_web_server; use rspotify::{ oauth2::SpotifyOAuth, util::{process_token, request_token}, }; use std::error::Error; use std::io; use user_config::UserC...
mod app; mod cli_app; mod config; mod network; mod redirect_uri; mod user_config; use cli_app::CliApp; use config::ClientConfig; use redirect_uri::redirect_uri_web_server; use rspotify::{ oauth2::SpotifyOAuth, util::{process_token, request_token}, }; use std::error::Error; use std::io; use user_config::UserC...
net .handle_network_event(IoEvent::GetCurrentPlayback) .await; let devices_list = match &cli.net.app.lock().await.devices { Some(p) => p .devices .iter() .map(|d| d.id.clone()) .collect::<Vec<String>>(), None => Vec::new(), }; ...
function_block-function_prefix_line
[ { "content": "pub fn redirect_uri_web_server(spotify_oauth: &mut SpotifyOAuth, port: u16) -> Result<String, ()> {\n\n let listener = TcpListener::bind(format!(\"127.0.0.1:{}\", port));\n\n\n\n match listener {\n\n Ok(listener) => {\n\n request_token(spotify_oauth);\n\n\n\n for stream in listener....
Rust
crates/core_simd/src/macros.rs
thomcc/stdsimd
a1c327a034425b1cc44f47a825ab2dcbfdd24b22
macro_rules! from_transmute { { unsafe $a:ty => $b:ty } => { from_transmute!{ @impl $a => $b } from_transmute!{ @impl $b => $a } }; { @impl $from:ty => $to:ty } => { impl core::convert::From<$from> for $to { #[inline] fn from(value: $from) -> $to { ...
macro_rules! from_transmute { { unsafe $a:ty => $b:ty } => { from_transmute!{ @impl $a => $b } from_transmute!{ @impl $b => $a } }; { @impl $from:ty => $to:ty } => { impl core::convert::From<$from> for $to { #[inline] fn from(value: $from) -> $to { ...
} } } macro_rules! integer_vector_traits { { $name:path => [$type:ty; $lanes:literal] } => { impl Eq for $name {} impl Ord for $name { #[inline] fn cmp(&self, other: &Self) -> core::cmp::Ordering { AsRef::<[$type]>::as_ref(self).cmp(AsRef::<[$type]>::as_...
safe { core::mem::transmute(value) } } } }; } macro_rules! from_transmute_x86 { { unsafe $generic:ty => $intel:ident } => { #[cfg(target_arch = "x86")] from_transmute! { unsafe $generic => core::arch::x86::$intel } #[cfg(target_arch = "x86_64")] from_transmu...
random
[ { "content": "pub fn apply_unary_lanewise<T: Copy, V: AsMut<[T]> + Default>(mut x: V, f: impl Fn(T) -> T) -> V {\n\n for lane in x.as_mut() {\n\n *lane = f(*lane)\n\n }\n\n x\n\n}\n\n\n", "file_path": "crates/core_simd/tests/helpers/lanewise.rs", "rank": 0, "score": 58551.31246244428...
Rust
src/resolv/transport/pending.rs
cloudshipping/domain-rs
a9dd399ffe2f58aa0e07ed97a2c92f71579203ca
use std::io; use std::collections::{HashMap, VecDeque}; use std::time::{Duration, Instant}; use futures::{Async, Future}; use rand::random; use tokio_core::reactor; use super::super::error::Error; use super::super::request::TransportRequest; pub struct PendingRequests { requests: HashMap<u16,...
use std::io; use std::collections::{HashMap, VecDeque}; use std::time::{Duration, Instant}; use futures::{Async, Future}; use rand::random; use tokio_core::reactor; use super::super::error::Error; use super::super::request::TransportRequest; pub struct PendingRequests { requests: HashMap<u16,...
let id = self.expires.pop_front().unwrap().0; if let Some(Some(item)) = self.requests .remove(&id) { item.timeout() } } ...
match self.expires.front() { Some(&(_, at)) if at < Instant::now() => { } _ => break }
if_condition
[ { "content": "/// Spawns a new TCP transport for the given server config into a reactor.\n\n///\n\n/// Returns the transport handle for the TCP transport or `None` if TCP\n\n/// was disabled for this server.\n\npub fn tcp_transport(reactor: &reactor::Handle, conf: &ServerConf)\n\n -> Option<...
Rust
backend_library/src/data.rs
jutuon/program-launcher
f99dce5aeb123651033f2f5035b0858e49742525
use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::fs::{File, create_dir}; use Error; use serde_json; #[derive(Deserialize)] pub struct LibraryFileProgram { pub name: String, pub download_command: Option<CommandData>, pub working_directory: String, pub command_queues: Vec<CommandQu...
use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::fs::{File, create_dir}; use Error; use serde_json; #[derive(Deserialize)] pub struct LibraryFileProgram { pub name: String, pub download_command: Option<CommandData>, pub working_directory: String, pub command_queues: Vec<CommandQu...
pub(crate) fn load_library(file_path: &Path, library_directory: &Path) -> Result<ProgramLibrary, Error> { let mut file = match File::open(file_path) { Ok(file) => file, Err(io_error) => return Err(Error::IoError(io_error)), }; let mut text = String::new(); match file.read_to_string(&...
pub(crate) fn create_library_directory_if_not_exists(directory_path: &Path) -> Result<(), Error> { if directory_path.exists() { Ok(()) } else { match create_dir(directory_path) { Ok(_) => Ok(()), Err(io_error) => Err(Error::IoError(io_error)), } } }
function_block-full_function
[ { "content": "pub trait InputUpdater {\n\n fn set_quit(&mut self, value: bool);\n\n fn update_right(&mut self, key_event: KeyEvent, current_time: &TimeMilliseconds);\n\n fn update_left(&mut self, key_event: KeyEvent, current_time: &TimeMilliseconds);\n\n fn update_up(&mut self, key_event: KeyEvent, ...
Rust
server/core/src/engine/registry.rs
spartanoah/mine.js
1be49f42194681ec0f62d5138e794cbc6ec27edb
#![allow(dead_code)] use std::collections::HashMap; use std::fs::File; use serde::{Deserialize, Serialize}; use server_common::types::{Block, TypeMap, UV}; use server_utils::json; pub type Ranges = HashMap<String, UV>; pub type Blocks = HashMap<u32, Block>; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(r...
#![allow(dead_code)] use std::collections::HashMap; use std::fs::File; use serde::{Deserialize, Serialize}; use server_common::types::{Block, TypeMap, UV}; use server_utils::json; pub type Ranges = HashMap<String, UV>; pub type Blocks = HashMap<u32, Block>; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(r...
th = format!("./assets/metadata/blocks/{}", block_file); let mut block_json: serde_json::Value = serde_json::from_reader(File::open(path).unwrap()).unwrap(); let base = &block_json["base"]; let base = match base { serde_json::Value::String(base_str) ...
PackDetails = serde_json::from_reader( File::open(format!("assets/textures/packs/{}/pack.json", pack_name)).unwrap(), ) .unwrap(); for (id, block_file) in blocks_json.iter() { let pa
random
[]
Rust
research/gaia/pegasus/server/src/desc/operator.rs
varinic/GraphScope
b8cb7c404ed38841d46bf2cd35d8fe3fa812bf21
use crate::desc::{Resource, SharedResource}; use crate::generated::protobuf as pb; use pegasus::api::{Range, RANGES}; use pegasus::codec::Decode; use pegasus::BuildJobError; use pegasus_common::downcast::*; use prost::Message; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] ...
use crate::desc::{Resource, SharedResource}; use crate::generated::protobuf as pb; use pegasus::api::{Range, RANGES}; use pegasus::codec::Decode; use pegasus::BuildJobError; use pegasus_common::downcast::*; use prost::Message; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] ...
} impl OperatorDesc { pub fn new<R: Resource>(op_kind: OpKind, ch_kind: ChannelDesc, resource: R) -> Self { OperatorDesc { op_kind, ch_kind, resource: SharedResource::new(resource) } } pub fn parse(op: pb::OperatorDef) -> Result<Self, BuildJobError> { let ch_kind = op.ch.map(|ch| ch.into(...
Some(pb::channel_def::ChKind::ToOthers(res)) => { if res.resource.is_empty() { ChannelDesc::Broadcast(None) } else { ChannelDesc::Broadcast(Some(res.resource.into())) } } Some(pb::channel_def::ChKind::ToOne(t...
function_block-function_prefix_line
[]
Rust
src/to_dump.rs
zfzackfrost/hexxd
83ebecdb4b02147fb4134e6f47b7c4dcebbbb040
use crate::cli::Cli; use crate::error::HexxdError; use std::io::prelude::*; fn write_index(w: &mut Box<dyn Write>, upper: bool, idx: usize) -> Result<(), HexxdError> { if upper { write!(w, "{:08X}: ", idx).map_err(|x| HexxdError::from(x)) } else { write!(w, "{:08x}: ", i...
use crate::cli::Cli; use crate::error::HexxdError; use std::io::prelude::*; fn write_index(w: &mut Box<dyn Write>, upper: bool, idx: usize) -> Result<(), HexxdError> { if upper { write!(w, "{:08X}: ", idx).map_err(|x| HexxdError::from(x)) } else { write!(w, "{:08x}: ", i...
pub fn dump_binary(cli: Cli, mut w: Box<dyn Write>, mut r: Box<dyn Read>) -> Result<(), HexxdError> { let mut binary = Vec::new(); r.read_to_end(&mut binary).map_err(|x| HexxdError::from(x))?; if binary.is_empty() { return Ok(()); } let upper = cli.upper; let cols = cli.cols; ...
t<(), HexxdError> { let s = String::from_utf8(bin).map_err(|x| HexxdError::from(x))?; let s = s .replace("\n", ".") .replace("\t", ".") .replace("\r", ".") .replace("\0", "."); write!(w, " {}", s).map_err(|x| HexxdError::from(x)) }
function_block-function_prefixed
[ { "content": "pub fn undump_binary(_cli: Cli, mut w: Box<dyn Write>, mut r: Box<dyn Read>) -> Result<(), HexxdError> {\n\n // Read all input into a string\n\n let data_str = {\n\n let mut s = String::new();\n\n r.read_to_string(&mut s).map_err(|x| HexxdError::from(x))?;\n\n s\n\n }...
Rust
src/io/async.rs
jerry73204/rust-tffile
b0285d172c8a84413018e0cdf69437d164728a50
use std::mem; use crate::error::{Error, Result}; use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; pub async fn try_read_record<R>(reader: &mut R, check_integrity: bool) -> Result<Option<Vec<u8>>> where R: AsyncRead + Unpin, { let len = match try_read_len(reader, check_integrity).await? {...
use std::mem; use crate::error::{Error, Result}; use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; pub async fn try_read_record<R>(reader: &mut R, check_integrity: bool) -> Result<Option<Vec<u8>>> where R: AsyncRead + Unpin, { let len = match try_read_len(reader, check_integrity).await? {...
mut = buf.as_mut(); let mut offset = 0; let len = as_mut.len(); loop { match reader.read(&mut as_mut[offset..]).await { Ok(0) => { if offset == len { return Ok(Some(buf)); } else if offset == 0 { return Ok(None); ...
r: &mut R, len: usize, check_integrity: bool, ) -> Result<Vec<u8>> where R: AsyncRead + Unpin, { let buf = { let mut buf = vec![0u8; len]; reader.read_exact(&mut buf).await?; buf }; let expect_cksum = { let mut buf = [0u8; mem::size_of::<u32>()]; reader.re...
random
[ { "content": "/// Read the record raw bytes with given length from a generic reader.\n\n///\n\n/// It is internally called by [try_read_record].\n\npub fn try_read_record_data<R>(reader: &mut R, len: usize, check_integrity: bool) -> Result<Vec<u8>>\n\nwhere\n\n R: Read,\n\n{\n\n let buf = {\n\n let...
Rust
src/compiler/calling_conventions.rs
svenslaggare/stackjit-rs
82316ef560f74a641ad42e8cfcfa4e29bab15a7f
use iced_x86::Register; use crate::compiler::ir::{HardwareRegister, HardwareRegisterExplicit, InstructionIR, Variable}; use crate::compiler::stack_layout; use crate::compiler::stack_layout::{STACK_ENTRY_SIZE, STACK_OFFSET}; use crate::model::function::{Function, FunctionDeclaration, FunctionSignature}; use crate::mode...
use iced_x86::Register; use crate::compiler::ir::{HardwareRegister, HardwareRegisterExplicit, InstructionIR, Variable}; use crate::compiler::stack_layout; use crate::compiler::stack_layout::{STACK_ENTRY_SIZE, STACK_OFFSET}; use crate::model::function::{Function, FunctionDeclaration, FunctionSignature}; use crate::mode...
pub const RETURN_VALUE: Register = Register::RAX; pub const RETURN_VALUE_32: Register = Register::EAX; } pub mod float_register_call_arguments { use iced_x86::Register; use crate::model::typesystem::TypeId; pub const ARG0: Register = Register::XMM0; pub const ARG1: Register = Register::XMM1...
k; } match parameter { TypeId::Float32 => {}, _ => { relative_argument_index += 1; } } } relative_argument_index }
function_block-function_prefixed
[ { "content": "pub fn argument_stack_offset(_function: &Function, index: u32) -> i32 {\n\n (STACK_VALUE_OFFSET + index) as i32 * -STACK_ENTRY_SIZE\n\n}\n\n\n", "file_path": "src/compiler/stack_layout.rs", "rank": 0, "score": 326906.61653503997 }, { "content": "pub fn virtual_register_stack...
Rust
src/docker.rs
meinside/rockerize
eb64c7ef1916b4e4b8c5e7590ad91b89e70a8225
const DOCKER_BIN_NAME: &str = "docker"; const BUILT_DOCKER_IMAGE_NAME_PREFIX: &str = "rockerized"; const BUILT_DOCKER_IMAGE_TAG: &str = "latest"; const TEMP_DOCKERFILE_NAME: &str = "Dockerfile.rockerize"; pub enum BuildType { Locally, } use which::which; fn check_docker() -> Result<(), String> { ma...
const DOCKER_BIN_NAME: &str = "docker"; const BUILT_DOCKER_IMAGE_NAME_PREFIX: &str = "rockerized"; const BUILT_DOCKER_IMAGE_TAG: &str = "latest"; const TEMP_DOCKERFILE_NAME: &str = "Dockerfile.rockerize"; pub enum BuildType { Locally, } use which::which; fn check_docker() -> Result<(), String> { ma...
fn gen_dockerfile_from_local( bin_name: &String, exposed_ports: Vec<i32>, add_files: Vec<String>, ) -> String { let mut ports: String = String::from(""); for port in exposed_ports { ports.push_str(&format!("EXPOSE {}\n", port)); } let mut files: String = String::from(""); for ...
fn extract_bin_name() -> Result<String, String> { match env::current_dir() { Ok(pwd) => { let filepath = Path::new(&pwd).join("Cargo.toml"); match fs::read_to_string(&filepath) { io::Result::Ok(content) => match content.parse::<toml::Va...
function_block-full_function
[ { "content": "/// Processes given command line arguments.\n\npub fn process_args(args: &Vec<String>) {\n\n if args.contains(&ARG_HELP.to_string()) {\n\n match Path::new(&args[0]).file_name() {\n\n Some(filename) => {\n\n print_help(filename.to_str().unwrap_or(&args[0]));\n\n ...
Rust
src/service/provider.rs
dragfire/leetup
1b6a26e9d618d3633fd36cc8ea794aa09c4a9752
use crate::{ cmd::{self, OrderBy, Query, User}, icon::Icon, Config, LeetUpError, Result, }; use ansi_term::Colour::{Green, Red, Yellow}; use cookie::Cookie; use leetup_cache::kvstore::KvStore; use serde::{Deserialize, Serialize}; use serde_repr::*; use std::cmp::Ordering; use std::str::FromStr; pub trait S...
use crate::{ cmd::{self, OrderBy, Query, User}, icon::Icon, Config, LeetUpError, Result, }; use ansi_term::Colour::{Green, Red, Yellow}; use cookie::Cookie; use leetup_cache::kvstore::KvStore; use serde::{Deserialize, Serialize}; use serde_repr::*; use std::cmp::Ordering; use std::str::FromStr; pub trait S...
} #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct Session { pub id: String, pub csrf: String, } impl Session { pub fn new(id: String, csrf: String) -> Self { Session { id, csrf } } } impl FromStr for Session { type Err = cookie::ParseError; fn from_str(raw: &str)...
fn from(key: CacheKey) -> Self { match key { CacheKey::Session => "session".to_string(), CacheKey::Problems => "problems".to_string(), CacheKey::Problem(id) => format!("problem_{}", id), } }
function_block-full_function
[ { "content": "fn capture_value(i: usize, re: Regex, text: &str) -> Result<String> {\n\n let caps = re.captures(text).ok_or(LeetUpError::OptNone)?;\n\n caps.get(i)\n\n .map(|m| String::from(m.as_str()))\n\n .ok_or(LeetUpError::OptNone)\n\n}\n\n\n", "file_path": "src/service/auth.rs", ...
Rust
pallets/sp-mvm/src/benchmarking.rs
w3f-community/sp-move
84371353e687f5fbfbd4d871f0539869ecf70fb5
#![cfg(feature = "runtime-benchmarks")] use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::RawOrigin; use move_core_types::account_address::AccountAddress; use move_core_types::identifier::Identifier; use move_core_types::language_storage::{CORE_CODE_ADDRESS, ModuleI...
#![cfg(feature = "runtime-benchmarks")] use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::RawOrigin; use move_core_types::account_address::AccountAddress; use move_core_types::identifier::Identifier; use move_core_types::language_storage::{CORE_CODE_ADDRESS, ModuleI...
de_bytes!("../tests/benchmark_assets/target/modules/14_Offer.mv").to_vec(), ), ( "Time", include_bytes!("../tests/benchmark_assets/target/modules/15_Time.mv").to_vec(), ), ( "Security", include_bytes!("../tests/benchmark_assets/target/modul...
e: Identifier::new("Store").unwrap(), name: Identifier::new("Container").unwrap(), type_params: vec![] }; let ak = AccessKey::from((&AccountAddress::from_hex_literal("0xd861ea1ebf4800d4b89f4ff787ad79ee96d9a708c85b57da7eb8f9ddeda61291").unwrap(), &tag)); assert!(VMStora...
random
[ { "content": "fn call_execute_script_tx_block(origin: Origin, tx: UserTx) {\n\n const GAS_LIMIT: u64 = 1_000_000;\n\n let txbc = tx.bc().to_vec();\n\n\n\n let result = Mvm::execute(origin, txbc, GAS_LIMIT);\n\n eprintln!(\"execute_script result: {:?}\", result);\n\n assert_ok!(result);\n\n}\n\n\n...
Rust
dora/src/semck.rs
dinfuehr/dora
bcfdac576b729e2bbb2422d0239426b884059b2c
use std::collections::HashSet; use crate::error::msg::SemError; use crate::sym::{NestedSymTable, Sym}; use crate::ty::SourceType; use crate::vm::{FileId, TypeParam, TypeParamId, VM}; use dora_parser::ast; use dora_parser::interner::Name; use dora_parser::lexer::position::Position; pub use globaldef::should_file_be_pa...
use std::collections::HashSet; use crate::error::msg::SemError; use crate::sym::{NestedSymTable, Sym}; use crate::ty::SourceType; use crate::vm::{FileId, TypeParam, TypeParamId, VM}; use dora_parser::ast; use dora_parser::interner::Name; use dora_parser::lexer::position::Position; pub use globaldef::should_file_be_pa...
; match ty { Some(SourceType::Trait(trait_id, _)) => { if !type_params[type_param_id].trait_bounds.insert(trait_id) { let msg = SemError::DuplicateTraitBound; vm.diag.lock().report(file_id, type_param.po...
read_type( vm, symtable, file_id, bound, TypeParamContext::None, AllowSelf::No, )
call_expression
[ { "content": "pub fn fct_pattern_match(vm: &VM, fct: &Fct, pattern: &str) -> bool {\n\n if pattern == \"all\" {\n\n return true;\n\n }\n\n\n\n let fct_name = fct.name_with_params(vm);\n\n\n\n for part in pattern.split(',') {\n\n if fct_name.contains(part) {\n\n return true;\...
Rust
src/io/csv/infer_schema.rs
domoritz/arrow2
ed74a46efb62bc628efd3a5363af51273e10ca8b
use std::{ collections::HashSet, fs::File, io::{Read, Seek, SeekFrom}, }; use csv::StringRecord; use crate::datatypes::DataType; use crate::datatypes::{Field, Schema}; use crate::error::Result; pub fn infer_file_schema<R: Read + Seek, F: Fn(&str) -> DataType>( reader: &mut R, delimiter: u8, ...
use std::{ collections::HashSet, fs::File, io::{Read, Seek, SeekFrom}, }; use csv::StringRecord; use crate::datatypes::DataType; use crate::datatypes::{Field, Schema}; use crate::error::Result; pub fn infer_file_schema<R: Read + Seek, F: Fn(&str) -> DataType>( reader: &mut R, delimiter: u8, ...
pub fn infer_schema_from_files<F: Fn(&str) -> DataType>( files: &[String], delimiter: u8, max_read_records: Option<usize>, has_header: bool, infer: F, ) -> Result<Schema> { let mut schemas = vec![]; let mut records_to_read = max_read_records.unwrap_or(std::usize::MAX); for fname in fi...
y)); } } 2 => { if possibilities.contains(&DataType::Int64) && possibilities.contains(&DataType::Float64) { fields.push(Field::new(&field_name, DataType::Float64, has_validity)); ...
function_block-function_prefixed
[ { "content": "/// Infer the fields of a JSON file by reading the first n records of the file, with\n\n/// `max_read_records` controlling the maximum number of records to read.\n\n///\n\n/// If `max_read_records` is not set, the whole file is read to infer its field types.\n\n///\n\n/// Contrary to [`infer_json_...
Rust
src/shaders.rs
SharpCoder/hexagon2
0a565a263e5a3513c15e7e10ef75a9b6cd64efdb
use crate::pixel_engine::color::*; use crate::pixel_engine::shader::*; use teensycore::{system::vector::*, vector}; use teensycore::clock::uNano; const TIME: uNano = 1000 * crate::WORLD_MUTIPLIER; pub fn initialize_shaders<'a>() -> Vector<Shader> { return vector!( ...
use crate::pixel_engine::color::*; use crate::pixel_engine::shader::*; use teensycore::{system::vector::*, vector}; use teensycore::clock::uNano; const TIME: uNano = 1000 * crate::WORLD_MUTIPLIER;
pub fn initialize_shaders<'a>() -> Vector<Shader> { return vector!( Shader::new(b"Medbay") .with_color(rgb(0, 255, 0)) .transition_to(rgb(0,0,255), TIME) ...
function_block-full_function
[ { "content": "/// Sets the current unix epoch in seconds\n\npub fn set_world_time(time_s: uNano) {\n\n unsafe {\n\n UPTIME_WORLDTIME_OFFSET_S = nanos() / S_TO_NANO;\n\n WORLD_TIME_S = time_s;\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 50902.96942898632 },...
Rust
src/wl/protocols/common/wl_output.rs
nuta/kazari
cdbd7a2dc4e9e6e0ca6e839f8fb66cf3f077572b
#![allow(unused)] #![allow(clippy::from_over_into)] #![allow(clippy::match_single_binding)] use crate::wl::protocols::common::{EventSet, RequestSet}; use crate::wl::{ Array, Connection, DeserializeError, Handle, Interface, Message, NewId, ObjectId, Opcode, Payload, PayloadType, RawMessage, SendError, }; use ...
#![allow(unused)] #![allow(clippy::from_over_into)] #![allow(clippy::match_single_binding)] use crate::wl::protocols::common::{EventSet, RequestSet}; use crate::wl::{ Array, Connection, DeserializeError, Handle, Interface, Message, NewId, ObjectId, Opcode, Payload, PayloadType, RawMessage, SendError, }; use ...
} #[derive(Debug)] pub enum Event { Geometry { x: i32, y: i32, physical_width: i32, physical_height: i32, subpixel: Subpixel, make: String, model: Str...
fn from(value: u32) -> Mode { match value { 0x1 => Mode::Current, 0x2 => Mode::Preferred, _ => unreachable!(), } }
function_block-full_function
[]
Rust
src/models/db/models.rs
reslario/web-quiz
4077e243520c9b2738b969ef016b5d5217eac595
use { serde::{Serialize, Deserialize}, std::time::{Duration, SystemTime}, diesel::{Identifiable, Queryable, Associations}, super::{ CategoryId, schema::{questions, question_stats, categories, scores, admins} } }; const NUM_ANSWERS: usize = 4; const NUM_INCORRECT: usize = NUM_ANSWERS...
use { serde::{Serialize, Deserialize}, std::time::{Duration, SystemTime}, diesel::{Identifiable, Queryable, Associations}, super::{ CategoryId, schema::{questions, question_stats, categories, scores, admins} } }; const NUM_ANSWERS: usize = 4; const NUM_INCORRECT: usize = NUM_ANSWERS...
]> for Incorrect { fn into(self) -> [String; NUM_INCORRECT] { self.0 } } impl <DB, ST> Queryable<ST, DB> for Incorrect where DB: Backend, Vec<String>: Queryable<ST, DB>, { type Row = <Vec<String> as Queryable<ST, DB>>::Row; fn bui...
el::{ Queryable, backend::Backend } }; #[derive(PartialEq, Debug)] pub struct Incorrect([String; NUM_INCORRECT]); impl Into<[String; NUM_INCORRECT
random
[ { "content": "pub fn new_game_state(user: String, categories: &[CategoryId], conn: &PgConnection) -> QueryResult<GameState> {\n\n Category::load_with_ids(&categories, &conn)\n\n .map(|cats| GameState::new(user, cats))\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use {\n\n super::*,\n\n ...
Rust
src/main.rs
geshan/sample_rocket_web_app
c9007487a9b93f314998b4589a70b35f1a0975e2
#![allow(proc_macro_derive_resolution_fallback, unused_attributes)] #[macro_use] extern crate rocket; #[macro_use] extern crate diesel; #[macro_use] extern crate rocket_sync_db_pools; #[macro_use] extern crate diesel_migrations; use askama::Template; use diesel::OptionalExtension; use diesel::{RunQueryDsl, QueryDsl};...
#![allow(proc_macro_derive_resolution_fallback, unused_attributes)] #[macro_use] extern crate rocket; #[macro_use] extern crate diesel; #[macro_use] extern crate rocket_sync_db_pools; #[macro_use] extern crate diesel_migrations; use askama::Template; use diesel::OptionalExtension; use diesel::{RunQueryDsl, QueryDsl};...
_size, 10) .map_err(|e| DbLoadErrors::DbConnectionPoolSizeParse(e))?; let db: Map<_, Value> = map! { "url" => db_url.into(), "pool_size" => db_conn_pool_size.into() }; let figment = rocket::Config::figment() .merge( ("databases", map!["confessions_db" => db]) ); ...
v::var("CONNECTION_POOL_SIZE") .map_err(|e| DbLoadErrors::DbConnectionPoolSizeNotFound(e))?; let db_conn_pool_size = i32::from_str_radix(&db_conn_pool
function_block-random_span
[ { "content": "DROP FUNCTION IF EXISTS diesel_set_updated_at();", "file_path": "migrations/0000_init/down.sql", "rank": 3, "score": 53803.6040196702 }, { "content": "DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);\n", "file_path": "migrations/0000_init/down.sql", "ran...
Rust
corewars-sim/src/core/process.rs
ian-h-chamberlain/corewa.rs
a67aec6e8c180d72a38aa0dd8b2d6da684aefea6
use std::collections::{BTreeMap, VecDeque}; use thiserror::Error as ThisError; use super::Offset; #[derive(Debug, Eq, PartialEq)] pub struct Entry { pub name: String, pub thread: usize, pub offset: Offset, } #[derive(Debug)] pub struct Queue { queue: VecDeque<Entry>, proce...
use std::collections::{BTreeMap, VecDeque}; use thiserror::Error as ThisError; use super::Offset; #[derive(Debug, Eq, PartialEq)] pub struct Entry { pub name: String, pub thread: usize, pub offset: Offset, } #[derive(Debug)] pub struct Queue { queue: VecDeque<Entry>, proce...
ng_offset } ); assert!(queue.thread_count("p1") > 0); queue.push("p1".into(), starting_offset, Some(1)); queue.pop().unwrap(); assert_eq!( queue.peek().unwrap(), &Entry { name: "p1".into(), thread: 1, ...
Ok(entry) }) } pub fn peek(&self) -> Result<&Entry, Error> { self.queue.get(0).ok_or(Error::NoRemainingProcesses) } pub fn push(&mut self, process_name: String, offset: Offset, thread: Option<usize>) { let thread_id = thread.map_or_else( ...
random
[ { "content": "#[allow(clippy::too_many_lines)]\n\npub fn execute(core: &mut Core, program_counter: Offset) -> Result<Executed, process::Error> {\n\n let instruction = core.get_offset(program_counter).clone();\n\n let opcode = instruction.opcode;\n\n\n\n // These are basically just useful constants that...
Rust
firmware/small-modular-printed-cnc/src/motionkernel.rs
knoby/small_modular_printed_cnc
05a76b336b466b8f7991559467e81a0fa38e1189
use defmt::debug; use num_traits::Float; use crate::ramp_gen::{Direction, RampGenerator}; #[derive(Debug, Clone, Copy, defmt::Format, PartialEq, PartialOrd)] pub enum Axis { XAxis, YAxis, ZAxis, } #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)] pub struct Acceleration { x: f32, y:...
use defmt::debug; use num_traits::Float; use crate::ramp_gen::{Direction, RampGenerator}; #[derive(Debug, Clone, Copy, defmt::Format, PartialEq, PartialOrd)] pub enum Axis { XAxis, YAxis, ZAxis, } #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)] pub struct Acceleration { x: f32, y:...
pub fn move_to(&mut self, target_pos: Position) { self.target_pos = target_pos; self.setup_bresenham(); match self.primary_axis { Axis::XAxis => { self.ramp_gen.set_current_pos(self.current_pos.x); let max_vel = (s...
core::cmp::Ordering::Greater => Direction::Positive, }; let z_step = match self.current_pos.z.cmp(&last_pos.z) { core::cmp::Ordering::Less => Direction::Negative, core::cmp::Ordering::Equal => Direction::StandStill, core::cmp::Ordering::Greater => ...
function_block-function_prefix_line
[ { "content": "#[allow(dead_code)]\n\npub fn exit() -> ! {\n\n loop {\n\n cortex_m::asm::bkpt();\n\n }\n\n}\n", "file_path": "firmware/small-modular-printed-cnc/src/misc.rs", "rank": 0, "score": 83540.70145330444 }, { "content": "#[defmt::panic_handler]\n\nfn panic() -> ! {\n\n ...
Rust
truck-meshalgo/src/filters/subdivision.rs
ARCaide-Development/truck
69769dcfeb1f8f7bcaca47184c1160e67cb1292c
use super::*; use rustc_hash::FxHashMap as HashMap; use std::f64::consts::PI; pub trait Subdivision { fn loop_subdivision(&mut self) -> &mut Self; } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] struct Edge(usize, usize); #[derive(Clone, Copy, Debug)] struc...
use super::*; use rustc_hash::FxHashMap as HashMap; use std::f64::consts::PI; pub trait Subdivision { fn loop_subdivision(&mut self) -> &mut Self; } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] struct Edge(usize, usize); #[derive(Clone, Copy, Debug)] struc...
} fn calc_new_position( v: usize, adjacency: &[usize], edges: &HashMap<Edge, EdgeInfo>, positions: &[Point3], ) -> Point3 { use VertexBoundaryCondition::*; let point = positions[v]; match VertexBoundaryCondition::new(v, adjacency, edges) { Corner(_, _) => point, Boundary(w0...
w)), _ => binfo, } }); if let (Some(x), Some(y)) = binfo { if adjacency.len() == 2 { Self::Corner(x, y) } else { Self::Boundary(x, y) } } else { Self::Inner } }
function_block-function_prefixed
[ { "content": "fn all_nor_mut(faces: &mut Faces) -> impl Iterator<Item = &mut usize> {\n\n faces\n\n .face_iter_mut()\n\n .flatten()\n\n .filter_map(move |v| v.nor.as_mut())\n\n}\n\n\n\nimpl OptimizingFilter for PolygonMesh {\n\n fn remove_unused_attrs(&mut self) -> &mut Self {\n\n ...
Rust
src/codec.rs
kolapapa/mini-telnet
2a03ebd719ac54b420bcf25e7f3c86ad05074376
use bytes::{Buf, BytesMut}; use tokio_util::codec::Decoder; use crate::error::TelnetError; pub struct TelnetCodec { sb_flag: bool, current_line: Vec<u8>, } impl Default for TelnetCodec { fn default() -> Self { TelnetCodec { sb_flag: false, current_line: Vec::with_capacity(...
use bytes::{Buf, BytesMut}; use tokio_util::codec::Decoder; use crate::error::TelnetError; pub struct TelnetCodec { sb_flag: bool, current_line: Vec<u8>, } impl Default for TelnetCodec { fn default() -> Self { TelnetCodec { sb_flag: false, current_line: Vec::with_capacity(...
fn is_three_byte_iac(byte: u8) -> bool { matches!(byte, 251..=254) } fn is_sub(byte: u8) -> bool { byte == 240 || byte == 250 }
fn try_parse_iac(bytes: &[u8]) -> (ParseIacResult, usize) { if bytes.len() < 2 { return (ParseIacResult::NeedMore, 0); } if bytes[0] != 0xff { unreachable!(); } if is_three_byte_iac(bytes[1]) && bytes.len() < 3 { return (ParseIacResult::NeedMore, 0); } if is_sub(byte...
function_block-full_function
[ { "content": "fn decode(line: &[u8]) -> Result<String, TelnetError> {\n\n match String::from_utf8(line.to_vec()) {\n\n Ok(result) => Ok(result),\n\n Err(e) => {\n\n if let Ok(result) = GBK.decode(line, DecoderTrap::Strict) {\n\n return Ok(result);\n\n }\n\n\...
Rust
libsplinter/src/rest_api/auth/authorization/rbac/store/mod.rs
CLEckhardt/splinter
707f44179f2e19f5cc273c45b0dac6040acb6e8b
#[cfg(feature = "diesel")] mod diesel; mod error; use crate::error::InvalidStateError; #[cfg(feature = "diesel")] pub use self::diesel::DieselRoleBasedAuthorizationStore; pub use error::RoleBasedAuthorizationStoreError; pub const ADMIN_ROLE_ID: &str = "admin"; #[derive(Clone)] pub struct Role { id: String, ...
#[cfg(feature = "diesel")] mod diesel; mod error; use crate::error::InvalidStateError; #[cfg(feature = "diesel")] pub use self::diesel::DieselRoleBasedAuthorizationStore; pub use error::RoleBasedAuthorizationStoreError; pub const ADMIN_ROLE_ID: &str = "admin"; #[derive(Clone)] pub struct Role { id: String, ...
let id = self .id .ok_or_else(|| InvalidStateError::with_message("A role requires an id field".into()))?; if id.is_empty() { return Err(InvalidStateError::with_message( "A role requires a non-empty id field".into(), )); } ...
if self.permissions.is_empty() { return Err(InvalidStateError::with_message( "A role requires at least one permission".into(), )); }
if_condition
[ { "content": "pub fn admin_service_id(node_id: &str) -> String {\n\n format!(\"admin::{}\", node_id)\n\n}\n", "file_path": "libsplinter/src/admin/token/mod.rs", "rank": 0, "score": 536484.4230685222 }, { "content": "pub fn admin_service_id(node_id: &str) -> String {\n\n format!(\"admin...
Rust
src/lib.rs
D1plo1d/bsd-pidfile-rs
1a2462ff71b8b5cb000408be8330dff067913313
use std::ffi::{CString, NulError}; use std::fs::Permissions; use std::io; use std::os::unix::{ffi::OsStringExt, fs::PermissionsExt}; use std::path::PathBuf; use libc::{c_char, c_int, mode_t, pid_t}; use log::warn; use thiserror::Error; #[allow(non_camel_case_types)] enum pidfn {} extern { #[link_name = "pidfile...
use std::ffi::{CString, NulError}; use std::fs::Permissions; use std::io; use std::os::unix::{ffi::OsStringExt, fs::PermissionsExt}; use std::path::PathBuf; use libc::{c_char, c_int, mode_t, pid_t}; use log::warn; use thiserror::Error; #[allow(non_camel_case_types)] enum pidfn {} extern { #[link_name = "pidfile...
} } impl Drop for Pidfile { fn drop(&mut self) { if unsafe { bsd_pidfile_remove(self.pidfn) != 0 } { let err = io::Error::last_os_error(); warn!("Failed to remove the PID file: {}", err); } } } #[cfg(test)] mod tests { use crate::*; ...
if unsafe { bsd_pidfile_close(self.pidfn) != 0 } { let err = io::Error::last_os_error(); warn!("Failed to close the PID file: {}", err); }
if_condition
[ { "content": "fn main() {\n\n if pkg_config::Config::new().probe(\"libbsd\").is_ok() {\n\n println!(\"cargo:rustc-cfg=pidfile\");\n\n }\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n}\n", "file_path": "build.rs", "rank": 1, "score": 19436.528300117898 }, { "content": ...
Rust
oauth1-request/src/signature_method.rs
tesaguri/oauth1-request-rs
13d35d94be032f0bb982e26ff75bcd352e7c27c0
#[cfg(feature = "hmac-sha1")] pub mod hmac_sha1; pub mod identity; pub mod plaintext; #[cfg(feature = "either")] mod either; #[cfg(feature = "hmac-sha1")] pub use self::hmac_sha1::HmacSha1; pub use self::identity::Identity; pub use self::plaintext::Plaintext; use std::fmt::{Display, Write}; use crate::util::perce...
#[cfg(feature = "hmac-sha1")] pub mod hmac_sha1; pub mod identity; pub mod plaintext; #[cfg(feature = "either")] mod either; #[cfg(feature = "hmac-sha1")] pub use self::hmac_sha1::HmacSha1; pub use self::identity::Identity; pub use self::plaintext::Plaintext; use std::fmt::{Display, Write}; use crate::util::perce...
fn timestamp(&mut self, value: u64) { self.parameter("oauth_timestamp", value); } fn use_timestamp(&self) -> bool { true } provide! { token, verifier, } fn version(&mut self) { self.parameter("oauth_version", ...
y>(&mut self, key: &str, value: V); fn delimiter(&mut self); fn end(self) -> Self::Signature; provide! { callback, consumer_key, nonce, } fn use_nonce(&self) -> bool { true } fn signature_method(&mut self) { self.paramet...
random
[ { "content": "/// Turns a `Request` to a query string and appends it to the given URI.\n\n///\n\n/// This function naively concatenates a query string to `uri` and if `uri` already has\n\n/// a query part, it will have a duplicate query part like `?foo=bar?baz=qux`.\n\npub fn to_uri_query<R>(uri: String, reques...
Rust
src/lib.rs
kolbma/rocket-response
a1fb8aa7fb43943ba7c26c120f1840e36d0663ec
#![deny(unsafe_code)] #![deny(warnings)] #![deny(clippy::all)] #![deny(missing_docs)] #![deny(missing_doc_code_examples)] #[cfg(any(feature = "json", feature = "msgpack"))] use rocket::serde; use rocket::{ fs::NamedFile, http::Status, response::{ content::{Css, Custom, Html, JavaScript, Json, Msg...
#![deny(unsafe_code)] #![deny(warnings)] #![deny(clippy::all)] #![deny(missing_docs)] #![deny(missing_doc_code_examples)] #[cfg(any(feature = "json", feature = "msgpack"))] use rocket::serde; use rocket::{ fs::NamedFile, http::Status, response::{ content::{Css, Custom, Html, JavaScript, Json, Msg...
ponse() { let rocket = rocket::build().mount("/", routes![route_response]); let client = Client::tracked(rocket).expect("no rocket instance"); let req = client.get("/response/2"); let res = req.dispatch(); assert_eq!(Status::Ok, res.status()); assert_eq!(ContentType::Pla...
String(String), Status(Status), #[cfg(any(feature = "templates-tera", feature = "templates-handlebars"))] Template(Template), TokioFile(tokio::fs::File), Unauthorized(Unauthorized<&'static str>), Vec(Vec<u8>), Xml(Xml<&'static str>), } #[derive(Responder)] ...
random
[ { "content": "## Example\n\n\n\n```rust\n\nuse rocket::{get, response::{self, status, Redirect}};\n\nuse rocket_response::RocketResponseGeneric2 as RocketResponse;\n\n\n\n#[get(\"/<id>\")]\n\npub(crate) fn rocket_response_generic2(\n\n id: usize,\n\n) -> RocketResponse<&'static str, Redirect> {\n\n match ...
Rust
core/src/ops/cnn/pools.rs
mithril-security/tract-sgx-xargo
ea0d7cc5a81f413250dbfca89d5d876e76746b89
use crate::internal::*; use crate::ops::cnn::{PaddingSpec, Patch, PatchSpec}; use crate::ops::nn::{BaseDataShape, DataFormat, DataShape, SymDataShape}; use super::padding::ComputedPaddedDim; #[derive(Debug, Clone, new, Default, Hash, PartialEq)] pub struct PoolSpec { pub data_format: DataFormat, pub kernel_s...
use crate::internal::*; use crate::ops::cnn::{PaddingSpec, Patch, PatchSpec}; use crate::ops::nn::{BaseDataShape, DataFormat, DataShape, SymDataShape}; use super::padding::ComputedPaddedDim; #[derive(Debug, Clone, new, Default, Hash, PartialEq)] pub struct PoolSpec { pub data_format: DataFormat, pub kernel_s...
if let Some(strides) = self.pool_spec.strides.clone() { spec = spec.with_strides(strides); } if let Some(dilations) = self.pool_spec.dilations.clone() { spec = spec.with_dilations(dilations); } let patch = spec.into_patch(); let output_shape = inp...
let mut spec = PatchSpec::for_full_shape(self.pool_spec.data_format, input_full_shape)? .with_output_inner_stride(output_inner_stride) .with_kernel_shape(self.pool_spec.kernel_shape.clone()) .with_padding(self.pool_spec.padding.clone());
assignment_statement
[ { "content": "pub fn natural_strides(shape: &[usize]) -> TVec<isize> {\n\n let mut strides = tvec!();\n\n compute_natural_stride_to(&mut strides, shape);\n\n strides\n\n}\n\n\n", "file_path": "data/src/tensor.rs", "rank": 0, "score": 369973.5122921893 }, { "content": "pub fn param(s...
Rust
robonomics/frame/provider/src/lib.rs
chebykin/substrate-node-robonomics
d468e5171e434290c008a160483ba8278e08d85a
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Encode, Decode}; use sp_std::{ prelude::*, collections::btree_map::BTreeMap, }; use sp_runtime::{RuntimeDebug, traits::Hash}; use support::{ decl_module, decl_event, decl_storage, debug, StorageValue, weights::SimpleDispatchInfo, }; use primitiv...
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Encode, Decode}; use sp_std::{ prelude::*, collections::btree_map::BTreeMap, }; use sp_runtime::{RuntimeDebug, traits::Hash}; use support::{ decl_module, decl_event, decl_storage, debug, StorageValue, weights::SimpleDispatchInfo, }; use primitiv...
None => None }; (new_state, result) }) } fn get_offer(order_id: <T as system::Trait>::Hash, now: T::BlockNumber) -> Option<Order<T>> { Self::storage_mutate(now, |state| { let mut new_state = state.clone(); let result = match new_state...
e = state.clone(); let result = match new_state.demand_of.get_mut(&order_id) { Some(list) => list.pop(),
function_block-random_span
[ { "content": "pub fn get_liability(pool: &ProviderPool, id: MultiID) -> impl traits::Liability {\n\n pool.filter_map(|p| p.get(id)).collect()\n\n}\n\n\n\npub struct EthereumLiability {\n\n\n\n}\n\n\n\nimpl EthereumLiability {\n\n pub fn new(address: u8[32]) {\n\n }\n\n}\n\n\n\npub struct EthereumRPCPro...
Rust
diem/vendor/cipher/src/block.rs
Soptq/phala-blockchain
f2fbd1e62b1b8c2567bfed993ae85a56f227a880
#[cfg(feature = "dev")] #[cfg_attr(docsrs, doc(cfg(feature = "dev")))] pub mod dev; mod errors; pub use errors::InvalidKeyLength; pub use generic_array::{self, typenum::consts}; use core::convert::TryInto; use generic_array::{typenum::Unsigned, ArrayLength, GenericArray}; pub type Key<B> = GenericArray<u8, <B as...
#[cfg(feature = "dev")] #[cfg_attr(docsrs, doc(cfg(feature = "dev")))] pub mod dev; mod errors; pub use errors::InvalidKeyLength; pub use generic_array::{self, typenum::consts}; use core::convert::TryInto; use generic_array::{typenum::Unsigned, ArrayLength, GenericArray}; pub type Key<B> = GenericArray<u8, <B as...
#[inline] fn decrypt_blocks(&self, blocks: &mut ParBlocks<Self>) { for block in blocks.iter_mut() { self.decrypt_block(block); } } #[inline] fn decrypt_slice(&self, mut blocks: &mut [Block<Self>]) { let pb = Self::ParBlocks::to_usize();...
fn encrypt_slice(&self, mut blocks: &mut [Block<Self>]) { let pb = Self::ParBlocks::to_usize(); if pb > 1 { let mut iter = blocks.chunks_exact_mut(pb); for chunk in &mut iter { self.encrypt_blocks(chunk.try_into().unwrap()) } blocks = it...
function_block-full_function
[ { "content": "pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {\n\n let fd = get_rng_fd()?;\n\n let read = |buf: &mut [u8]| unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) };\n\n\n\n if cfg!(target_os = \"emscripten\") {\n\n // `Crypto.getRandomValues` documents `dest...
Rust
src/syscore/linux/iouring/iouring.rs
vertexclique/nuclei
916ef9250f65b3aae28a383ee6ee3ed50b7af182
use core::mem::MaybeUninit; use futures::channel::oneshot; use iou::{ CompletionQueue, CompletionQueueEvent, IoUring, Registrar, SubmissionQueue, SubmissionQueueEvent, }; use lever::sync::prelude::*; use pin_utils::unsafe_pinned; use std::collections::HashMap; use std::future::Future; use std::io; use std::os::...
use core::mem::MaybeUninit; use futures::channel::oneshot; use iou::{ CompletionQueue, CompletionQueueEvent, IoUring, Registrar, SubmissionQueue, SubmissionQueueEvent, }; use lever::sync::prelude::*; use pin_utils::unsafe_pinned; use std::collections::HashMap; use std::future::Future; use std::io; use std::os::...
c }); cc }; sub_comp.ok_or(io::Error::from(io::ErrorKind::Wou...
= self.submitter_id.fetch_add(1, Ordering::Relaxed); if id == MANUAL_TIMEOUT { id = self.submitter_id.fetch_add(2, Ordering::Relaxed) + 2; } let (tx, rx) = oneshot::channel(); io_submit(sqe); ...
function_block-random_span
[]
Rust
src/mlx.rs
jiricodes/minilibx-rs
f79c66ca3babb17834717687d91c35399db915f8
use std::ffi::CString; use std::mem::MaybeUninit; use std::ptr; use x11::xlib::{ CWBackPixel, CWBorderPixel, CWColormap, CWEventMask, Colormap, CopyFromParent, Depth, Display, InputOutput, PMaxSize, PMinSize, PPosition, PSize, Screen, Visual, Window, XCreateWindow, XGCValues, XSetWMNormalHints, XSetWindo...
use std::ffi::CString; use std::mem::MaybeUninit; use std::ptr; use x11::xlib::{ CWBackPixel, CWBorderPixel, CWColormap, CWEventMask, Colormap, CopyFromParent, Depth, Display, InputOutput, PMaxSize, PMinSize, PPosition, PSize, Screen, Visual, Window, XCreateWindow, XGCValues, XSetWMNormalHints, XSetWindo...
} #[cfg(test)] mod test { use super::*; #[test] fn test() { let mut mlx = Mlx::new(); dbg!(&mlx); mlx.anti_resize_win(0, 10, 10); } }
d"); let screen = unsafe { xlib::XDefaultScreen(display) }; let root = unsafe { xlib::XRootWindow(display, screen) }; let cmap = unsafe { xlib::XDefaultColormap(display, screen) }; let depth = unsafe { xlib::XDefaultDepth(display, screen) }; let visual = unsa...
function_block-function_prefixed
[ { "content": "\n\n#[derive(Debug)]\n\npub struct MlxWindow {\n\n window: Window,\n\n gc: GC,\n\n}\n\n\n\nimpl MlxWindow {\n\n pub fn new(window: Window, gc: GC) -> Self {\n\n Self { window, gc }\n\n }\n\n\n\n pub fn clear() {\n\n unimplemented!()\n\n }\n\n\n\n /// Origin for x...
Rust
src/utils.rs
juan-riveros/pqrs
c4ef9afbd89c2c8533bf0b4146a294922afacf8a
use crate::errors::PQRSError; use crate::errors::PQRSError::{CouldNotOpenFile, UnsupportedOperation}; use arrow::{datatypes::Schema, record_batch::RecordBatch}; use log::debug; use parquet::arrow::{ArrowReader, ArrowWriter, ParquetFileArrowReader}; use parquet::file::reader::{FileReader, SerializedFileReader}; use parq...
use crate::errors::PQRSError; use crate::errors::PQRSError::{CouldNotOpenFile, UnsupportedOperation}; use arrow::{datatypes::Schema, record_batch::RecordBatch}; use log::debug; use parquet::arrow::{ArrowReader, ArrowWriter, ParquetFileArrowReader}; use parquet::file::reader::{FileReader, SerializedFileReader}; use parq...
pub fn get_size(file: File) -> Result<(i64, i64), PQRSError> { let parquet_reader = SerializedFileReader::new(file)?; let row_group_metadata = parquet_reader.metadata().row_groups(); let uncompressed_size = row_group_metadata .iter() .map(|rg| rg.total_byte_size()...
erializedFileReader::new(file)?; let row_group_metadata = parquet_reader.metadata().row_groups(); let total_num_rows = row_group_metadata.iter().map(|rg| rg.num_rows()).sum(); Ok(total_num_rows) }
function_block-function_prefixed
[ { "content": "/// Run the appropriate subcommand based on the input from the user.\n\npub fn run_command(matches: ArgMatches) -> Result<(), PQRSError> {\n\n // match based on the subcommand name, create an instance and execute the command\n\n match matches.subcommand() {\n\n (\"cat\", Some(m)) => C...
Rust
src/lib.rs
ray33ee/thread_lake
bf4b0ad6131a51438dc2af240bd38e9a6409a4e2
pub mod threadlake; pub mod threadutilities; pub mod iterators; pub mod builder; pub mod traits; pub mod disjointer; pub mod split; #[cfg(test)] mod tests { use crate::threadlake::ThreadLake; use std::time::Duration; use crate::threadutilities::ThreadUtilities; use crate::builder::Builder; u...
pub mod threadlake; pub mod threadutilities; pub mod iterators; pub mod builder; pub mod traits; pub mod disjointer; pub mod split; #[cfg(test)] mod tests { use crate::threadlake::ThreadLake; use std::time::Duration; use crate::threadutilities::ThreadUtilities; use crate::builder::Builder; u...
.spawn(|_: ThreadUtilities<_>| {}); for (i, (_, str)) in lake.thread_iter().enumerate() { assert_eq!(str, format!("My Thread {}", i).as_str()); } lake.join(); } /*fn multithreaded_reduce<T, B, F>(list: Vec<T>, init: T, f: F) -> T where T: Sync...
::new(5) .spawn(|x|{ if x.index() == 0 { x.send(()).unwrap(); } while !x.check() { std::thread::sleep(Duration::from_millis(100)); } }); ...
random
[ { "content": "///ThreadCount describes types that take the available concurrency (in the form of Option<usize) and calculate from this the number of threads to spawn\n\npub trait ThreadCount {\n\n fn get(self, available_concurrency: Result<usize>) -> usize;\n\n}\n\n\n\nimpl ThreadCount for usize {\n\n fn ...
Rust
src/main.rs
JKShop/coordinator
100460e15e0b64df60b5ff8567ffd6df74e56426
#![forbid(unsafe_code)] #![deny(clippy::needless_borrow, clippy::panic, clippy::unwrap_used)] #![deny(unused_imports)] #![forbid(missing_docs)] use actix_web::web::Json; use actix_web::{web, App, HttpServer}; use dotenv::{dotenv}; use once_cell::sync::Lazy; use serde::Serialize; use std::env; use std::sync::Mutex; use...
#![forbid(unsafe_code)] #![deny(clippy::needless_borrow, clippy::panic, clippy::unwrap_used)] #![deny(unused_imports)] #![forbid(missing_docs)] use actix_web::web::Json; use actix_web::{web, App, HttpServer}; use dotenv::{dotenv}; use once_cell::sync::Lazy; use serde::Serialize; use std::env; use std::sync::Mutex; use...
async fn get_id() -> Result<Json<Response>, ()> { let mut worker_status = WORKER_STATUS .lock() .expect("Failed to lock WORKER_STATUS mutex"); let time = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_secs(); let outdated = { ...
ackwards") .as_secs(); let idx = { worker_status .iter() .position(|f| f.worker_id == id) .expect("Existing item does not exist") }; { let worker = &worker_status[idx]; let update_time = worker.timestamp; let max_update_time = upd...
function_block-function_prefixed
[ { "content": " def copy(self):\n\n \"\"\"Return a shallow copy of this graph.\"\"\"\n\n other = DirectedGraph()\n\n other._vertices = set(self._vertices)\n\n other._forwards = {k: set(v) for k, v in self._forwards.items()}\n\n other._backwards = {k: set(v) for k, v in self....
Rust
src/commands/projects.rs
omarking05/switcher
ee4a3a3d21acf8be3775dc54f8e79b74a8921b0c
use super::types::FeatureConfig; use crate::commands::types::{AddProject, ProjectCommand, ProjectInfo, SyncProjectBranch}; use crate::config; use crate::core::cli::ProgramInfo; use crate::core::git; use std::fs; use std::io::prelude::*; use std::io::{stdin, stdout, Write}; use std::path::{Path, PathBuf}; use std::proce...
use super::types::FeatureConfig; use crate::commands::types::{AddProject, ProjectCommand, ProjectInfo, SyncProjectBranch}; use crate::config; use crate::core::cli::ProgramInfo; use crate::core::git; use std::fs; use std::io::prelude::*; use std::io::{stdin, stdout, Write}; use std::path::{Path, PathBuf}; use std::proce...
pub fn sync_projects(program: ProgramInfo) { let mut config = config::get(); let params = SyncProjectBranch::init(&program); let project = match config.get_project(&params.name) { None => { println!( "Unable to find project [{}] please consider running 'add_project {} <...
match project_info.sub_command { ProjectCommand::Add => add(project_info), ProjectCommand::Remove => remove(project_info), ProjectCommand::Help => projects_help(), }; }
function_block-function_prefixed
[ { "content": "pub fn run_command(command: String, args: Vec<&str>, cwd: &Path) -> (String, String) {\n\n let command = match Command::new(command).current_dir(cwd).args(args).output() {\n\n Err(err) => panic!(\"Error running command [{}]\", err),\n\n Ok(cmd) => cmd,\n\n };\n\n\n\n let err...
Rust
common/io/src/buffer/buffer_reader.rs
zhyass/databend
e54bef9ef4f6cb8c4a9c0b7be177f738f0cb7330
use std::cmp; use std::fmt; use std::io; use std::io::ErrorKind; use std::io::IoSliceMut; use std::io::Read; use std::io::ReadBuf; use std::io::Result; use std::mem::MaybeUninit; use crate::buffer::BufferRead; pub struct BufferReader<R> { inner: R, buf: Box<[MaybeUninit<u8>]>, pos: usize, cap: usize...
use std::cmp; use std::fmt; use std::io; use std::io::ErrorKind; use std::io::IoSliceMut; use std::io::Read; use std::io::ReadBuf; use std::io::Result; use std::mem::MaybeUninit; use crate::buffer::BufferRead; pub struct BufferReader<R> { inner: R, buf: Box<[MaybeUninit<u8>]>, pos: usize, cap: usize...
pty() { Err(std::io::Error::new( ErrorKind::UnexpectedEof, "failed to fill whole buffer", )) } else { Ok(()) } }
fferRead for BufferReader<R> { fn working_buf(&self) -> &[u8] { self.buffer() } fn fill_buf(&mut self) -> Result<&[u8]> { if self.pos >= self.cap { debug_assert!(self.pos == self.cap); let mut readbuf = ReadBuf::uninit(&mut self.buf); ...
random
[ { "content": "fn read_until<R: BufferRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {\n\n let mut read = 0;\n\n loop {\n\n let (done, used) = {\n\n let available = match r.fill_buf() {\n\n Ok(n) => n,\n\n Err(ref e) if e.kind() == E...
Rust
src/tty.rs
Trikzon/oxid-os
154c4aa240b8e4848a502fcf1e63dd99f9cf3798
use crate::vga; use core::fmt; use lazy_static::lazy_static; use spin::Mutex; use volatile::Volatile; const VGA_WIDTH: usize = 80; const VGA_HEIGHT: usize = 25; const DEFAULT_FOREGROUND_COLOR: vga::Color = vga::Color::White; const DEFAULT_BACKGROUND_COLOR: vga::Color = vga::Color::Black; lazy_static! { pub stati...
use crate::vga; use core::fmt; use lazy_static::lazy_static; use spin::Mutex; use volatile::Volatile; const VGA_WIDTH: usize = 80; const VGA_HEIGHT: usize = 25; const DEFAULT_FOREGROUND_COLOR: vga::Color = vga::Color::White; const DEFAULT_BACKGROUND_COLOR: vga::Color = vga::Color::Black; lazy_static! { pub stati...
pub fn clear_row(&mut self, row: usize) { let blank_char = vga::Char::new(b' ', self.char_color); for column in 0..VGA_WIDTH { self.buffer[row][column].write(blank_char); } } pub fn clear(&mut self) { for row in 0..VGA_HEIGHT { self.clear_row(row); ...
pub fn new_line(&mut self) { for row in 1..VGA_HEIGHT { for column in 0..VGA_WIDTH { let char = self.buffer[row][column].read(); self.buffer[row - 1][column].write(char); } } self.clear_row(VGA_HEIGHT - 1); self.column = 0; }
function_block-full_function
[ { "content": "pub fn exit(exit_code: ExitCode) {\n\n let mut port = Port::new(0xf4);\n\n unsafe { port.write(exit_code as u32) };\n\n}\n", "file_path": "src/qemu.rs", "rank": 2, "score": 45129.99393055399 }, { "content": "#[doc(hidden)]\n\n#[inline]\n\npub fn _print(args: fmt::Argument...
Rust
src/main_day4.rs
skerkewitz/advent_of_code_2020
5ac3f446ba002d604f78c547806114ac228aa1b7
mod test; fn parse_amount(amount_str: &str) -> (i32, i32) { assert!(!amount_str.is_empty()); let split: Vec<&str> = amount_str.split('-').collect(); assert_eq!(split.len(), 2); let min = split[0]; let max = split[1]; let m0 = min.parse::<i32>().unwrap(); let m1 = max.parse::<i32>().unwra...
mod test; fn parse_amount(amount_str: &str) -> (i32, i32) { assert!(!amount_str.is_empty()); let split: Vec<&str> = amount_str.split('-').collect(); assert_eq!(split.len(), 2); let min = split[0]; let max = split[1]; let m0 = min.parse::<i32>().unwrap(); let m1 = max.parse::<i32>().unwra...
fn hair_color_check(v: &String) -> bool { if v.chars().next().unwrap() != '#' { return false } let values = v.split_at(1); if values.1.len() != 6 { return false } return values.1.chars().all(|c| c.is_ascii_hexdigit()); } fn heigh...
e), "ecl" => return eye_colors.contains(self.value.as_str()), "pid" => return self.value.len() == 9 && self.value.chars().all(char::is_numeric), "cid" => return true, _ => panic!("Its something else {}", self.key) } return true; }
function_block-function_prefixed
[ { "content": "fn run(acc: i32, pi: usize, prg: &Vec<(Opcode, i32)>, mark: &mut Vec<bool>) -> Result<i32, String> {\n\n\n\n // println!(\"Debug acc:{} pi:{}\", acc, pi);\n\n\n\n if pi >= mark.len() {\n\n return Ok(acc);\n\n }\n\n\n\n if mark[pi] == true {\n\n return Err(\"Did loop\".to_...
Rust
src/manifests/mod.rs
mriehl/comtrya
5cc3d13035fe7b0b3f204dfd5553bcf0ed205ead
mod providers; pub use providers::register_providers; pub use providers::ManifestProvider; use crate::actions::Actions; use petgraph::prelude::*; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Manifest { #[serde(default)] pub name: Optio...
mod providers; pub use providers::register_providers; pub use providers::ManifestProvider; use crate::actions::Actions; use petgraph::prelude::*; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Manifest { #[serde(default)] pub name: Optio...
!( "test.hello", get_manifest_name(&manifest_directory, &location) ); } #[test] fn test_main_nested_yaml() { let manifest_directory = PathBuf::from("/tmp"); let location = PathBuf::from("/tmp/test/nested/main.yaml"); assert_eq!( "test.nes...
b root_dir: Option<PathBuf>, #[serde(skip)] pub dag_index: Option<NodeIndex<u32>>, } pub fn get_manifest_name(manifest_directory: &PathBuf, location: &PathBuf) -> String { let local_name = location.strip_prefix(&manifest_directory).unwrap(); let manifest_name = local_name .componen...
random
[ { "content": "/// ManifestProviders are responsible for taking a String\n\n/// and returning a `PathBuf`. Providers, such as Git, are\n\n/// responsible for accepting the String and cloning the\n\n/// repository, in-order to return the `PathBuf`.\n\npub trait ManifestProvider {\n\n /// This functions is call...
Rust
src/model/mod.rs
MaxOhn/rosu-v2
d7e19c568ceb276652fca008102387ba1fab78a7
macro_rules! def_enum { (@BASE $type:tt { $($variant:ident = $n:literal,)* }) => { #[allow(clippy::upper_case_acronyms, missing_docs)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum $type { $($variant = $n,)* } impl<'de> serde::Deserialize<'de> ...
macro_rules! def_enum { (@BASE $type:tt { $($variant:ident = $n:literal,)* }) => { #[allow(clippy::upper_case_acronyms, missing_docs)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum $type { $($variant = $n,)* } impl<'de> serde::Deserialize<'de> ...
} fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Self::Value, E> { match s { $(stringify!($variant) => Ok(<$type>::$variant),)* _ => { Err(serde::de::Error::unknown_variant(s, &[stringify!($($variant),*)])) ...
h key { "id" | "name" => { result.replace(map.next_value()?); } _ => { let _: serde::de::IgnoredAny = map.next_value()?; } } } result.ok_or_else(|| ser...
random
[ { "content": "fn ser_de<T: DeserializeOwned + Serialize + PartialEq + Debug>(val: T) {\n\n let serialized =\n\n serde_json::to_string(&val).unwrap_or_else(|e| panic!(\"Failed to serialize: {}\", e));\n\n\n\n let deserialized: T = serde_json::from_str(&serialized)\n\n .unwrap_or_else(|e| pani...
Rust
src/core/lcore.rs
condy0919/dpdk-rs
660e1d88c6b12a94b42a35bbdc43ec715d307784
use crate::core::{cvt, read_r, write_r, thread}; use std::io; use std::mem; use std::panic; use std::result; use std::any::Any; use std::sync::Arc; use std::cell::UnsafeCell; use std::os::unix::io::RawFd; use std::sync::atomic::{AtomicUsize, Ordering, fence, spin_loop_hint}; pub type Result<T> = result::Result<T, Bo...
use crate::core::{cvt, read_r, write_r, thread}; use std::io; use std::mem; use std::panic; use std::result; use std::any::Any; use std::sync::Arc; use std::cell::UnsafeCell; use std::os::unix::io::RawFd; use std::sync::atomic::{AtomicUsize, Ordering, fence, spin_loop_hint}; pub type Result<T> = result::Result<T, Bo...
esult<T>>>>); unsafe impl<T: Send> Send for Packet<T> {} unsafe impl<T: Sync> Sync for Packet<T> {} struct FuncPacket<R>(Arc<UnsafeCell<Option<Box<dyn FnOnce() -> R>>>>); unsafe impl<R> Send for FuncPacket<R> {} unsafe impl<R> Sync for FuncPacket<R> {}
t_t = unsafe { mem::MaybeUninit::zeroed().assume_init() }; unsafe { libc::CPU_ZERO(&mut cpuset); for &cpu in cpuvec.iter() { libc::CPU_SET(cpu, &mut cpuset); } } self.cpuset = Some(cpuset); self } ...
random
[ { "content": "#[inline]\n\npub fn read(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {\n\n cvt(unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len() as libc::size_t) })\n\n .map(|r| r as usize)\n\n}\n\n\n", "file_path": "src/core/mod.rs", "rank": 2, "score": 118971.28092543558 ...
Rust
src/population.rs
SilvanCodes/set-neat
5e55b8eb23feb59328722abbe3643c82bbfbfb0d
use set_genome::{Genome, GenomeContext}; use std::{mem, time::Instant}; use crate::{ individual::{ behavior::{Behavior, Behaviors}, scores::Score, Individual, }, parameters::{NeatParameters, Reproduction, Speciation}, species::Species, statistics::PopulationStatistics, P...
use set_genome::{Genome, GenomeContext}; use std::{mem, time::Instant}; use crate::{ individual::{ behavior::{Behavior, Behaviors}, scores::Score, Individual, }, parameters::{NeatParameters, Reproduction, Speciation}, species::Species, statistics::PopulationStatistics, P...
pub fn speciate(&mut self) { let now = Instant::now(); for genome in mem::replace(&mut self.individuals, Vec::new()) { self.place_genome_into_species(genome); } self.statistics.species.sizes = self.species.iter().map(|s| s.members.len()).collect(); ...
fn remove_stale_species(&mut self) { self.species .sort_by(|species_0, species_1| species_1.score.partial_cmp(&species_0.score).unwrap()); let len_before_threshold = self.species.len(); let Reproduction { elitism_species, generations_until_...
function_block-full_function
[ { "content": "pub fn crossover_same_genome_benchmark(c: &mut Criterion) {\n\n let mut id_gen = IdGenerator::default();\n\n let parameters: Parameters = Default::default();\n\n\n\n // create randomn source\n\n let mut rng = NeatRng::new(\n\n parameters.setup.seed,\n\n parameters.mutatio...
Rust
wallet/tests/account.rs
rmourey26/chain-wallet-libs
22fe22574019feea774832b61f9f5ef65ca9173f
mod utils; use self::utils::State; use chain_impl_mockchain::{ certificate::VoteCast, fragment::Fragment, value::Value, vote::{Choice, Payload}, }; use std::convert::TryInto; use wallet::{transaction::dump_icarus_utxo, RecoveryBuilder}; const BLOCK0: &[u8] = include_bytes!("../../test-vectors/block0")...
mod utils; use self::utils::State; use chain_impl_mockchain::{ certificate::VoteCast, fragment::Fragment, value::Value, vote::{Choice, Payload}, }; use std::convert::TryInto; use wallet::{transaction::dump_icarus_utxo, RecoveryBuilder}; const BLOCK0: &[u8] = include_bytes!("../../test-vectors/block0")...
#[test] fn cast_vote() { let wallet = RecoveryBuilder::new() .mnemonics(&bip39::dictionary::ENGLISH, MNEMONICS) .expect("valid mnemonics"); let mut yoroi = wallet .build_yoroi() .expect("recover an Icarus/Yoroi wallet"); let mut account = wallet.build_wallet().expect("rec...
t"); assert_eq!(account.confirmed_value(), Value::zero()); account.update_state(Value(110), 0); assert_eq!(account.confirmed_value(), Value(110)); }
function_block-function_prefixed
[ { "content": "pub fn send_to_one_address<K: Clone + Groupable, WB: WitnessBuilder>(\n\n settings: &crate::Settings,\n\n address: &chain_addr::Address,\n\n utxo_store: &UtxoStore<K>,\n\n mk_witness: &'static dyn Fn(K) -> WB,\n\n) -> Option<(Transaction<NoExtra>, Vec<Input>)> {\n\n let payload = ch...
Rust
src/syscore/linux/epoll/epoll.rs
vertexclique/nuclei
916ef9250f65b3aae28a383ee6ee3ed50b7af182
use crate::sys::epoll::*; use futures::channel::oneshot; use lever::prelude::*; use pin_utils::unsafe_pinned; use std::future::Future; use std::io::{self, Read, Write}; use std::mem::MaybeUninit; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::pin::Pin; use std::task::{Context, Poll}; use std::{collections...
use crate::sys::epoll::*; use futures::channel::oneshot; use lever::prelude::*; use pin_utils::unsafe_pinned; use std::future::Future; use std::io::{self, Read, Write}; use std::mem::MaybeUninit; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::pin::Pin; use std::task::{Context, Poll}; use std::{collections...
type CompletionList = Vec<(i32, oneshot::Sender<i32>)>; pub struct SysProactor { epoll_fd: RawFd, event_fd: TTas<File>, registered: TTas<HashMap<RawFd, i32>>, completions: TTas<HashMap<RawFd, CompletionList>>, } impl SysProactor { pub(crate) fn new() -> io::Result<SysProac...
pub(crate) fn shim_to_af_unix(sockaddr: &SockAddr) -> io::Result<UnixSocketAddr> { let addr = unsafe { &*(sockaddr.as_ptr() as *const libc::sockaddr_un) }; if addr.sun_family != libc::AF_UNIX as libc::sa_family_t { return Err(io::Error::new( io::ErrorKind::InvalidData, "socket is...
function_block-full_function
[]
Rust
src/dev/pcf8574.rs
Rahix/port-expander
ce2091d1d75521cb9b4e6c57854f94ffe72423e8
pub struct Pcf8574<M>(M); pub struct Pcf8574a<M>(M); impl<I2C> Pcf8574<shared_bus::NullMutex<Driver<I2C>>> where I2C: crate::I2cBus, { pub fn new(i2c: I2C, a0: bool, a1: bool, a2: bool) -> Self { Self::with_mutex(i2c, a0, a1, a2) } } impl<I2C> Pcf8574a<shared_bus::NullMutex<Driver<I2C>>> where ...
pub struct Pcf8574<M>(M); pub struct Pcf8574a<M>(M); impl<I2C> Pcf8574<shared_bus::NullMutex<Driver<I2C>>> where I2C: crate::I2cBus, { pub fn new(i2c: I2C, a0: bool, a1: bool, a2: bool) -> Self { Self::with_mutex(i2c, a0, a1, a2) } } impl<I2C> Pcf8574a<shared_bus::NullMutex<Driver<I2C>>> where ...
::i2c as mock_i2c; #[test] fn pcf8574() { let expectations = [ mock_i2c::Transaction::write(0x21, vec![0b11111111]), mock_i2c::Transaction::write(0x21, vec![0b11111011]), mock_i2c::Transaction::read(0x21, vec![0b01000000]), mock_i2c::Transaction::read(0x2...
sk_low: u32) -> Result<(), Self::Error> { self.out |= mask_high as u8; self.out &= !mask_low as u8; self.i2c.write(self.addr, &[self.out])?; Ok(()) } fn is_set(&mut self, mask_high: u32, mask_low: u32) -> Result<u32, Self::Error> { Ok(((self.out as u32) & mask_high) | (!...
random
[ { "content": "/// Blanket trait for types implementing `i2c::WriteRead + i2c::Write + i2c::Read`\n\npub trait I2cBus: hal_i2c::WriteRead + hal_i2c::Write + hal_i2c::Read {\n\n type BusError: From<<Self as hal_i2c::WriteRead>::Error>\n\n + From<<Self as hal_i2c::Write>::Error>\n\n + From<<Self a...
Rust
src/connectivity/bluetooth/profiles/bt-avrcp/src/packets/inform_battery_status.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use fidl_fuchsia_bluetooth_avrcp::BatteryStatus; use packet_encoding::{Decodable, Encodable}; use crate::packets::{ AvcCommandType, Error, PacketResult, PduId, VendorCommand, VendorDependentPdu, }; #[derive(Debug)] pub struct InformBatteryStatusOfCtCommand { battery_status: BatteryStatus, } impl InformBatt...
use fidl_fuchsia_bluetooth_avrcp::BatteryStatus; use packet_encoding::{Decodable, Encodable}; use crate::packets::{ AvcCommandType, Error, PacketResult, PduId, VendorCommand, VendorDependentPdu, }; #[derive(Debug)] pub struct InformBatteryStatusOfCtCommand { battery_status: BatteryStatus, } impl InformBatt...
T } } impl VendorCommand for InformBatteryStatusOfCtCommand { fn command_type(&self) -> AvcCommandType { AvcCommandType::Control } } impl Decodable for InformBatteryStatusOfCtCommand { type Error = Error; fn decode(buf: &[u8]) -> PacketResult<Self> { if buf.len() < 1 { ...
(&self) -> BatteryStatus { self.battery_status } } impl VendorDependentPdu for InformBatteryStatusOfCtCommand { fn pdu_id(&self) -> PduId { PduId::InformBatteryStatusOfC
random
[]
Rust
src/auto/completion.rs
antoyo/gtksourceview-rs
2410b0de7d9a3f2dbb89384165d21851de2af8ab
use CompletionContext; use CompletionInfo; use CompletionProvider; use Error; use View; use ffi; use glib; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use gtk; use gtk_ffi; use libc; use std::boxed::Box as Box_; ...
use CompletionContext; use CompletionInfo; use CompletionProvider; use Error; use View; use ffi; use glib; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use gtk; use gtk_ffi; use libc; use std::boxed::Box as Box_; ...
unsafe extern "C" fn move_cursor_trampoline<P>(this: *mut ffi::GtkSourceCompletion, step: gtk_ffi::GtkScrollStep, num: libc::c_int, f: glib_ffi::gpointer) where P: IsA<Completion> { callback_guard!(); let f: &Box_<Fn(&P, gtk::ScrollStep, i32) + 'static> = transmute(f); f(&Completion::from_glib_none(this)....
unsafe extern "C" fn hide_trampoline<P>(this: *mut ffi::GtkSourceCompletion, f: glib_ffi::gpointer) where P: IsA<Completion> { callback_guard!(); let f: &Box_<Fn(&P) + 'static> = transmute(f); f(&Completion::from_glib_none(this).downcast_unchecked()) }
function_block-full_function
[ { "content": "pub trait ViewExt {\n\n fn get_auto_indent(&self) -> bool;\n\n\n\n #[cfg(feature = \"v3_16\")]\n\n fn get_background_pattern(&self) -> BackgroundPatternType;\n\n\n\n fn get_completion(&self) -> Option<Completion>;\n\n\n\n fn get_draw_spaces(&self) -> DrawSpacesFlags;\n\n\n\n fn g...
Rust
src/action/mod.rs
tarkov-database/identity-server
67bd21d6329ef811748544a820f5b63f58337b2a
mod handler; mod routes; use crate::{ authentication::token::{TokenClaims, TokenConfig, TokenType}, error, mail, model::Status, }; use std::collections::HashMap; use chrono::{serde::ts_seconds, DateTime, Duration, Utc}; use hyper::StatusCode; use serde::{Deserialize, Serialize}; pub use routes::routes; ...
mod handler; mod routes; use crate::{ authentication::token::{TokenClaims, TokenConfig, TokenType}, error, mail, model::Status, }; use std::collections::HashMap; use chrono::{serde::ts_seconds, DateTime, Duration, Utc}; use hyper::StatusCode; use serde::{Deserialize, Serialize}; pub use routes::routes; ...
f where A: IntoIterator<Item = String>, { let mut claims = Self::new(aud, sub, ActionType::Verify); claims.email = Some(email.into()); claims } } impl TokenClaims for ActionClaims { const TOKEN_TYPE: TokenType = TokenType::Action; fn get_type(&self) -> &TokenType {...
b enum ActionType { Verify, Reset, } impl ActionType { const fn expiration_time(&self) -> std::time::Duration { match self { ActionType::Verify => std::time::Duration::from_secs(3 * 60 * 60 * 24), ActionType::Reset => std::time::Duration::from_secs(30 * 60), } } ...
random
[ { "content": "/// Token routes\n\npub fn routes() -> axum::Router {\n\n axum::Router::new().route(\"/\", get(handler::get).post(handler::create))\n\n}\n", "file_path": "src/token/routes.rs", "rank": 0, "score": 135243.1373680666 }, { "content": "/// User routes\n\npub fn routes() -> axum:...
Rust
src/gui/pipeline.rs
Trangar/crystal-engine
fb27cf728bf01cabb65f99e4cc5f279f60cb54c2
use super::{fs, vs, GuiElementRef, Vertex}; use std::sync::Arc; use vulkano::{ buffer::{BufferUsage, CpuAccessibleBuffer, CpuBufferPool}, command_buffer::{AutoCommandBufferBuilder, DynamicState}, descriptor::descriptor_set::{PersistentDescriptorSet, StdDescriptorPool}, device::Device, framebuffer::{...
use super::{fs, vs, GuiElementRef, Vertex}; use std::sync::Arc; use vulkano::{ buffer::{BufferUsage, CpuAccessibleBu
ions.1 as f32, ], size: [ element_data.dimensions.2 as f32, element_data.dimensions.3 as f32, ], }; let data = self.uniform_buffer.next(data).unwrap(); let layout = self.pipeline.descriptor_set_layout(0).unwra...
ffer, CpuBufferPool}, command_buffer::{AutoCommandBufferBuilder, DynamicState}, descriptor::descriptor_set::{PersistentDescriptorSet, StdDescriptorPool}, device::Device, framebuffer::{RenderPassAbstract, Subpass}, pipeline::{GraphicsPipeline, GraphicsPipelineAbstract}, sampler::{Filter, MipmapMo...
random
[ { "content": "/// Returns the vector.\n\nfn get_vec(pvs: &PolygonVertices<'_>, pvi: PolygonVertexIndex) -> anyhow::Result<Point3<f64>> {\n\n pvs.control_point(pvi)\n\n .map(Into::into)\n\n .ok_or_else(|| anyhow!(\"Index out of range: {:?}\", pvi))\n\n}\n\n\n", "file_path": "src/model/loader...
Rust
src/uncompress.rs
robey/gingersnap
f418104dc4cb3506f03cf496128d8ba3dd4ea11d
use aliases::{ByteStream}; use bytes::{Buf, Bytes, IntoBuf, LittleEndian}; use futures::{Async, Poll, Stream}; use snap; use std::collections::VecDeque; use std::convert::TryFrom; use std::io; use shared::{crc32c_masked, FrameType}; const MAGIC: &'static [u8] = b"sNaPpY"; #[derive(PartialEq)] enum State { Heade...
use aliases::{ByteStream}; use bytes::{Buf, Bytes, IntoBuf, LittleEndian}; use futures::{Async, Poll, Stream}; use snap; use std::collections::VecDeque; use std::convert::TryFrom; use std::io; use shared::{crc32c_masked, FrameType}; const MAGIC: &'static [u8] = b"sNaPpY"; #[derive(PartialEq)] enum State { Heade...
} impl<S> Stream for SnappyUncompress<S> where S: ByteStream { type Item = Bytes; type Error = io::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { loop { match self.state { State::Header => { if self.saved_length < 4 { match self.feed() { ...
Ok(FrameType::Compressed) => { let compressed = data.slice_from(4); let expected_crc = data.into_buf().get_u32::<LittleEndian>(); match self.decoder.decompress_vec(compressed.as_ref()) { Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e)), Ok(uncompressed) => { ...
function_block-function_prefix_line
[]
Rust
src/player.rs
ahenshaw/netpong
610419a13709804bed3cc86f028c5bd8a63de687
use std::net::UdpSocket; use quick_protobuf::{Writer}; use ggez::{Context, GameResult, graphics}; use ggez::input::mouse; use crate::netpong::mod_Update::{OneOfUpdateType}; use crate::netpong::{Update, Paddle}; use crate::{SCREEN_WIDTH, SCREEN_HEIGHT, Position, Ball}; use crate::wacky_tube_man::WackyTubeMan; use num...
use std::net::UdpSocket; use quick_protobuf::{Writer}; use ggez::{Context, GameResult, graphics}; use ggez::input::mouse; use crate::netpong::mod_Update::{OneOfUpdateType}; use crate::netpong::{Update, Paddle}; use crate::{SCREEN_WIDTH, SCREEN_HEIGHT, Position, Ball}; use crate::wacky_tube_man::WackyTubeMan; use num...
pub fn set_mode(&mut self, mode: PlayerMode) { self.mode = mode; } pub fn draw_score(&self, ctx: &mut Context) -> GameResult { let font = graphics::Font::new(ctx, "/Orbitron-Bold.ttf")?; let fragment = graphics::TextFragment { text: format!("{}", self.score), ...
pub fn draw(&self, ctx: &mut Context) -> GameResult { let mesh = graphics::Mesh::new_rectangle( ctx, graphics::DrawMode::fill(), graphics::Rect::new( self.pos.x-self.width/2.0, self.pos.y-self.height/2.0, self.width, ...
function_block-function_prefix_line
[ { "content": "fn message(ctx: &mut Context, s: &str) -> GameResult {\n\n let text = graphics::Text::new(s);\n\n let r = text.dimensions(ctx);\n\n\n\n graphics::draw(ctx, \n\n &text, \n\n graphics::DrawParam::default().dest([(SCREEN_WIDTH - r.w)/2.0, (SCREEN_HEIGHT - r.h)/2.0])\n\n )?;\...
Rust
alumina_opt/src/adam.rs
russellwmy/alumina
19f913f88cc9643a7f61a3d6b450c535ce9035d7
use crate::{calc_change_sqr, GradientStepper}; use alumina_core::{errors::ExecError, graph::Node}; use indexmap::{indexmap, IndexMap}; use ndarray::{ArcArray, ArrayD, IxDyn, Zip}; use rayon::prelude::*; #[derive(Clone, Debug)] struct NodeState { momentums: ArrayD<f32>, curvatures: ArrayD<f32>, } #[derive(Clone, Deb...
use crate::{calc_change_sqr, GradientStepper}; use alumina_core::{errors::ExecError, graph::Node}; use indexmap::{indexmap, IndexMap}; use ndarray::{ArcArray, ArrayD, IxDyn, Zip}; use rayon::prelude::*; #[derive(Clone, Debug)] struct NodeState { momentums: ArrayD<f32>, curvatures: ArrayD<f32>, } #[derive(Clone, Deb...
}
m, state)| { parameters_and_grad_values .swap_remove(param) .map(|grad_arr| (param, state, grad_arr.to_owned())) }) .par_bridge() .map(|(param, state, mut grad_arr)| { let param_arr = param.value().unwrap(); if bias_correct { Zip::from(&param_arr) .and(&mut state.mom...
function_block-function_prefixed
[ { "content": "/// print step number, loss, and L2 norm of variable change\n\npub fn print_step_data<S: GradientStepper>(batch_size: f32) -> impl FnMut(&mut S, &StepData) -> Signal {\n\n\tmove |_step, data| {\n\n\t\tprintln!(\n\n\t\t\t\"step:{}\\tloss:{}\\tchange:{}\",\n\n\t\t\tdata.step,\n\n\t\t\tdata.loss / ba...
Rust
rpc/src/module/stats.rs
brson/ckb
b9bf40024b8a5acd9b8871dba669c89f38be297d
use ckb_jsonrpc_types::{AlertMessage, ChainInfo, PeerState}; use ckb_network_alert::notifier::Notifier as AlertNotifier; use ckb_shared::shared::Shared; use ckb_sync::Synchronizer; use ckb_traits::BlockMedianTimeContext; use ckb_util::Mutex; use jsonrpc_core::Result; use jsonrpc_derive::rpc; use std::sync::Arc; #[rpc(...
use ckb_jsonrpc_types::{AlertMessage, ChainInfo, PeerState}; use ckb_network_alert::notifier::Notifier as AlertNotifier; use ckb_shared::shared::Shared; use ckb_sync::Synchronizer; use ckb_traits::BlockMedianTimeContext; use ckb_util::Mutex; use jsonrpc_core::Result; use jsonrpc_derive::rpc; use std::sync::Arc; #[rpc(...
} }
Ok(self .synchronizer .shared() .state() .read_inflight_blocks() .blocks_iter() .map(|(peer, blocks)| PeerState::new(peer.value(), 0, blocks.len())) .collect())
call_expression
[]
Rust
arch/cortex-m4/src/systick.rs
alevy/tock-chalmers
986a2b458066f9818ba033d2fa7f3533c0a0a524
use kernel; use kernel::common::regs::{ReadOnly, ReadWrite}; use kernel::common::StaticRef; #[repr(C)] struct SystickRegisters { syst_csr: ReadWrite<u32, ControlAndStatus::Register>, syst_rvr: ReadWrite<u32, ReloadValue::Register>, syst_cvr: ReadWrite<u32, CurrentValue::Register>, syst_calib: ReadOnl...
use kernel; use kernel::common::regs::{ReadOnly, ReadWrite}; use kernel::common::StaticRef; #[repr(C)] struct SystickRegisters { syst_csr: ReadWrite<u32, ControlAndStatus::Register>, syst_rvr: ReadWrite<u32, ReloadValue::Register>, syst_cvr: ReadWrite<u32, CurrentValue::Register>, syst_calib: ReadOnl...
SYSTICK_BASE .syst_csr .write(ControlAndStatus::ENABLE::SET + ControlAndStatus::CLKSOURCE::SET); } } }
if with_interrupt { SYSTICK_BASE.syst_csr.write( ControlAndStatus::ENABLE::SET + ControlAndStatus::TICKINT::SET + ControlAndStatus::CLKSOURCE::SET, ); } else {
function_block-random_span
[ { "content": "/// Get closest power of two greater than the given number.\n\npub fn closest_power_of_two(mut num: u32) -> u32 {\n\n num -= 1;\n\n num |= num >> 1;\n\n num |= num >> 2;\n\n num |= num >> 4;\n\n num |= num >> 8;\n\n num |= num >> 16;\n\n num += 1;\n\n num\n\n}\n\n\n\n#[deri...
Rust
zcash_primitives/src/consensus/wtp/demo.rs
boltlabs-inc/librustzcash
d8bf16159a403ae7b1cd3c1da0b8e074dc917cf6
use blake2b_simd::Params; use super::context; use crate::wtp::{demo, Predicate}; pub struct Program; impl Program { pub(super) fn verify<'a>( predicate: &demo::Predicate, witness: &demo::Witness, ctx: &context::V1<'a>, ) -> Result<(), &'static str> { ...
use blake2b_simd::Params; use super::context; use crate::wtp::{demo, Predicate}; pub struct Program; impl Program { pub(super) fn verify<'a>( predicate: &demo::Predicate, witness: &demo::Witness, ctx: &context::V1<'a>, ) -> Result<(), &'static str> { ...
} #[cfg(test)] mod tests { use crate::{ consensus::wtp::{Context, Programs}, transaction::{ components::{Amount, OutPoint, WtpIn, WtpOut}, TransactionData, }, wtp::{self, demo}, }; use blake2b_simd::Params; #[test] fn demo_program() { ...
0); h.update(&p_close.0); let hash = h.finalize(); if hash.as_bytes() == p_open.0 { Ok(()) } else { Err("hash mismatch") ...
function_block-function_prefixed
[ { "content": "fn parse_close_witness_input(input: [u8; 180]) -> close::Witness {\n\n let witness_type = input[0];\n\n let mut address= Vec::new();\n\n let mut signature = Vec::new();\n\n let mut revoke_token = Vec::new();\n\n\n\n address.extend_from_slice(&input[1..34]);\n\n // cust-sig or mer...
Rust
jl_compiler/src/cps/k_struct.rs
vain0x/jacco-lang
f1982710a8b9a6198ebb14692570e83774d3659b
use super::*; use crate::{ source::Loc, utils::{VecArena, VecArenaId}, }; #[derive(Clone, Debug)] pub(crate) enum KStructParent { Enum { struct_enum: KStructEnum, index: usize, }, Struct { ty_params: Vec<KTyParam>, }, } impl KStructParent { pub(crate) fn n...
use super::*; use crate::{ source::Loc, utils::{VecArena, VecArenaId}, }; #[derive(Clone, Debug)] pub(crate) enum KStructParent { Enum { struct_enum: KStructEnum, index: usize, }, Struct {
fn tag_ty(self, structs: &KStructArena, struct_enums: &KStructEnumArena) -> KTy { match structs[self].parent { KStructParent::Enum { struct_enum, .. } => struct_enum.tag_ty(struct_enums), KStructParent::Struct { .. } => KTy::Unit, } } pub(crate) fn tag_value_opt(self, st...
ty_params: Vec<KTyParam>, }, } impl KStructParent { pub(crate) fn new_enum(struct_enum: KStructEnum, index: usize) -> Self { Self::Enum { struct_enum, index } } } pub(crate) struct KStructTag; pub(crate) type KStruct = VecArenaId<KStructTag>; pub(crate) type KStructArena = VecArena<KStructTag,...
random
[ { "content": "fn unique_struct_enum_name(struct_enum: KStructEnum, cx: &mut Cx) -> String {\n\n struct_enum.name(&cx.mod_outline.struct_enums).to_string()\n\n}\n\n\n", "file_path": "jl_compiler/src/clang/clang_gen.rs", "rank": 0, "score": 169662.21613426268 }, { "content": "fn gen_struct_...
Rust
src/rsync.rs
allonsy/resilient
24e1468781941e5fb31c603acf0d42517fcb8da9
use super::config::Config; use super::commit::Commit; use super::status; use std::process::Command; use std::fs; use tempdir::TempDir; const DATA_FOLDER_NAME: &str = "data"; pub fn make_commit(conf: &Config, name: String, message: String, verbose: bool) -> Commit { let backups_dir = conf.get_backups_folder(); ...
use super::config::Config; use super::commit::Commit; use super::status; use std::process::Command; use std::fs; use tempdir::TempDir; const DATA_FOLDER_NAME: &str = "data"; pub fn make_commit(conf: &Config, name: String, message: String, verbose: bool) -> Commit { let backups_dir = conf.get_backups_folder(); ...
se { "-aAX" }; let rsync_command = Command::new("rsync") .arg(flags) .arg("--delete") .arg(&src_arg) .arg(&dest_arg) .status(); if rsync_command.is_err() { eprintln!("Unable to spawn rsync command"); std::process::exit(1); } let ...
("resilient"); if empty_dir.is_err() { eprintln!("Unable to allocate empty dir!"); std::process::exit(1); } empty_dir.unwrap().path().to_path_buf() }; let src_arg = format!("{}/", conf.get_backup_location().display()); let dest_arg = format!("{}", compare_pat...
random
[ { "content": "fn get_toml_string_key(table: &Table, key: &str) -> String {\n\n let value = table.get(key);\n\n if value.is_none() {\n\n eprintln!(\"Cannot find key '{}' in toml\", key);\n\n std::process::exit(1);\n\n }\n\n\n\n let value = value.unwrap();\n\n if !value.is_str() {\n\n...
Rust
src/bin/main.rs
Szymongib/bookmark
477807a2543253bd9f44943c1c829060dbc355dc
extern crate clap; use clap::{App, Arg, ArgMatches, SubCommand}; use crate::interactive::interactive_mode::enter_interactive_mode; use crate::interactive::subcommand::add; use bookmark_lib::registry::{URLRegistry, DEFAULT_GROUP}; use bookmark_lib::storage::FileStorage; use bookmark_lib::Registry; use bookmark_lib::f...
extern crate clap; use clap::{App, Arg, ArgMatches, SubCommand}; use crate::interactive::interactive_mode::enter_interactive_mode; use crate::interactive::subcommand::add; use bookmark_lib::registry::{URLRegistry, DEFAULT_GROUP}; use bookmark_lib::storage::FileStorage; use bookmark_lib::Registry; use bookmark_lib::f...
pub fn import_sub_cmd(&self, matches: &ArgMatches) { let version = matches .value_of("version") .expect("Version from which to import not provided"); let old_file = matches .value_of("old-file") .expect("Old version file path not provided"); ...
eleted { println!("URL '{}' removed", id) } else { println!("URL '{}' not found", id) } } Err(why) => println!("Error deleting '{}' URL: {}", id, why), } }
function_block-function_prefixed
[ { "content": "fn strip_protocol(url: &str) -> String {\n\n let possible_prefix = &[\"https://www.\", \"http://www.\", \"https://\", \"http://\"];\n\n for prefix in possible_prefix {\n\n if let Some(u) = url.strip_prefix(prefix) {\n\n return u.to_string();\n\n }\n\n }\n\n\n\n ...
Rust
sway-core/src/type_engine.rs
binggh/sway
e75cbd7c975beb8ef1f93f5913abfb8db84e11f9
use crate::error::*; use std::fmt::{Debug, Display}; mod engine; mod integer_bits; mod type_info; mod unresolved_type_check; pub use engine::*; use fuels_types::Property; pub use integer_bits::*; pub use type_info::*; pub(crate) use unresolved_type_check::UnresolvedTypeCheck; #[derive(PartialEq, Eq, Hash, Clone, Copy...
use crate::error::*; use std::fmt::{Debug, Display}; mod engine; mod integer_bits; mod type_info; mod unresolved_type_check; pub use engine::*; use fuels_types::Property; pub use integer_bits::*; pub use type_info::*; pub(crate) use unresolved_type_check::UnresolvedTypeCheck; #[derive(PartialEq, Eq, Hash, Clone, Copy...
, _ => None, } } } #[test] fn generic_enum_resolution() { use crate::semantic_analysis::ast_node::TypedEnumVariant; use crate::{span::Span, Ident}; let engine = Engine::default(); let sp = Span::dummy(); let variant_types = vec![TypedEnumVariant { name: Ident::new_...
Some( variant_types .iter() .map(|x| x.generate_json_abi()) .collect(), )
call_expression
[ { "content": "fn print_inner_types(name: String, inner_types: impl Iterator<Item = TypeId>) -> String {\n\n format!(\n\n \"{}<{}>\",\n\n name,\n\n inner_types\n\n .map(|x| x.friendly_type_str())\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n )\n\n}\n",...
Rust
src/main.rs
cholcombe973/yesterday_weather
b42b315c7af101adde513707a25a3bc82ab472a6
use std::path::Path; use std::str::FromStr; use chrono::prelude::*; use chrono::{DateTime, Duration, Local, NaiveDateTime}; use clap::{crate_authors, crate_version, App, AppSettings, Arg, ArgMatches}; use forecast::{ApiClient, ExcludeBlock, Lang, TimeMachineRequestBuilder, Units}; use reqwest::Client; use rusqlite::{C...
use std::path::Path; use std::str::FromStr; use chrono::prelude::*; use chrono::{DateTime, Duration, Local, NaiveDateTime}; use clap::{crate_authors, crate_version, App, AppSettings, Arg, ArgMatches}; use forecast::{ApiClient, ExcludeBlock, Lang, TimeMachineRequestBuilder, Units}; use reqwest::Client; use rusqlite::{C...
; let min: f64 = match data.get("temperatureMin").unwrap().as_f64() { Some(value) => value, None => { println!("mintempi f64 parse failed"); 0.00 } }; let heat_units = ((max + min) / 2_f64) - 55_f64; let rainfall: f64 = match data.get("precipIntensityMax"...
match data.get("temperatureMax").unwrap().as_f64() { Some(value) => value, None => { println!("temperatureMax f64 parse failed"); 0.00 } }
if_condition
[ { "content": "# yesterday_weather\n\n\n\nA small program that connects to weather underground and uses their api to gather information about the previous day.\n\nThat info is then used to calculate the [heat units](http://sandhillpreservation.com/pages/sweetpotato_catalog.html) \n\nand record them in a sqlite d...
Rust
statick-tools/src/lib/statick/lexer.rs
thomasdenney/statick-and-stannel
b599cf44e7fa81daa2c049c6e4f731f6ccdf688d
extern crate regex; use regex::Regex; use std::error::Error; use std::fmt; #[derive(Clone, Debug, Eq, PartialEq)] pub enum TokenKind { Number(u16), Assign, Identifier(String), OpenParen, CloseParen, OpenSquare, CloseSquare, VerticalBar, Arrow, Offset, Quote, Underscore,...
extern crate regex; use regex::Regex; use std::error::Error; use std::fmt; #[derive(Clone, Debug, Eq, PartialEq)] pub enum TokenKind { Number(u16), Assign, Identifier(String), OpenParen, CloseParen, OpenSquare, CloseSquare, VerticalBar, Arrow, Offset, Quote, Underscore,...
#[test] fn skips_comments() -> Result<(), LexerError> { let result = lex("main = hello apply -- The start of the program\nhello = ( )")?; assert_eq!(result.len(), 8); assert_eq!(result[0].source.line_number, 1); assert_eq!(result[0].kind, TokenKind::Identifier("main".to_string(...
if let Err(lexer_error) = result { assert_eq!(lexer_error.error_tokens.len(), 1); assert_eq!(lexer_error.error_tokens[0].text, "1241234"); } }
function_block-function_prefix_line
[ { "content": "pub fn lex_str(src: &str) -> Result<Vec<ParserToken>, String> {\n\n lex(Lines { iter: src.lines() })\n\n}\n\n\n", "file_path": "statick-tools/src/lib/assembler/mod.rs", "rank": 0, "score": 319167.7861524135 }, { "content": "pub fn lex<I>(line_iter: I) -> Result<Vec<ParserTok...
Rust
chalk-ir/src/fold/in_place.rs
eggyal/chalk
e0c94db8a497eee4ed1f49534fb0714801cb90e8
use std::marker::PhantomData; use std::{mem, ptr}; fn is_zst<T>() -> bool { mem::size_of::<T>() == 0 } fn is_layout_identical<T, U>() -> bool { mem::size_of::<T>() == mem::size_of::<U>() && mem::align_of::<T>() == mem::align_of::<U>() } pub(super) fn fallible_map_box<T, U, E>( b: Box<T>, map: impl ...
use std::marker::PhantomData; use std::{mem, ptr}; fn is_zst<T>() -> bool { mem::size_of::<T>() == 0 } fn is_layout_identical<T, U>() -> bool { mem::size_of::<T>() == mem::size_of::<U>() && mem::align_of::<T>() == mem::align_of::<U>() } pub(super) fn fallible_map_box<T, U, E>( b: Box<T>, map: impl ...
struct VecMappedInPlace<T, U> { ptr: *mut T, len: usize, cap: usize, map_in_progress: usize, _elem_tys: PhantomData<(T, U)>, } impl<T, U> VecMappedInPlace<T, U> { fn new(mut vec: Vec<T>) -> Self { assert!(is_layout_identical::<T, U>()); let ptr = vec.as_mut_ptr(); ...
pub(super) fn fallible_map_vec<T, U, E>( vec: Vec<T>, mut map: impl FnMut(T) -> Result<U, E>, ) -> Result<Vec<U>, E> { if !is_layout_identical::<T, U>() || is_zst::<T>() { return vec.into_iter().map(map).collect(); } let mut vec = VecMappedInPlace::<T, U>::new(vec); unsafe { ...
function_block-full_function
[ { "content": "pub fn as_display<F: Fn(&mut Formatter<'_>) -> Result>(f: F) -> impl Display {\n\n struct ClosureDisplay<F: Fn(&mut Formatter<'_>) -> Result>(F);\n\n\n\n impl<F: Fn(&mut Formatter<'_>) -> Result> Display for ClosureDisplay<F> {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> Result {\n\n ...
Rust
mods/galangua-common/src/app/game/traj.rs
tyfkda/galangua
db30860c2f2769ff2263db9244053caf9a981363
use crate::app::consts::*; use crate::app::game::traj_command::TrajCommand; use crate::app::game::traj_command::TrajCommand::*; use crate::app::game::FormationIndex; use crate::framework::types::{Vec2I, ZERO_VEC}; use crate::util::math::{calc_velocity, ANGLE, COS_TABLE, ONE, SIN_TABLE}; #[cfg(debug_assertions)] use cr...
use crate::app::consts::*; use crate::app::game::traj_command::TrajCommand; use crate::app::game::traj_command::TrajCommand::*; use crate::app::game::FormationIndex; use crate::framework::types::{Vec2I, ZERO_VEC}; use crate::util::math::{calc_velocity, ANGLE, COS_TABLE, ONE, SIN_TABLE}; #[cfg(debug_assertions)] use cr...
}
x { vangle = -vangle; } self.vangle = vangle; } Delay(delay) => { self.delay = delay; return false; } Accelerate => { const MAX_STAGE: i32 = 64; const MAX_S...
function_block-function_prefixed
[ { "content": "pub fn new_seqanime(sprites: &'static [&'static str], offset: Vec2I, frame_wait: u32, delay: u32) -> SequentialSpriteAnime {\n\n SequentialSpriteAnime {sprites, frame_wait, delay: delay + 1, offset, count: 0}\n\n}\n\n\n", "file_path": "mods/galangua-ecs/src/app/system/system_effect.rs", ...
Rust
src/http/server.rs
rdesarz/rust-http-server
5c2f184c7cf8b17e8ef3ff0907d0c1be07130fe6
use crate::http::content::{build_content_type, find_mimetype, load_content_from_uri, Message}; use crate::http::request::{HttpMethod, HttpRequest}; use http::StatusCode; use std::fmt; use std::str::FromStr; #[derive(Debug, Clone)] pub struct ServerError { msg: String, } impl ServerError { pub(crate) fn n...
use crate::http::content::{build_content_type, find_mimetype, load_content_from_uri, Message}; use crate::http::request::{HttpMethod, HttpRequest}; use http::StatusCode; use std::fmt; use std::str::FromStr; #[derive(Debug, Clone)] pub struct ServerError { msg: String, } impl ServerError { pub(crate) fn n...
} impl Connection for TestConnection { fn listen<T: 'static + Copy + Fn(&[u8]) -> Result<Message, ServerError> + Send + Sync>( &self, callback: T, ) { self.push_message .borrow_mut() .push((callback)(&self.pull_message[0]).unw...
fn new() -> TestConnection { TestConnection { pull_message: vec![ String::from("1").as_bytes().to_vec(), String::from("2").as_bytes().to_vec(), String::from("3").as_bytes().to_vec(), ], push_message: ...
function_block-full_function
[ { "content": "/// Returns a string of a standard content type line based on the Mime type.\n\npub fn build_content_type(mime: &Mime) -> String {\n\n format!(\"Content-Type: {}/{}\\r\\n\", mime.type_(), mime.subtype())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn t...
Rust
tests/messaging.rs
shangsony/pea2pea
da218c582628f6185055c3745972597cb108e3e7
use bytes::Bytes; use parking_lot::Mutex; use tokio::time::sleep; use tracing::*; mod common; use pea2pea::{ protocols::{Reading, Writing}, Config, Node, Pea2Pea, }; use TestMessage::*; use std::{collections::HashSet, io, net::SocketAddr, sync::Arc, time::Duration}; #[derive(PartialEq, Eq, Hash, Debug, Clone...
use bytes::Bytes; use parking_lot::Mutex; use tokio::time::sleep; use tracing::*; mod common; use pea2pea::{ protocols::{Reading, Writing}, Config, Node, Pea2Pea, }; use TestMessage::*; use std::{collections::HashSet, io, net::SocketAddr, sync::Arc, time::Duration}; #[derive(PartialEq, Eq, Hash, Debug, Clone...
} } #[derive(Clone)] struct EchoNode { node: Node, echoed: Arc<Mutex<HashSet<TestMessage>>>, } impl Pea2Pea for EchoNode { fn node(&self) -> &Node { &self.node } } #[async_trait::async_trait] impl Reading for EchoNode { type Message = TestMessage; fn read_message<R: io::Read>( ...
match byte { 0 => Self::Herp, 1 => Self::Derp, _ => panic!("can't deserialize a TestMessage!"), }
if_condition
[ { "content": "pub fn prefix_with_len(len_size: usize, message: &[u8]) -> Vec<u8> {\n\n let mut vec = Vec::with_capacity(len_size + message.len());\n\n\n\n match len_size {\n\n 2 => vec.extend_from_slice(&(message.len() as u16).to_le_bytes()),\n\n 4 => vec.extend_from_slice(&(message.len() as...
Rust
common/functions/src/scalars/maths/trigonometric.rs
swaitw/databend
e55c19b4f0b842db80fefa683f4050cb04512ef0
use std::fmt; use common_datavalues::prelude::*; use common_datavalues::DataSchema; use common_datavalues::DataType; use common_exception::Result; use crate::scalars::function_factory::FunctionDescription; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::Function; #[derive(Clone)] pub st...
use std::fmt; use common_datavalues::prelude::*; use common_datavalues::DataSchema; use common_datavalues::DataType; use common_exception::Result; use crate::scalars::function_factory::FunctionDescription; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::Function; #[derive(Clone)] pub st...
} impl TrigonometricFunction { pub fn try_create_func(t: Trigonometric) -> Result<Box<dyn Function>> { Ok(Box::new(TrigonometricFunction { t })) } } impl Function for TrigonometricFunction { fn name(&self) -> &str { "TrigonometricFunction" } fn num_arguments(&self) -> usize { ...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let display = match &self { Trigonometric::SIN => "sin", Trigonometric::COS => "cos", Trigonometric::TAN => "tan", Trigonometric::COT => "cot", }; write!(f, "{}", display) }
function_block-function_prefix_line
[ { "content": "pub trait SeriesTrait: Send + Sync + fmt::Debug {\n\n fn data_type(&self) -> &DataType;\n\n fn len(&self) -> usize;\n\n fn is_empty(&self) -> bool;\n\n fn is_null(&self, row: usize) -> bool;\n\n fn null_count(&self) -> usize;\n\n\n\n fn get_array_memory_size(&self) -> usize;\n\n ...
Rust
src/lib/builtins/job_control.rs
clash-language/ion-clash
0b87bcca00ff3b23730723ef587371154f1fa630
use super::Status; use crate::{ shell::{BackgroundProcess, Shell}, types, }; use smallvec::SmallVec; pub fn disown(shell: &mut Shell<'_>, args: &[types::Str]) -> Result<(), String> { let mut no_sighup = false; let mut all_jobs = false; let mut run_jobs = false; let mut co...
use super::Status; use crate::{ shell::{BackgroundProcess, Shell}, types, }; use smallvec::SmallVec; pub fn disown(shell: &mut Shell<'_>, args: &[types::Str]) -> Result<(), String> { let mut no_sighup = false; let mut all_jobs = false; let mut run_jobs = false; let mut co...
let mut process_table = shell.background_jobs_mut(); if all_jobs { process_table.iter_mut().for_each(action); } else if run_jobs { process_table.iter_mut().filter(|p| p.is_running()).for_each(action) } else { for current_jobspec in collected_jobs { if ...
let action: fn(&mut BackgroundProcess) = if no_sighup { |process| process.set_ignore_sighup(true) } else { |process| process.forget() };
assignment_statement
[ { "content": "pub fn math(args: &[crate::types::Str], _: &mut crate::Shell<'_>) -> Status {\n\n if args.get(1).is_some() {\n\n let result = calc_or_polish_calc(&args[1..].join(\" \"));\n\n match result {\n\n Ok(v) => {\n\n println!(\"{}\", v);\n\n Status...
Rust
src/screen.rs
c25vdw/rsst
6411d59738a7a3d8511b1d17b1ed127368825581
use anyhow::Result; use std::io::{self, Read, Write}; use std::os::unix::io::AsRawFd; use crate::Buffer; pub struct Screen { pub width: i32, pub height: i32, pub stdout: io::Stdout, pub stdin: io::Stdin, } impl Screen { pub fn new() -> Result<Self> { let stdout = io::stdout(); le...
use anyhow::Result; use std::io::{self, Read, Write}; use std::os::unix::io::AsRawFd; use crate::Buffer; pub struct Screen { pub width: i32, pub height: i32, pub stdout: io::Stdout, pub stdin: io::Stdin, } impl Screen { pub fn new() -> Result<Self> { let stdout = io::stdout(); le...
}
use termios::*; tcsetattr(self.stdin.as_raw_fd(), TCSAFLUSH, &self.original) .expect("cannot set original TC attributes"); self.stdout .write_all(b"\x1b[?1049l") .expect("failed to clean up screen"); }
function_block-function_prefix_line
[ { "content": "pub fn get_terminal_dimension() -> Result<(usize, usize)> {\n\n let mut screen = Screen::new()?;\n\n let (width, height) = screen.get_window_size()?;\n\n Ok((width as usize, height as usize))\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 87820.91136019528 }, ...
Rust
dosio-macros/src/parquet_io.rs
rodrigo-romano/dosio
faa7105e080b2384cccd610c1cd5422b2fff96cf
use arrow::{array::StringArray, record_batch::RecordBatch}; use parquet::{ arrow::{ArrowReader, ParquetFileArrowReader}, file::reader::SerializedFileReader, util::cursor::SliceableCursor, }; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::quote; use std::env; use std::{fs::File, io::...
use arrow::{array::StringArray, record_batch::RecordBatch}; use parquet::{ arrow::{ArrowReader, ParquetFileArrowReader}, file::reader::SerializedFileReader, util::cursor::SliceableCursor, }; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::quote; use std::env; use std::{fs::File, io::...
map(|s| { let (first, last) = s.split_at(1); first.to_uppercase() + last }) .collect::<String>(); Ident::new(&fem_io_rsed, Span::call_site()) }) .collect()) ...
function_block-function_prefix_line
[]
Rust
src/tree/token.rs
coletonodonnell/rust-cas
26d5f67a70adaf88580429204a71ad6761172574
use std::panic; #[derive(Debug)] #[derive(Clone)] pub enum Token { ADD, MUL, DIV, EXP, VAR(String), NUM(f32), LGROUP, RGROUP, } fn to_add(to_token: String) -> Option<Token> { if to_token == "+".to_string() { return Some(Token::ADD) } else { return None } } ...
use std::panic; #[derive(Debug)] #[derive(Clone)] pub enum Token { ADD, MUL, DIV, EXP, VAR(String), NUM(f32), LGROUP, RGROUP, } fn to_add(to_token: String) -> Option<Token> { if to_token == "+".to_string() { return Some(Token::ADD) } else { return None } } ...
right_right_value = i as usize; break; } } _ => {} } } left_right_value = right_right_value; } let mut sorted_group_locations: Vec<(i32, i32)> = Vec::new(); sorted_group_locations.push((...
!= 0 { panic!("There must be an even number of group symbols!") } let mut group_locations: Vec<(i32, i32)> = Vec::new(); if total_group == 0 { return group_locations } let mut unsorted_lgroup_locations: Vec<i32> = Vec::new(); let mut left_right_value: usize = 0...
random
[ { "content": "// Splits a vector into branches\n\nfn vector_split(mut token_vector: Vec<token::Token>, split_location: i32) -> (Vec<token::Token>, Vec<(i32, i32)>, Vec<token::Token>, Vec<(i32, i32)>) {\n\n // let the right branch be the split off branch, including split location\n\n let mut right_branch: ...
Rust
native/wasmex/src/namespace.rs
myobie/wasmex
7acf9b564db534bd13336573072ed6c566f8d2a8
use rustler::{ resource::ResourceArc, types::atom::is_truthy, types::tuple, types::ListIterator, Atom, Encoder, Env, Error, MapIterator, OwnedEnv, Term, }; use std::sync::{Arc, Condvar, Mutex}; use wasmer_runtime::{self as runtime}; use wasmer_runtime_core::{ import::Namespace, typed_func::DynamicFunc, ty...
use rustler::{ resource::ResourceArc, types::atom::is_truthy, types::tuple, types::ListIterator, Atom, Encoder, Env, Error, MapIterator, OwnedEnv, Term, }; use std::sync::{Arc, Condvar, Mutex}; use wasmer_runtime::{self as runtime}; use wasmer_runtime_core::{ import::Namespace, typed_func::DynamicFunc, ty...
fn term_to_arg_type(term: Term) -> Result<Type, Error> { match Atom::from_term(term) { Ok(atom) => { if atoms::i32().eq(&atom) { Ok(Type::I32) } else if atoms::i64().eq(&atom) { Ok(Type::I64) } else if atoms::f32().eq(&atom) { ...
fn create_import( namespace: &mut Namespace, namespace_name: &str, import_name: &str, definition: Term, ) -> Result<(), Error> { let import_tuple = tuple::get_tuple(definition)?; let import_type = import_tuple .get(0) .ok_or_else(|| Error::Atom("missing_import_type"))?; let ...
function_block-full_function
[ { "content": "pub fn length<'a>(env: Env<'a>, args: &[Term<'a>]) -> Result<Term<'a>, Error> {\n\n let (resource, size, offset) = extract_params(args)?;\n\n let memory = resource.memory.lock().unwrap();\n\n let length = view_length(&memory, offset, size);\n\n Ok(length.encode(env))\n\n}\n\n\n", "...
Rust
src/control.rs
Beardiegames/swarm_pool
a7ab3d6f2d482f708b528181af5e85abcca68837
use super::types::*; pub struct SwarmControl<'a, ItemType, Properties> { pub(crate) max: &'a usize, pub(crate) spawns: &'a mut Vec<Spawn>, pub(crate) free: &'a mut Vec<Spawn>, pub(crate) order: &'a mut Vec<usize>, pub(crate) len: usize, pub(crate) pos: usize, pub pool: &'a mut Vec<...
use super::types::*; pub struct SwarmControl<'a, ItemType, Properties> { pub(crate) max: &'a usize, pub(crate) spawns: &'a mut Vec<Spawn>, pub(crate) free: &'a mut Vec<Spawn>, pub(crate) order: &'a mut Vec<usize>, pub(crate) len: usize, pub(crate) pos: usize, pub pool: &'a mut Vec<...
pub fn for_while<Predicate> (&self, predicate: Predicate) -> Option<Spawn> where Predicate: Fn(&ItemType) -> bool { let count = self.len; let mut i = 0; while &i < &count { if predicate(&self.pool[self.order[i]]) { retur...
if predicate(&self.pool[self.order[i]]) { return Some(self.spawns[i].mirror()); } i += 1; } return None }
function_block-function_prefix_line
[ { "content": "/// Returns the number of items in the pool.\n\n/// \n\n/// # Example\n\n/// ```\n\n/// use swarm_pool::tools::sized_pool::SizedPool16;\n\n/// use swarm_pool::tools::sized_pool;\n\n/// \n\n/// fn main() {\n\n/// let mut pool: SizedPool16<u8> = SizedPool16::new();\n\n/// assert_eq!(sized_po...
Rust
src/bin/render.rs
oli-obk/miri-tools
30f6fd2d2e031e5cb238ed375638d40076c0e070
use clap::Parser; use color_eyre::eyre::Result; use miri_the_world::{Crate, Status}; use rayon::prelude::*; use std::{ fs::{self, File}, io::Write, }; #[derive(Parser)] struct Args {} fn main() -> Result<()> { if std::env::var("RUST_BACKTRACE").is_err() { std::env::set_var("RUST_BACKTRACE", "1"); ...
use clap::Parser; use color_eyre::eyre::Result; use miri_the_world::{Crate, Status}; use rayon::prelude::*; use std::{ fs::{self, File}, io::Write, }; #[derive(Parser)] struct Args {} fn main() -> Result<()> { if std::env::var("RUST_BACKTRACE").is_err() { std::env::set_var("RUST_BACKTRACE", "1"); ...
} fs::rename(".ub.html", "ub.html")?; Ok(()) }
if let Status::UB { cause: causes, .. } = &c.status { write!( output, "<div class=\"row\" onclick=\"change_log(&quot;{}&quot;, &quot;{}&quot;)\"><div class=\"crate\">{} {}</div>", c.name, c.version, c.name, c.version ) ?; write!(output, "<d...
if_condition
[ { "content": "fn diagnose_crate(krate: &mut Crate) -> Result<()> {\n\n let path = format!(\"logs/{}/{}\", krate.name, krate.version);\n\n if let Ok(output) = fs::read_to_string(&path) {\n\n krate.status = if output.contains(\"Undefined Behavior: \") {\n\n Status::UB {\n\n ...
Rust
src/set1/challenge1.rs
TalkTakesTime/matasano
e8675ed58076c5df166c93f3787faa0979836f19
use super::shared::*; use std::collections::HashMap; use std::iter::FromIterator; fn base64_keys() -> HashMap<u8, char> { (('A' as u8)..('Z' as u8 + 1)) .chain(('a' as u8)..('z' as u8 + 1)) .chain(('0' as u8)..('9' as u8 + 1)) .chain(('+' as u8)..('+' as u8 + 1)) .chain(('/' as u8)....
use super::shared::*; use std::collections::HashMap; use std::iter::FromIterator; fn base64_keys() -> HashMap<u8, char> { (('A' as u8)..('Z' as u8 + 1)) .chain(('a' as u8)..('z' as u8 + 1)) .chain(('0' as u8)..('9' as u8 + 1)) .chain(('+' as u8)..('+' as u8 + 1)) .chain(('/' as u8)....
fn nth_byte(num: u32, n: u32) -> u32 { num >> (n * 8) & 0xff } pub fn base64_to_hex(base64_str: &str) -> String { let keys: HashMap<char, u8> = base64_keys().iter().map(|(&k, &v)| (v, k)).collect(); let chars = Vec::from_iter(base64_str.chars()); let bytes = chars .chunks(4) ...
pub fn hex_to_base64(hex_str: &str) -> String { let bytes = hex_string_to_bytes(hex_str).unwrap(); let mut chars: Vec<char> = Vec::new(); let mut triplet = 0u32; let triplet_count = (bytes.len() + 2) / 3; for i in 0..(triplet_count * 3) { let num = if let Some(&n) = bytes.get(i) { n }...
function_block-full_function
[ { "content": "fn decode(message: &Vec<u8>, key: u8) -> Vec<u8> {\n\n xor_bytes(message, &iter::repeat(key as u8).take(message.len()).collect())\n\n}\n\n\n", "file_path": "src/set1/challenge3.rs", "rank": 2, "score": 85051.16189430893 }, { "content": "pub fn encode(data: &Vec<u8>, key: &Ve...
Rust
examples/vendored/complicated_cargo_library/cargo/vendor/specs-0.10.0/src/storage/restrict.rs
tommilligan/cargo-raze
b20c29f8f6a0902a7aadf5424dd830cd045ac92d
use std::borrow::{Borrow, BorrowMut}; use std::fmt; use std::marker::PhantomData; use std::ops::DerefMut; use hibitset::BitSet; use {Component, Entities, Entity, Index, Join, ParJoin, Storage, UnprotectedStorage}; use storage::MaskedStorage; use world::EntityIndex; pub enum NormalRestriction { } pub enum ParallelRe...
use std::borrow::{Borrow, BorrowMut}; use std::fmt; use std::marker::PhantomData; use std::ops::DerefMut; use hibitset::BitSet; use {Component, Entities, Entity, Index, Join, ParJoin, Storage, UnprotectedStorage}; use storage::MaskedStorage; use world::EntityIndex; pub enum NormalRestriction { } pub enum ParallelRe...
} impl<'st, T, D> Storage<'st, T, D> where T: Component, D: DerefMut<Target = MaskedStorage<T>>, { pub fn restrict<'rf>( &'rf mut self, ) -> RestrictedStorage<'rf, 'st, &BitSet, T, &mut T::Storage, NormalRestriction> { let (mask, data) = self.data.open_mut(); Res...
use std::mem; let entry = Entry { id, pointer: value.data.borrow() as *const T::Storage, phantom: PhantomData, }; let value: &'rf mut Self::Value = mem::transmute(value); (entry, value) }
function_block-function_prefix_line
[ { "content": "pub fn main() {\n\n env_logger::init();\n\n\n\n let random_val = rand::thread_rng().gen::<i64>();\n\n\n\n info!(\"Got a value: {}\", random_val);\n\n}\n", "file_path": "examples/remote/non_cratesio/src/main.rs", "rank": 0, "score": 82700.88138949958 }, { "content": "pub fn m...
Rust
core/src/model/mod.rs
aldanor/tract
5ce5fdea99ed7755e8bb3caad1382e405ba79644
use std::collections::HashMap; use std::str; use std::sync::Arc; pub mod dsl; mod order; pub use self::order::eval_order; pub use crate::analyser::types::TensorFact; use crate::context::Context; pub use self::dsl::ModelDsl; use crate::{ops, TractResult}; #[derive(Debug, Clone)] #[cfg_attr(feature = "serialize", deri...
use std::collections::HashMap; use std::str; use std::sync::Arc; pub mod dsl; mod order; pub use self::order::eval_order; pub use crate::analyser::types::TensorFact; use crate::context::Context; pub use self::dsl::ModelDsl; use crate::{ops, TractResult}; #[derive(Debug, Clone)] #[cfg_attr(feature = "serialize", deri...
} pub fn into_optimized(mut self) -> TractResult<Model> { self.analyse()?; let passes = self.ctx.optimizer_passes(); for pass in passes { info!("Optization pass: {:?}", pass); pass.pass(&mut self)?; if cfg!(debug_assertions) { self.ch...
Ok(self .eval_order()? .iter() .flat_map(|&node| { self.nodes[node] .outputs .iter() .enumerate() .map(move |(ix, outlet)| (OutletId::new(node, ix), outlet)) }) .fi...
call_expression
[ { "content": "/// Partial information about any value.\n\npub trait Fact: fmt::Debug + Clone + PartialEq + Default {\n\n type Concrete: fmt::Debug;\n\n\n\n /// Tries to transform the fact into a concrete value.\n\n fn concretize(&self) -> Option<Self::Concrete>;\n\n\n\n /// Returns whether the value...
Rust
tests/test.rs
hellobbn/QLivePlayer-Lib
9e8073729e62c88bc2011e88faa18a909bd3d28d
use log::*; use std::{ collections::{ HashMap, LinkedList, }, sync::{ Arc, Mutex, }, }; use tokio::runtime::Builder; extern crate qliveplayer_lib; struct TestUrl { bilibili_live_url: String, bilibili_video_url: String, douyu_live_url: String, huya_live_u...
use log::*; use std::{ collections::{ HashMap, LinkedList, }, sync::{ Arc, Mutex, }, }; use tokio::runtime::Builder; extern crate qliveplayer_lib; struct TestUrl { bilibili_live_url: String, bilibili_video_url: String, douyu_live_url: String, huya_live_u...
} #[test] fn test_bilibili_video() { Builder::new_current_thread().enable_all().build().unwrap().block_on(async move { let u = TestUrl::new(); let b = qliveplayer_lib::streamfinder::bilibili::Bilibili::new(); match b.get_video(u.bilibili_video_url.as_ref(), "").await { Ok(it) =...
pub fn new() -> Self { TestUrl { bilibili_live_url: "https://live.bilibili.com/3".to_owned(), bilibili_video_url: "https://www.bilibili.com/bangumi/play/ep422334".to_owned(), douyu_live_url: "https://www.douyu.com/9999".to_owned(), huya_live_url: "https://www.huya...
function_block-full_function
[ { "content": "pub fn run_danmaku_client(url: &str, dm_fifo: Arc<Mutex<LinkedList<HashMap<String, String>>>>, stop_flag: Arc<AtomicBool>) {\n\n Builder::new_current_thread().enable_all().build().unwrap().block_on(async move {\n\n let dmc = async move {\n\n loop {\n\n if url.co...
Rust
crab-excel-derive/src/lib.rs
LittleGuest/hairy-crabs
8181d0fb7e9f44b6337a66d8e0ec739b547064a0
/* 设计 #[derive(Excel)] struct User{ #[excel_col(name = "用户ID", order = 1,width = 14, type = Type::r#String)] id: u32, name: String, role_name: String, #[excel_col(name = "创建时间", order = 2, date_format = "yyyy-MM-dd HH:mm::ss")] create_time: u32, } Excel 自定义派生宏 定义为 trait,只能用于struct,只要实现了该trai...
/* 设计 #[derive(Excel)] struct User{ #[excel_col(name = "用户ID", order = 1,width = 14, type = Type::r#String)] id: u32, name: String, role_name: String, #[excel_col(name = "创建时间", order = 2, date_format = "yyyy-MM-dd HH:mm::ss")] create_time: u32, } Excel 自定义派生宏 定义为 trait,只能用于struct,只要实现了该trai...
r| { let sw = sheet_writer; sw.append_row(#fnq)?; for dt in data.iter(){ ...
function_block-function_prefixed
[ { "content": "pub trait ExcelWriter {\n\n type Input;\n\n fn simple_write(data: &[Self::Input]) -> Result<Option<Vec<u8>>, ExcelError>;\n\n}\n", "file_path": "crab-excel/src/writer.rs", "rank": 0, "score": 337603.65482920967 }, { "content": "pub trait ExcelReader {\n\n fn read<T>() ...
Rust
rustzx-core/src/zx/tape/tap.rs
pacmancoder/rustzx
6818e164fae45029bd610f0b3caeb9655e5606c4
use crate::{ error::TapeLoadError, host::{LoadableAsset, SeekFrom, SeekableAsset}, zx::tape::TapeImpl, Result, }; const PILOT_LENGTH: usize = 2168; const PILOT_PULSES_HEADER: usize = 8063; const PILOT_PULSES_DATA: usize = 3223; const SYNC1_LENGTH: usize = 667; const SYNC2_LENGTH: usize = 735; const BIT...
use crate::{ error::TapeLoadError, host::{LoadableAsset, SeekFrom, SeekableAsset}, zx::tape::TapeImpl, Result, }; const PILOT_LENGTH: usize = 2168; const PILOT_PULSES_HEADER: usize = 8063; const PILOT_PULSES_DATA: usize = 3223; const SYNC1_LENGTH: usize = 667; const SYNC2_LENGTH: usize = 735; const BIT...
fn rewind(&mut self) -> Result<()> { self.curr_bit = false; self.curr_byte = 0x00; self.block_bytes_read = 0; self.bufer_offset = 0; self.current_block_size = None; self.delay = 0; self.asset.seek(SeekFrom::Start(0))?; self.tape_ended = false; ...
fn play(&mut self) { if self.state == TapeState::Stop { if self.prev_state == TapeState::Stop { self.state = TapeState::Play; } else { self.state = self.prev_state; } } }
function_block-full_function
[ { "content": "/// SNA snapshot loading function\n\npub fn load<H, A>(emulator: &mut Emulator<H>, mut asset: A) -> Result<()>\n\nwhere\n\n H: Host,\n\n A: LoadableAsset + SeekableAsset,\n\n{\n\n let size = asset.seek(SeekFrom::End(0))?;\n\n asset.seek(SeekFrom::Start(0))?;\n\n\n\n let is_128k = si...
Rust
crates/gen/src/serde_schema.rs
CrepeGoat/iron-EBMLem
b5f1951c9699c121c0d0402040969cf134e56290
use serde_derive::{Deserialize, Serialize}; pub(crate) use serde_xml_rs::{from_reader, from_str, to_string}; pub(crate) mod custom_serde { pub(crate) mod hexadecimal { use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer}; pub(crate) fn deserialize<'de, D>...
use serde_derive::{Deserialize, Serialize}; pub(crate) use serde_xml_rs::{from_reader, from_str, to_string}; pub(crate) mod custom_serde { pub(crate) mod hexadecimal { use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer}; pub(crate) fn deserialize<'de, D>...
} } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] #[serde(rename = "EBMLSchema")] #[serde(rename_all = "camelCase")] pub(crate) struct EbmlSchema { pub(crate) doc_type: String, pub(crate) version: u32, pub(crate) ebml: Option<u32>, #[serde(rename = "$value")] pub(crate) elements: ...
crate) fn serialize<S>(value: &u32, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { format!("{:#X}", value).serialize(serializer) }
function_block-function_prefixed
[ { "content": "pub fn stream_diff<'a>(first: &'a [u8], second: &'a [u8]) -> usize {\n\n unsafe { second.as_ptr().offset_from(first.as_ptr()) }\n\n .try_into()\n\n .unwrap()\n\n}\n\n\n\npub mod parse {\n\n use std::cmp::min;\n\n use std::mem::size_of;\n\n use std::ops::RangeFrom;\n\n\n\n...
Rust
src/redisaccessor_async.rs
syrupofplum/rustcommon
2131b312c38f2eb185b00a2806f81bcdac5f7f85
use crate::redisaccessor::{RedisAccessorError, RedisAccessorErrorType, RedisAccessor}; use redis::{Commands, RedisResult}; use std::collections::HashMap; macro_rules! check_conn_open { ($ins:expr) => { { if $ins.async_conn.is_none() { return Err(RedisAccessorError { ...
use crate::redisaccessor::{RedisAccessorError, RedisAccessorErrorType, RedisAccessor}; use redis::{Commands, RedisResult}; use std::collections::HashMap; macro_rules! check_conn_open { ($ins:expr) => { { if $ins.async_conn.is_none() { return Err(RedisAccessorError { ...
pub fn host(mut self, host: &'a str) -> Self { self.host = host; self } pub fn port(mut self, port: u16) -> Self { self.port = port; self } pub fn user(mut self, user: &'a str) -> Self { self.user = user; self } pub fn passwd(mut self, pas...
pub fn new() -> Self { Self { host: "localhost", port: 6380, user: "", passwd: "", db: 0, client: None, async_conn: None } }
function_block-full_function
[ { "content": "pub trait RedisAccessor {\n\n}\n", "file_path": "src/redisaccessor.rs", "rank": 0, "score": 54609.15842909673 }, { "content": "struct DummyFutureError {\n\n}\n\n\n\nimpl future::Future for DummyFutureError {\n\n type Output = ();\n\n\n\n fn poll(self: Pin<&mut Self>, _cx:...
Rust
src/threads.rs
tuckerthomas/path_of_auction
23be63e220b1ff2aaef4aad2678a36369b10355e
use std::thread; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::collections::VecDeque; use crate::models::{Account, TableItem, TableStashTab, StashTab}; use crate::PgPool; use diesel::prelude::*; struct WorkQueue<T: Send> { queue: Arc<Mutex<VecDeque<T>>>, } impl<T: Send> WorkQueue<T> { fn new() ...
use std::thread; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::collections::VecDeque; use crate::models::{Account, TableItem, TableStashTab, StashTab}; use crate::PgPool; use diesel::prelude::*; struct WorkQueue<T: Send> { queue: Arc<Mutex<VecDeque<T>>>, } impl<T: Send> WorkQueue<T> { fn new() ...
Err(_e) => { Account::create_account(conn, stash_tab.account_name.clone().unwrap().as_str(), stash_tab.last_character_name.clone().unwrap().as_str()) } }; let stash = match TableStashTab::upsert_stash(conn, account.id, stash_tab.clone()) { Ok(sta...
ab: StashTab) { let account = match Account::lookup_account(conn, stash_tab.account_name.clone().unwrap().as_str()) { Ok(mut account) => { account.last_character = stash_tab.last_character_name.clone().unwrap(); account = match Account::update_account(conn, account....
random
[ { "content": "pub fn establish_connection(num_threads: u32) -> Arc<PgPool> {\n\n dotenv().ok();\n\n\n\n let database_url = env::var(\"DATABASE_URL\").expect(\"DATABASE_URL must be set\");\n\n init_pool(&database_url, num_threads)\n\n}", "file_path": "src/lib.rs", "rank": 3, "score": 73177.8...
Rust
src/body.rs
yuto51942/rs-json-parser-sample
f5e6b928261360dbeed24121c726d98b483b68a9
use crate::symbol; use std::error::Error; pub struct Body<'a> { body: &'a [u8], pub start_index: usize, is_text: bool, text_buffer: Vec<u8>, pub exist_text: bool, } impl<'a> Body<'a> { pub fn new(body: &'a str) -> Self { Self { body...
use crate::symbol; use std::error::Error; pub struct Body<'a> { body: &'a [u8], pub start_index: usize, is_text: bool, text_buffer: Vec<u8>, pub exist_text: bool, } impl<'a> Body<'a> { pub fn new(body: &'a str) -> Self { Self { body...
} #[cfg(test)] mod tests { use crate::body::Body; #[test] fn pop_works() { let sample_txt = "aiueonya"; let text_length = sample_txt.len(); let sample_txt_bytes = sample_txt.as_bytes(); let mut body = Body::new(sample_txt); for byte in sample_txt_bytes { ...
pub fn get_text(&mut self) -> Result<String, Box<dyn Error>> { let result = String::from_utf8(self.text_buffer.clone())?; self.text_buffer = Vec::new(); Ok(result) }
function_block-full_function
[ { "content": "/// Check if the character is `:`.\n\n///\n\n/// ## Arguments\n\n///\n\n/// - `target` - target string.\n\npub fn is_colon(target: &u8) -> bool {\n\n // `:` is 58\n\n comparison_symbol(target, &58u8)\n\n}\n\n\n", "file_path": "src/symbol.rs", "rank": 0, "score": 136356.1020421359...
Rust
src/builder2/fft_data.rs
bobtwinkles/fftw3-rs
05852dd5d89eb07b04c6993d545d68a61509c014
use num::Complex; use libc::c_int; use ffi; use strided::{MutStrided, MutStride}; use plan::RawPlan; use super::{FftData, Meta, Secret, Inplace, Io, FftSpec, PlanResult, do_plan, Dim, PlanningError, Ready, R2R}; impl<T: FftData<T>, I: MutStrided<Elem = T>> FftSpec for Inplace<I> { type Input = T; ...
use num::Complex; use libc::c_int; use ffi; use strided::{MutStrided, MutStride}; use plan::RawPlan; use super::{FftData, Meta, Secret, Inplace, Io, FftSpec, PlanResult, do_plan, Dim, PlanningError, Ready, R2R}; impl<T: FftData<T>, I: MutStrided<Elem = T>> FftSpec for Inplace<I> { type Input = T; ...
#[doc(hidden)] fn secret() -> Secret { Secret(()) } } /* trait Split<T> { fn split(&mut self) -> (T, T); } impl<T> Split<*mut T> for Complex<T> { fn split(&mut self) -> (*mut T, *mut T) { let ptr = self as *mut _ as *mut T; unsafe { (ptr, ptr.offset(1)) } } } i...
let required_len = if use_default_length { in_len } else { Dim::size(&*meta.dims).0 }; if in_len < required_len || out_len < required_len { return Err(PlanningError::BufferTooSmall(in_len, out_len, meta.dims.clone())) } let (rank,d...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn r2c_c2r_smoke_test() {\n\n smoke_test!(r2c, c2r, random(), N / 2 + 1, |x: &f64, scale| *x * scale, almost_eq)\n\n}\n\n\n", "file_path": "tests/builder_smoke_tests.rs", "rank": 0, "score": 73587.97467131293 }, { "content": "fn almost_eq(x: &[f64], y: &[f64]) -> ...
Rust
src/resizable.rs
overhacked/deadqueue
f92e9d6907734550a08e87354293cdbfa656d2b6
use std::convert::TryInto; use std::fmt::Debug; use std::iter::FromIterator; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::{Mutex, Semaphore}; use crate::unlimited::Queue as UnlimitedQueue; pub struct Queue<T> { queue: UnlimitedQueue<T>, capacity: AtomicUsize, push_semaphore: Semapho...
use std::convert::TryInto; use std::fmt::Debug; use std::iter::FromIterator; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::{Mutex, Semaphore}; use crate::unlimited::Queue as UnlimitedQueue; pub struct Queue<T> { queue: UnlimitedQueue<T>, capacity: AtomicUsize, push_semaphore: Semapho...
pub async fn pop(&self) -> T { let item = self.queue.pop().await; self.push_semaphore.add_permits(1); item } pub fn try_pop(&self) -> Option<T> { let item = self.queue.try_pop(); if item.is_some() { self.push_semaphore.add_permits(1); ...
pub fn new(max_size: usize) -> Self { Self { queue: UnlimitedQueue::new(), capacity: AtomicUsize::new(max_size), push_semaphore: Semaphore::new(max_size), resize_mutex: Mutex::default(), } }
function_block-function_prefix_line
[ { "content": "//! Unlimited queue implementation\n\n\n\nuse std::convert::TryInto;\n\nuse std::fmt::Debug;\n\nuse std::iter::FromIterator;\n\n\n\nuse crossbeam_queue::SegQueue;\n\nuse tokio::sync::Semaphore;\n\n\n\nuse crate::atomic::Available;\n\n\n\n/// Queue that is unlimited in size.\n\n///\n\n/// This queu...
Rust
paddlers-game-master/src/db/db_actor.rs
jakmeier/paddlers-browser-game
6c7afbb1ac13467ed94c418a5515fcf98224149e
mod collect_quest; mod messages; pub use messages::*; use crate::db::*; use actix::prelude::*; use paddlers_shared_lib::game_mechanics::worker::hero_max_mana; pub struct DbActor { dbpool: Pool, } impl Handler<DeferredDbStatement> for DbActor { type Result = (); fn handle(&mut self, msg: DeferredDbStateme...
mod collect_quest; mod messages; pub use messages::*; use crate::db::*; use actix::prelude::*; use paddlers_shared_lib::game_mechanics::worker::hero_max_mana; pub struct DbActor { dbpool: Pool, } impl Handler<DeferredDbStatement> for DbActor { type Result = ();
} impl Handler<PlayerHomeLookup> for DbActor { type Result = PlayerHome; fn handle(&mut self, msg: PlayerHomeLookup, _ctx: &mut SyncContext<Self>) -> Self::Result { PlayerHome( self.db() .player_villages(msg.player) .pop() .expect("player mus...
fn handle(&mut self, msg: DeferredDbStatement, ctx: &mut SyncContext<Self>) { match msg { DeferredDbStatement::NewProphet(village) => { self.db().add_prophet(village); } DeferredDbStatement::NewAttack(planned_atk) => { let attack = self.db().in...
function_block-full_function
[]
Rust
src/parse.rs
zregvart/cargo-deadlinks
accd7d1e7c6ccc52fdfa97091dc9e79cce71f018
use std::collections::HashSet; use std::path::Path; use log::{debug, info}; use lol_html::{element, RewriteStrSettings}; use url::Url; pub fn parse_html_file(root_dir: &Path, path: &Path) -> HashSet<Url> { info!("Checking doc page at {}", path.display()); let html = std::fs::read_to_string(path) .unwr...
use std::collections::HashSet; use std::path::Path; use log::{debug, info}; use lol_html::{element, RewriteStrSettings}; use url::Url; pub fn parse_html_file(root_dir: &Path, path: &Path) -> HashSet<Url> { info!("Checking doc page at {}", path.display()); let html = std::fs::read_to_string(path) .unwr...
#[test] fn test_parse_a_hrefs_in_subdirectory() { let html = r#" <!DOCTYPE html> <html> <body> <a href="a.html">a</a> <a href="/b/c.html">a</a> <a href="../d.html">d</a> </body> </html>"#; let urls...
l> <body> <a href="a.html">a</a> <a href="/b/c.html">a</a> </body> </html>"#; let urls = parse_a_hrefs( html, Url::from_directory_path("/base").unwrap(), Url::from_file_path("/base/test.html").unwrap(), ...
function_block-function_prefixed
[ { "content": "fn check_http_fragment(url: &Url, fragment: &str) -> Result<(), CheckError> {\n\n debug!(\"Checking fragment {} of URL {}.\", fragment, url.as_str());\n\n\n\n let html = || {\n\n let mut url = url.clone();\n\n url.set_fragment(None);\n\n\n\n let resp = ureq::get(url.as_s...
Rust
src/main.rs
Srikanth-M-02/gnethogs-rust
87f6ef6a257987c3ce562c18b98b5100666d4557
use std::{collections::HashMap, env::args, ffi::CStr}; use gio::prelude::*; use glib::Sender; use gtk::{prelude::*, TreeIter}; use once_cell::sync::OnceCell; static SENDER: OnceCell<Sender<NetHogsData>> = OnceCell::new(); #[derive(Debug, Clone, Copy)] enum Columns { Pid, User, Program, Device, Se...
use std::{collections::HashMap, env::args, ffi::CStr}; use gio::prelude::*; use glib::Sender; use gtk::{prelude::*, TreeIter}; use once_cell::sync::OnceCell; static SENDER: OnceCell<Sender<NetHogsData>> = OnceCell::new(); #[derive(Debug, Clone, Copy)] enum Columns { Pid, User, Program, Device, Se...
fn main() { let application = gtk::Application::new(Some("com.example.gnethogs"), Default::default()) .expect("Initialization failed..."); application.connect_activate(|app| { build_ui(app); }); application.run(&args().collect::<Vec<_>>()); }
if map.contains_key(&msg.id) { let user: String = cache .get_user_by_uid(msg.user) .unwrap() .name() .to_str() .unwrap() .to_owned(); let values: [&dyn ToValue; 6] = [ ...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n // Tell cargo to tell rustc to link the system bzip2\n\n // shared library.\n\n println!(\"cargo:rustc-link-lib=nethogs\");\n\n\n\n // Tell cargo to invalidate the built crate whenever the wrapper changes\n\n println!(\"cargo:rerun-if-changed=wrapper.h\");\n\n\n\n ...
Rust
wasm/game-of-life/src/lib.rs
Fahien/exrust
b323c4ba7d464f9599ba84bc7400e9e8b405746b
mod utils; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; macro_rules! log { ( $( $t:tt )* ) => { web_sys::console::log_1(&format!( $( $t )* ).into()); } } #[wasm_bindgen] #[repr(u8)] #[derive(Copy, Clone...
mod utils; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; macro_rules! log { ( $( $t:tt )* ) => { web_sys::console::log_1(&format!( $( $t )* ).into()); } } #[wasm_bindgen] #[repr(u8)] #[derive(Copy, Clone...
}) .collect(); Self { width: width as u32, height: height as u32, cells, } } pub fn render(&self) -> String { self.to_string() } pub fn get_width(&self) -> u32 { self.width } pub fn get_heig...
if i % 2 == 0 || i % 7 == 0 { Cell::Alive } else { Cell::Dead }
if_condition
[ { "content": "fn area_simple(width: u32, height: u32) -> u32 {\n\n width * height\n\n}\n\n\n", "file_path": "the-book/using-structs-to-structure-related-data/src/main.rs", "rank": 0, "score": 253772.13506430737 }, { "content": "fn area_tuple(dimensions: (u32, u32)) -> u32 {\n\n dimensi...
Rust
meilisearch-http/tests/auth/payload.rs
phial3/MeiliSearch
ce6ff294cff789f636faa4c3a9cb315ec92a0477
use crate::common::Server; use actix_web::test; use meilisearch_http::{analytics, create_app}; use serde_json::{json, Value}; #[actix_rt::test] async fn error_api_key_bad_content_types() { let content = json!({ "indexes": ["products"], "actions": [ "documents.add" ], "ex...
use crate::common::Server; use actix_web::test; use meilisearch_http::{analytics, create_app}; use serde_json::{json, Value}; #[actix_rt::test] async fn error_api_key_bad_content_types() { let content = json!({ "indexes": ["products"], "actions": [ "documents.add" ], "ex...
async fn error_api_key_malformed_payload() { let content = r#"{"malormed": "payload""#; let mut server = Server::new_auth().await; server.use_api_key("MASTER_KEY"); let app = test::init_service(create_app!( &server.service.meilisearch, &server.service.auth, true, &server...
function_block-full_function
[ { "content": "/// This is required because Payload is not Sync nor Send\n\nfn payload_to_stream(mut payload: Payload) -> impl Stream<Item = Result<Bytes, PayloadError>> {\n\n let (snd, recv) = mpsc::channel(1);\n\n tokio::task::spawn_local(async move {\n\n while let Some(data) = payload.next().awai...
Rust
golden-dawn/src/main.rs
Hidetoshi-YSHK/golden-dawn
15e8416ecf27da62588f439693cf56717495d7f2
#![windows_subsystem = "windows"] use std::io; use std::fs; use std::path::Path; use std::env::current_exe; use chrono::{Local, LocalResult, NaiveDate, TimeZone}; use serde_derive::Deserialize; const CONFIG_FILE: &str = "config.toml"; const OLD_DIR: &str = "old"; #[derive(Deserialize)] struct Config { parent_di...
#![windows_subsystem = "windows"] use std::io; use std::fs; use std::path::Path; use std::env::current_exe; use chrono::{Local, LocalResult, NaiveDate, TimeZone}; use serde_derive::Deserialize; const CONFIG_FILE: &str = "config.toml"; const OLD_DIR: &str = "old"; #[derive(Deserialize)] struct Config { parent_di...
fn read_config_file() -> io::Result<String> { let mut exe_dir = current_exe()?; exe_dir.pop(); let config_file = Path::join(&exe_dir, CONFIG_FILE); Ok(fs::read_to_string(config_file)?) } fn create_today_dir(parent_dir_path: &Path, date_format: &String) -> io::Result<()> { let today = Local::toda...
fn main() { let config_str = read_config_file().expect("Could not read config file."); let config = toml::from_str::<Config>(&config_str) .expect("Could not parse config file."); let parent_dir = Path::new(&config.parent_dir); create_today_dir(parent_dir, &config.date_format) ...
function_block-full_function
[]
Rust
src/dataflow/mod.rs
ICGog/erdos
5152b7a5c66aed54304ebc394897920d6ba47876
pub mod callback_builder; #[doc(hidden)] pub mod graph; pub mod message; pub mod operator; pub mod operators; pub mod state; pub mod stream; pub(crate) use stream::EventMakerT; pub use message::{Data, Message, Timestamp, TimestampedData}; pub use operator::{Operator, OperatorConfig}; pub use state::State; pub use s...
pub mod callback_builder; #[doc(hidden)] pub mod graph; pub mod message; pub mod operator; pub mod operators; pub mod state; pub mod stream; pub(crate) use stream::EventMakerT; pub use message::{Data, Message, Timestamp, TimestampedData}; pub use operator::{Operator, OperatorConfig}; pub use state::State; pub use s...
)); assert!(events.len() == 1); match events.pop() { Some(event) => { (event.callback)(); assert_eq!(rx.try_recv().unwrap(), 3); } None => unreachable!(), } } #[test] fn test_multi_stream_stateful_callback...
m<usize>>> = (&rs2).into(); let (tx, mut rx) = mpsc::unbounded_channel(); let cb = move |_t: &Timestamp, s1: &CounterState, s2: &CounterState| { tx.send(s1.count + s2.count).unwrap(); }; crate::add_watermark_callback!((srs1, srs2), (), (cb)); let msg1 = Mess...
function_block-random_span
[ { "content": "/// Adds an operator to the default graph.\n\n///\n\n/// The operator is pinned on a given node.\n\npub fn add_operator<F: OperatorRunner>(\n\n id: OperatorId,\n\n name: Option<String>,\n\n node_id: NodeId,\n\n read_stream_ids: Vec<StreamId>,\n\n write_stream_ids: Vec<StreamId>,\n\n...
Rust
host/cmsis-dap/src/cortex_m.rs
Lotterleben/embedded2020
623fa53461c4da29d69318aa85de8b4119c50719
use anyhow::bail; use cm::{ dcb::{dcrsr, demcr, dhcsr, DCRDR, DCRSR, DEMCR, DHCSR}, scb::{aircr, AIRCR}, }; use log::info; use crate::{adiv5, util}; #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] #[repr(u8)] pub enum Register { R0 = 0b00000, R1 = 0b00001, R2 = 0b0...
use anyhow::bail; use cm::{ dcb::{dcrsr, demcr, dhcsr, DCRDR, DCRSR, DEMCR, DHCSR}, scb::{aircr, AIRCR}, }; use log::info; use crate::{adiv5, util}; #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] #[repr(u8)] pub enum Register { R0 = 0b00000, R1 = 0b00001, R2 = 0b0...
} pub fn read_core_register(&mut self, reg: Register) -> Result<u32, anyhow::Error> { const READ: u8 = 0; info!("reading Cortex-M register {:?} ... ", reg); let mut w = dcrsr::W::zero(); w.REGWnR(READ).REGSEL(reg.regsel()); self.memory_write_word(DCRSR::address()...
Ok(if self.debugen == Some(true) { dhcsr::R::from(self.memory_read_word(DHCSR::address() as usize as u32)?).S_HALT() != 0 } else { false })
call_expression
[ { "content": "fn read_word_16(core: &mut Core, addr: u32) -> Result<u16, anyhow::Error> {\n\n if addr % 4 == 0 {\n\n Ok(core.read_word_32(addr)? as u16)\n\n } else if addr % 4 == 2 {\n\n Ok((core.read_word_32(addr - 2)? >> 16) as u16)\n\n } else {\n\n unreachable!()\n\n }\n\n}\n...
Rust
src/de/internal.rs
qzed/serde_tagged
9762b998d2d55bd5f3274ccc94e44a5806c36204
use de::seed::SeedFactory; use util::de::content::{Content, ContentDeserializer, ContentVisitor}; use std; use std::marker::PhantomData; use serde; pub fn deserialize<'de, T, D, F>( deserializer: D, tag_key: &'static str, seed_factory: F, ) -> Result<F::Value, D::Error> where T: serde::Deserialize<...
use de::seed::SeedFactory; use util::de::content::{Content, ContentDeserializer, ContentVisitor}; use std; use std::marker::PhantomData; use serde; pub fn deserialize<'de, T, D, F>( deserializer: D, tag_key: &'static str, seed_factory: F, ) -> Result<F::Value, D::Error> where T: serde::Deserialize<...
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::de::Deserializer<'de>, { ContentVisitor::new() .visit_newtype_struct(deserializer) .map(TagOrValue::Value) } fn visit_seq<A>(self, seq: A) -> Result<Self::Val...
fn visit_unit<E>(self) -> Result<Self::Value, E> where E: serde::de::Error, { ContentVisitor::new().visit_unit().map(TagOrValue::Value) }
function_block-full_function
[ { "content": "struct SeqDeserializer<'de, E>\n\nwhere\n\n E: de::Error,\n\n{\n\n iter: <Vec<Content<'de>> as IntoIterator>::IntoIter,\n\n err: PhantomData<E>,\n\n}\n\n\n\nimpl<'de, E> SeqDeserializer<'de, E>\n\nwhere\n\n E: de::Error,\n\n{\n\n fn new(vec: Vec<Content<'de>>) -> Self {\n\n ...
Rust
crates/wasm-encoder/tests/linking.rs
imor/wasm-tools
f632261627a0ea758762e431d8be32740111e33c
use anyhow::{Context, Result}; use std::fs; use std::io::{self, Write}; use std::process::{Command, Stdio}; use wasm_encoder::*; fn wabt_linking_section(wasm: &[u8]) -> Result<Option<String>> { let tmp = tempfile::NamedTempFile::new().context("failed to create a named temp file")?; fs::write(tmp.path(), wasm)....
use anyhow::{Context, Result}; use std::fs; use std::io::{self, Write}; use std::process::{Command, Stdio}; use wasm_encoder::*; fn wabt_linking_section(wasm: &[u8]) -> Result<Option<String>> { let tmp = tempfile::NamedTempFile::new().context("failed to create a named temp file")?; fs::write(tmp.path(), wasm)....
#[test] fn sym_tab_flags() -> Result<()> { let mut sym_tab = SymbolTable::new(); sym_tab.function( SymbolTable::WASM_SYM_BINDING_WEAK | SymbolTable::WASM_SYM_VISIBILITY_HIDDEN, 1337, Some("func"), ); let mut linking = LinkingSection::new(); linking.symbol_table(&sym_tab); ...
fn sym_tab_function() -> Result<()> { let mut sym_tab = SymbolTable::new(); sym_tab.function(0, 42, Some("func")); let mut linking = LinkingSection::new(); linking.symbol_table(&sym_tab); assert_wabt_linking( &linking, " - name: \"linking\" - symbol table [count=1] - 0: F <fu...
function_block-full_function
[ { "content": "fn get_name_section(wasm: &[u8]) -> anyhow::Result<NameSectionReader<'_>> {\n\n for payload in Parser::new(0).parse_all(&wasm) {\n\n if let Payload::CustomSection {\n\n name: \"name\",\n\n data,\n\n data_offset,\n\n range: _,\n\n } = pay...