lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/jtalk.rs
MamoruDS/jtalk_wrap
5f92c95bf5628d29dcf36fcf2ddebf32900a3678
use crate::req::{Method, ReqClient}; use regex::Regex; use reqwest::{ cookie::CookieStore, header::LOCATION, redirect::Policy, ClientBuilder, StatusCode, Url, }; use scraper::{ElementRef, Html, Selector}; use std::fs; pub type ConvertResult = (String, Option<String>); fn custom_client(client_builder: ClientBuild...
use crate::req::{Method, ReqClient}; use regex::Regex; use reqwest::{ cookie::CookieStore, header::LOCATION, redirect::Policy, ClientBuilder, StatusCode, Url, }; use scraper::{ElementRef, Html, Selector}; use std::fs; pub type ConvertResult = (String, Option<String>); fn custom_client(client_builder: ClientBuild...
</body>").unwrap(); let caps = re.captures(&html).unwrap(); let re = Regex::new( r"((?P<blk>[^\[|\]|\p{Han}]{0,}(?P<bot>[^\[]{1,})?)(\[(?P<top>[\p{Hiragana}|\p{Han}]+)\])?)", ) .unwrap(); let mut results: Vec<(String, Option<String>)> = Vec::new(); for cap in r...
re = Regex::new(r"\n|<br>").unwrap(); let html = format!("{}", re.replace_all(html, "")); let re = Regex::new(r"###\sBRACKETS(.+)
random
[ { "content": "pub fn char_remap(text: &String, char_map: HashMap<char, char>) -> String {\n\n text.chars()\n\n .map(|c| match char_map.get(&c) {\n\n Some(kanji) => *kanji,\n\n None => c,\n\n })\n\n .collect::<String>()\n\n}\n", "file_path": "src/remap.rs", "...
Rust
srt-tokio/examples/ts_streamer.rs
Majored/srt-rs
5e0128712a06b8d8906f16d0fe677aa5706249b2
#[cfg(feature = "ac-ffmpeg")] #[tokio::main] async fn main() -> anyhow::Result<()> { use std::{ env::args, fs::File, io::{self, Write}, time::{Duration, Instant}, }; use ac_ffmpeg::{ format::{ demuxer::Demuxer, io::IO, muxer::{Muxe...
#[cfg(feature = "ac-ffmpeg")] #[tokio::main] async fn main() -> anyhow::Result<()> { use std::{ env::args, fs::File, io::{self, Write}, time::{Duration, Instant}, }; use ac_ffmpeg::{ format::{ demuxer::Demuxer, io::IO, muxer::{Muxe...
map_err(|(_, err)| err)?; for (index, stream) in demuxer.streams().iter().enumerate() { let params = stream.codec_parameters(); println!("Stream #{}:", index); println!(" duration: {}", stream.duration().as_f64().unwrap_or(0f64)); if let Some(params) = params.as_audio_codec_param...
unks(1316) { if self .0 .try_send((Instant::now(), Bytes::copy_from_slice(chunk))) .is_err() { println!("Sender was throttled and buffer exausted, dropping p...
random
[]
Rust
humphrey/src/client.rs
w-henderson/Humphrey
43a879dbaadd7a6ab60daab95d798e07d7908c25
use crate::http::address::Address; use crate::http::cookie::Cookie; use crate::http::headers::{HeaderLike, HeaderType, Headers}; use crate::http::method::Method; use crate::http::{Request, Response, StatusCode}; use std::error::Error; use std::io::Write; use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; #[cfg(f...
use crate::http::address::Address; use crate::http::cookie::Cookie; use crate::http::headers::{HeaderLike, HeaderType, Headers}; use crate::http::method::Method; use crate::http::{Request, Response, StatusCode}; use std::error::Error; use std::io::Write; use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; #[cfg(f...
Protocol::Http => self.client.request(self.address, self.request.clone()), Protocol::Https => self.client.request_tls(self.address, self.request.clone()), }; if self.follow_redirects && response .as_ref() .map(|r| { ...
ClientConfig, ClientConnection, RootCertStore, StreamOwned}; #[cfg(feature = "tls")] use rustls_native_certs::load_native_certs; #[cfg(feature = "tls")] use std::convert::TryInto; #[cfg(feature = "tls")] use std::sync::Arc; #[derive(Default)] pub struct Client { #[cfg(feature = "tls")] tls_config: Option<Arc<...
random
[ { "content": "export class Header extends Component {\n\n render() {\n\n return (\n\n <div className=\"Header\"><h1>Humphrey Chat</h1></div>\n\n )\n\n }\n", "file_path": "examples/chat-app/client/src/components/Header.tsx", "rank": 0, "score": 90319.59920100903 }, { "content": "...
Rust
device-scanner/device-scanner-daemon/src/state.rs
intel-hpdd/-intel-manager-for-lustre
f8a6f61205b42cc62f4bbcb8d81214ad4f215cd6
use crate::error::{self, Result}; use device_types::{ devices::{ Dataset, Device, LogicalVolume, MdRaid, Mpath, Partition, Root, ScsiDevice, VolumeGroup, Zpool, }, get_vdev_paths, mount::Mount, state, uevent::UEvent, DevicePath, }; use im::{ordset, vector, HashSet, OrdSet, ...
use crate::error::{self, Result}; use device_types::{ devices::{ Dataset, Device, LogicalVolume, MdRaid, Mpath, Partition, Root, ScsiDevice, VolumeGroup, Zpool, }, get_vdev_paths, mount::Mount, state, uevent::UEvent, DevicePath, }; use im::{ordset, vector, HashSet, OrdSet, ...
minor, children, paths, .. }) => { let vs = get_vgs(&b, &major, &minor)?; let ps = get_partitions(&b, &ys, major, minor)?; let mds = get_mds(&b, &ys, &paths)?; let pools = get_pools(&b, &ys, &paths)?; for mut x i...
inor)?; let ps = get_partitions(&b, &ys, major, minor)?; let mds = get_mds(&b, &ys, &paths)?; let pools = get_pools(&b, &ys, &paths)?; for mut x in HashSet::unions(vec![vs, ps, mds, pools]) { build_device_graph(&mut x, b, ys)?; childre...
function_block-random_span
[ { "content": "pub fn get_pool(zed_events: &mut state::ZedEvents, guid: u64) -> Result<&mut libzfs_types::Pool> {\n\n zed_events.get_mut(&guid).ok_or_else(|| {\n\n Error::LibZfsError(libzfs_types::LibZfsError::PoolNotFound(None, Some(guid)))\n\n })\n\n}\n\n\n", "file_path": "device-scanner/devic...
Rust
daemon/src/engine/mod.rs
queer/squish
13728c326a656496f5f4cc6265f49f64bbdc6c8a
pub mod alpine; pub mod containers; pub mod slirp; use std::error::Error; use std::ffi::CStr; use std::fs::File; use std::io::Write; use std::net::TcpListener; use std::os::unix::io::FromRawFd; use std::process::{Command, Stdio}; use libsquish::squishfile::Squishfile; use nix::fcntl; use nix::sys::memfd; use nix::uni...
pub mod alpine; pub mod containers; pub mod slirp; use std::error::Error; use std::ffi::CStr; use std::fs::File; use std::io::Write; use std::net::TcpListener; use std::os::unix::io::FromRawFd; use std::process::{Command, Stdio}; use libsquish::squishfile::Squishfile; use nix::fcntl; use nix::sys::memfd; use nix::uni...
?; debug!( "{}: added port forward: {} -> {}", &id, port.host(), port.container() ); } Ok((Pid::from_raw(child_pid), Pid::from_raw(slirp_pid))) } fn check_port_bind(port: &u16) -> Result<(), Box<dyn Error + Send + Sync>> { TcpListener::bind((...
::FcntlArg::F_SETFD(fcntl::FdFlag::from_bits_truncate(fixed_flags)), )?; lseek(memfd, 0, Whence::SeekSet)?; debug!("{}: pid1 setup", &id); let base_version = alpine::VERSION.to_string(); let base_arch = alpine::ARCH.to_string(); let alpine_version = match squishfile.layers().get(...
function_block-random_span
[ { "content": "pub fn path_to(id: &String) -> String {\n\n format!(\"container/{}\", id)\n\n}\n", "file_path": "daemon/src/engine/containers.rs", "rank": 0, "score": 171302.77808670935 }, { "content": "/// The rootfs directory. This is the directory that Alpine rootfs images are\n\n/// cac...
Rust
exonum/src/api/private/system.rs
nuland-project/exonum
4a8688f694623be3c8b1841187986fb3b2589b03
use iron::prelude::*; use router::Router; use serde_json; use std::{collections::HashMap, net::SocketAddr}; use api::{Api, ApiError}; use blockchain::{Blockchain, Service, SharedNodeState}; use crypto::PublicKey; use messages::PROTOCOL_MAJOR_VERSION; use node::{ApiSender, ExternalMessage}; #[derive(Serialize, Dese...
use iron::prelude::*; use router::Router; use serde_json; use std::{collections::HashMap, net::SocketAddr}; use api::{Api, ApiError}; use blockchain::{Blockchain, Service, SharedNodeState}; use crypto::PublicKey; use messages::PROTOCOL_MAJOR_VERSION; use node::{ApiSender, ExternalMessage}; #[derive(Serialize, Dese...
fn handle_network(self, router: &mut Router) { let network = move |_: &mut Request| -> IronResult<Response> { let info = self.info.clone(); self.ok_response(&serde_json::to_value(info).unwrap()) }; router.get("/v1/network", network, "network_info"); } fn h...
fn handle_peer_add(self, router: &mut Router) { let peer_add = move |request: &mut Request| -> IronResult<Response> { #[derive(Serialize, Deserialize, Clone, Debug)] struct PeerAddInfo { ip: SocketAddr, } let PeerAddInfo { ip } = self.parse_body(r...
function_block-full_function
[ { "content": "/// Simplified compared to real life / testkit, but we don't need to test *everything*\n\n/// here.\n\npub fn create_block(blockchain: &mut Blockchain, transactions: Vec<Box<Transaction>>) {\n\n use exonum::helpers::{Round, ValidatorId};\n\n use exonum::messages::{Precommit, Propose};\n\n ...
Rust
src/worker/worker_config.rs
Dash83/MeshSim
a273cc62af1686b2696ebdd20311333bcb6c79f7
use crate::mobility::{Position, Velocity}; use crate::worker::listener::Listener; use crate::worker::protocols::*; use crate::worker::radio::*; use crate::worker::radio::{self, LoraFrequencies, SimulatedRadio, WifiRadio}; use crate::worker::{Channel, OperationMode, Worker, Write}; use crate::{MeshSimError, MeshSimErr...
use crate::mobility::{Position, Velocity}; use crate::worker::listener::Listener; use crate::worker::protocols::*; use crate::worker::radio::*; use crate::worker::radio::{self, LoraFrequencies, SimulatedRadio, WifiRadio}; use crate::worker::{Channel, OperationMode, Worker, Write}; use crate::{MeshSimError, MeshSimErr...
r_type, self.range, mac_layer_retries, mac_layer_base_wait, max_delay_per_node, rng, logger, )?; Ok((Arc::new(radio), listener)) } } } } #[d...
.max_delay_per_node .unwrap_or(DEFAULT_TX_DELAY_PER_NODE); let (radio, listener) = SimulatedRadio::new( timeout, work_dir, worker_id, worker_name,
random
[ { "content": "///Used to produce a Lora Radio trait object\n\npub fn new_lora_radio(\n\n _frequency: u64,\n\n _spreading_factor: u32,\n\n _transmission_power: u8,\n\n) -> Result<Channel, MeshSimError> {\n\n panic!(\"Lora radio creation is only supported on Linux\");\n\n}\n", "file_path": "src/wo...
Rust
vm_tools/crostini_client/frontends/vmc.rs
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
use std::error::Error; use std::fmt; use backends::Backend; use frontends::Frontend; use EnvMap; enum VmcError { Command(&'static str, u32, Box<Error>), ExpectedCrosUserIdHash, ExpectedName, ExpectedVmAndContainer, ExpectedVmAndFileName, ExpectedVmAndPath, ExpectedNoArgs, InvalidEmai...
use std::error::Error; use std::fmt; use backends::Backend; use frontends::Frontend; use EnvMap; enum VmcError { Command(&'static str, u32, Box<Error>), ExpectedCrosUserIdHash, ExpectedName, ExpectedVmAndContainer, ExpectedVmAndFileName, ExpectedVmAndPath, ExpectedNoArgs, InvalidEmai...
fn destroy(&mut self) -> VmcResult { if self.args.len() != 1 { return Err(ExpectedName.into()); } let vm_name = self.args[0]; let user_id_hash = self .environ .get("CROS_USER_ID_HASH") .ok_or(ExpectedCrosUserIdHash)?; match ...
n() != 1 { return Err(ExpectedName.into()); } let vm_name = self.args[0]; let user_id_hash = self .environ .get("CROS_USER_ID_HASH") .ok_or(ExpectedCrosUserIdHash)?; try_command!(self.backend.vm_stop(vm_name, user_id_hash)); Ok((...
function_block-function_prefixed
[ { "content": "// Prints |name| and value of entry /pros/sys/vm/|name| (or 0, if the entry is\n\n// missing) to file |out|.\n\nfn log_from_procfs(out: &mut File, dir: &Path, name: &str) -> Result<()> {\n\n let procfs_path = dir.join(name);\n\n let value = read_int(&procfs_path).unwrap_or(0);\n\n writeln...
Rust
crates/macros/src/class.rs
TorstenDittmann/ext-php-rs
910400a1b2ce02f85cf4a08f9787bc4d7d26b3ae
use std::collections::HashMap; use crate::STATE; use anyhow::{anyhow, bail, Context, Result}; use darling::{FromMeta, ToTokens}; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use syn::parse::ParseStream; use syn::{Attribute, AttributeArgs, Expr, Fields, FieldsNamed, ItemStruct, LitStr, Token}; #[deri...
use std::collections::HashMap; use crate::STATE; use anyhow::{anyhow, bail, Context, Result}; use darling::{FromMeta, ToTokens}; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use syn::parse::ParseStream; use syn::{Attribute, AttributeArgs, Expr, Fields, FieldsNamed, ItemStruct, LitStr, Token}; #[deri...
; let setter = if let Some(setter) = setter { let ident = Ident::new(setter, Span::call_site()); quote! { Some(Self::#ident) } } else { quote! { None } }; quote! { (#name, ::ex...
if let Some(getter) = getter { let ident = Ident::new(getter, Span::call_site()); quote! { Some(Self::#ident) } } else { quote! { None } }
if_condition
[ { "content": "pub fn parser(args: AttributeArgs, input: ItemFn) -> Result<(TokenStream, Function)> {\n\n let attr_args = match AttrArgs::from_list(&args) {\n\n Ok(args) => args,\n\n Err(e) => bail!(\"Unable to parse attribute arguments: {:?}\", e),\n\n };\n\n\n\n let ItemFn { sig, .. } = ...
Rust
src/bin/wallet.rs
jtwray/solana
dafdab1bbce5c4d1ebea89da8bf406ea51834794
#[macro_use] extern crate clap; extern crate dirs; #[macro_use] extern crate solana; use clap::{App, Arg, ArgMatches, SubCommand}; use solana::logger; use solana::signature::{read_keypair, KeypairUtil}; use solana::wallet::{gen_keypair_file, parse_command, process_command, WalletConfig, WalletError}; use std::error; u...
#[macro_use] extern crate clap; extern crate dirs; #[macro_use] extern crate solana; use clap::{App, Arg, ArgMatches, SubCommand}; use solana::logger; use solana::signature::{read_keypair, KeypairUtil}; use solana::wallet::{gen_keypair_file, parse_command, process_command, WalletConfig, WalletError}; use std::error; u...
e pubkey of recipient"), ).arg( Arg::with_name("tokens") .index(2) .value_name("NUM") .takes_value(true) .required(true) .help("The number of tokens to send"), ...
x(1) .value_name("SIGNATURE") .takes_value(true) .required(true) .help("The transaction signature to confirm"), ), ).subcommand( SubCommand::with_name("deploy") .about("Dep...
random
[ { "content": "pub fn read_keypair(path: &str) -> Result<Keypair, Box<error::Error>> {\n\n let file = File::open(path.to_string())?;\n\n let bytes: Vec<u8> = serde_json::from_reader(file)?;\n\n let keypair = Keypair::from_bytes(&bytes).unwrap();\n\n Ok(keypair)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {...
Rust
src/mates/cli.rs
gyscos/mates.rs
816b28b09d8e63c621c1f0a190933f364e146d36
use std::borrow::ToOwned; use std::env; use std::error::Error; use std::fmt; use std::fs; use std::io; use std::io::{Read, Write}; use std::path; use std::process; use atomicwrites::{AllowOverwrite, AtomicFile}; use crate::app; use crate::editor; use crate::utils; use crate::utils::CustomPathExt; #[inline] fn get_pw...
use std::borrow::ToOwned; use std::env; use std::error::Error; use std::fmt; use std::fs; use std::io; use std::io::{Read, Write}; use std::path; use std::process; use atomicwrites::{AllowOverwrite, AtomicFile}; use crate::app; use crate::editor; use crate::utils; use crate::utils::CustomPathExt; #[inline] fn get_pw...
pub struct Configuration { pub index_path: path::PathBuf, pub vdir_path: path::PathBuf, pub grep_cmd: String, } impl Configuration { pub fn new() -> Result<Configuration, String> { Ok(Configuration { index_path: match get_envvar("MATES_INDEX") { Some(x) => path::Pa...
fn email_query<'a>(config: &Configuration, query: &str) -> MainResult<()> { for item in utils::index_query(config, query)? { if item.name.len() > 0 && item.email.len() > 0 { println!("{} <{}>", item.name, item.email); }; } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Write sender from given email as .vcf file to given directory.\n\npub fn add_contact_from_email(contact_dir: &path::Path, email_input: &str) -> io::Result<Contact> {\n\n let from_header = match read_sender_from_email(email_input) {\n\n Some(x) => x,\n\n None => {\n\n ...
Rust
src/cypher/transaction.rs
manonthemat/rusted-cypher
394eb0b1ccf37c5ecd8bef0ab2713ffa49ce1ed3
use std::any::Any; use std::marker::PhantomData; use std::mem; use hyper::Client; use hyper::header::{Headers, Location}; use time::{self, Tm}; use ::error::{GraphError, Neo4jError}; use super::result::{CypherResult, ResultTrait}; use super::statement::Statement; const DATETIME_RFC822: &'static str = "%a, %d %b %Y ...
use std::any::Any; use std::marker::PhantomData; use std::mem; use hyper::Client; use hyper::header::{Headers, Location}; use time::{self, Tm}; use ::error::{GraphError, Neo4jError}; use super::result::{CypherResult, ResultTrait}; use super::statement::Statement; const DATETIME_RFC822: &'static str = "%a, %d %b %Y ...
back {}", self.transaction); Ok(()) } pub fn reset_timeout(&mut self) -> Result<(), GraphError> { super::send_query(&self.client, &self.transaction, self.headers, vec![]) .map(|_| ()) }...
e(Deserialize)] #[allow(dead_code)] struct CommitResult { results: Vec<CypherResult>, errors: Vec<Neo4jError>, } impl ResultTrait for CommitResult { fn results(&self) -> &Vec<CypherResult> { &self.results } fn errors(&self) -> &Vec<Neo4jError> { &self.errors } } pub struct Tra...
random
[ { "content": "#[test]\n\nfn transaction_create_on_commit() {\n\n let rust = Language {\n\n name: \"Rust\".to_owned(),\n\n level: \"low\".to_owned(),\n\n safe: true,\n\n };\n\n\n\n let graph = GraphClient::connect(URI).unwrap();\n\n\n\n let statement = Statement::new(\n\n ...
Rust
samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs
bendrucker/openapi-generator
ebcce674197b0bea1772d1a3074acf0c10650b60
/* * OpenAPI Petstore * * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://openapi-generator.tech */ #[allow(unused_imports)] use std::rc::Rc; use std::bor...
/* * OpenAPI Petstore * * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://openapi-generator.tech */ #[allow(unused_imports)] use std::rc::Rc; use std::bor...
pub async fn login_user(configuration: &configuration::Configuration, params: LoginUserParams) -> Result<String, Error> { let username = params.username; let password = params.password; let client = &configuration.client; let uri_str = format!("{}/user/login", configurat...
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } let req = req_builder.build()?; Ok(client.execute(req).await?.error_for_status()?.json::<crate::models::User>().await?) }
function_block-function_prefix_line
[]
Rust
bin/desktop/src/main.rs
joao-conde/jc-chip8
a6df229e9f7e2154a2b3980da20cadebe253e5dd
use jc_chip8::chip8::{Chip8, SCREEN_PIXEL_HEIGHT, SCREEN_PIXEL_WIDTH}; use sdl2::{event::Event, keyboard::Keycode, pixels::PixelFormatEnum}; use std::{fs::File, io::Read}; const PIXEL_SET: [u8; 3] = [80, 203, 147]; const SYSTEM_HZ: u32 = 240; const SCREEN_SCALE: f32 = 15.0; const TITLE: &str = "Drag and drop the ROM f...
use jc_chip8::chip8::{Chip8, SCREEN_PIXEL_HEIGHT, SCREEN_PIXEL_WIDTH}; use sdl2::{event::Event, keyboard::Keycode, pixels::PixelFormatEnum}; use std::{fs::File, io::Read}; const PIXEL_SET: [u8; 3] = [80, 203, 147]; const SYSTEM_HZ: u32 = 240; const SCREEN_SCALE: f32 = 15.0; const TITLE: &str = "Drag and drop the ROM f...
let mut file = File::open(path).unwrap(); let mut rom = Vec::new(); file.read_to_end(&mut rom).unwrap(); rom }
function_block-function_prefix_line
[ { "content": " }\n\n\n\n pub fn key_lift(&mut self, key: u8) {\n\n if key < NUM_KEYS as u8 {\n\n self.keys[key as usize] = false;\n\n }\n\n }\n\n}\n\n\n\nimpl Chip8 {\n\n fn process_opcode(&mut self, opcode: u16) {\n\n let id = opcode & 0xF000;\n\n let addr = o...
Rust
benches/distributions.rs
TheIronBorn/rand
e1b60350d0936e6f17c7fd017ed18f3151006f43
#![feature(test)] #![cfg_attr(feature = "simd_support", feature(stdsimd))] #![cfg_attr(feature = "i128_support", feature(i128_type, i128))] extern crate test; extern crate rand; const RAND_BENCH_N: u64 = 1000; use std::mem::size_of; #[cfg(feature = "simd_support")] use std::simd::*; use test::{black_box, Bencher}; ...
#![feature(test)] #![cfg_attr(feature = "simd_support", feature(stdsimd))] #![cfg_attr(feature = "i128_support", feature(i128_type, i128))] extern crate test; extern crate rand; const RAND_BENCH_N: u64 = 1000; use std::mem::size_of; #[cfg(feature = "simd_support")] use std::simd::*; use test::{black_box, Bencher}; ...
fn dist_iter(b: &mut Bencher) { let mut rng = XorShiftRng::new(); let distr = Normal::new(-2.71828, 3.14159); let mut iter = distr.sample_iter(&mut rng); b.iter(|| { let mut accum = 0.0; for _ in 0..::RAND_BENCH_N { accum += iter.next().unwrap(); } black_box(...
function_block-full_function
[ { "content": "#[bench]\n\nfn misc_gen_bool(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let mut accum = true;\n\n for _ in 0..::RAND_BENCH_N {\n\n accum ^= rng.gen_bool(0.18);\n\n }\n\n black_box(accum);\n\n...
Rust
src/lib.rs
YakoYakoYokuYoku/rust-number-prefix
87f7f17523874be801e9ae21cca7b28345959e40
#![crate_name = "number_prefix"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![deny(unsafe_code)] #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(trivial_numeric_casts)] #![warn(unreachable_pub)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] use ...
#![crate_name = "number_prefix"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![deny(unsafe_code)] #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(trivial_numeric_casts)] #![warn(unreachable_pub)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] use ...
assert_eq!(result, "The file is 705 bytes in size"); } #[test] fn example_three() { let result = match NumberPrefix::binary(8542_f32) { Standalone(bytes) => format!("The file is {} bytes in size", bytes), Prefixed(prefix, n) => format!("The file is {:.1} {}B in size", n, prefix), }; assert_...
let result = match NumberPrefix::decimal(705_f32) { Standalone(bytes) => format!("The file is {} bytes in size", bytes), Prefixed(prefix, n) => format!("The file is {:.1} {}B in size", n, prefix), };
assignment_statement
[ { "content": "fn main() {\n\n\n\n // part one\n\n let mut n = 1_f64;\n\n\n\n for _ in 0 .. 8 {\n\n n *= 1000_f64;\n\n\n\n let decimal = match NumberPrefix::decimal(n) {\n\n Prefixed(prefix, n) => format!(\"{:.3} {}B\", n, prefix),\n\n Standalone(_) => unreachab...
Rust
src/irc/mod.rs
rubo77/matrix-ircd
7a08a681b2aad54f750e25d9a58c6a08daa6dc1a
pub mod transport; mod protocol; mod models; pub use self::protocol::{Command, IrcCommand, IrcLine, Numeric}; use crate::ConnectionContext; use crate::stream_fold::StreamFold; use tokio_io::{AsyncRead, AsyncWrite}; use futures::{Async, Future, Poll}; use futures::stream::Stream; use std::io; pub struct IrcUserC...
pub mod transport; mod protocol; mod models; pub use self::protocol::{Command, IrcCommand, IrcLine, Numeric}; use crate::ConnectionContext; use crate::stream_fold::StreamFold; use tokio_io::{AsyncRead, AsyncWrite}; use futures::{Async, Future, Poll}; use futures::stream::Stream; use std::io; pub struct IrcUserC...
; let user = user_nick.user.expect("user"); let user_prefix = format!("{}!{}@{}", &nick, &user, &server_name); let user_conn = IrcUserConnection { conn: irc_conn, user: user, nick: nick, rea...
if let Some(p) = user_nick.password { p } else { irc_conn.write_password_required(&nick); return Err(io::Error::new(io::ErrorKind::InvalidData, "IRC user did not supply password")); }
if_condition
[ { "content": "fn do_json_post<I: Serialize, O: DeserializeOwned + 'static>(method: &'static str, stream: &mut HttpClient, url: &Url, input: &I)\n\n -> Box<Future<Item=O, Error=JsonPostError>>\n\n{\n\n let f = stream.send_request(Request {\n\n method: method,\n\n path: format!(\"{}?{}\", url....
Rust
compiler/src/statement.rs
ar90n/nand2tetris-rs
f6bf07a86a5c04d6898b756aa9954c3ff7fec887
use anyhow::*; use super::expression::*; use super::foundation::*; use super::token::Token; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ReturnStatement(pub Box<Optional<Expression>>); impl Parsable for ReturnStatement { fn parse(tokens: &[Token]) -> Result<(Box<Self>, &[Token])> { let (_, rem) = to...
use anyhow::*; use super::expression::*; use super::foundation::*; use super::token::Token; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ReturnStatement(pub Box<Optional<Expression>>); impl Parsable for ReturnStatement { fn parse(tokens: &[Token]) -> Result<(Box<Self>, &[Token])> { let (_, rem) = to...
(rem)?; Ok(( Box::new(Self { condition, then_body, else_body, }), rem, )) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct LetStatement { pub var_name: Box<Identifier>, pub array_size: Box<Option<Box<Ex...
option_parser(drop1_parser( token_parser(Token::Else), surround_parser(Statements::parse, Token::LBrace, Token::RBrace), ))
call_expression
[ { "content": "pub fn dump_as_xml(tokens: &[Token]) -> String {\n\n let mut tags = vec![\"<tokens>\".to_string()];\n\n for token in tokens {\n\n tags.push(token.dump_as_xml(0));\n\n }\n\n tags.push(\"</tokens>\".to_string());\n\n tags.join(\"\\n\")\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests ...
Rust
worker/src/headers.rs
gsquire/workers-rs
3417a303ec471dea42982e6b9cd31d6ea7fa2c62
use crate::{error::Error, Result}; use std::{ iter::{FromIterator, Map}, result::Result as StdResult, str::FromStr, }; use http::{header::HeaderName, HeaderMap, HeaderValue}; use js_sys::Array; use wasm_bindgen::JsValue; use worker_sys::Headers as EdgeHeaders; pub struct Headers(pub EdgeHeaders); impl s...
use crate::{error::Error, Result}; use std::{ iter::{FromIterator, Map}, result::Result as StdResult, str::FromStr, }; use http::{header::HeaderName, HeaderMap, HeaderValue}; use js_sys::Array; use wasm_bindgen::JsValue; use worker_sys::Headers as EdgeHeaders; pub struct Headers(pub EdgeHeaders); impl s...
pub fn values(&self) -> impl Iterator<Item = String> { self.0 .values() .unwrap() .into_iter() .map(|a| a.unwrap().as_string().unwrap()) } } impl Default for Headers { fn default() -> Self { Heade...
s() .unwrap() .into_iter() .map(|a| a.unwrap().as_string().unwrap()) }
function_block-function_prefixed
[ { "content": "pub fn bundle_worker(shim_src: String, mut dst: impl Write) -> Result<()> {\n\n let globals = Globals::default();\n\n let cm = Arc::new(SourceMap::default());\n\n\n\n let mut bundler = Bundler::new(\n\n &globals,\n\n cm.clone(),\n\n BundleLoader(cm.clone()),\n\n ...
Rust
wasabi/src/shared_state.rs
maxmcd/wasabi-archive
25f1d5c3a1d4a1f597a798146132cf2b131e59c1
use bytes::i32_as_u8_le; use failure::Error; use js; use mem::{Actions, Mem}; use std::collections::{HashMap, VecDeque}; use std::net::IpAddr; use timeout_heap::ToHeap; use wasabi_io; use wasabi_io::IOLoop; use wasmtime_runtime::VMMemoryDefinition; #[derive(Debug)] pub struct SharedState { pub exited: bool, pu...
use bytes::i32_as_u8_le; use failure::Error; use js; use mem::{Actions, Mem}; use std::collections::{HashMap, VecDeque}; use std::net::IpAddr; use timeout_heap::ToHeap; use wasabi_io; use wasabi_io::IOLoop; use wasmtime_runtime::VMMemoryDefinition; #[derive(Debug)] pub struct SharedState { pub exited: bool, pu...
elf.mem.get_i32(address + 8); for n in 0..len { out.push(self.load_value(array + n * 8)) } out } pub fn store_value_bytes(&mut self, b: Vec<u8>) -> i32 { self.js.slab_add(js::Value::Bytes(b)) as i32 } fn recv_net_events(&mut self) -> Option<Vec<wasabi_io::Resp...
ce_of_values(&self, address: i32) -> Vec<(i64, bool)> { let mut out = Vec::new(); let array = self.mem.get_i32(address); let len = s
function_block-random_span
[ { "content": "pub fn int_from_value(val: (i64, bool)) -> i64 {\n\n if val == (1, true) {\n\n 0\n\n } else {\n\n val.0\n\n }\n\n}\n\n\n\nimpl Js {\n\n pub fn new() -> Result<Self, Error> {\n\n let mut js = Self {\n\n slab: Slab::new(),\n\n static_strings: Ha...
Rust
src/service.rs
uheee/oss-rust-sdk
1d9442c20929076960e51372e3516f28d28edd0c
use quick_xml::{events::Event, Reader}; use reqwest::header::{HeaderMap, DATE}; use std::collections::HashMap; use super::auth::*; use super::errors::Error; use super::oss::OSS; #[derive(Clone, Debug)] pub struct ListBuckets { prefix: String, marker: String, max_keys: String, is_truncated: bool, n...
use quick_xml::{events::Event, Reader}; use reqwest::header::{HeaderMap, DATE}; use std::collections::HashMap; use super::auth::*; use super::errors::Error; use super::oss::OSS; #[derive(Clone, Debug)] pub struct ListBuckets { prefix: String, marker: String, max_keys: String, is_truncated: bool, n...
pub fn prefix(&self) -> &str { &self.prefix } pub fn marker(&self) -> &str { &self.marker } pub fn max_keys(&self) -> &str { &self.max_keys } pub fn is_truncated(&self) -> bool { self.is_truncated } pub fn next_marker(&self) -> &str { &se...
Self { ListBuckets { prefix, marker, max_keys, is_truncated, next_marker, id, display_name, buckets, } }
function_block-function_prefix_line
[ { "content": "#[inline]\n\nfn get_oss_resource_str(bucket: &str, object: &str, oss_resources: &str) -> String {\n\n let oss_resources = if oss_resources != \"\" {\n\n String::from(\"?\") + oss_resources\n\n } else {\n\n String::new()\n\n };\n\n if bucket == \"\" {\n\n format!(\"...
Rust
src/mixer.rs
rockerBOO/rtmp-switcher
0ba705fd460219f696d3cdead6204c09360a11bd
extern crate gstreamer as gst; use gst::prelude::*; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::sync::{Arc, Mutex}; pub struct Output { audio: gst::Element, video: gst::Element, } #[derive(Debug)] pub struct MixerError { details: String, } impl MixerError { fn new(msg...
extern crate gstreamer as gst; use gst::prelude::*; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::sync::{Arc, Mutex}; pub struct Output { audio: gst::Element, video: gst::Element, } #[derive(Debug)] pub struct MixerError { details: String, } impl MixerError { fn new(msg...
} else { println!("Link succeeded (type {}).", new_pad_type); } } else if new_pad_type.starts_with("video/x-raw") { let sink_pad = video_mixer .get_request_pad("sink_%u") .expect("Failed to get static sink pa...
MixerError { details: msg.into(), } } } impl fmt::Display for MixerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.details) } } impl Error for MixerError { fn description(&self) -> &str { &self.details } } pub struct Mixer ...
random
[ { "content": "fn main() {\n\n // Initialize GStreamer\n\n gst::init().unwrap();\n\n\n\n let rtmp_uri = \"rtmp://learntv-transcoder.eastus.azurecontainer.io:1935/live/STREAM_KEY\";\n\n let rtmp_uri2 = \"rtmp://learntv-transcoder.eastus.azurecontainer.io:1935/live/STREAM_KEY2\";\n\n\n\n let uri =\n...
Rust
consensus/safety-rules/src/safety_rules_test.rs
end-o/libra
38d2a1ed3fde793784b2dba978ee349099cdecfe
use crate::{ConsensusState, Error, SafetyRules}; use consensus_types::{ block::Block, block_info::BlockInfo, common::Round, quorum_cert::QuorumCert, vote::Vote, vote_data::VoteData, vote_proposal::VoteProposal, }; use libra_crypto::hash::{CryptoHash, HashValue}; use libra_types::{ crypto_proxies::Validato...
use crate::{ConsensusState, Error, SafetyRules}; use consensus_types::{ block::Block, block_info::BlockInfo, common::Round, quorum_cert::QuorumCert, vote::Vote, vote_data::VoteData, vote_proposal::VoteProposal, }; use libra_crypto::hash::{CryptoHash, HashValue}; use libra_types::{ crypto_proxies::Validato...
y_rules.update(a4.block().quorum_cert()); assert_eq!( safety_rules.construct_and_sign_vote(&a4), Err(Error::OldProposal { last_vote_round: 7, proposal_round: 7, }) ); safety_rules.update(b4.block().quorum_cert()); assert_eq!( safety_rules.construct...
ound + 4, b1.block(), None, &validator_signer); let b3 = make_proposal_with_parent(round + 5, b2.block(), None, &validator_signer); let a3 = make_proposal_with_parent(round + 6, a2.block(), None, &validator_signer); let a4 = make_proposal_with_parent(round + 7, a3.block(), None, &validator_signer); saf...
random
[ { "content": "fn random_vote_data(round: Round) -> VoteData {\n\n assert!(round >= 1);\n\n VoteData::new(BlockInfo::random(round), BlockInfo::random(round - 1))\n\n}\n\n\n\n#[test]\n", "file_path": "consensus/src/chained_bft/block_storage/pending_votes_test.rs", "rank": 0, "score": 340718.7670...
Rust
src/tests.rs
MinusGix/llama
7b0c7b0b5147978fc1e409ed106d0f00867be98f
use crate::*; #[test] fn codegen() -> Result<(), Error> { let context = Context::new()?; let module = Module::new(&context, "test_codegen")?; let builder = Builder::new(&context)?; let i32 = Type::of::<i32>(&context)?; let ft = FuncType::new(i32, &[i32, i32])?; module.declare_function(&build...
use crate::*; #[test] fn codegen() -> Result<(), Error> { let context = Context::new()?; let module = Module::new(&context, "test_codegen")?; let builder = Builder::new(&context)?; let i32 = Type::of::<i32>(&context)?; let ft = FuncType::new(i32, &[i32, i32])?; module.declare_function(&build...
#[test] fn for_loop() -> Result<(), Error> { let ctx = Context::new()?; let module = Module::new(&ctx, "test_for_loop")?; let build = Builder::new(&ctx)?; let i64 = Type::int(&ctx, 64)?; let ft = FuncType::new(i64, &[i64])?; module.declare_function(&build, "testing", ft, |f| { let pa...
let f32 = Type::float(&ctx)?; let ft = FuncType::new(f32, &[f32])?; module.declare_function(&builder, "testing", ft, |f| { let params = f.params(); let cond = builder.fcmp( Fcmp::LLVMRealULT, &params[0], Const::real(f32, 10.0)?, "cond", )?;...
function_block-function_prefix_line
[ { "content": "fn main() -> Result<(), Error> {\n\n let context = Context::new()?;\n\n let module = Module::new(&context, \"sum\")?;\n\n let build = Builder::new(&context)?;\n\n let engine = ExecutionEngine::new_jit(module, 0)?;\n\n let mut codegen = CodeGen {\n\n context: context,\n\n ...
Rust
src/factory/collections/factory_vec_deque.rs
mskorkowski/relm4
c1deccc1e6e46ab790d99108b2481ea5afdf4146
use gtk::glib::Sender; use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use super::Widgets; use crate::factory::{Factory, FactoryListView, FactoryPrototype, FactoryView}; #[derive(Debug, PartialEq, Eq)] pub struct DynamicIndex { inner: RefCell<usize>, } impl DynamicIndex { ...
use gtk::glib::Sender; use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use super::Widgets; use crate::factory::{Factory, FactoryListView, FactoryPrototype, FactoryView}; #[derive(Debug, PartialEq, Eq)] pub struct DynamicIndex { inner: RefCell<usize>, } impl DynamicIndex { ...
a.index, &widgets[index].widgets); } ChangeType::Remove(num) => { for _ in 0..*num { let remove_widget = widgets.remove(index).unwrap(); view.remove(&remove_widget.root); } } ...
: FactoryPrototype, { data: VecDeque<IndexedData<Data>>, widgets: RefCell<VecDeque<Widgets<Data::Widgets, <Data::View as FactoryView<Data::Root>>::Root>>>, changes: RefCell<Vec<Change>>, } impl<Data> FactoryVecDeque<Data> where Data: FactoryPrototype, { #[must_use] pub fn new() -> ...
random
[ { "content": "/// Sets a custom global stylesheet.\n\n///\n\n/// # Panics\n\n///\n\n/// This function panics if [`RelmApp::new`] wasn't called before\n\n/// or this function is not called on the thread that also called [`RelmApp::new`].\n\npub fn set_global_css(style_data: &[u8]) {\n\n let display = gtk::gdk...
Rust
src/split.rs
GNQG/safeeft
37b5202e83c88f9107a2afbea033e4c8c8909221
use traits::FloatEFT; #[inline] pub fn split<T: FloatEFT>(a: T) -> (T, T) { let tmp = a.clone() * T::split_coef(); let x = tmp.clone() - (tmp - a.clone()); (x.clone(), a - x) } #[inline] pub fn safesplit_branch<T: FloatEFT>(a: T) -> (T, T) { if a > T::one() { let t = split(a * T::eps...
use traits::FloatEFT; #[inline] pub fn split<T: FloatEFT>(a: T) -> (T, T) { let tmp = a.clone() * T::split_coef(); let x = tmp.clone() - (tmp - a.clone()); (x.clone(), a - x) } #[inline] pub fn safesplit_branch<T: FloatEFT>(a: T) -> (T, T) { if a > T::one() { let t = split(a * T::eps...
assert!(s2.0.abs() * 2f64.powi(-26) >= s2.1.abs()); assert_eq!(s1.0, s2.0 * 2.); assert_eq!(s1.1, s2.1 * 2.); } } #[test] fn large() { let mut rng = rand::thread_rng(); for _ in 0..10000000 { let fl = (rng.gen_range::<i64>...
(t.0 / T::epsilon(), t.1 / T::epsilon()) } else { split(a) } } #[inline] pub fn safesplit_straight<T: FloatEFT>(a: T) -> (T, T, T) { let aa = a.clone() / T::radix(); let err = a - aa.clone() * T::radix(); let step = (((aa.clone() + T::min_positive()) - aa.clone()) / T::min_p...
random
[ { "content": "#[inline]\n\npub fn fasttwosum<T: FloatEFT>(x: T, y: T) -> (T, T) {\n\n let sum = x.clone() + y.clone();\n\n (sum.clone(), y - (sum - x))\n\n}\n\n\n", "file_path": "src/twosum.rs", "rank": 0, "score": 60323.84215343371 }, { "content": "#[inline]\n\npub fn twosum<T: FloatE...
Rust
tests/command/test_amend.rs
Spread0x/git-branchless
51c6b03e4c10944b9fb864dd6faa3faf779e7474
use branchless::testing::{make_git, GitRunOptions}; #[test] fn test_amend_with_children() -> eyre::Result<()> { let git = make_git()?; if !git.supports_committer_date_is_author_date()? { return Ok(()); } git.init_repo()?; git.detach_head()?; git.commit_file("test1", 1)?; git.commi...
use branchless::testing::{make_git, GitRunOptions}; #[test] fn test_amend_with_children() -> eyre::Result<()> { let git = make_git()?; if !git.supports_committer_date_is_author_date()? { return Ok(()); } git.init_repo()?; git.detach_head()?; git.commit_file("test1", 1)?; git.commi...
end"], &GitRunOptions { expected_exit_code: 1, ..Default::default() }, )?; insta::assert_snapshot!(stdout, @"Cannot amend, because there are unresolved merge conflicts. Resolve the merge conflicts and try again. "); } Ok(()) }
&["merge", "branch1"], &GitRunOptions { expected_exit_code: 1, ..Default::default() }, )?; { let (stdout, _stderr) = git.run_with_options( &["branchless", "am
function_block-random_span
[ { "content": "#[test]\n\nfn test_restack_amended_master() -> eyre::Result<()> {\n\n let git = make_git()?;\n\n\n\n if !git.supports_committer_date_is_author_date()? {\n\n return Ok(());\n\n }\n\n\n\n git.init_repo()?;\n\n\n\n git.commit_file(\"test1\", 1)?;\n\n git.commit_file(\"test2\"...
Rust
src/ruffbox/synth/synths/ambisonic.rs
the-drunk-coder/ruffbox-synth
30ce5e108522f326b78789e79493009cca86e026
use crate::ruffbox::synth::ambisonics::encoder_o1::EncoderO1; use crate::ruffbox::synth::envelopes::*; use crate::ruffbox::synth::filters::*; use crate::ruffbox::synth::oscillators::*; use crate::ruffbox::synth::sampler::Sampler; use crate::ruffbox::synth::Synth; use crate::ruffbox::synth::SynthParameter; use crate::ru...
use crate::ruffbox::synth::ambisonics::encoder_o1::EncoderO1; use crate::ruffbox::synth::envelopes::*; use crate::ruffbox::synth::filters::*; use crate::ruffbox::synth::oscillators::*; use crate::ruffbox::synth::sampler::Sampler; use crate::ruffbox::synth::Synth; use crate::ruffbox::synth::SynthParameter; use crate::ru...
fn reverb_level(&self) -> f32 { self.reverb } fn delay_level(&self) -> f32 { self.delay } } pub struct LFSquareSynthAmbiO1<const BUFSIZE: usize> { oscillator: LFSquare<BUFSIZE>, filter: Lpf18<BUFSIZE>, envelope: ASREnvelope<BUFSIZE>, encoder: EncoderO1<BUFSIZE>, r...
lock(out, start_sample); out = self.envelope.process_block(out, start_sample); self.encoder.process_block(out) }
function_block-function_prefixed
[ { "content": "/// timed event, to be created in the trigger method, then\n\n/// sent to the event queue to be either dispatched directly\n\n/// or pushed to the pending queue ...\n\nstruct ScheduledEvent<const BUFSIZE: usize, const NCHAN: usize> {\n\n timestamp: f64,\n\n source: Box<dyn Synth<BUFSIZE, NCH...
Rust
research/gaia-x/pegasus/pegasus/examples/apply.rs
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
use std::path::PathBuf; use std::sync::Arc; use std::time::Instant; use pegasus::api::{CorrelatedSubTask, Count, Map, Sink}; use pegasus::{Configuration, JobConf, ServerConf}; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "correlated k-hop ", about = "Search k-hop neighbors on parallel data...
use std::path::PathBuf; use std::sync::Arc; use std::time::Instant; use pegasus::api::{CorrelatedSubTask, Count, Map, Sink}; use pegasus::{Configuration, JobConf, ServerConf}; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "correlated k-hop ", about = "Search k-hop neighbors on parallel data...
len * 0.99) as usize; println!("99% k-hop count <= {}", cnt_list[i]); i = (len * 0.90) as usize; println!("90% k-hop count <= {}", cnt_list[i]); i = (len * 0.5) as usize; println!("50% k-hop count <= {}", cnt_list[i]); let total: u64 = cnt_list.iter().sum(); println!("avg k-hop count {}/{} {...
x.unwrap(); if n > 0 { println!("{}\tfind k-hop\t{}\tneighbors, use {:?}us;", id, cnt, elp); } n -= 1; cnt_list.push(cnt); elp_list.push(elp); } let elp = start.elapsed(); println!("..."); println!("====================================================...
random
[ { "content": "pub fn start_connection(self_index: usize, remote_addresses: Vec<(usize, String)>, mut retry_times: u64) -> ::std::io::Result<Vec<(usize, String, TcpStream)>> {\n\n let mut result = Vec::with_capacity(remote_addresses.len());\n\n\n\n for (remote_index, remote_address) in remote_addresses {\n...
Rust
boa_engine/src/syntax/ast/node/object/mod.rs
nekevss/boa
ae01d5c20bef227a47d7a9647d85da8bcd2b48c5
use crate::syntax::ast::{ node::{ declaration::block_to_string, join_nodes, AsyncFunctionExpr, AsyncGeneratorExpr, FunctionExpr, GeneratorExpr, Node, }, Const, }; use boa_gc::{unsafe_empty_trace, Finalize, Trace}; use boa_interner::{Interner, Sym, ToInternedString}; #[cfg(feature = "deser...
use crate::syntax::ast::{ node::{ declaration::block_to_string, join_nodes, AsyncFunctionExpr, AsyncGeneratorExpr, FunctionExpr, GeneratorExpr, Node, }, Const, }; use boa_gc::{unsafe_empty_trace, Finalize, Trace}; use boa_interner::{Interner, Sym, ToInternedString}; #[cfg(feature = "deser...
} impl ToInternedString for Object { fn to_interned_string(&self, interner: &Interner) -> String { self.to_indented_string(interner, 0) } } impl<T> From<T> for Object where T: Into<Box<[PropertyDefinition]>>, { fn from(props: T) -> Self { Self { properties: props.into(), ...
pub(in crate::syntax::ast::node) fn to_indented_string( &self, interner: &Interner, indent_n: usize, ) -> String { let mut buf = "{\n".to_owned(); let indentation = " ".repeat(indent_n + 1); for property in self.properties().iter() { buf.push_str(&match...
function_block-full_function
[ { "content": "/// This trait allows Rust types to be passed around as objects.\n\n///\n\n/// This is automatically implemented, when a type implements `Debug`, `Any` and `Trace`.\n\npub trait NativeObject: Debug + Any + Trace {\n\n /// Convert the Rust type which implements `NativeObject` to a `&dyn Any`.\n\...
Rust
src/gpg.rs
dtolnay-contrib/toml-bombadil
635d6ce3a4cb9e068850d260ef5efa8f802a3a04
use crate::templating::Variables; use anyhow::Result; use std::io::Write; use std::path::Path; use std::process::{Command, Stdio}; const PGP_HEADER: &str = "-----BEGIN PGP MESSAGE-----\n\n"; const PGP_FOOTER: &str = "\n-----END PGP MESSAGE-----"; pub(crate) const GPG_PREFIX: &str = "gpg:"; pub struct Gpg { pub us...
use crate::templating::Variables; use anyhow::Result; use std::io::Write; use std::path::Path; use std::process::{Command, Stdio}; const PGP_HEADER: &str = "-----BEGIN PGP MESSAGE-----\n\n"; const PGP_FOOTER: &str = "\n-----END PGP MESSAGE-----"; pub(crate) const GPG_PREFIX: &str = "gpg:"; pub struct Gpg { pub us...
} fn decrypt(&self, content: &str) -> Result<String> { let mut child = Command::new("gpg") .arg("--decrypt") .arg("--armor") .arg("-r") .arg(&self.user_id) .arg("-q") .stdin(Stdio::piped()) .stdout(Stdio::piped()) ...
match output { Ok(output) => { if output.status.success() { Ok(String::from_utf8(output.stdout)?) } else { Err(anyhow!(String::from_utf8(output.stdout)?)) } } Err(err) => Err(anyhow!("Error encryp...
if_condition
[ { "content": "fn print_clone_progress(state: &mut State) {\n\n let stats = state.progress.as_ref().unwrap();\n\n let network_pct = (100 * stats.received_objects()) / stats.total_objects();\n\n let index_pct = (100 * stats.indexed_objects()) / stats.total_objects();\n\n let co_pct = if state.total > ...
Rust
src/vga_buffer.rs
hogum/x86-kernel
e9f89eabd4a78cb9158ca1e7b5607aa96e32d90d
use core::fmt; use lazy_static::lazy_static; use spin::Mutex; use volatile::Volatile; lazy_static! { pub static ref WRITER: Mutex<ScreenWriter> = Mutex::new(ScreenWriter { column_position: 0, colour_code: ColourCode::new(Colour::Yellow, Colour::Black), buffer: unsafe { &mut *(0xb...
use core::fmt; use lazy_static::lazy_static; use spin::Mutex; use volatile::Volatile; lazy_static! { pub static ref WRITER: Mutex<ScreenWriter> = Mutex::new(ScreenWriter { column_position: 0, colour_code: ColourCode::new(Colour::Yellow, Colour::Black), buffer: unsafe { &mut *(0xb...
n!(screen_char_w, "\n{}", s).expect("writeln failed"); for (i, c) in s.chars().enumerate() { let sc_char = screen_char_w.buffer.chars[BUFFER_HEIGHT - 2][i].read(); assert_eq!(char::from(screen_char.ascii_char), c); } serial_println!("[ok]"); }); }
function_block-function_prefixed
[ { "content": "/// Linker entry point\n\npub fn kernel_entry(boot_info: &'static BootInfo) -> ! {\n\n use x86_64::structures::paging::Page;\n\n use x86_64::VirtAddr;\n\n use x86_kernel::memory::{self};\n\n\n\n x86_kernel::init();\n\n\n\n let physical_mem_offset = VirtAddr::new(boot_info.physical_m...
Rust
packages/terra-rust-bot-essentials/src/shared/mod.rs
Philipp-Sc/terra-rust-bot
4ac6e3926c188da527673d56c3d9fd0e6c0d9c0d
use serde::Deserialize; use serde::Serialize; use rust_decimal::Decimal; use std::str::FromStr; use std::fs; use std::io; use std::hash::{Hash}; use serde_json::{Value}; #[derive(Debug)] pub struct Maybe<T> { pub data: anyhow::Result<T>, pub timestamp: i64, } impl<T: Clone> Clone for Maybe<T> { fn clone(&...
use serde::Deserialize; use serde::Serialize; use rust_decimal::Decimal; use std::str::FromStr; use std::fs; use std::io; use std::hash::{Hash}; use serde_json::{Value}; #[derive(Debug)] pub struct Maybe<T> { pub data: anyhow::Result<T>, pub timestamp: i64, } impl<T: Clone> Clone for Maybe<T> { fn clone(&...
pub fn load_user_settings(path: &str) -> UserSettings { let user_settings: UserSettings = match fs::read_to_string(path) { Ok(file) => { match serde_json::from_str(&file) { Ok(res) => { res } Err(err) => { ...
tokens": serde_json::from_str::<Value>(&fs::read_to_string(format!("{}tokens.json", path)).unwrap()).unwrap(), "custom": serde_json::from_str::<Value>(&fs::read_to_string(format!("{}custom.json", path)).unwrap()).unwrap(), }) }
function_block-function_prefix_line
[ { "content": "pub fn pairs_dex(list: &AssetWhitelist, assets: [&str; 2], dex: &str) -> Option<String> {\n\n let none_value = json!(\"None\");\n\n let pairs_list = list.pairs_dex.as_object().unwrap().get(\"mainnet\").unwrap().as_object().unwrap();\n\n for (key, value) in pairs_list {\n\n let valu...
Rust
src/matrix/sync.rs
vmiklos/matrix-ircd
8d75483de992a489b192d6e4960e1b404629c361
use futures::stream::Stream; use futures::{Async, Future, Poll}; use serde_json; use std::io; use super::protocol::SyncResponse; use tokio_core::reactor::Handle; use url::Url; use crate::http::{HttpClient, HttpResponseFuture, Request}; use slog::*; pub struct MatrixSyncClient { url: Url, access_token:...
use futures::stream::Stream; use futures::{Async, Future, Poll}; use serde_json; use std::io; use super::protocol::SyncResponse; use tokio_core::reactor::Handle; use url::Url; use crate::http::{HttpClient, HttpResponseFuture, Request}; use slog::*; pub struct MatrixSyncClient { url: Url, access_token:...
} #[cfg(test)] mod tests { use super::MatrixSyncClient; use futures::Stream; use mockito::{mock, Matcher}; #[test] fn matrix_sync_request() { let base_url = mockito::server_url().as_str().parse::<url::Url>().unwrap(); let access_token = "sample_access_token"; let mut core ...
fn poll(&mut self) -> Poll<Option<SyncResponse>, io::Error> { task_trace!("Matrix Sync Polled"); let res = futures::try_ready!(self.poll_sync()); Ok(Async::Ready(Some(res))) }
function_block-full_function
[ { "content": "fn read_into_vec<R: io::Read>(stream: &mut R, buf: &mut netbuf::Buf) -> Poll<usize, io::Error> {\n\n let size = tokio_core::try_nb!(buf.read_from(stream));\n\n Ok(Async::Ready(size))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use futures::Async;\n\n use std::io::{...
Rust
src/controller/key_event_matcher.rs
Atul9/twilight-commander
87899ae881eecdbbddd6dcf04dbee3121286ce0c
use crate::controller::EventQueue; use crate::model::path_node::PathNode; use crate::model::tree_index::TreeIndex; use std::io::Write; use termion::event::Key; impl<W: Write> EventQueue<W> { pub fn match_key_event(&mut self, key: Key) -> Option<()> { match key { Key::Char('q') => self.do_quit()...
use crate::controller::EventQueue; use crate::model::path_node::PathNode; use crate::model::tree_index::TreeIndex; use std::io::Write; use termion::event::Key; impl<W: Write> EventQueue<W> { pub fn match_key_event(&mut self, key: Key) -> Option<()> { match key { Key::Char('q') => self.do_quit()...
assert!(result.is_none()); } #[test] fn match_key_event_r_test() { let result = { let mut event_queue = prepare_event_queue(); event_queue.match_key_event(Key::Char('r')) }; assert!(result.is_some()); } #[test] fn match_key_event_retur...
let result = { let mut event_queue = prepare_event_queue(); event_queue.match_key_event(Key::Char('q')) };
assignment_statement
[ { "content": "pub fn read_file(file_name: &str) -> std::io::Result<String> {\n\n let mut file = File::open(file_name)?;\n\n let mut contents = String::new();\n\n file.read_to_string(&mut contents)?;\n\n Ok(contents)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 0, "score": 65835.1212...
Rust
ts-bindgen-gen/src/codegen/named.rs
ratchetdesigns/ts-bindgen
1e81e05f21967d44c88e9ad1aaecafb80c31b86f
use crate::codegen::funcs::Constructor; use crate::codegen::ns_path::ToNsPath; use crate::codegen::resolve_target_type::ResolveTargetType; use crate::fs::Fs; use crate::identifier::{ make_identifier, to_camel_case_ident, to_ident, to_snake_case_ident, Identifier, }; use crate::ir::{Builtin, Func, TargetEnrichedType...
use crate::codegen::funcs::Constructor; use crate::codegen::ns_path::ToNsPath; use crate::codegen::resolve_target_type::ResolveTargetType; use crate::fs::Fs; use crate::identifier::{ make_identifier, to_camel_case_ident, to_ident, to_snake_case_ident, Identifier, }; use crate::ir::{Builtin, Func, TargetEnrichedType...
&FS, ns_base: &T, ) -> (&str, Identifier) { let ns = self.to_ns_path(fs, ns_base); name_for_type_ref(self, &ns) } } trait JsName { fn js_name(&self) -> &str; } impl JsName for Builtin { fn js_name(&self) -> &str { self.to_name().0 } } impl JsName for TypeIdent { ...
HashMap<String, JsValue>), ), Builtin::Optional => ("Option", to_ident("Option")), Builtin::Variadic => ("", to_ident("")), Builtin::Named(n) => (n, Identifier::with_path(n)), } } fn to_rel_qualified_name<FS: Fs + ?Sized, T: ToModPathIter>( &self,...
random
[ { "content": "pub fn to_unique_ident<T: Fn(&str) -> bool>(mut desired: String, taken: &T) -> Identifier {\n\n while taken(&desired) {\n\n desired += \"_\";\n\n }\n\n\n\n to_ident(&desired)\n\n}\n\n\n\n#[cfg(test)]\n\nmod ident_tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn snake_case_...
Rust
decoder.rs
lewinzki/hpack
c2b3dd128735b0c599686ef9dc648b0ccf884664
use std::str; use header_table::{HeaderTable, DEFAULT_HEADER_TABLE_SIZE}; use header_set::HeaderSet; use reference_set::ReferenceSet; use integer_representation::decode_int; use header_field::HeaderField; use header_collection::HeaderCollection; use static_header_table::StaticHeaderTable; use huffman::huffman_decode...
use std::str; use header_table::{HeaderTable, DEFAULT_HEADER_TABLE_SIZE}; use header_set::HeaderSet; use reference_set::ReferenceSet; use integer_representation::decode_int; use header_field::HeaderField; use header_collection::HeaderCollection; use static_header_table::StaticHeaderTable; use huffman::huffman_decode...
Some(buffer) } /* * Reads a string from the header block (and consumes it) */ fn read_string(&mut self, mut header_block: ~[u8]) -> Option<(~[u8], ~[u8])> { let mut string; let huffman_encoded = header_block[0] & 0x80 == 0x80; let (string_length, buffer) ...
> x, None => return None, } ); ) pub struct Decoder { priv header_table: ~HeaderTable, priv reference_set: ~ReferenceSet, priv header_set: ~HeaderSet, priv static_header_table: ~StaticHeaderTable, priv huffman_decoder: HuffmanDecoder, } impl Dec...
random
[ { "content": " // Remeber, HPACK uses 1-indexing!!!\n\n pub fn get(&self, index: uint) -> Option<HeaderField> {\n\n if index < 1 || index > self.fields.len() {\n\n return None;\n\n }\n\n\n\n Some(self.fields[index - 1].clone())\n\n }\n\n\n\n // Search for a header fie...
Rust
src/client/src/fluvio.rs
avinassh/fluvio
acf2c6a2fd30981674ca025acc63706a75b8b530
use std::convert::TryFrom; use std::sync::Arc; use tracing::debug; use once_cell::sync::OnceCell; use fluvio_socket::{AllMultiplexerSocket, SharedAllMultiplexerSocket}; use fluvio_future::task::run_block_on; use fluvio_future::native_tls::AllDomainConnector; use semver::Version; use crate::config::ConfigFile; use cr...
use std::convert::TryFrom; use std::sync::Arc; use tracing::debug; use once_cell::sync::OnceCell; use fluvio_socket::{AllMultiplexerSocket, SharedAllMultiplexerSocket}; use fluvio_future::task::run_block_on; use fluvio_future::native_tls::AllDomainConnector; use semver::Version; use crate::config::ConfigFile; use cr...
pub async fn partition_consumer<S: Into<String>>( &self, topic: S, partition: i32, ) -> Result<PartitionConsumer, FluvioError> { let topic = topic.into(); debug!(top...
pub async fn topic_producer<S: Into<String>>( &self, topic: S, ) -> Result<TopicProducer, FluvioError> { let topic = topic.into(); debug!(topic = &*topic, "Creating producer"); Ok(TopicProducer::new(topic, self.spu_pool()?)) }
function_block-full_function
[ { "content": "/// Prompt the user about a new available version of the Fluvio CLI\n\npub fn prompt_available_update(latest_version: &Version) {\n\n println!();\n\n println!(\"💡 An update to Fluvio is available!\");\n\n println!(\n\n \"💡 Run 'fluvio update' to install v{} of Fluvio\",\n\n ...
Rust
src/imp/libc/net/read_sockaddr.rs
sunfishcode/posish
bbcd131a0d95bc57ce52af659fb209c8b90c65d8
use super::super::c; #[cfg(unix)] use super::addr::SocketAddrUnix; use super::ext::{in6_addr_s6_addr, in_addr_s_addr, sockaddr_in6_sin6_scope_id}; #[cfg(not(windows))] use crate::as_ptr; #[cfg(not(windows))] use crate::ffi::ZStr; use crate::io; use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddrAny, SocketAddrV4, SocketAdd...
use super::super::c; #[cfg(unix)] use super::addr::SocketAddrUnix; use super::ext::{in6_addr_s6_addr, in_addr_s_addr, sockaddr_in6_sin6_scope_id}; #[cfg(not(windows))] use crate::as_ptr; #[cfg(not(windows))] use crate::ffi::ZStr; use crate::io; use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddrAny, SocketAddrV4, SocketAdd...
pub(crate) unsafe fn maybe_read_sockaddr_os( storage: *const c::sockaddr_storage, len: usize, ) -> Option<SocketAddrAny> { if len == 0 { return None; } assert!(len >= size_of::<c::sa_family_t>()); let family = read_ss_family(storage).into(); if family == c::AF_UNSPEC { Non...
t), ))) } c::AF_INET6 => { if len < size_of::<c::sockaddr_in6>() { return Err(io::Error::INVAL); } let decode = *storage.cast::<c::sockaddr_in6>(); #[cfg(not(windows))] let s6_addr = decode.sin6_addr.s6_addr; ...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn read<Fd: AsFd>(fd: Fd, buf: &mut [u8]) -> io::Result<usize> {\n\n imp::io::syscalls::read(fd.as_fd(), buf)\n\n}\n\n\n\n/// `write(fd, buf)`—Writes to a stream.\n\n///\n\n/// # References\n\n/// - [POSIX]\n\n/// - [Linux]\n\n///\n\n/// [POSIX]: https://pubs.opengroup.org/on...
Rust
src/glyph_extension.rs
StT191/rust-wgx
0b4948ae85ac8d9a9d43610cba20ed39c89632c8
use crate::{Wgx, DEPTH, RenderAttachment}; use cgmath::Matrix4; use wgpu_glyph::{*, ab_glyph::{FontArc, InvalidFont}}; use wgpu::util::StagingBelt; pub trait WgxGlyphBrushBuilderExtension { fn glyph_brush(&self, format:wgpu::TextureFormat, font_data:Vec<u8>) -> Result<GlyphBrush<(), FontArc>, InvalidFont>...
use crate::{Wgx, DEPTH, RenderAttachment}; use cgmath::Matrix4; use wgpu_glyph::{*, ab_glyph::{FontArc, InvalidFont}}; use wgpu::util::StagingBelt; pub trait WgxGlyphBrushBuilderExtension { fn glyph_brush(&self, format:wgpu::TextureFormat, font_data:Vec<u8>) -> Result<GlyphBrush<(), FontArc>, InvalidFont>...
layout { section = section.with_layout(layout); } self.queue(section); } } pub trait EncoderGlyphDrawExtension { fn draw_glyphs( &mut self, wgx:&Wgx, attachment:&RenderAttachment, glypths:&mut GlyphBrush<()>, transform:Matrix4<f32>, region:Option<[u32; 4]>, staging_belt:Option<&mut St...
from_vec(font_data)?; Ok(self.add_font(font)) } fn add_text( &mut self, text:Vec<Text>, position:Option<(f32, f32)>, bounds:Option<(f32, f32)>, layout:Option<Layout<BuiltInLineBreaker>>) { let mut section = Section { text, ..Section::default()}; if let Some(position...
random
[ { "content": "pub fn flat_window_projection(width: f32, height: f32, depth: f32) -> Mat4 {\n\n Mat4::from_translation([-1.0, 1.0, 0.0].into()) *\n\n Mat4::from_scale([\n\n 2.0 / width, -2.0 / height, if depth == 0.0 { 0.0 } else { 1.0 / depth },\n\n ].into())\n\n}\n\n\n\n\n\n\n\n// utilities\n\n...
Rust
examples/server/main.rs
jurplel/libsynchro
f0a5d517f2d9563d1b15d7eca3299f356621260e
use libsynchro::{SynchroConnection, Event, Command}; use std::collections::HashMap; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use futures_channel::mpsc; use async_std::prelude::*; use async_std::net::{TcpListener, TcpStream}; use async_std::task; struct ClientInfo { name: Option<String>, file_s...
use libsynchro::{SynchroConnection, Event, Command}; use std::collections::HashMap; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use futures_channel::mpsc; use async_std::prelude::*; use async_std::net::{TcpListener, TcpStream}; use async_std::task; struct ClientInfo { name: Option<String>, file_s...
fn send_client_list_to_all( client_hashmap: &ClientHashmapArc ) -> Result<(), Box<dyn std::error::Error>> { let retrieved_list = get_list_of_clients(client_hashmap)?; let mut clients = client_hashmap.lock().unwrap(); for info in clients.values_mut() { let sender = info.unbounded_sender.as_ref(...
fn get_list_of_clients( client_hashmap: &ClientHashmapArc ) -> Result<String, Box<dyn std::error::Error>> { let clients = client_hashmap.lock().unwrap(); let mut client_list = String::new(); for key in clients.keys() { if !client_list.is_empty() { client_list.push_str(","); ...
function_block-full_function
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n task::block_on(connect())\n\n}\n\n\n\nasync fn connect() -> Result<(), Box<dyn std::error::Error>> {\n\n let args: Vec<String> = env::args().collect();\n\n let addr_str;\n\n if args.len() < 2 {\n\n addr_str = \"127.0.0.1:...
Rust
src/test/instruction_tests/instr_vpandq.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpandq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPANDQ, opera...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpandq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPANDQ, opera...
#[test] fn vpandq_13() { run_test( &Instruction { mnemonic: Mnemonic::VPANDQ, operand1: Some(Direct(ZMM3)), operand2: Some(Direct(ZMM6)), operand3: Some(Direct(ZMM2)), operand4: None, lock: false, rounding_mode: None, ...
mnemonic: Mnemonic::VPANDQ, operand1: Some(Direct(YMM11)), operand2: Some(Direct(YMM7)), operand3: Some(IndirectScaledIndexed( RSI, RDX, Four, Some(OperandSize::Qword), None, )), o...
function_block-function_prefix_line
[ { "content": "fn encode16_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
src/event/events.rs
codec-abc/kas
5193ecd446e2147e7eb60e0081c1f66af049f244
#[allow(unused)] use super::{GrabMode, Manager, Response}; use super::{MouseButton, UpdateHandle, VirtualKeyCode}; use crate::geom::{Coord, DVec2}; use crate::{WidgetId, WindowId}; #[non_exhaustive] #[derive(Clone, Debug, PartialEq)] pub enum Event { None, Activate, ...
#[allow(unused)] use super::{GrabMode, Manager, Response}; use super::{MouseButton, UpdateHandle, VirtualKeyCode}; use crate::geom::{Coord, DVec2}; use crate::{WidgetId, WindowId}; #[non_exhaustive] #[derive(Clone, Debug, PartialEq)] pub enum Event { None, Activate, ...
(self) -> bool { match self { PressSource::Mouse(button, _) => button == MouseButton::Left, PressSource::Touch(_) => true, } } #[inline] pub fn is_touch(self) -> bool { match self { PressSource::Touch(_) => true, _ => false, ...
NavigateBackward => CK::Backward, NumpadEnter => CK::Return, Tab => CK::Tab, Cut => CK::Cut, Copy => CK::Copy, Paste => CK::Paste, _ => return None, }) } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PressSource...
random
[ { "content": "#[derive(Clone, Debug)]\n\nenum Pending {\n\n LostCharFocus(WidgetId),\n\n}\n\n\n\n/// Event manager state\n\n///\n\n/// This struct encapsulates window-specific event-handling state and handling.\n\n/// Most operations are only available via a [`Manager`] handle, though some\n\n/// are availab...
Rust
src/graphql/mutation_root.rs
sha-el/vouch
52be3988c1a189809b1782c76dc8f1cd38361366
use async_graphql::{Context, FieldResult, Object}; use vouch_lib::{auth::login, beatrix::bson::oid::ObjectId}; use super::{ application::{ApplicationMutationInput, ApplicationNode}, check_auth, group::{GroupMutationInput, GroupNode}, organization::{self, OrganizationMutationInput, OrganizationNode}, ...
use async_graphql::{Context, FieldResult, Object}; use vouch_lib::{auth::login, beatrix::bson::oid::ObjectId}; use super::{ application::{ApplicationMutationInput, ApplicationNode}, check_auth, group::{GroupMutationInput, GroupNode}, organization::{self, OrganizationMutationInput, OrganizationNode}, ...
}
g( &self, ctx: &Context<'_>, id: ObjectId, user_ids: Vec<ObjectId>, ) -> FieldResult<OrganizationNode> { check_auth(ctx)?; organization::add_users(&id, user_ids).await }
function_block-function_prefixed
[ { "content": "pub fn check_auth(context: &Context<'_>) -> FieldResult<Session> {\n\n match context.data_opt::<Session>() {\n\n Some(session) => Ok(session.clone()),\n\n None => Err(Error(ServiceError::Unauthorized(\"Invalid token\".into())).extend()),\n\n }\n\n}\n", "file_path": "src/gra...
Rust
src/client/parser.rs
planet-s/actix-web
ed9971b2128ec7a8b1455fc67123613cc38420d6
use bytes::{Bytes, BytesMut}; use futures::{Async, Poll}; use http::header::{self, HeaderName, HeaderValue}; use http::{HeaderMap, HttpTryFrom, StatusCode, Version}; use httparse; use std::mem; use error::{ParseError, PayloadError}; use server::h1::{chunked, Decoder}; use server::{utils, IoStream}; use super::Client...
use bytes::{Bytes, BytesMut}; use futures::{Async, Poll}; use http::header::{self, HeaderName, HeaderValue}; use http::{HeaderMap, HttpTryFrom, StatusCode, Version}; use httparse; use std::mem; use error::{ParseError, PayloadError}; use server::h1::{chunked, Decoder}; use server::{utils, IoStream}; use super::Client...
}
debug!("illegal Content-Length: {:?}", len); return Err(ParseError::Header); } } else if chunked(&hdrs)? { Some(Decoder::chunked()) } else { None }; if let Some(decoder) = decoder { Ok(Async::Ready(( ...
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn apply_mask(buf: &mut [u8], mask: u32) {\n\n apply_mask_fast32(buf, mask)\n\n}\n\n\n\n/// A safe unoptimized mask application.\n", "file_path": "src/ws/mask.rs", "rank": 0, "score": 291511.10668398155 }, { "content": "#[inline]\n\n#[allow(dead_code)]\n\nfn...
Rust
zinc-compiler/src/lexical/tests.rs
sunny-g/zinc
302a9ea570ba34e980fdeb313426e7c404c1cf4e
#![cfg(test)] use crate::lexical::error::Error; use crate::lexical::stream::TokenStream; use crate::lexical::token::lexeme::identifier::Identifier; use crate::lexical::token::lexeme::keyword::Keyword; use crate::lexical::token::lexeme::literal::integer::Integer; use crate::lexical::token::lexeme::literal::Literal; u...
#![cfg(test)] use crate::lexical::error::Error; use crate::lexical::stream::TokenStream; use crate::lexical::token::lexeme::identifier::Identifier; use crate::lexical::token::lexeme::keyword::Keyword; use crate::lexical::token::lexeme::literal::integer::Integer; use crate::lexical::token::lexeme::literal::Literal; u...
) { let input = "0o378"; let expected: Result<Token, Error> = Err(Error::expected_one_of_octal(Location::new(1, 5), '8')); let result = TokenStream::new(input).next(); assert_eq!(result, expected); } #[test] fn error_expected_one_of_decimal() { let input = "42x"; let expected: Resul...
_one_of_binary() { let input = "0b102"; let expected: Result<Token, Error> = Err(Error::expected_one_of_binary(Location::new(1, 5), '2')); let result = TokenStream::new(input).next(); assert_eq!(result, expected); } #[test] fn error_expected_one_of_octal(
random
[]
Rust
src/armour-host/src/instance.rs
ARM-software/armour
018c37a9ee756a78219e1a1f61147caa9be28743
/* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights ...
/* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights ...
e { pub id: usize, pub host: Addr<ArmourDataHost>, pub uds_framed: actix::io::FramedWrite<PolicyRequest, WriteHalf<tokio::net::UnixStream>, HostCodec>, } impl Actor for ArmourDataInstance { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { sel...
e { n.to_string() } }) .collect::<Vec<String>>() .join(","); write!(f, "[{}]", s) } } pub struct ArmourDataInstanc
random
[ { "content": "/// Escape tags in such a way that it is suitable for inclusion in a\n\n/// Graphviz HTML label.\n\npub fn escape_html(s: &str) -> String {\n\n s.replace(\"&\", \"&amp;\")\n\n .replace(\"\\\"\", \"&quot;\")\n\n .replace(\"<\", \"&lt;\")\n\n .replace(\">\", \"&gt;\")\n\n}\n\...
Rust
src/transfer.rs
paavohuhtala/pneumatic
2d6720217d7283feb6c5ed7ca938cea202c8f4ab
use crate::config::ServerConfig; use async_trait::async_trait; use crossbeam::queue::SegQueue; use futures::future; use serde::{Deserialize, Serialize}; use std::{ path::{Path, PathBuf}, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, time::SystemTime, }; use tokio::fs::read_dir; #[deriv...
use crate::config::ServerConfig; use async_trait::async_trait; use crossbeam::queue::SegQueue; use futures::future; use serde::{Deserialize, Serialize}; use std::{ path::{Path, PathBuf}, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, time::SystemTime, }; use tokio::fs::read_dir; #[deriv...
} }; let mut file_stream = read_dir(path).await?; let mut files = Vec::new(); while let Some(entry) = file_stream.next_entry().await? { let file_type = entry.file_type().await?; ...
fn root(&self) -> &std::path::Path; fn convert_metadata(&self, path: &std::path::Path, metadata: Self::Metadata) -> FileMetadata; async fn discover_files_recursively( self: Arc<Self>, path: PathBuf, output: tokio::sync::mpsc::Sender<DiscoveryMessage>, ) -> Result<(), anyhow::Erro...
random
[ { "content": "pub trait FileSystem: Send + Sync {\n\n fn list_files(&self, path: &std::path::Path, output: &mut Vec<std::path::PathBuf>);\n\n}\n\n\n\npub struct MockFileSystem {}\n\n\n\nimpl MockFileSystem {\n\n pub fn new() -> Self {\n\n MockFileSystem {}\n\n }\n\n}\n\n\n\nimpl FileSystem for M...
Rust
src/parse.rs
lukakerr/mdtg
89370952e1a99ad50072208226696d7d99a7d7ff
use tokenize::Token; #[derive(Debug, Clone, PartialEq)] pub enum AST { Column(usize), Row(usize), Position(char), Cross, Table, } #[derive(Debug, Clone, PartialEq)] pub struct Node { pub children: Vec<Node>, pub item: AST, } impl Node { pub fn new(item: AST) -> Node { Nod...
use tokenize::Token; #[derive(Debug, Clone, PartialEq)] pub enum AST { Column(usize), Row(usize), Position(char), Cross, Table, } #[derive(Debug, Clone, PartialEq)] pub struct Node { pub children: Vec<Node>, pub item: AST, } impl Node { pub fn new(item: AST) -> Node { Nod...
}
assert_eq!( parse(tokens), Err("Number of positions exceed number of columns".to_string()) ); }
function_block-function_prefix_line
[ { "content": "fn gen_positions(ast: &Node, output: &mut String) {\n\n if let AST::Column(c) = ast.item {\n\n let positional_row = |left, right| [left, DASHES, right].concat();\n\n\n\n for i in 0..c {\n\n output.push_str(\"|\");\n\n\n\n if let Some(position_node) = ast.chil...
Rust
day-7/src/main.rs
CryZe/AdventOfCode
c62f3cddfefd703c7a5b8dc89439a56cdffe33dd
use std::collections::HashMap; use std::ops::Not; use std::str::FromStr; use std::path::Path; use std::fs::File; use std::io::prelude::*; use Expression::*; struct CPU { registers: HashMap<String, Expression>, cache: HashMap<String, Option<u16>>, } #[derive(Debug, PartialEq, Clone)] enum Expression { Reg...
use std::collections::HashMap; use std::ops::Not; use std::str::FromStr; use std::path::Path; use std::fs::File; use std::io::prelude::*; use Expression::*; struct CPU { registers: HashMap<String, Expression>, cache: HashMap<String, Option<u16>>, } #[derive(Debug, PartialEq, Clone)] enum Expression { Reg...
#[test] fn test_execute() { let mut cpu = CPU::new(); cpu.insert(Instruction::parse("NOT y -> i")); cpu.insert(Instruction::parse("x OR y -> e")); cpu.insert(Instruction::parse("123 -> x")); cpu.insert(Instruction::parse("456 -> y")); cpu.insert(Instruction::parse("x AND y -> d")); cpu.ins...
And(Box::new(Register("x".to_owned())), Box::new(Register("y".to_owned()))))); assert_eq!(Instruction::parse("x OR y -> e"), Instruction::new("e", Or(Box::new(Register("x".to_owned())), Box::new(Reg...
function_block-function_prefix_line
[ { "content": "fn read_file(path: &Path) -> String {\n\n let mut input = String::new();\n\n let mut file = File::open(path).expect(\"File could not be found.\");\n\n file.read_to_string(&mut input).expect(\"File could not be read.\");\n\n input\n\n}\n\n\n", "file_path": "day-13/src/main.rs", ...
Rust
tests/c_api_experimental_test.rs
songww/tensorflow-lite-sys
edd6295a76283927ee0962d28308d5401e5adf23
#![cfg(feature = "experimental")] use std::ffi::{c_void, CStr, CString}; use std::mem::size_of; use std::os::raw::c_char; use vsprintf::vsprintf; use tensorflow_lite_sys as ffi; extern "C" fn registration_invoke( _: *mut ffi::TfLiteContext, _: *mut ffi::TfLiteNode, ) -> ffi::TfLiteStatus { ffi::TfLiteSt...
#![cfg(feature = "experimental")] use std::ffi::{c_void, CStr, CString}; use std::mem::size_of; use std::os::raw::c_char; use vsprintf::vsprintf; use tensorflow_lite_sys as ffi; extern "C" fn registration_invoke( _: *mut ffi::TfLiteContext, _: *mut ffi::TfLiteNode, ) -> ffi::TfLiteStatus { ffi::TfLiteSt...
#[test] fn c_api_experimental_selected_builtins_test() { unsafe { let path = CString::new("testdata/add.bin").unwrap(); let model: *mut ffi::TfLiteModel = ffi::TfLiteModelCreateFromFile(path.as_ptr()); assert!(!model.is_null()); let options: *mut ffi::TfLiteInterpreterOptions = ff...
fn c_api_experimental_smoke_test() { unsafe { let path = CString::new("testdata/add.bin").unwrap(); let model: *mut ffi::TfLiteModel = ffi::TfLiteModelCreateFromFile(path.as_ptr()); assert!(!model.is_null()); let options: *mut ffi::TfLiteInterpreterOptions = ffi::TfLiteInterpreterOp...
function_block-full_function
[ { "content": "#[test]\n\nfn test_version() {\n\n // Test the TfLiteVersion function.\n\n let version = unsafe {\n\n let version: *const c_char = ffi::TfLiteVersion();\n\n CStr::from_ptr(version)\n\n };\n\n println!(\"Version = {:?}\", version);\n\n if cfg!(feature = \"v2.4\") {\n\n ...
Rust
src/sorts/msd_sort.rs
lakwet/voracious_sort
682af6acafa1dd1011601e760b3e42cc081486e6
use super::super::algo::k_way_merge::k_way_merge; use super::super::algo::verge_sort_heuristic::verge_sort_preprocessing; use super::super::{RadixKey, Radixable}; use super::utils::{get_histogram, prefix_sums, Params}; const UNROLL_SIZE: usize = 4; #[inline] pub fn copy_by_histogram<T, K>( size: usize, source...
use super::super::algo::k_way_merge::k_way_merge; use super::super::algo::verge_sort_heuristic::verge_sort_preprocessing; use super::super::{RadixKey, Radixable}; use super::utils::{get_histogram, prefix_sums, Params}; const UNROLL_SIZE: usize = 4; #[inline] pub fn copy_by_histogram<T, K>( size: usize, source...
pub fn msd_radixsort<T: Radixable<K>, K: RadixKey>( arr: &mut [T], radix: usize, ) { if arr.len() <= 128 { arr.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); return; } let mut separators = verge_sort_preprocessing(arr, radix, &msd_radixsort_aux); k_way_merge(arr, ...
fn msd_radixsort_aux<T: Radixable<K>, K: RadixKey>( arr: &mut [T], radix: usize, ) { if arr.len() <= 128 { arr.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); return; } let dummy = arr[0]; let (_, raw_offset) = dummy.compute_offset(arr, radix); let max_level = dummy.comp...
function_block-full_function
[ { "content": "pub fn fallback<T: Radixable<K>, K: RadixKey>(arr: &mut [T], p: Params) {\n\n let size = arr.len();\n\n // It is a fallback, we don't want to sort big array.\n\n assert!(size <= 128_000);\n\n\n\n if size <= 256 {\n\n arr.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());\n\n ...
Rust
src/lib.rs
jamestjw/rcc
3710b5184276698ecb8ff45340cca20b076ed426
pub mod code_generation; pub mod debug; pub mod parser; pub mod scanner; pub mod string_table; pub mod token; use crate::parser::{DataType, SymClass, SymType, SymbolTableEntry}; use code_generation::Generator; use std::path::Path; use std::process::Command; #[macro_export] macro_rules! enum_str { (#[derive($($t...
pub mod code_generation; pub mod debug; pub mod parser; pub mod scanner; pub mod string_table; pub mod token; use crate::parser::{DataType, SymClass, SymType, SymbolTableEntry}; use code_generation::Generator; use std::path::Path; use std::process::Command; #[macro_export] macro_rules! enum_str { (#[derive($($t...
const fn num_bits<T>() -> usize { std::mem::size_of::<T>() * 8 } pub fn log_2(u: u32) -> u32 { num_bits::<u32>() as u32 - u.leading_zeros() - 1 }
e .arg("-o") .arg(output_fname) .arg(input_fname) .arg("src/extras/print.c"); assemble .status() .expect("Failed to execute assembler and linker"); }
function_block-function_prefixed
[ { "content": "// Return a String containing what was written to stdout during execution of a file\n\n// TODO: Consider making this return a result and move it to lib if we need it elsewhere,\n\n// otherwise it is probably find to retain the calls to expect() and panic!() here.\n\npub fn execute_file(input_fname...
Rust
src/platform.rs
jsatka/opencl3
ab0b02edaefa5e6a641b696d9d005f6b36ade40a
use cl3::device; use cl3::platform; use cl3::program; use cl3::types::{ cl_device_id, cl_device_type, cl_int, cl_name_version, cl_platform_id, cl_ulong, cl_version, }; use std::ffi::CString; pub struct Platform { id: cl_platform_id, } impl Platform { pub fn new(id: cl_platform_id) -> Platform { ...
use cl3::device; use cl3::platform; use cl3::program; use cl3::types::{ cl_device_id, cl_device_type, cl_int, cl_name_version, cl_platform_id, cl_ulong, cl_version, }; use std::ffi::CString; pub struct Platform { id: cl_platform_id, } impl Platform { pub fn new(id: cl_platform_id) -> Platform { ...
#[cfg(test)] mod tests { use super::*; use crate::error_codes::error_text; #[test] fn test_get_platforms() { let platforms = get_platforms().unwrap(); println!("Number of platforms: {}", platforms.len()); assert!(0 < platforms.len()); for platform in platforms { ...
c<Platform> = Vec::with_capacity(platform_ids.len()); for id in platform_ids.iter() { platforms.push(Platform::new(*id)); } Ok(platforms) }
function_block-function_prefixed
[ { "content": "pub fn get_mem_uses_svm_pointer(memobj: cl_mem) -> Result<cl_uint, cl_int> {\n\n let value = memory::get_mem_object_info(memobj, MemInfo::CL_MEM_USES_SVM_POINTER)?;\n\n Ok(value.to_uint())\n\n}\n\n\n", "file_path": "src/memory.rs", "rank": 1, "score": 88217.85419898931 }, { ...
Rust
src/models/transaction/deadline.rs
proximax-storage/rust-xpx-chain-sdk
55613067328d511dbd9a129be30b9e048ef79175
/* * Copyright 2018 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ use { ::std::{ ops::Add, time::{Duration, SystemTime, UNIX_EPOCH}, }, chrono::{ prelude::DateTime, {Loca...
/* * Copyright 2018 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ use { ::std::{ ops::Add, time::{Duration, SystemTime, UNIX_EPOCH}, }, chrono::{ prelude::DateTime, {Loca...
} impl Default for Deadline { fn default() -> Self { Deadline::new(1, 0, 0) } }
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&format!("{}", self)) }
function_block-full_function
[ { "content": "pub fn array_u8_to_u64(bytes: &[u8]) -> u64 {\n\n (bytes[0] as u64)\n\n | (bytes[1] as u64) << 8\n\n | (bytes[2] as u64) << 16\n\n | (bytes[3] as u64) << 24\n\n | (bytes[4] as u64) << 32\n\n | (bytes[5] as u64) << 40\n\n | (bytes[6] as u64) << 48\n\n ...
Rust
examples/hello_world/src/main.rs
bonedaddy/i2p-rs
bd905b37663883e6fd961034bdf0193da0804d9c
use crossbeam::sync::WaitGroup; use env_logger; use i2p; use crossbeam_channel::select; use i2p::net::{I2pListener, I2pStream}; use i2p::sam_options::{ I2CPClientOptions, I2CPOptions, I2CPRouterOptions, I2CPTunnelInboundOptions, I2CPTunnelOutboundOptions, SAMOptions, SignatureType, }; use log::*; use std::io::{Read,...
use crossbeam::sync::WaitGroup; use env_logger; use i2p; use crossbeam_channel::select; use i2p::net::{I2pListener, I2pStream}; use i2p::sam_options::{ I2CPClientOptions, I2CPOptions, I2CPRouterOptions, I2CPTunnelInboundOptions, I2CPTunnelOutboundOptions, SAMOptions, SignatureType, }; use log::*; use std::io::{Read,...
ccept connection {:#?}", err); } } std::thread::sleep(std::time::Duration::from_millis(125)); } }); } info!("waiting 10 seconds for tunnel things to happen"); std::thread::sleep(std::time::Duration::from_secs(10)); let mut client_conn = match I2pStream::connect(&format!("{}:0", pubkey))...
select! { recv(rx) -> _msg => { warn!("server received exit signal, goodbye..."); match sam_session.sam.conn.shutdown(Shutdown::Both) { Ok(_) => info!("server shutdown ok"), Err(err) => error!("server failed to properly shutdown {:#?}", err) } drop(wg); ...
random
[ { "content": "fn main() {\n\n\tenv_logger::init();\n\n\n\n\t// start a TCP server that will get forwards from i2p\n\n\tlet server = I2pListener::bind().unwrap();\n\n\tlet our_dest = server.local_addr().unwrap();\n\n\tthread::spawn(move || {\n\n\t\tfor stream in server.incoming() {\n\n\t\t\tmatch stream {\n\n\t\...
Rust
src/plugins.rs
StarryInternet/collectd-rust-plugin
fc7a8b229ba854638b645948a5c254d0875be8e0
use api::{ConfigItem, LogLevel, ValueList}; use chrono::Duration; use errors::NotImplemented; use failure::Error; bitflags! { #[derive(Default)] pub struct PluginCapabilities: u32 { const READ = 0b0000_0001; const LOG = 0b0000_0010; const WRITE = 0b0000_0100; const FL...
use api::{ConfigItem, LogLevel, ValueList}; use chrono::Duration; use errors::NotImplemented; use failure::Error; bitflags! { #[derive(Default)] pub struct PluginCapabilities: u32 { const READ = 0b0000_0001; const LOG = 0b0000_0010; const WRITE = 0b0000_0100; const FL...
inCapabilities::READ; assert_eq!(capabilities.has_read(), true); assert_eq!(capabilities.has_write(), false); } }
EAD | PluginCapabilities::WRITE; assert_eq!(capabilities.has_read(), true); assert_eq!(capabilities.has_write(), true); let capabilities = Plug
function_block-random_span
[ { "content": "/// Sends message and log level to collectd. Collectd configuration determines if a level is logged\n\n/// and where it is delivered. Messages that are too long are truncated (1024 was the max length as\n\n/// of collectd-5.7).\n\n///\n\n/// # Panics\n\n///\n\n/// If a message containing a null ch...
Rust
src/view_models/transaction_data_vm.rs
Josef212/GitGud-Greedy
b99054618c43c528558b09a4b241b624a58420f9
use std::collections::HashMap; use crate::Db; use crate::models::transaction::Transaction; use comfy_table::{Table, Row, ContentArrangement, Cell, Attribute, Color}; use comfy_table::presets::UTF8_FULL; use comfy_table::modifiers::UTF8_ROUND_CORNERS; struct TagInfo { id: i32, count: usize, amount: f32, } ...
use std::collections::HashMap; use crate::Db; use crate::models::transaction::Transaction; use comfy_table::{Table, Row, ContentArrangement, Cell, Attribute, Color}; use comfy_table::presets::UTF8_FULL; use comfy_table::modifiers::UTF8_ROUND_CORNERS; struct TagInfo { id: i32, count: usize, amount: f32, } ...
pub fn plot(&self, _db: &Db) { } fn recap(&self) { let mut table = TransactionDataVm::create_table(vec!["Total", "Tags count", "Avg. price"]); table.add_row(vec![ Cell::new(format!("{:.2}", self.total_amount)), Cell::new(format!("{}", self.tags_inf...
g"]); for t in self.transactions { let tag = db.get_tag_str(t.tag_id).unwrap_or(String::from("Unknown")); table.add_row(vec![ Cell::new(t._id), Cell::new(&t.name), Cell::new(&t.date), Cell::new(t.amount), Ce...
function_block-function_prefixed
[ { "content": "fn load_db(db_name: &str) -> Db {\n\n match Db::load(db_name) {\n\n Err(e) => {\n\n log::error!(\"Error loading db [{}]: {}\", db_name, e);\n\n std::process::exit(1);\n\n },\n\n Ok(db) => return db\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", ...
Rust
src/handlers/primary/shim.rs
ALinuxPerson/try-drop
1b2ac32ba746747f3af51278a689d19a94261691
#[cfg(feature = "ds-write")] mod imp { use super::ShimPrimaryHandler; use crate::drop_strategies::WriteDropStrategy; use crate::handlers::common::handler::CommonHandler; use crate::handlers::common::shim::UseDefaultOnUninitShim; use crate::handlers::common::Primary; use crate::FallibleTryDrop...
#[cfg(feature = "ds-write")] mod imp { use super::ShimPrimaryHandler; use crate::drop_strategies::WriteDropStrategy; use crate::handlers::common::handler::CommonHandler; use crate::handlers::common::shim::UseDefaultOnUninitShim; use crate::handlers::common::Primary; use crate::FallibleTryDrop...
} } impl FallibleTryDropStrategy for ShimPrimaryHandler<ErrorOnUninit> { type Error = anyhow::Error; fn try_handle_error(&self, error: crate::Error) -> Result<(), Self::Error> { self.on_all_uninit(error, |uninit_error, _| Err(uninit_error)) } } impl FallibleTryDropStrategy for ShimPrimaryHan...
match self .thread_local .try_handle_error(ArcError::clone(&error).into()) { Ok(()) => Ok(()), Err(_) if self.thread_local.last_drop_failed() => { match self.global.try_handle_error(ArcError::clone(&error).into()) { Ok(()) => Ok...
if_condition
[ { "content": "/// Signifies that this type can be converted into an [`AdHocMutDropStrategy`].\n\npub trait IntoAdHocMutDropStrategy: FnMut(crate::Error) + Sized {\n\n /// Convert this type into an [`AdHocMutDropStrategy`].\n\n fn into_drop_strategy(self) -> AdHocMutDropStrategy<Self> {\n\n AdHocMut...
Rust
src/rules/constructor_super.rs
ardyfeb/deno_lint
1cfa3f82e94b9d7603ffed436178df346304d2e1
use std::sync::Arc; pub struct ConstructorSuper; use super::Context; use super::LintRule; use swc_ecmascript::ast::{ Class, ClassMember, Constructor, Expr, ExprOrSuper, Stmt, }; use swc_ecmascript::visit::Node; use swc_ecmascript::visit::Visit; impl LintRule for ConstructorSuper { fn new() -> Box<Self> { Box...
use std::sync::Arc; pub struct ConstructorSuper; use super::Context; use super::LintRule; use swc_ecmascript::ast::{ Class, ClassMember, Constructor, Expr, ExprOrSuper, Stmt, }; use swc_ecmascript::visit::Node; use swc_ecmascript::visit::Visit; impl LintRule for ConstructorSuper { fn new() -> Box<Self> { Box...
constructor() {} } super(); } } "#, 5, 20, ); assert_lint_err_on_line::<ConstructorSuper>( r#" class A extends B { constructor() { super(); } foo() { class C extends D { constructor() {} } } } "#, 8, 20, ); assert_lint_err...
Super>( "class A extends null { constructor() { super(); } }", 37, ); assert_lint_err::<ConstructorSuper>( "class A extends null { constructor() { } }", 37, ); assert_lint_err::<ConstructorSuper>( "class A extends 100 { constructor() { super(); } }", 36, ); as...
function_block-random_span
[ { "content": "pub fn assert_lint_ok_n<T: LintRule + 'static>(cases: Vec<&str>) {\n\n for source in cases {\n\n assert_lint_ok::<T>(source);\n\n }\n\n}\n\n\n", "file_path": "src/test_util.rs", "rank": 14, "score": 286843.04047751427 }, { "content": "class B { foo() {} }\n\n \"#,\n\n...
Rust
openapi/src/v2/codegen/emitter.rs
u5surf/paperclip
9221316e278ced0edb74458bacf3a18f3f60821b
use super::object::{ApiObject, ObjectField, OpRequirement, Parameter}; use super::state::EmitterState; use super::RUST_KEYWORDS; use crate::error::PaperClipError; use crate::v2::{ models::{self, Api, DataType, DataTypeFormat, OperationMap}, Schema, }; use failure::Error; use heck::{CamelCase, SnekCase}; use st...
use super::object::{ApiObject, ObjectField, OpRequirement, Parameter}; use super::state::EmitterState; use super::RUST_KEYWORDS; use crate::error::PaperClipError; use crate::v2::{ models::{self, Api, DataType, DataTypeFormat, OperationMap}, Schema, }; use failure::Error; use heck::{CamelCase, SnekCase}; use st...
fn emit_object(&self, def: &E::Definition, define: bool) -> Result<EmittedUnit, Error> { match self.try_emit_map(def, define)? { EmittedUnit::None => (), x => return Ok(x), } if !define { let mut ty_path ...
fn emit_array(&self, def: &E::Definition, define: bool) -> Result<EmittedUnit, Error> { if define { return Ok(EmittedUnit::None); } let it = def .items() .ok_or(PaperClipError::MissingArrayItem(self.def_name(def).ok()))?; let schema = it.read(); ...
function_block-full_function
[ { "content": "/// Deserialize the schema from the given reader. Currently, this only supports\n\n/// JSON and YAML formats.\n\npub fn from_reader<R, S>(mut reader: R) -> Result<Api<S>, PaperClipError>\n\nwhere\n\n R: Read + Seek,\n\n for<'de> S: Deserialize<'de>,\n\n S: Schema,\n\n{\n\n let mut buf ...
Rust
plex-api/src/tests/mod.rs
glensc/plex-api.rs
6abd1128377c25729caf01045d19a5b69d4f01d3
macro_rules! test_case_online_anonymous { ($testing_function_name:ident) => { paste! { #[cfg(feature = "test_connect_anonymous")] #[tokio::test] async fn [<$testing_function_name _anonymous>]() { let srv = crate::tests::get_server_anonymous().await; ...
macro_rules! test_case_online_anonymous { ($testing_function_name:ident) => { paste! { #[cfg(feature = "test_connect_anonymous")] #[tokio::test] async fn [<$testing_function_name _anonymous>]() { let srv = crate::tests::get_server_anonymous().await; ...
self.display_name, self.max_attempts ); return RetryPolicy::ForwardError(e); } eprintln!( "[{}] Attempt {}/{} has failed", self.display_name, current_attempt, self.max_attempts ); match e { ...
ne_anonymous!($testing_function_name); test_case_online_authenticated!($testing_function_name); }; } mod headers; mod media_container; mod library; mod my_plex; mod server; #[cfg(any( feature = "test_connect_authenticated", feature = "test_connect_anonymous" ))] fn set_client_identifier_from_env(...
random
[ { "content": "#[test]\n\nfn decode_prefs() {\n\n let s = r##\"\n\n{\n\n \"size\": 132,\n\n \"Setting\": [\n\n {\"id\": \"FriendlyName\",\"label\": \"Friendly name\",\"summary\": \"This name will be used to identify this media server to other computers on your network. If you leave it blank, your...
Rust
src/svd.rs
rusty-fast-solvers/rusty-compression
eaa93bbef41b7623a082483cdfc29154d37dfcc7
use crate::qr::{QRTraits, QR}; use crate::CompressionType; use ndarray::{s, Array1, Array2, ArrayView1, ArrayView2, ArrayViewMut1, ArrayViewMut2, Axis, Zip}; use num::ToPrimitive; use rusty_base::types::Result; use rusty_base::types::{c32, c64, ConjMatMat, Scalar}; pub struct SVD<A: Scalar> { pub u: Array2<...
use crate::qr::{QRTraits, QR}; use crate::CompressionType; use ndarray::{s, Array1, Array2, ArrayView1, ArrayView2, ArrayViewMut1, ArrayViewMut2, Axis, Zip}; use num::ToPrimitive; use rusty_base::types::Result; use rusty_base::types::{c32, c64, ConjMatMat, Scalar}; pub struct SVD<A: Scalar> { pub u: Array2<...
fn to_qr(self) -> Result<QR<Self::A>>; fn compress(&self, compression_type: CompressionType) -> Result<SVD<Self::A>> { match compression_type { CompressionType::ADAPTIVE(tol) => self.compress_svd_tolerance(tol), CompressionType::RANK(rank) => self.compress_svd_rank(r...
fn to_mat(&self) -> Array2<Self::A> { let mut scaled_vt = Array2::<Self::A>::zeros((self.get_vt().nrows(), self.get_vt().ncols())); scaled_vt.assign(&self.get_vt()); Zip::from(scaled_vt.axis_iter_mut(Axis(0))) .and(self.get_s().view()) .apply(|mut row, &s_ele...
function_block-function_prefix_line
[ { "content": "pub trait QRTraits {\n\n type A: Scalar;\n\n\n\n /// Number of rows\n\n fn nrows(&self) -> usize {\n\n self.get_q().nrows()\n\n }\n\n\n\n /// Number of columns\n\n fn ncols(&self) -> usize {\n\n self.get_r().ncols()\n\n }\n\n\n\n /// Rank of the QR Decompositi...
Rust
kernel/src/arch/x86_64/memory/paging/mod.rs
aeleos/VeOS
4c766539ac10ad7b044bcf1b49fd5f0ae8fc21c6
mod current_page_table; mod frame_allocator; mod free_list; pub mod inactive_page_table; mod page_table; pub mod page_table_entry; pub mod page_table_manager; pub use self::current_page_table::CURRENT_PAGE_TABLE; use self::frame_allocator::FRAME_ALLOCATOR; use self::page_table_entry::*; use self::page_table_manager::...
mod current_page_table; mod frame_allocator; mod free_list; pub mod inactive_page_table; mod page_table; pub mod page_table_entry; pub mod page_table_manager; pub use self::current_page_table::CURRENT_PAGE_TABLE; use self::frame_allocator::FRAME_ALLOCATOR; use self::page_table_entry::*; use self::page_table_manager::...
pub fn convert_flags(flags: PageFlags) -> PageTableEntryFlags { let mut entry_flags = PageTableEntryFlags::PRESENT; if flags.contains(PageFlags::WRITABLE) { entry_flags |= PageTableEntryFlags::WRITABLE; } if !flags.contains(PageFlags::EXECUTABLE) { entry_flags |= PageTableEntryFlags:...
e should only be initialized once."); debug!("Initializing the free list..."); free_list::init(); debug!("Remapping the kernel..."); unsafe { remap_kernel() }; debug!("Mapping the initramfs..."); unsafe { map_initramfs(initramfs_area) }; }
function_block-function_prefixed
[ { "content": "/// Maps the given page to the given frame using the given flags.\n\npub fn map_page_at(page_address: VirtualAddress, frame_address: PhysicalAddress, flags: PageFlags) {\n\n paging::map_page_at(page_address, frame_address, flags);\n\n}\n\n\n", "file_path": "kernel/src/arch/x86_64/memory/mod...
Rust
device/src/drivers/ble/mesh/driver/pipeline/unprovisioned/provisioning_bearer.rs
jcrossley3/drogue-device
d9ad12333b6bef40bb1148ddcab9123c2e17a5df
use crate::drivers::ble::mesh::driver::pipeline::mesh::MeshContext; use crate::drivers::ble::mesh::driver::pipeline::unprovisioned::segmentation::outbound::{ OutboundSegments, OutboundSegmentsIter, }; use crate::drivers::ble::mesh::driver::pipeline::unprovisioned::segmentation::Segmentation; use crate::drivers::ble...
use crate::drivers::ble::mesh::driver::pipeline::mesh::MeshContext; use crate::drivers::ble::mesh::driver::pipeline::unprovisioned::segmentation::outbound::{ OutboundSegments, OutboundSegmentsIter, }; use crate::drivers::ble::mesh::driver::pipeline::unprovisioned::segmentation::Segmentation; use crate::drivers::ble...
fn should_process_transaction(&mut self, transaction_number: u8) -> bool { match ( self.inbound_transaction_number, self.acked_inbound_transaction_number, ) { (Some(inbound), _) if inbound == transaction_number => { true ...
match pbc { ProvisioningBearerControl::LinkOpen(uuid) => { if ctx.uuid() == *uuid { if let None = self.link_id { self.inbound_transaction_number .replace(pdu.transaction_number); ...
function_block-function_prefix_line
[ { "content": "// Perform a process step for an Actor, processing a single message\n\npub fn step_actor(actor_fut: &mut impl Future<Output = ()>) {\n\n let waker = futures::task::noop_waker_ref();\n\n let mut cx = std::task::Context::from_waker(waker);\n\n let _ = unsafe { Pin::new_unchecked(&mut *actor...
Rust
contracts/core/pool-v2/src/handler/core.rs
kyscott18/interest_split
e24541f6ecfb228ab1397a1f058bb45149c413a9
use cosmwasm_bignumber::Uint256; use cosmwasm_std::*; use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg}; use pylon_core::pool_v2_msg::Cw20HookMsg; use pylon_token::collector::ExecuteMsg as CollectorHandleMsg; use pylon_utils::tax::deduct_tax; use std::ops::Div; use crate::error::ContractError; use crate::querier::{adapter, f...
use cosmwasm_bignumber::Uint256; use cosmwasm_std::*; use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg}; use pylon_core::pool_v2_msg::Cw20HookMsg; use pylon_token::collector::ExecuteMsg as CollectorHandleMsg; use pylon_utils::tax::deduct_tax; use std::ops::Div; use crate::error::ContractError; use crate::querier::{adapter, f...
g.dp_token = address.to_string(); config::store(deps.storage, &config).unwrap(); Ok(Response::new().add_attribute("dp_token", address.to_string())) } pub fn receive( deps: DepsMut, env: Env, info: MessageInfo, cw20_msg: Cw20ReceiveMsg, ) -> Result<Response, ContractError> { match from_bina...
deps.storage).unwrap(); if config.dp_token != *"" { return Err(ContractError::Unauthorized { action: "register_dp_token".to_string(), expected: "<empty>".to_string(), actual: config.dp_token, }); } confi
function_block-random_span
[ { "content": "#[allow(dead_code)]\n\n#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {\n\n Ok(Response::default())\n\n}\n", "file_path": "contracts/gateway/factory/src/contract.rs", "rank": 0, "...
Rust
src/data.rs
mickus777/rusty_raft
15e8594703e0c84fd9719bc66f7a7b9ae75acc56
#[derive(Clone, serde::Deserialize, serde::Serialize)] pub struct LogPost { pub term: u64, pub value: i32 } impl std::cmp::PartialEq for LogPost { fn eq(&self, other: &Self) -> bool { self.term == other.term && self.value == other.value } } impl std::fmt::Debug for LogPost { fn fmt(&self, ...
#[derive(Clone, serde::Deserialize, serde::Serialize)] pub struct LogPost { pub term: u64, pub value: i32 } impl std::cmp::PartialEq for LogPost { fn eq(&self, other: &Self) -> bool { self.term == other.term && self.value == other.value } } impl std::fmt::Debug for LogPost { fn fmt(&self, ...
}
let b = vec!(LogPost { term: 0, value: 0 }); let expected = vec!(LogPost { term: 0, value: 0 }); append_entries_from(&mut a, &b, &None); assert_eq!(a, expected); }
function_block-function_prefix_line
[ { "content": "pub fn top(list: &Vec<data::LogPost>) -> Option<&data::LogPost> {\n\n match list.len() {\n\n 0 => None,\n\n n => Some(&list[n-1])\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 4, "score": 103735.81108805168 }, { "content": "pub fn get_message_term(...
Rust
src/optfields.rs
AndreaGuarracino/rs-gfa
d1f86f98a6c437e774ce817fcbcd5981fe208bbf
use bstr::ByteSlice; use lazy_static::lazy_static; use regex::bytes::Regex; pub type OptionalFields = Vec<OptField>; pub type NoOptionalFields = (); #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct OptField { pub tag: [u8; 2], pub value: OptFieldVal, } #[derive(Debug, Clone, PartialEq, PartialOrd)]...
use bstr::ByteSlice; use lazy_static::lazy_static; use regex::bytes::Regex; pub type OptionalFields = Vec<OptField>; pub type NoOptionalFields = (); #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct OptField { pub tag: [u8; 2], pub value: OptFieldVal, } #[derive(Debug, Clone, PartialEq, PartialOrd)]...
b'Z' => RE_STRING .find(o_contents) .map(|s| s.as_bytes().into()) .map(Z), b'J' => RE_STRING .find(o_contents) .map(|s| s.as_bytes().into()) .map(J), b'H' => RE_BYTE...
s_bytes()[0]).map(A), b'i' => RE_INT .find(o_contents) .and_then(|s| s.as_bytes().to_str().ok()) .and_then(|s| s.parse().ok()) .map(Int), b'f' => RE_FLOAT .find(o_contents) ....
random
[]
Rust
src/commands/osu/leaderboard.rs
MaxOhn/Bathbot
609a9367ac60e86b0e54a333375d3a8eb3bd3e56
use crate::{ arguments::{MapModArgs, ModSelection}, database::MySQL, embeds::{EmbedData, LeaderboardEmbed}, pagination::{LeaderboardPagination, Pagination}, scraper::Scraper, util::{ discord, globals::{AVATAR_URL, OSU_API_ISSUE}, MessageExt, }, DiscordLinks, Osu, ...
use crate::{ arguments::{MapModArgs, ModSelection}, database::MySQL, embeds::{EmbedData, LeaderboardEmbed}, pagination::{LeaderboardPagination, Pagination}, scraper::Scraper, util::{ discord, globals::{AVATAR_URL, OSU_API_ISSUE}, MessageExt, }, DiscordLinks, Osu, ...
#[command] #[description = "Display the belgian leaderboard of a given map. \ If no map is given, I will choose the last map \ I can find in my embeds of this channel"] #[usage = "[map url / map id]"] #[example = "2240404"] #[example = "https://osu.ppy.sh/beatmapsets/902425#osu/22404...
t?; match discord::map_id_from_history(msgs, &ctx.cache).await { Some(id) => id, None => { msg.channel_id .say( ctx, "No beatmap specified and none found in recent channel history. \ ...
function_block-function_prefixed
[ { "content": "pub fn simulate_score(score: &mut Score, map: &Beatmap, args: SimulateArgs) {\n\n if let Some((mods, selection)) = args.mods {\n\n if selection == ModSelection::Exact || selection == ModSelection::Includes {\n\n score.enabled_mods = mods;\n\n }\n\n }\n\n match map...
Rust
src/lib.rs
Phobos001/squares-rng-rs
4cb8e9fc9629a4930bd1c67c32bc2e63abe6a65d
#![crate_type = "lib"] #[cfg(feature = "keys_table")] mod keys_table; pub struct SquaresRNG { pub key: u64, pub counter: u64, } impl SquaresRNG { const U64_REMAINDER: u64 = u32::MAX as u64; const TEST_COUNT: u64 = 10_000_000; const TEST_KEY: u64 = 0x2467cb532b5ce8d1; #[...
#![crate_type = "lib"] #[cfg(feature = "keys_table")] mod keys_table; pub struct SquaresRNG { pub key: u64, pub counter: u64, } impl SquaresRNG { const U64_REMAINDER: u64 = u32::MAX as u64; const TEST_COUNT: u64 = 10_000_000; const TEST_KEY: u64 = 0x2467cb532b5ce8d1; #[...
#[test] pub fn test_vec4f64_uniformality() { let mut rng: SquaresRNG = SquaresRNG::new_with_key(0, SquaresRNG::TEST_KEY); let count: u64 = SquaresRNG::TEST_COUNT; let mut average: (f64, f64, f64, f64) = (0.0, 0.0, 0.0, 0.0); for _ in 0..count { let rnd = rng.vec4f64(); average.0 += r...
average.1 /= count as f64; average.2 /= count as f64; println!("\nRNG vec3f64 Uniformality (Closer to 0.0): x: {}, y: {}, z: {}\n", average.0, average.1, average.2); assert!(average.0 < 0.01 && average.0 > -0.01); assert!(average.1 < 0.01 && average.1 > -0.01); assert!(average.2 < 0.01 && ...
function_block-function_prefix_line
[ { "content": "#[cfg(feature = \"keys_table\")]\n\npub mod keys_table {\n\n /// Keys are u64's that have half ones and half zeros in their bits.\n\n /// Each key can make 2^64 random numbers. This should be enough, right?\n\n /// \n\n /// Table was generated from the 'keys' program provided by the Sq...
Rust
src/engine/operators/subpartition.rs
Joylei/LocustDB
e3f5b5d351c30b2063ff858c28dff4d5d4e893d2
use crate::engine::*; use std::fmt::Debug; use std::marker::PhantomData; #[derive(Debug)] pub struct SubPartition<T, C> { pub partitioning: BufferRef<Premerge>, pub left: BufferRef<T>, pub right: BufferRef<T>, pub sub_partitioning: BufferRef<Premerge>, pub c: PhantomData<C>, } impl<'a, T: VecData<...
use crate::engine::*; use std::fmt::Debug; use std::marker::PhantomData; #[derive(Debug)] pub struct SubPartition<T, C> { pub partitioning: BufferRef<Premerge>, pub left: BufferRef<T>, pub right: BufferRef<T>, pub sub_partitioning: BufferRef<Premerge>, pub c: PhantomData<C>, } impl<'a, T: VecData<...
}
ate_partitioned::<u32>(&result, &left2, &right2); assert_eq!(&merging, &[1, 3, 5, 7, 0, 2, 1, 1, 2]); assert_eq!(&merge_ops, &[ TakeLeft, TakeLeft, MergeRight, TakeRight, TakeLeft, TakeRight, TakeLeft, MergeR...
function_block-function_prefixed
[ { "content": "pub fn partition<'a, T, C>(left: &[T], right: &[T], limit: usize) -> Vec<Premerge>\n\n where T: VecData<T> + 'a, C: Comparator<T> {\n\n let mut result = Vec::new();\n\n let mut i = 0;\n\n let mut j = 0;\n\n let limit = if limit > u32::MAX as usize { u32::MAX } else { limit as u32 };...
Rust
src/write/page.rs
youngsofun/parquet2
e8a0c3576d5b43636fd16a942bc392d450344416
use std::io::Write; use std::sync::Arc; use futures::{AsyncWrite, AsyncWriteExt}; use parquet_format_async_temp::thrift::protocol::{ TCompactOutputProtocol, TCompactOutputStreamProtocol, }; use parquet_format_async_temp::{DictionaryPageHeader, Encoding, PageType}; use crate::error::Result; use crate::page::{ ...
use std::io::Write; use std::sync::Arc; use futures::{AsyncWrite, AsyncWriteExt}; use parquet_format_async_temp::thrift::protocol::{ TCompactOutputProtocol, TCompactOutputStreamProtocol, }; use parquet_format_async_temp::{DictionaryPageHeader, Encoding, PageType}; use crate::error::Result; use crate::page::{ ...
header: &ParquetPageHeader, ) -> Result<u64> { let mut protocol = TCompactOutputStreamProtocol::new(&mut writer); Ok(header.write_to_out_stream_protocol(&mut protocol).await? as u64) }
function_block-function_prefix_line
[ { "content": "/// Encodes `value` in ULEB128 into `container`. The exact number of bytes written\n\n/// depends on `value`, and cannot be determined upfront. The maximum number of bytes\n\n/// required are 10.\n\n/// # Panic\n\n/// This function may panic if `container.len() < 10` and `value` requires more byte...
Rust
vendor/az-1.2.0/src/tests/to_float.rs
INTERUPT13/rust-esp32-std-demo
d6641f5fc10ce9a63839dc45eb813014c73153a5
use crate::{cast, checked_cast, unwrapped_cast}; use core::{f32, f64}; macro_rules! slice_to_float { ($vals: expr) => { for &val in $vals { if val != val { assert!(cast::<_, f32>(val).is_nan()); assert!(checked_cast::<_, f32>(val).unwrap().is_nan()); ...
use crate::{cast, checked_cast, unwrapped_cast}; use core::{f32, f64}; macro_rules! slice_to_float { ($vals: expr) => { for &val in $vals { if val != val { assert!(cast::<_, f32>(val).is_nan()); assert!(checked_cast::<_, f32>(val).unwrap().is_nan()); ...
#[test] fn specific_to_float() { assert_eq!( cast::<_, f32>(0xFFFF_FE80u32), (24f32.exp2() - 2.0) * 8f32.exp2() ); assert_eq!( cast::<_, f32>(0xFFFF_FE81u32), (24f32.exp2() - 1.0) * 8f32.exp2() ); assert_eq!( cast::<_, f32>(0xFFFF_FF00u32), ...
mall_u); slice_to_float!(small_f); slice_to_float!(big_i); slice_to_float!(big_u); slice_to_float!(big_f); }
function_block-function_prefixed
[ { "content": "#[allow(deprecated)]\n\nfn test_atomics() {\n\n let a = AtomicUsize::new(0);\n\n let v1 = a.compare_and_swap(0, 1, Ordering::SeqCst);\n\n let v2 = a.swap(2, Ordering::SeqCst);\n\n\n\n let (r1, r2) = unsafe {\n\n // don't optimize our atomics out\n\n let r1 = core::ptr::re...
Rust
xtask/src/bindgen.rs
jacoblockard99/rbspy
e97de41a4c708447a5e1452ec8918791ef1620e1
use anyhow::{anyhow, Context, Result}; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; pub fn generate_ruby_bindings( ruby_source_path: std::path::PathBuf, version_tag: &str, ) -> Result<()> { prepare_ruby_source(&ruby_source_path, version_tag) .context("prep...
use anyhow::{anyhow, Context, Result}; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; pub fn generate_ruby_bindings( ruby_source_path: std::path::PathBuf, version_tag: &str, ) -> Result<()> { prepare_ruby_source(&ruby_source_path, version_tag) .context("prep...
p_buf")?; writeln!(wrapper, "#include \"{}/vm_core.h\"", path.to_string_lossy())?; writeln!(wrapper, "#include \"{}/iseq.h\"", path.to_string_lossy())?; return Ok(wrapper_path); } fn postprocess_bindings_for_windows(path: &Path) -> Result<()> { fn regex_replace(expr: &str, path: &Path) -> Result<()> {...
t("create work directory")?; log::info!( "Working directory path is {}", work_path.path().to_string_lossy() ); let wrapper_path = prepare_ruby_headers(work_path.path(), &ruby_source_path) .context("prepare ruby headers")?; let bindings = bindgen::builder() .allowlist_typ...
random
[ { "content": "pub fn initialize(pid: Pid, lock_process: bool) -> Result<StackTraceGetter> {\n\n #[cfg(all(windows, target_arch = \"x86_64\"))]\n\n if is_wow64_process(pid).context(\"check wow64 process\")? {\n\n return Err(format_err!(\n\n \"Unable to profile 32-bit Ruby with 64-bit rbsp...
Rust
2021/day19/src/main.rs
poszu/advent-of-code
248103609b36978493d7c79da2cf7b7ec0b1bc38
use std::collections::HashMap; use std::collections::HashSet; use itertools::Itertools; extern crate nalgebra as na; #[derive(Debug, Clone, PartialEq)] struct Scanner { probes: Vec<na::Point3<i32>>, } #[derive(Debug)] struct LocatedScanner { position: na::Point3<i32>, scanner: Scanner, } fn rotate(vec: ...
use std::collections::HashMap; use std::collections::HashSet; use itertools::Itertools; extern crate nalgebra as na; #[derive(Debug, Clone, PartialEq)] struct Scanner { probes: Vec<na::Point3<i32>>, } #[derive(Debug)] struct LocatedScanner { position: na::Point3<i32>, scanner: Scanner, } fn rotate(vec: ...
fn find_manhattan_distance(scanners: &[LocatedScanner]) -> usize { scanners .iter() .combinations(2) .map(|pair| { let dist = pair[1].position - pair[0].position; (dist[0].abs() + dist[1].abs() + dist[2].abs()) as usize }) .max() .unwrap() } ...
HashSet::<na::Point3<i32>>::from_iter( scanners .iter() .map(|scanner| scanner.scanner.probes.iter().copied()) .flatten(), ) }
function_block-function_prefix_line
[ { "content": "fn parse_input<I: AsRef<str>>(input: impl IntoIterator<Item = I>) -> Vec<Line> {\n\n input\n\n .into_iter()\n\n .map(|l| l.as_ref().parse().unwrap())\n\n .collect::<Vec<Line>>()\n\n}\n\n\n", "file_path": "2021/day5/src/main.rs", "rank": 1, "score": 281873.601503...
Rust
mpd_client/src/errors.rs
elomatreb/mpd_client
60046917d284a44d45ab5cb9b8f7441ad69f1c9f
use tokio::sync::{mpsc::error::SendError, oneshot::error::RecvError}; use std::error::Error; use std::fmt; use crate::commands::responses::TypedResponseError; use crate::raw::{ErrorResponse, Frame, MpdProtocolError}; #[derive(Debug)] pub enum CommandError { ConnectionClosed, Protocol(MpdProtocolErr...
use tokio::sync::{mpsc::error::SendError, oneshot::error::RecvError}; use std::error::Error; use std::fmt; use crate::commands::responses::TypedResponseError; use crate::raw::{ErrorResponse, Frame, MpdProtocolError}; #[derive(Debug)] pub enum CommandError { ConnectionClosed, Protocol(MpdProtocolErr...
StateChangeError::Protocol(e) => Some(e), _ => None, } } } #[doc(hidden)] impl From<ErrorResponse> for StateChangeError { fn from(r: ErrorResponse) -> Self { StateChangeError::ErrorMessage(r) } } #[doc(hidden)] impl From<MpdProtocolError> for StateChangeError { fn ...
esful_frames.is_empty() { write!(f, " (after {} succesful frames)", succesful_frames.len())?; } Ok(()) } } } } impl Error for CommandError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { CommandErro...
random
[ { "content": "fn validate_command_part(command: &str) -> Result<(), CommandError> {\n\n if command.is_empty() {\n\n return Err(CommandError::Empty);\n\n }\n\n\n\n validate_no_extra_whitespace(command)?;\n\n\n\n if let Some((i, c)) = command\n\n .char_indices()\n\n .find(|(_, c)|...
Rust
src/model/filerec.rs
bhank/inno-updater
f8e8c2ef393f4db88f980d7620c7e95d9d7cbf03
/*----------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *-----------------------------------------------------------------------...
/*----------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *-----------------------------------------------------------------------...
", self.0) } } impl<'a> error::Error for FileRecParseError<'a> { fn description(&self) -> &str { "FileRecParseError" } fn cause(&self) -> Option<&error::Error> { None } } #[derive(Debug, Clone)] pub struct FileRecWriteError<'a>(&'a str); impl<'a> fmt::Display for FileRecWriteError<'a> { fn fmt(&self, f: &...
deError<'a>(&'a str); impl<'a> fmt::Display for StringEncodeError<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "String encode error: {}", self.0) } } impl<'a> error::Error for StringEncodeError<'a> { fn description(&self) -> &str { "StringEncodeError" } fn cause(&self) -> Option<&e...
random
[ { "content": "pub fn read_utf8_string(reader: &mut Read, capacity: usize) -> Result<String, ReadUtf8StringError> {\n\n\tlet mut vec = vec![0; capacity];\n\n\n\n\treader\n\n\t\t.read_exact(&mut vec)\n\n\t\t.map_err(|err| ReadUtf8StringError::IOError(err))\n\n\t\t.and_then(|_| {\n\n\t\t\tlet pos = vec.iter().posi...
Rust
examples/session_example.rs
qiaojialin/iotdb-client-rs
43942b4c09af603b640c14adcbf9ca6c07c50209
use std::vec; use chrono; use chrono::Local; use iotdb::client::remote::{Config, RpcSession}; use iotdb::client::{MeasurementSchema, Result, RowRecord, Session, Tablet, Value}; use iotdb::protocal::{TSCompressionType, TSDataType, TSEncoding}; use prettytable::{cell, Row, Table}; use structopt::StructOpt; #[derive(...
use std::vec; use chrono; use chrono::Local; use iotdb::client::remote::{Config, RpcSession}; use iotdb::client::{MeasurementSchema, Result, RowRecord, Session, Tablet, Value}; use iotdb::protocal::{TSCompressionType, TSDataType, TSEncoding}; use prettytable::{cell, Row, Table}; use structopt::StructOpt; #[derive(...
"root.sg_rs.device2.tick_count", "root.sg_rs.device2.description", ], 0, i64::MAX, )?; let mut table = Table::new(); table.set_titles(Row::new( dataset .get_column_names() .iter() ...
lis() - 1, ], vec![ vec!["restart_count", "tick_count", "price"], vec!["temperature", "description", "status"], ], vec![ vec![Value::Int32(1), Value::Int64(2018), Value::Double(1988.1)], vec![ ...
random
[ { "content": "#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n\nstruct TSIServiceInsertTabletsResult {\n\n result_value: Option<TSStatus>,\n\n}\n\n\n\nimpl TSIServiceInsertTabletsResult {\n\n fn read_from_in_protocol(i_prot: &mut dyn TInputProtocol) -> thrift::Result<TSIServiceInsertTabletsResu...
Rust
src/make_credential_command.rs
gebogebogebo/ctap-hid-fido2
eb57851256d90bf02aab1b19371a42a19adc9f02
use crate::ctapdef; use crate::make_credential_params::Extension; use crate::util; use serde_cbor::to_vec; use serde_cbor::Value; use std::collections::BTreeMap; #[derive(Debug, Default)] pub struct Params { pub rp_id: String, pub rp_name: String, pub user_id: Vec<u8>, pub user_name: String, pub us...
use crate::ctapdef; use crate::make_credential_params::Extension; use crate::util; use serde_cbor::to_vec; use serde_cbor::Value; use std::collections::BTreeMap; #[derive(Debug, Default)] pub struct Params { pub rp_id: String, pub rp_name: String, pub user_id: Vec<u8>, pub user_name: String, pub us...
if let Some(x) = pin_auth { make_credential.insert(Value::Integer(0x08), x); make_credential.insert(Value::Integer(0x09), pin_protocol); } let cbor = Value::Map(make_credential); let mut payload = [ctapdef::AUTHENTICATOR_MAKE_CREDENTIAL].to_vec(); payload.append(&mut to_vec(&cbor)....
function_block-function_prefix_line
[ { "content": "fn option_message(typ: &str, info_option: &InfoOption, val: Option<bool>) -> Result<String> {\n\n let value_str = match val {\n\n Some(v) => format!(\"{}\", v),\n\n None => \"Not Supported\".to_string(),\n\n };\n\n let message1 = format!(\"option {} = {}\", typ, value_str);\...
Rust
pallets/nft/src/benchmarking.rs
WinterBoy-Galois/DeerProtocol-Rust
1f4b02a707e5639e575490bb583bf6c4a5c5cbbc
#![cfg(feature = "runtime-benchmarks")] use super::*; use frame_benchmarking::{ account, benchmarks_instance_pallet, impl_benchmark_test_suite, whitelist_account, whitelisted_caller, }; use frame_support::{traits::Get, BoundedVec}; use frame_system::RawOrigin as SystemOrigin; use sp_runtime::{traits::Bounded, Perbil...
#![cfg(feature = "runtime-benchmarks")] use super::*; use frame_benchmarking::{ account, benchmarks_instance_pallet, impl_benchmark_test_suite, whitelist_account, whitelisted_caller, }; use frame_support::{traits::Get, BoundedVec}; use frame_system::RawOrigin as SystemOrigin; use sp_runtime::{traits::Bounded, Perbil...
fn assert_last_event<T: Config<I>, I: 'static>(generic_event: <T as Config<I>>::Event) { let events = frame_system::Pallet::<T>::events(); let system_event: <T as frame_system::Config>::Event = generic_event.into(); let frame_system::EventRecord { event, .. } = &events[events.len() - 1]; assert_eq!(event, &syst...
fn add_instance_attribute<T: Config<I>, I: 'static>( instance: T::InstanceId, ) -> (BoundedVec<u8, T::KeyLimit>, T::AccountId) { let caller = Class::<T, I>::get(T::ClassId::default()).unwrap().owner; if caller != whitelisted_caller() { whitelist_account!(caller); } let key: BoundedVec<_, _> = vec![0; T::KeyLimit...
function_block-full_function
[ { "content": "fn create_nft<T: Config<I>, I: 'static>(owner: &T::AccountId) -> (T::ClassId, T::InstanceId) {\n\n\tlet class = Default::default();\n\n\tlet instance = Default::default();\n\n\tassert!(\n\n\t\tNFT::<T, I>::create(SystemOrigin::Signed(owner.clone()).into(), class, rate(10)).is_ok()\n\n\t);\n\n\tass...
Rust
src/iobuf.rs
cxuhua/btx
2dc0a471068010a8175a6b2e65b037fa8805d813
use crate::bytes::{FromBytes, IntoBytes}; use crate::errors; use crate::hasher::Hasher; use bytes::Buf; use bytes::BufMut; pub trait Serializer { fn encode(&self, w: &mut Writer); fn decode(r: &mut Reader) -> Result<Self, errors::Error> where Self: Default; fn pack(&self) -> Writ...
use crate::bytes::{FromBytes, IntoBytes}; use crate::errors; use crate::hasher::Hasher; use bytes::Buf; use bytes::BufMut; pub trait Serializer { fn encode(&self, w: &mut Writer); fn decode(r: &mut Reader) -> Result<Self, errors::Error> where Self: Default; fn pack(&self) -> Writ...
pub fn u16(&mut self) -> Result<u16, errors::Error> { self.check(2)?; Ok(self.inner.get_u16_le()) } pub fn u32(&mut self) -> Result<u32, errors::Error> { self.check(4)?; Ok(self.inner.get_u32_le()) } pub fn u64(&mut self) -> Result<u64, errors::Error> { self....
match size { 1 => Ok(self.u8()? as usize), 2 => Ok(self.u16()? as usize), 3 => Ok(self.u32()? as usize), _ => errors::Error::msg("IoBufReadErr"), } }
function_block-function_prefix_line
[ { "content": "///二机制生成\n\npub trait IntoBytes: Sized {\n\n fn into_bytes(&self) -> Vec<u8>;\n\n}\n\n\n", "file_path": "src/bytes.rs", "rank": 0, "score": 141257.8558624681 }, { "content": "///从进制生成\n\npub trait FromBytes: IntoBytes {\n\n fn from_bytes(bb: &Vec<u8>) -> Result<Self, Erro...
Rust
clap_blocks/src/catalog_dsn.rs
r4ntix/influxdb_iox
5ff874925101e2afbafa6853385260a2ba044394
use iox_catalog::{ create_or_get_default_records, interface::Catalog, mem::MemCatalog, postgres::{PostgresCatalog, PostgresConnectionOptions}, }; use observability_deps::tracing::*; use snafu::{OptionExt, ResultExt, Snafu}; use std::{ops::DerefMut, sync::Arc, time::Duration}; #[derive(Debug, Snafu)] pu...
use iox_catalog::{ create_or_get_default_records, interface::Catalog, mem::MemCatalog, postgres::{PostgresCatalog, PostgresConnectionOptions}, }; use observability_deps::tracing::*; use snafu::{OptionExt, ResultExt, Snafu}; use std::{ops::DerefMut, sync::Arc, time::Duration}; #[derive(Debug, Snafu)] pu...
_schema_name: String, #[clap( long = "--catalog-connect-timeout", env = "INFLUXDB_IOX_CATALOG_CONNECT_TIMEOUT", default_value = default_connect_timeout(), parse(try_from_str = humantime::parse_duration), )] pub connect_timeout: Duration, #[clap( long =...
default_value = default_max_connections(), )] pub max_catalog_connections: u32, #[clap( long = "--catalog-postgres-schema-name", env = "INFLUXDB_IOX_CATALOG_POSTGRES_SCHEMA_NAME", default_value = PostgresConnectionOptions::DEFAULT_SCHEMA_NAME, )] pub postgres
random
[ { "content": "// Parses a `dsn-file://` scheme, according to the rules of the IDPE kit/sql package.\n\n//\n\n// If the dsn matches the `dsn-file://` prefix, the prefix is removed and the rest is interpreted\n\n// as a file name, in which case this function will return `Some(filename)`.\n\n// Otherwise it will r...
Rust
src/termdict/sstable_termdict/termdict.rs
StyMaar/tantivy
458ed29a31d4a8929193ba4f41b83cd69eaac5f9
use std::io; use common::BinarySerializable; use once_cell::sync::Lazy; use tantivy_fst::automaton::AlwaysMatch; use tantivy_fst::Automaton; use crate::directory::{FileSlice, OwnedBytes}; use crate::postings::TermInfo; use crate::termdict::sstable_termdict::sstable::sstable_index::BlockAddr; use crate::termdict::ssta...
use std::io; use common::BinarySerializable; use once_cell::sync::Lazy; use tantivy_fst::automaton::AlwaysMatch; use tantivy_fst::Automaton; use crate::directory::{FileSlice, OwnedBytes}; use crate::postings::TermInfo; use crate::termdict::sstable_termdict::sstable::sstable_index::BlockAddr; use crate::termdict::ssta...
let term_info = sstable_reader.value().clone(); return Ok(Some(term_info)); } } } Ok(None) } pub async fn get_async<K: AsRef<[u8]>>(&self, key: K) -> AsyncIoResult<Option<TermInfo>> { if let Some(block_addr) = self.sst...
(Box::new(owned_bytes))) } pub fn empty() -> Self { TermDictionary::open(EMPTY_TERM_DICT_FILE.clone()).unwrap() } pub fn num_terms(&self) -> usize { self.num_terms as usize } pub fn term_ord<K: AsRef<[u8]>>(&self, key: K) -> io::Result<Option<TermOrdinal>> ...
random
[ { "content": "pub fn serialize(mut val: u64, buffer: &mut [u8]) -> usize {\n\n for (i, b) in buffer.iter_mut().enumerate() {\n\n let next_byte: u8 = (val & 127u64) as u8;\n\n val >>= 7;\n\n if val == 0u64 {\n\n *b = next_byte;\n\n return i + 1;\n\n } else {\n...
Rust
src/input.rs
MCluck90/ggez-goodies
a527cc666204ed136cf098fa7c80494e3aff6d05
use ggez::event::KeyCode; use std::collections::HashMap; use std::hash::Hash; #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone)] enum InputType { KeyEvent(KeyCode), } #[derive(Debug, Copy, Clone, PartialEq)] pub enum InputEffect<Axes, Buttons> where Axes: Eq + Hash + Clone, Buttons: Eq + Hash + Clone, ...
use ggez::event::KeyCode; use std::collections::HashMap; use std::hash::Hash; #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone)] enum InputType { KeyEvent(KeyCode), } #[derive(Debug, Copy, Clone, PartialEq)] pub enum InputEffect<Axes, Buttons> where Axes: Eq + Hash + Clone, Buttons: Eq + Hash + Clone, ...
pub fn bind_key_to_button(mut self, keycode: KeyCode, button: Buttons) -> Self { self.bindings.insert( InputType::KeyEvent(keycode), InputEffect::Button(button.clone()), ); self } pub fn resolve(&self, keycode: KeyCode) -> Option<InputEffect<...
pub fn bind_key_to_axis(mut self, keycode: KeyCode, axis: Axes, positive: bool) -> Self { self.bindings.insert( InputType::KeyEvent(keycode), InputEffect::Axis(axis.clone(), positive), ); self }
function_block-full_function
[ { "content": "/// Linear interpolation; assumes input value is in the range 0-1 and\n\n/// returns it interpolated to the given bounds.\n\n///\n\n/// For example: `lerp(easing::cubic_inout(v), 0.0, 100.0)`\n\npub fn lerp(v: f32, from: f32, to: f32) -> f32 {\n\n let delta = to - from;\n\n v * delta\n\n}\n\...
Rust
src/storage/concurrency_manager/key_handle.rs
ldeng-ustc/tikv
c4b7e8fa20f8f2022e634c445a53212b54e8f016
use super::lock_table::LockTable; use parking_lot::Mutex; use std::{mem, sync::Arc}; use tokio::sync::{Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; use txn_types::{Key, Lock}; pub struct KeyHandle { pub key: Key, table: LockTable, mutex: AsyncMutex<()>, lock_store: Mutex<Option<Lock>>, } im...
use super::lock_table::LockTable; use parking_lot::Mutex; use std::{mem, sync::Arc}; use tokio::sync::{Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; use txn_types::{Key, Lock}; pub struct KeyHandle { pub key: Key, table: LockTable, mutex: AsyncMutex<()>, lock_store: Mutex<Option<Lock>>, } im...
handles.push(handle); } for handle in handles { handle.await.unwrap(); } assert_eq!(counter.load(Ordering::SeqCst), 100); } #[tokio::test] async fn test_ref_count() { let table = LockTable(Arc::new(Mutex::new(BTreeMap::new()))); let ...
let handle = tokio::spawn(async move { let _guard = key_handle.lock().await; let counter_val = counter.fetch_add(1, Ordering::SeqCst) + 1; delay_for(Duration::from_millis(1)).await; assert_eq!(counter.load(Ordering::SeqCst...
assignment_statement
[ { "content": "#[inline]\n\npub fn decode_int_handle(mut key: &[u8]) -> Result<i64> {\n\n check_record_key(key)?;\n\n key = &key[PREFIX_LEN..];\n\n key.read_i64().map_err(Error::from)\n\n}\n\n\n\n/// `decode_common_handle` decodes key key and gets the common handle.\n", "file_path": "components/tidb...
Rust
src/types.rs
sile/erl_pp
38e34fb106500a307737fb79308bedad0666262d
use erl_tokenize::tokens::{AtomToken, SymbolToken, VariableToken}; use erl_tokenize::values::Symbol; use erl_tokenize::{LexicalToken, Position, PositionRange}; use std::fmt; use std::hash::{Hash, Hasher}; use std::mem; use crate::token_reader::{ReadFrom, TokenReader}; use crate::{Error, Result}; #[derive(Debug, Clon...
use erl_tokenize::tokens::{AtomToken, SymbolToken, VariableToken}; use erl_tokenize::values::Symbol; use erl_tokenize::{LexicalToken, Position, PositionRange}; use
t.text(), MacroName::Variable(ref t) => t.text(), } } } impl PartialEq for MacroName { fn eq(&self, other: &Self) -> bool { self.value() == other.value() } } impl Eq for MacroName {} impl Hash for MacroName { fn hash<H: Hasher>(&self, hasher: &mut H) { self.value().h...
std::fmt; use std::hash::{Hash, Hasher}; use std::mem; use crate::token_reader::{ReadFrom, TokenReader}; use crate::{Error, Result}; #[derive(Debug, Clone)] #[allow(missing_docs)] pub enum MacroName { Atom(AtomToken), Variable(VariableToken), } impl MacroName { pub fn value(&self) -> &str { m...
random
[ { "content": "use clap::{App, Arg};\n\nuse erl_pp::{MacroDef, Preprocessor};\n\nuse erl_tokenize::tokens::AtomToken;\n\nuse erl_tokenize::{Lexer, Position, PositionRange};\n\nuse std::env;\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::path::Path;\n\nuse std::time::{Duration, Instant};\n\n\n", "fil...
Rust
diesel/src/lib.rs
elephantry/benchmark
c881ef1b176cc5660b764461fa570c5de2fef210
#![feature(test)] #![allow(soft_unstable)] #[macro_use] extern crate diesel; extern crate test; use diesel::prelude::*; #[derive(diesel::Insertable)] #[table_name = "users"] pub struct NewUser<'a> { name: &'a str, hair_color: Option<&'a str>, } impl<'a> NewUser<'a> { pub fn new() -> Self { NewUs...
#![feature(test)] #![allow(soft_unstable)] #[macro_use] extern crate diesel; extern crate test; use diesel::prelude::*; #[derive(diesel::Insertable)] #[table_name = "users"] pub struct NewUser<'a> { name: &'a str, hair_color: Option<&'a str>, } impl<'a> NewUser<'a> {
} diesel::table! { users { id -> Uuid, name -> VarChar, hair_color -> Nullable<VarChar>, created_at -> Timestamp, } } diesel::table! { posts { id -> Uuid, title -> Text, content -> Text, author -> Uuid, } } allow_tables_to_appear_in_sam...
pub fn new() -> Self { NewUser { name: "User", hair_color: Some("hair color"), } }
function_block-full_function
[ { "content": "pub trait Client: Sized {\n\n type Error: Sized;\n\n type User: Sized;\n\n\n\n /**\n\n * Creates a new database connection.\n\n */\n\n fn create(dsn: &str) -> Result<Self, Self::Error>;\n\n\n\n /**\n\n * Execute a simple query (used to create and drop table).\n\n */\...
Rust
src/fft/ctrl.rs
U007D/k210_pac
0e1521db307b349b016bfbff27aa5a085f229e19
#[doc = "Reader of register ctrl"] pub type R = crate::R<u64, super::CTRL>; #[doc = "Writer for register ctrl"] pub type W = crate::W<u64, super::CTRL>; #[doc = "Register ctrl `reset()`'s with value 0"] impl crate::ResetValue for super::CTRL { type Type = u64; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register ctrl"] pub type R = crate::R<u64, super::CTRL>; #[doc = "Writer for register ctrl"] pub type W = crate::W<u64, super::CTRL>; #[doc = "Register ctrl `reset()`'s with value 0"] impl crate::ResetValue for super::CTRL { type Type = u64; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Checks if the value of the field is `P512`"] #[inline(always)] pub fn is_p512(&self) -> bool { *self == POINT_A::P512 } #[doc = "Checks if the value of the field is `P256`"] #[inline(always)] pub fn is_p256(&self) -> bool { *self == POINT_A::P256 } #[doc = "...
pub fn variant(&self) -> crate::Variant<u8, POINT_A> { use crate::Variant::*; match self.bits { 0 => Val(POINT_A::P512), 1 => Val(POINT_A::P256), 2 => Val(POINT_A::P128), 3 => Val(POINT_A::P64), i => Res(i), } }
function_block-full_function
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
_obsolete/solver_rust/src/lib.rs
convexbrain/Totsu
a492825bead1f1f5ef241aa7d1c5d91190c5409c
/*! Totsu ([凸](http://www.decodeunicode.org/en/u+51F8) in Japanese) means convex. <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML' async></script> This crate for Rust provides a basic **primal-dual interior-point method** solver: [`PDIPM`](pdipm/struct.PDIPM.html)....
/*! Totsu ([凸](http://www.decodeunicode.org/en/u+51F8) in Japanese) means convex. <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML' async></script> This crate for Rust provides a basic **primal-dual interior-point method** solver: [`PDIPM`](pdipm/struct.PDIPM.html)....
#[test] fn test_socp() { let n: usize = 2; let m: usize = 1; let p: usize = 0; let ni: usize = 2; let vec_f = Mat::new_vec(n).set_all(1.); let mut mat_g = vec![Mat::new(ni, n); m]; let vec_h = vec![Mat::new_vec(ni); m]; let vec_c = vec![Mat...
1; let p: usize = 0; let mut mat_p = vec![Mat::new(n, n); m + 1]; let mut vec_q = vec![Mat::new_vec(n); m + 1]; let mut scl_r = vec![0. as FP; m + 1]; mat_p[0].assign_iter(&[ 1., 0., 0., 1. ]); vec_q[0].assign_iter(&[ ...
function_block-function_prefixed
[ { "content": "/// Finds dominant eigenvalue by power iteration\n\npub fn dom_eig(mat_a: &Mat) -> FP\n\n{\n\n let (m, n) = mat_a.size();\n\n assert_eq!(m, n);\n\n\n\n if n == 0 {\n\n return 0.;\n\n }\n\n\n\n let mut v = Mat::new_vec(n).set_all(1.);\n\n let mut lambda = 0.;\n\n\n\n loo...
Rust
src/engine/extension_registry.rs
colin-kiegel/twig-rust
3a70dc5e8f1d410b3e31c5f3bcc78fd8ea2da152
use extension::api::{self, Extension}; use std::collections::HashMap; use engine::Engine; use engine::error::ExtensionRegistryError; use api::error::Traced; pub type Iter<'a> = ::std::collections::hash_map::Values<'a, String, Box<Extension>>; #[derive(Debug, Default)] pub struct ExtensionRegistry { ext: HashMap...
use extension::api::{self, Extension}; use std::collections::HashMap; use engine::Engine; use engine::error::ExtensionRegistryError; use api::error::Traced; pub type Iter<'a> = ::std::collections::hash_map::Values<'a, String, Box<Extension>>; #[derive(Debug, Default)] pub struct ExtensionRegistry { ext: HashMap...
, Box<api::Filter>> { &self.filters } pub fn tests(&self) -> &HashMap<String, Box<api::Test>> { &self.tests } pub fn functions(&self) -> &HashMap<String, Box<api::Function>> { &self.functions } pub fn operators_unary(&self) -> &HashMap<String, api::Unary...
prev: prev, ext_name: ext.name(), }); } } for (k, v) in ext.tests() { if let Some(prev) = self.tests.insert(k, v) { return traced_err!(ExtensionRegistryError::DuplicateTest { ...
random
[ { "content": "// supposed to be *compatible* with PHP implementation\n\n// - http://php.net/manual/en/function.stripcslashes.php\n\n// - https://github.com/php/php-src/blob/master/ext/standard/string.c\n\n//\n\n// see also https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences\n\n//\n\npu...
Rust
build.rs
Juici/wchar-rs
4bd0b10010653099caef15be0b332324d99c5701
use std::collections::HashMap; macro_rules! consts { ($($arch:ident),* $(,)?) => { $( #[allow(non_upper_case_globals, dead_code)] pub const $arch: &str = stringify!($arch); )* }; } mod arch { consts! { aarch64, arm, hexagon, mips, ...
use std::collections::HashMap; macro_rules! consts { ($($arch:ident),* $(,)?) => { $( #[allow(non_upper_case_globals, dead_code)] pub const $arch: &str = stringify!($arch); )* }; } mod arch { consts! { aarch64, arm, hexagon, mips, ...
, Some(arch::powerpc | arch::powerpc64) => WChar::I32, Some(arch::riscv32 | arch::riscv64) => c_int, Some(arch::sparc | arch::sparc64) => WChar::I32, Some(arch::s390x) => WChar::I32, Some(arch::x86 | arch::x86_64) => WChar::I32, ...
WChar::U32, Some(arch::x86 | arch::x86_64) => WChar::I32, Some(arch::powerpc | arch::powerpc64) => WChar::U32, _ => WChar::Unknown, }, os if cfg.unix() => get_unix_wchar(&cfg, os), Some(os::hermit) => get_hermit_wchar(&cfg), os => { let en...
random
[ { "content": "pub fn expand_str(ty: WCharType, text: &str) -> TokenStream {\n\n fn quote_str<T: Encode>(text: &str) -> TokenStream {\n\n let chars = T::encode_str(text);\n\n quote::quote! { &[#(#chars),*] }\n\n }\n\n\n\n match ty {\n\n WCharType::U16(_) => quote_str::<u16>(text),\n...
Rust
examples/online_decrypt/src/main.rs
fossabot/mesatee
49f1d6c81d373471b6f28ddc49bda6265c96755c
use lazy_static::lazy_static; use mesatee_sdk::{Mesatee, MesateeEnclaveInfo}; use ring::aead; use ring::aead::Aad; use ring::aead::Nonce; use ring::rand; use ring::rand::SecureRandom; use serde_derive::{Deserialize, Serialize}; use std::net::SocketAddr; use std::{env, fs}; static FUNCTION_NAME: &'static str = "decry...
use lazy_static::lazy_static; use mesatee_sdk::{Mesatee, MesateeEnclaveInfo}; use ring::aead; use ring::aead::Aad; use ring::aead::Nonce; use ring::rand; use ring::rand::SecureRandom; use serde_derive::{Deserialize, Serialize}; use std::net::SocketAddr; use std::{env, fs}; static FUNCTION_NAME: &'static str = "decry...
#[derive(Serialize, Deserialize)] struct AEADKeyConfig { pub key: Vec<u8>, pub nonce: Vec<u8>, pub ad: Vec<u8>, } impl AEADKeyConfig { pub fn new() -> Self { let mut key_config = AEADKeyConfig { key: vec![0; 32], nonce: vec![0; 12], ad: vec![0; 5], ...
fn print_usage() { let msg = " ./online_decrypt gen_and_upload_key key_saving_path key_file_id_saving_path ./online_decrypt local_encrypt plaintxt_path encrypted_data_saving_path key_path ./online_decrypt online_decrypt encrypted_data_path key_file_id decrypted_data_saving_path gen_and_upload_key: ...
function_block-full_function
[ { "content": "fn launch_task(info: &MesateeEnclaveInfo, user_id: &str, user_token: &str, task_id: &str) {\n\n let mesatee = Mesatee::new(info, user_id, user_token, *TMS_ADDR, *TDFS_ADDR).unwrap();\n\n\n\n let task = mesatee.get_task(task_id).unwrap();\n\n let task_info = task.task_info.as_ref().unwrap(...
Rust
blog-client/src/locations.rs
AlterionX/benxu.dev
994e2d11e9948350287f750075c920ffccd9a148
use seed::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ messages::{AsyncM as GlobalAsyncM, M as GlobalM}, model::{Store as GlobalS, StoreOperations as GSOp}, }; pub mod editor; pub mod listing; pub mod login; pub mod viewer; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum M { Login...
use seed::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ messages::{AsyncM as GlobalAsyncM, M as GlobalM}, model::{Store as GlobalS, StoreOperations as GSOp}, }; pub mod editor; pub mod listing; pub mod login; pub mod viewer; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum M { Login...
pub fn view(loc: &Location, gs: &GlobalS) -> Vec<Node<GlobalM>> { match loc { Location::Logout => vec![h1!["Logging out..."]], Location::Listing(s) => listing::render(s, gs).map_msg(M::Listing), Location::Login(s) => vec![login::render(s, gs).map_msg(M::Login)], Location::Viewer(s) =...
function_block-full_function
[ { "content": "pub fn update(m: M, s: &mut S, gs: &GlobalS, orders: &mut impl Orders<GlobalM, GlobalM>) {\n\n use M::*;\n\n match s {\n\n S::Undetermined(_) => return,\n\n _ => (),\n\n };\n\n match m {\n\n Title(title) => s.update_title(title),\n\n Body(body) => s.update_b...
Rust
near/oysterpack-smart-account-management/src/domain/account_metrics.rs
oysterpack/oysterpack-smart
f2985636d7c035de06e319f7ac8bec92e1293362
use crate::AccountStorageEvent; use oysterpack_smart_near::near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, serde::{Deserialize, Serialize}, }; use crate::AccountNearDataObject; use lazy_static::lazy_static; use oysterpack_smart_near::{ data::{numbers::U128, Object}, domain::{StorageUsage, ...
use crate::AccountStorageEvent; use oysterpack_smart_near::near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, serde::{Deserialize, Serialize}, }; use crate::AccountNearDataObject; use lazy_static::lazy_static; use oysterpack_smart_near::{ data::{numbers::U128, Object}, domain::{StorageUsage, ...
account.save(); } } } AccountStorageEvent::Unregistered(account_near_balance) => { stats.total_registered_accounts = stats .total_registered_accounts .checked_sub(1) ...
if change.is_positive() { account.incr_storage_usage((change.value() as u64).into()) } else { account.decr_storage_usage((change.value().abs() as u64).into()) }
if_condition
[]
Rust
src/main.rs
chinmaydd/radeco
e8e4c71efed2a5dba8a964bebf69e7d8705248f6
#[cfg(feature = "trace_log")] extern crate env_logger; extern crate radeco_lib; extern crate r2pipe; extern crate r2api; extern crate base64; extern crate rustyline; use radeco_lib::analysis::cse::cse::CSE; use radeco_lib::analysis::interproc::fixcall::CallFixer; use radeco_lib::analysis::sccp; use radeco_lib::backen...
#[cfg(feature = "trace_log")] extern crate env_logger; extern crate radeco_lib; extern crate r2pipe; extern crate r2api; extern crate base64; extern crate rustyline; use radeco_lib::analysis::cse::cse::CSE; use radeco_lib::analysis::interproc::fixcall::CallFixer; use radeco_lib::analysis::sccp; use radeco_lib::backen...
let strings = rmod.strings() .iter() .filter(|ref s| s.vaddr.is_some() && s.string.is_some()) .cloned() .map(|s| { let (addr, _s) = (s.vaddr.unwrap(), s.string.unwrap()); let ...
let func_name_map = rmod.functions .iter() .map(|(&addr, f)| (addr, f.name.to_string())) .collect();
assignment_statement
[ { "content": "// Prints summary of the matching if any command line arguments were\n\n// specified,\n\n//\n\n// In case of full match, a message will be displayed to the user\n\n// In case of partial matching, a list of unmatched items will be shown\n\n// If no matching occurred, all the available results will ...
Rust
src/ssi0/ris.rs
pipex/cc2538
51ab96d8afed86bad1be5c4aee687d7909d98209
#[doc = "Reader of register RIS"] pub type R = crate::R<u32, super::RIS>; #[doc = "Writer for register RIS"] pub type W = crate::W<u32, super::RIS>; #[doc = "Register RIS `reset()`'s with value 0"] impl crate::ResetValue for super::RIS { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Reader of register RIS"] pub type R = crate::R<u32, super::RIS>; #[doc = "Writer for register RIS"] pub type W = crate::W<u32, super::RIS>; #[doc = "Register RIS `reset()`'s with value 0"] impl crate::ResetValue for super::RIS { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
rrupt state (before masking) of SSIRORINTR"] #[inline(always)] pub fn rorris(&mut self) -> RORRIS_W { RORRIS_W { w: self } } }
eserved, read as zero, do not modify."] #[inline(always)] pub fn reserved11(&self) -> RESERVED11_R { RESERVED11_R::new(((self.bits >> 4) & 0x0fff) as u16) } #[doc = "Bit 3 - 3:3\\] SSI SSITXINTR raw state (RO) Reset value: 0x1 Gives the raw interrupt state (before masking) of SSITXINTR"] #[i...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/config/serializer.rs
veeso/tuifeed
059337fdedf5e62b235df172ba5fec8047e414f3
/** * MIT License * * tuifeed - Copyright (c) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights ...
/** * MIT License * * tuifeed - Copyright (c) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights ...
} #[cfg(test)] mod test { use super::*; use crate::config::Config; use pretty_assertions::assert_eq; use std::fs::File; use std::io::Write; #[test] fn should_create_serialization_errors() { let error: SerializerError = SerializerError::new(SerializerErrorKind::Syntax...
match toml::de::from_str(data.as_str()) { Ok(deserialized) => Ok(deserialized), Err(err) => Err(SerializerError::new( SerializerErrorKind::Syntax, err.to_string(), )), }
if_condition
[ { "content": "/// ### open_file_read\n\n///\n\n/// Open file at `p` for read\n\npub fn open_file_read(p: &Path) -> Result<impl Read, IoError> {\n\n File::open(p)\n\n}\n\n\n", "file_path": "src/helpers/file.rs", "rank": 0, "score": 238295.2757211862 }, { "content": "/// ### write_file\n\n/...
Rust
src/shapes/moving_sphere.rs
IDragnev/ray-tracer
6364452255d243ea796bea99bb21292f5ac32bfc
use crate::{ math::{ self, Point3, Interval, }, core::{ Hittable, HitRecord, Ray, }, materials::{ Material, }, aabb::{ self, AABB, }, textures::{ TextureCoordinates, }, }; pub struct Centers { ...
use crate::{ math::{ self, Point3, Interval, }, core::{ Hittable, HitRecord, Ray, }, materials::{ Material, }, aabb::{ self, AABB, }, textures::{ TextureCoordinates, }, }; pub struct Centers { ...
fn bounding_box(&self, time_interval: &Interval<f32>) -> Option<AABB> { let v = math::vec3(self.radius, self.radius, self.radius); let center0 = self.center_at(time_interval.min()); let center1 = self.center_at(time_interval.max()); let box0 = AABB { min: center0 - v, ...
fn hit(&self, ray: &Ray, hit_interval: &Interval<f32>) -> Option<HitRecord> { use math::{dot, EuclideanSpace}; let center = self.center_at(ray.time); let oc = ray.origin - center; let a = dot(ray.direction, ray.direction); let b = dot(ray.direction, oc); let c = ...
function_block-full_function
[ { "content": "pub fn scene(camera_aspect: f32, time_interval: &Interval<f32>) -> (Scene, Camera) {\n\n let red = Box::new(Lambertian::new(Box::new(ConstantTexture::from_rgb(vec3(0.65, 0.05, 0.05))))) as Box<dyn Material>;\n\n let green = Box::new(Lambertian::new(Box::new(ConstantTexture::from_rgb(vec3(0.1...
Rust
nestadia-wgpu/src/debugger.rs
GoldenKain/nestadia
33c44084970ea3a72336312c7dedafc6031931a0
use crate::State; use std::io::{stdin, stdout, Write}; use structopt::clap::AppSettings; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(no_version)] enum DebuggerOpt { #[structopt(visible_alias = "c", no_version)] Continue, #[structopt(visible_alias = "b", no_version)] ...
use crate::State; use std::io::{stdin, stdout, Write}; use structopt::clap::AppSettings; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(no_version)] enum DebuggerOpt { #[structopt(visible_alias = "c", no_version)] Continue, #[structopt(visible_alias = "b", no_version)] ...
self.breakpoints.iter().enumerate() { println!("Breakpoint {}: {:#06x}", index, addr); } } fn print_registers(&self, register: Option<String>) { let cpu = self.emulator.cpu(); if let Some(register) = register { match register.as_str() { "a" => pri...
erInfoOpt { #[structopt(visible_alias = "b", no_version)] Break, #[structopt(visible_alias = "r", no_version)] Reg { register: Option<String> }, } fn parse_hex_addr(src: &str) -> Result<u16, std::num::ParseIntError> { let src = src.trim_start_matches("0x"); u16::from_str_radix(src, 16...
random
[ { "content": "fn to_u16(data: &[u8]) -> u16 {\n\n (data[0] as u16) | ((data[1] as u16) << 8)\n\n}\n", "file_path": "nestadia/src/cpu/disassembler.rs", "rank": 3, "score": 84670.03807645258 }, { "content": "enum EmulatorMsg {\n\n RenderFrame,\n\n KeyUp(web_sys::KeyboardEvent),\n\n ...
Rust
elf/src/program.rs
sos-os/sos-kernel
641b83fb078576e62facb242d3defefc73a05537
use super::ElfWord; pub trait Header: Sized { type Word: ElfWord; fn ty(&self) -> Type; fn offset(&self) -> usize; fn vaddr(&self) -> Self::Word; fn paddr(&self) -> Self::Word; fn file_size(&self) -> usize; fn mem_size...
use super::ElfWord; pub trait Header: Sized { type Word: ElfWord; fn ty(&self) -> Type; fn offset(&self) -> usize; fn vaddr(&self) -> Self::Word; fn paddr(&self) -> Self::Word; fn file_size(&self) -> usize; fn mem_size...
u32 , pub flags: Flags , pub align: u32 } }
fn flags(&self) -> Flags; fn offset(&self) -> usize; fn vaddr(&self) -> Self::Word; fn paddr(&self) -> Self::Word; fn file_size(&self) -> usize; fn mem_size(&self) -> usize; fn align(&self) -> usize; } ...
random
[ { "content": "/// Trait representing an ELF File Header.\n\n///\n\n/// This trait allows [HeaderRepr] to provide a consistent API regardless\n\n/// of whether the header section uses 32- or 64-bit [ELF word]s. A number of\n\n/// field values in the header of various sizes are converted to `usize` by\n\n/// this...