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/main.rs
rmsk2/rustpwman
a771d7715daa81704b02e5018d6ea1fed241595d
/* Copyright 2021 Martin Grap Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
/* Copyright 2021 Martin Grap Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
fn set_pbkdf_from_command_line(&mut self, matches: &clap::ArgMatches) { if matches.is_present(ARG_KDF) { let mut kdf_names: Vec<String> = Vec::new(); if let Some(names) = matches.values_of(ARG_KDF) { names.for_each(|x| kdf_names.push(String::from(x))); ...
r) -> (fcrypt::KeyDeriver, fcrypt::KdfId) { return match fcrypt::KdfId::from_str(deriver_name) { Some(v) => v.to_named_func(), _ => (self.default_deriver, self.default_deriver_id) } }
function_block-function_prefixed
[ { "content": "#[test]\n\npub fn test_fcrypt_enc_dec() {\n\n let mut ctx = fcrypt::GcmContext::new();\n\n let data_raw: Vec<u8> = vec![0; 32];\n\n\n\n let cipher_text = match ctx.encrypt(\"this is a test\", &data_raw) {\n\n Ok(c) => c,\n\n Err(_) => { panic!(\"Encryption failed\"); }\n\n ...
Rust
src/models/reference.rs
lancelafontaine/grimoire-lsp
ec6d7494c84ea24329ef36624d111d038a99aca5
use crate::models::Location; use crate::repositories::ReferencesRepository; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Serialize, Deserialize, Debug)] pub struct Reference { path: PathBuf, header: String, header_location: Location, persisted: bool, } impl Reference { pub...
use crate::models::Location; use crate::repositories::ReferencesRepository; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Serialize, Deserialize, Debug)] pub struct Reference { path: PathBuf, header: String, header_location: Location, persisted: bool, } impl Reference { pub...
}
fn reference_upsert() -> crate::Result<()> { let db = Database::mock(); let mut reference = Reference::mock(); assert!(!reference.persisted); db.execute(|repositories| { let references_repository = repositories.references(); reference.upsert(&references_repositor...
function_block-full_function
[ { "content": "pub fn path_cannot_convert_to_string(path: &Path) -> Error {\n\n let msg = format!(\"The following path {path:?} could not represented as a string.\");\n\n log::warn!(\"{}\", msg);\n\n anyhow!(msg)\n\n}\n\n\n", "file_path": "src/errors.rs", "rank": 0, "score": 130401.706053424...
Rust
src/main.rs
kamilpitula/RustySnake
cd47ffd72686e07a1e30c6adae9644ce8f072354
extern crate glutin_window; extern crate graphics; extern crate opengl_graphics; extern crate piston; extern crate piston_window; extern crate rand; extern crate itertools; extern crate find_folder; use glutin_window::GlutinWindow as Window; use opengl_graphics::{OpenGL, GlGraphics, GlyphCache}; use piston::event_loop...
extern crate glutin_window; extern crate graphics; extern crate opengl_graphics; extern crate piston; extern crate piston_window; extern crate rand; extern crate itertools; extern crate find_folder; use glutin_window::GlutinWindow as Window; use opengl_graphics::{OpenGL, GlGraphics, GlyphCache}; use piston::event_loop...
if let Some(args) = e.update_args(){ let stateFinished = current_state.update(&args); current_state = match stateFinished { State::Start(data) =>{Box::new(startgame::StartGame::new(32))}, State::Game(data) => {Box::new(game::Gam...
if let Some(args) = e.render_args(){ gl.draw(args.viewport(), |c, mut gl| { clear(colors::GRAY, gl); let (board_size_calculated, left, bottom) = calculate_viewport(&c); let c = c.scale( board_size_calculated / config::BOARD_SIZE as f64, ...
if_condition
[ { "content": "pub trait GameState {\n\n fn render(&mut self, ctx: &Context, gl: &mut GlGraphics, glyphs: &mut GlyphCache);\n\n fn update(&mut self, args: &UpdateArgs) -> State<GameData>;\n\n fn key_press(&mut self, args: &Button);\n\n}", "file_path": "src/gamestate.rs", "rank": 2, ...
Rust
src/composables/fused_pack.rs
tlrmchlsmth/mommies
a819fac29148ac4a4e9549933ddf318c259e731e
use core::marker::PhantomData; use matrix::{Scalar,Mat,PackPair,ResizableBuffer}; use thread_comm::ThreadInfo; use composables::{GemmNode,AlgorithmStep}; pub struct DelayedPackA<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, Apt: Mat<T>, S: GemmNode<T, PackPair<T,At,Apt>, Bt, Ct>> { child: S, a_pack: Apt...
use core::marker::PhantomData; use matrix::{Scalar,Mat,PackPair,ResizableBuffer}; use thread_comm::ThreadInfo; use composables::{GemmNode,AlgorithmStep}; pub struct DelayedPackA<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, Apt: Mat<T>, S: GemmNode<T, PackPair<T,At,Apt>, Bt, Ct>> { child: S, a_pack: Apt...
fn new() -> Self { let algo_desc = S::hierarchy_description(); let y_marker = AlgorithmStep::K{bsz: 0}; let x_marker = AlgorithmStep::N{bsz: 0}; DelayedPackB{ child: S::new(), b_pack: Bpt::empty(y_marker, x_marker, &algo_desc), algo_desc: algo_desc, _...
unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, thr: &ThreadInfo<T>) -> () { let y_marker = AlgorithmStep::K{bsz: 0}; let x_marker = AlgorithmStep::N{bsz: 0}; let capacity_for_bpt = Bpt:: capacity_for(b, y_marker, x_marker, &self.algo_desc); thr.barrier(); ...
function_block-full_function
[ { "content": "pub fn test_c_eq_a_b<T:Scalar, At:Mat<T>, Bt:Mat<T>, Ct:Mat<T>>( a: &mut At, b: &mut Bt, c: &mut Ct ) -> T {\n\n let mut ref_gemm: TripleLoop = TripleLoop{};\n\n\n\n let m = c.height();\n\n let n = b.width();\n\n let k = a.width();\n\n\n\n let mut w: Matrix<T> = Matrix::new(n, 1);\n...
Rust
src/day08.rs
srujun/aoc2020
340a42121c2d4111600021b5a3894508204f7063
use crate::problem::Problem; use std::collections::HashSet; #[derive(Clone, Copy, Debug)] enum Operation { ACC, JMP, NOP, } #[derive(Clone, Copy, Debug)] struct Instruction(Operation, i32); #[derive(Default)] pub struct DayEight {} impl DayEight { fn parse_instruction(line: &str) -> Instruction { let m...
use crate::problem::Problem; use std::collections::HashSet; #[derive(Clone, Copy, Debug)] enum Operation { ACC, JMP, NOP, } #[derive(Clone, Copy, Debug)] struct Instruction(Operation, i32); #[derive(Default)] pub struct DayEight {} impl DayEight { fn parse_instruction(line: &str) -> Instruction { let m...
ight::new(); let input = "nop +0\n\ acc +1\n\ jmp +4\n\ acc +3\n\ jmp -3\n\ acc -99\n\ acc +1\n\ jmp -4\n\ acc +6\n"; assert_eq!(problem.part_two(input).unwrap(), "8".to_string...
copy, iprs_seen.clone(), ipr, acc) { return final_acc; } program_copy[ipr] = instruction; } Operation::NOP => { program_copy[ipr] = Instruction(Operation::JMP, instruction.1); if let Some(final_acc) = Self::does_terminate(&program_...
random
[ { "content": "fn print_problem(day: usize, debug: bool) -> Result<(), String> {\n\n let day_str = format!(\"{:02}\", day);\n\n\n\n let problem =\n\n get_problem(day, debug).ok_or_else(|| format!(\"Day {} not implemented!\", day_str))?;\n\n let input = fs::read_to_string(format!(\"inputs/day{}.txt\", day_s...
Rust
crates/rome_js_formatter/src/utils/format_conditional.rs
mrkldshv/tools
c173b0c01ee499fcb49d6ae328f1229daa183868
use crate::prelude::*; use rome_formatter::{format_args, write}; use rome_js_syntax::{JsAnyExpression, JsConditionalExpression, TsConditionalType, TsType}; use rome_rowan::AstNode; pub enum Conditional { Expression(JsConditionalExpression), Type(TsConditionalType), } impl Conditional { fn from_type(ts_typ...
use crate::prelude::*; use rome_formatter::{format_args, write}; use rome_js_syntax::{JsAnyExpression, JsConditionalExpression, TsConditionalType, TsType}; use rome_rowan::AstNode; pub enum Conditional { Expression(JsConditionalExpression), Type(TsConditionalType), } impl Conditional { fn from_type(ts_typ...
), format_alternate ])] )?; } else { write!( f, [group_elements(&format_args![ space_token(), format_consequent, space_token(), format_alter...
format_consequent = format_with(|f| self.format_with_consequent(f, consequent.as_ref())); let format_alternate = format_with(|f| self.format_with_alternate(f, alternate.as_ref())); let _body = if left_or_right_is_conditional || parent_is_conditional { write!( f...
function_block-random_span
[ { "content": "pub fn parse_until_chr(input: &'_ str, f: impl Fn(char) -> bool) -> Option<(&'_ str, &'_ str)> {\n\n let mut qty = 0;\n\n\n\n for chr in input.chars() {\n\n if f(chr) {\n\n break;\n\n }\n\n\n\n qty += chr.len_utf8();\n\n }\n\n\n\n if qty > 0 {\n\n ...
Rust
src/light.rs
po-gl/Raytracer
e90e7d21a7bff88d8cb7968fa8d3f3a92d2f36d5
use super::tuple::Tuple; use super::color::Color; use crate::material::Material; use crate::{tuple, intersection}; use crate::float::Float; use crate::shape::Shape; use rand::{Rng}; use crate::world::World; use crate::shape::shape_list::ShapeList; use crate::ray::Ray; const DEFAULT_RAY_COUNT: usize = 100; #[derive(...
use super::tuple::Tuple; use super::color::Color; use crate::material::Material; use crate::{tuple, intersection}; use crate::float::Float; use crate::shape::Shape; use rand::{Rng}; use crate::world::World; use crate::shape::shape_list::ShapeList; use crate::ray::Ray; const DEFAULT_RAY_COUNT: usize = 100; #[derive(...
} #[cfg(test)] mod tests { use super::*; use crate::tuple::{point, vector}; #[test] fn light_point_light_creation() { let i = Color::new(1.0, 1.0, 1.0); let p = point(0.0, 0.0, 0.0); let light = Light::point_light(&p, &i); assert_eq!(light.position, p); assert_...
let light_dot_normal = Float(tuple::dot(&light_v, &normal_v)); if light_source.radius == None { if light_dot_normal < Float(0.0) || in_shadow { diffuse = Color::new(0.0, 0.0, 0.0); specular = Color::new(0.0, 0.0, 0.0); ...
function_block-function_prefix_line
[ { "content": "/// Recursively converts a point to its parent's point until\n\n/// getting a world space point\n\npub fn world_to_object(shape: Box<dyn Shape + Send>, point: Tuple, shape_list: &mut ShapeList) -> Tuple {\n\n let mut new_point = point;\n\n if shape.parent(shape_list) != None {\n\n new...
Rust
src/node.rs
dinaraparanid/Binary-Tree
aae41ca56dc45910f155e35db475c5c7757b77c5
use crate::branch::Branch; use std::cmp::Ordering; use std::collections::VecDeque; use std::mem; #[derive(Debug, Clone, PartialOrd, PartialEq)] pub(crate) enum Node<T> where T: Copy + Clone + Ord + Eq { Empty, NonEmpty(Box<Branch<T>>), } impl<T> Default for Node<T> where T: Copy + Clone + Ord + Eq { #[inline] f...
use crate::branch::Branch; use std::cmp::Ordering; use std::collections::VecDeque; use std::mem; #[derive(Debug, Clone, PartialOrd, PartialEq)] pub(crate) enum Node<T> where T: Copy + Clone + Ord + Eq { Empty, NonEmpty(Box<Branch<T>>), } impl<T> Default for Node<T> where T: Copy + Clone + Ord + Eq { #[inline] f...
#[inline] pub(crate) fn ignore_mut(&mut self) -> &mut Box<Branch<T>> { if let Node::NonEmpty(ref mut branch) = *self { return branch; } else { panic!("Empty tree"); } } #[inline] pub(crate) fn get_key(&self) -> &T { &self.ignore().key } pub(crate) fn insert(&mut self, val: &T...
pub(crate) fn ignore(&self) -> &Box<Branch<T>> { if let Node::NonEmpty(ref branch) = *self { return branch; } else { panic!("Empty tree"); } }
function_block-full_function
[ { "content": "fn find_vec<T>(src: &Vec<T>, val: &T) -> Option<usize>\n\n\twhere T: Copy + Clone + Ord + Eq\n\n{\n\n\tfor i in 0..src.len() {\n\n\t\tif src[i] == *val {\n\n\t\t\treturn Some(i)\n\n\t\t}\n\n\t}\n\n\tNone\n\n}\n\n\n\n/// *English*: Trait **Iterator** for tree. Now we can iterate in our tree.\n\n//...
Rust
inject-macro/src/inject/arguments/mod.rs
tobni/inject-rs
3fd9de0768486dd99922d4a57333b6298816e77e
use std::collections::HashSet; use argument::{DefaultArgs, InjectArgument, Mergable, NoInjectArgs}; use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{Error, Expr, Ident, Result, Token}; use crate::inject::input::...
use std::collections::HashSet; use argument::{DefaultArgs, InjectArgument, Mergable, NoInjectArgs}; use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{Error, Expr, Ident, Result, Token}; use crate::inject::input::...
} syn::FnArg::Receiver(receiver) => { return Err(Error::new( receiver.self_token.span(), "not allowed to reference 'self'", )) } } } if let Some(&extra_fi...
if let syn::Pat::Ident(syn::PatIdent { ident, .. }) = pat.as_ref() { let default_arg = self.get_default(&ident); let should_inject = !self.is_no_inject(&ident); fields.push(format!("'{}'", ident)); let injected_arg = ...
if_condition
[ { "content": "pub fn duplicate_field_error(field: &Ident) -> Error {\n\n Error::new(field.span(), format!(\"duplicate identifier '{}'\", field))\n\n}\n", "file_path": "inject-macro/src/inject/arguments/error.rs", "rank": 0, "score": 225205.28362161719 }, { "content": "#[fixture]\n\npub fn...
Rust
src/banking/sheba_table.rs
rustland-fa/persian-tools-rs
a7c39cbfcf84d930d08ee9cfed335762c12443ed
#[derive(Debug)] pub struct ShebaInfo { nickname: &'static str, name: &'static str, persian_name: &'static str, code: &'static str, } pub static SHEBA_CODE_TABLE: phf::Map<&'static str, ShebaInfo> = phf::phf_map! { "010" => ShebaInfo{ nickname: "central-bank", name: "Central Bank of...
#[derive(Debug)] pub struct ShebaInfo { nickname: &'static str, name: &'static str, persian_name: &'static str, code: &'static str, } pub static SHEBA_CODE_TABLE: phf::Map<&'static str, ShebaInfo> = phf::phf_map! { "010" => ShebaInfo{ nickname: "central-bank", name: "Central Bank of...
, "063" => ShebaInfo{ nickname: "ansar", name: "Ansar Bank", persian_name: "بانک انصار", code: "063", }, "064" => ShebaInfo{ nickname: "gardeshgari", name: "Gardeshgari Bank", persian_name: "بانک گردشگری", code: "064", }, "065" => Sheba...
persian_name: "بانک سامان", code: "056", }, "057" => ShebaInfo{ nickname: "pasargad", name: "Pasargad Bank", persian_name: "بانک پاسارگاد", code: "057", }, "058" => ShebaInfo{ nickname: "sarmayeh", name: "Sarmayeh Bank", persian_name: "...
random
[ { "content": "/// Set of helpers for the banking system of Iran.\n\npub trait Banking: AsRef<str> {\n\n /// Checks if the bank card number is valid or not.\n\n fn is_valid_bank_card_number(&self) -> bool {\n\n let number = self.as_ref();\n\n let len = number.len();\n\n if len < 16\n\n...
Rust
imxrt1062-pac/imxrt1062-can3/src/erfier.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register ERFIER"] pub type R = crate::R<u32, super::ERFIER>; #[doc = "Writer for register ERFIER"] pub type W = crate::W<u32, super::ERFIER>; #[doc = "Register ERFIER `reset()`'s with value 0"] impl crate::ResetValue for super::ERFIER { type Type = u32; #[inline(always)] fn reset_value() ...
#[doc = "Reader of register ERFIER"] pub type R = crate::R<u32, super::ERFIER>; #[doc = "Writer for register ERFIER"] pub type W = crate::W<u32, super::ERFIER>; #[doc = "Register ERFIER `reset()`'s with value 0"] impl crate::ResetValue for super::ERFIER { type Type = u32; #[inline(always)] fn reset_value() ...
ERFWMIIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ERFWMIIE`"] pub type ERFWMIIE_R = crate::R<bool, ERFWMIIE_A>; impl ERFWMIIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ERFWMIIE_A { match self.bits { false => ...
the value of the field is `ERFDAIE_1`"] #[inline(always)] pub fn is_erfdaie_1(&self) -> bool { *self == ERFDAIE_A::ERFDAIE_1 } } #[doc = "Write proxy for field `ERFDAIE`"] pub struct ERFDAIE_W<'a> { w: &'a mut W, } impl<'a> ERFDAIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inli...
random
[ { "content": "/// Computes the number of clock ticks that span the provide duration, given\n\n/// the clock frequency and clock divider. If there is no divider, use `Divider::default()`\n\n/// to specify an unused divider. Returns `Ok(ticks)` when the computation of\n\n/// clock ticks succeeds, or an error.\n\n...
Rust
2016/day18/src/main.rs
devonhollowood/adventofcode
9a26bc131e4028554daf93866fcd91a281937118
extern crate clap; extern crate itertools; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Tile { Safe, Trap, } impl Tile { fn is_safe(&self) -> bool { match *self { Tile::Safe => true, Tile::Trap => false, } } } #[derive(Debug, Clone, PartialEq, Eq)] struct ...
extern crate clap; extern crate itertools; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Tile { Safe, Trap, } impl Tile { fn is_safe(&self) -> bool { match *self { Tile::Safe => true, Tile::Trap => false, } } } #[derive(Debug, Clone, PartialEq, Eq)] struct ...
rows(10); assert_eq!(room.iter().flat_map(|row| row.tiles.iter()).filter(|t| t.is_safe()).count(), 38); } }
] fn example_room() { assert_eq!("..^^.".parse::<Row>().unwrap().generate_rows(3), vec!["..^^.".parse().unwrap(), ".^^^^".parse().unwrap(), "^^..^".parse().unwrap()]) } #[test] fn example_count() { let room = ".^^.^.^^^^...
random
[ { "content": "fn part2(initial: &str, input: &[Operation], count: usize) -> String {\n\n let cycle = cycle_len(initial, input);\n\n let mut result = initial.to_owned();\n\n for _ in 0..(count % cycle) {\n\n result = part1(&result, input);\n\n }\n\n result\n\n}\n\n\n", "file_path": "201...
Rust
core/src/mmu.rs
YushiOMOTE/rgy
da99dc58db212bfdd4ec1b38439601a5270a3edf
use alloc::rc::Rc; use alloc::{vec, vec::Vec}; use hashbrown::HashMap; pub enum MemRead { Replace(u8), PassThrough, } pub enum MemWrite { Replace(u8), PassThrough, Block, } pub trait MemHandler { fn on_read(&self, mmu: &Mmu, addr: u16) -> MemRead; fn on...
use alloc::rc::Rc; use alloc::{vec, vec::Vec}; use hashbrown::HashMap; pub enum MemRead { Replace(u8), PassThrough, } pub enum MemWrite { Replace(u8), PassThrough, Block, } pub trait MemHandler { fn on_read(&self, mmu: &Mmu, addr: u16) -> MemRead; fn on...
), handler.clone())), None => {} } } else { self.handlers .insert(i, vec![(handle.clone(), handler.clone())]); } } handle } #[allow(unused)] pub fn remove_handler<T>(&mut self, handle: &Han...
{ Mmu { ram: vec![0u8; 0x10000], handles: HashMap::new(), handlers: HashMap::new(), hdgen: 0, } } fn next_handle(&mut self) -> Handle { let handle = self.hdgen; self.hdgen += 1; Handle(handle) } pub fn add_...
random
[ { "content": "pub fn signed(v: u8) -> u16 {\n\n if v & 0x80 != 0 {\n\n 0xff00 | v as u16\n\n } else {\n\n v as u16\n\n }\n\n}\n\n\n", "file_path": "core/src/alu.rs", "rank": 0, "score": 257541.65765624653 }, { "content": "pub fn add16e(p: u16, q: u8, c: bool) -> (u16, ...
Rust
src/kvm/vm.rs
aztecher/toyvmm
9a8569d92bb7be08573a9719e28095d9bc5742c5
#[allow(unused_imports)] use std::{ os::unix::io::{AsRawFd, FromRawFd, RawFd}, result, }; use kvm_ioctls::{ VmFd, Kvm, }; use kvm_bindings::{ CpuId, kvm_pit_config, kvm_userspace_memory_region, KVM_MEM_LOG_DIRTY_PAGES, KVM_MAX_CPUID_ENTRIES, KVM_PIT_SPEAKER_DUMMY, }; use vm_memor...
#[allow(unused_imports)] use std::{ os::unix::io::{AsRawFd, FromRawFd, RawFd}, result, }; use kvm_ioctls::{ VmFd, Kvm, }; use kvm_bindings::{ CpuId, kvm_pit_config, kvm_userspace_memory_region, KVM_MEM_LOG_DIRTY_PAGES, KVM_MAX_CPUID_ENTRIES, KVM_PIT_SPEAKER_DUMMY, }; use vm_memor...
#[test] fn test_new() { use vmm_sys_util::tempfile::TempFile; let vm = Vm::new( &unsafe { Kvm::from_raw_fd(TempFile::new().unwrap().as_file().as_raw_fd()) } ); assert!(vm.is_err()); let kvm = Kvm::new().expect("Failed to open /dev/kvm or u...
pub(crate) fn setup_vm_with_mem(mem_size: usize) ->(Vm, GuestMemoryMmap) { let kvm = Kvm::new().expect("Faled to open /dev/kvm or unexpected error"); let gm = create_anon_guest_memory(&[(GuestAddress(0), mem_size)], false) .unwrap(); let mut vm = Vm::new(&kvm).expect("Cannot create n...
function_block-function_prefix_line
[ { "content": "fn write_idt_value(val: u64, guest_mem: &GuestMemoryMmap) -> Result<(), RegError> {\n\n let boot_idt_addr = GuestAddress(BOOT_IDT_OFFSET);\n\n guest_mem\n\n .write_obj(val, boot_idt_addr)\n\n .map_err(|_| RegError::WriteIdt)\n\n}\n\n\n", "file_path": "src/arch/x86_64.rs", ...
Rust
examples/datasources/k8s.rs
eliasyaoyc/sentinel-rust
62e3b036d0471e1f2118722675e30dad096cbc04
#![allow(unreachable_code)] use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition; use kube::{ api::{Api, Patch, PatchParams, PostParams}, runtime::wait::{await_condition, conditions}, Client, CustomResourceExt, }; use sentinel_rs::{ base, datasource::{ ...
#![allow(unreachable_code)] use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition; use kube::{ api::{Api, Patch, PatchParams, PostParams}, runtime::wait::{await_condition, conditions}, Client, CustomResourceExt, }; use sentinel_rs::{ base, datasource::{ ...
async fn task() { println!("{}: passed", sentinel_rs::utils::curr_time_millis()); sleep(Duration::from_millis(100)).await; } async fn dynamic_update( client: &Client, manager: &str, namespace: &str, cr_name: &str, ) -> Result<()> { let crds: Api<CustomResourceDefinition> = Api::all(client...
async fn basic_flow_example() -> Vec<JoinHandle<()>> { sentinel_rs::init_default().unwrap_or_else(|err| sentinel_rs::logging::error!("{:?}", err)); let resource_name = String::from("task"); flow::load_rules(vec![Arc::new(flow::Rule { resource: resource_name.clone(), threshold: 10.0...
function_block-full_function
[ { "content": "// An example on consul dynamic data source.\n\n// Install consul, and run `consul agent -data-dir ./` in your terminal first. Then run this example.\n\n// You will find that QPS number is restricted to 10 at first. But soon, it will be restricted to 1.\n\nfn main() -> Result<()> {\n\n let hand...
Rust
atat/src/error.rs
burrbull/atat
6732e8d099e2536302e35556c68a472558dab2bd
use heapless::Vec; #[derive(Clone, Debug, PartialEq)] pub enum InternalError { Read, Write, Timeout, InvalidResponse, Aborted, Overflow, Parse, Error(Vec<u8, 85>), } impl InternalError { pub fn as_byte(&self) -> u8 { match self { ...
use heapless::Vec; #[derive(Clone, Debug, PartialEq)] pub enum InternalError { Read, Write, Timeout, InvalidResponse, Aborted, Overflow, Parse, Error(Vec<u8, 85>), } impl InternalError { pub fn as_byte(&self) -> u8 { match self { ...
} } Self::Parse } } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct GenericError; impl core::str::FromStr for GenericError { type Err = core::convert::Infallible; fn ...
:Write => Self::Write, InternalError::Timeout => Self::Timeout, InternalError::InvalidResponse => Self::InvalidResponse, InternalError::Aborted => Self::Aborted, InternalError::Overflow => Self::Overflow, InternalError::Parse => Self::Parse, Intern...
function_block-random_span
[]
Rust
zebra-state/src/service/chain_tip/tests/prop.rs
luckytokidoki/zebra
20429b5efaf1faadd80c6274e147150c1e04f329
use std::{collections::HashSet, env, sync::Arc}; use futures::FutureExt; use proptest::prelude::*; use proptest_derive::Arbitrary; use zebra_chain::{ block::Block, chain_tip::ChainTip, fmt::{DisplayToDebug, SummaryDebug}, parameters::{Network, NetworkUpgrade}, }; use crate::service::chain_tip::{Chain...
use std::{collections::HashSet, env, sync::Arc}; use futures::FutureExt; use proptest::prelude::*; use proptest_derive::Arbitrary; use zebra_chain::{ block::Block, chain_tip::ChainTip, fmt::{DisplayToDebug, SummaryDebug}, parameters::{Network, NetworkUpgrade}, }; use crate::service::chain_tip::{Chain...
} pub fn is_finalized(&self) -> bool { matches!(self, BlockUpdate::Finalized(_)) } } #[derive(Arbitrary, Copy, Clone, Debug, Eq, PartialEq)] enum BlockConnection { Reset, Grow, } impl BlockConnection { pub fn is_grow(&self) -> bool { *self == BlockConnection::Grow ...
match self { BlockUpdate::Finalized(block) => block, BlockUpdate::NonFinalized(block) => block, }
if_condition
[ { "content": "/// Map a list of inventory hashes to the corresponding block hashes.\n\n/// Non-block inventory hashes are skipped.\n\nfn block_hashes(items: &'_ [InventoryHash]) -> impl Iterator<Item = block::Hash> + '_ {\n\n items.iter().filter_map(InventoryHash::block_hash)\n\n}\n", "file_path": "zebra...
Rust
tests/xflow_validation.rs
nosuchtype/xflow-rust
71712caa9be34a02c8ef27b9aa4df43df3a4b14a
extern crate env_logger; extern crate gears; use gears::structure::xflow::*; use gears::validation::xflow::*; mod common; use crate::common::load_doc; #[test] fn test_init_validation() { let xfs = load_doc::<XFlowDocument>("resource/docs/xflow/flows/10_steps.json"); assert_eq!(xfs.body.nodes.len(), 10); } #...
extern crate env_logger; extern crate gears; use gears::structure::xflow::*; use gears::validation::xflow::*; mod common; use crate::common::load_doc; #[test] fn test_init_validation() { let x
let xfs = load_doc::<XFlowDocument>("resource/docs/xflow/bad_flows/no_terminal_nodes.json"); let res_a = Validation::has_terminal_nodes(&xfs); assert_eq!(res_a.len(), 1); assert_eq!(res_a[0].code, 1); assert_eq!(res_a[0].paths[0], "/nodes"); } #[test] fn test_all_node_actions_have_matching_requireme...
fs = load_doc::<XFlowDocument>("resource/docs/xflow/flows/10_steps.json"); assert_eq!(xfs.body.nodes.len(), 10); } #[test] fn test_validations_ok() { let xfs = load_doc::<XFlowDocument>("resource/docs/xflow/flows/10_steps.json"); let res_a = Validation::all_edges_have_nodes(&xfs); assert_eq!(res_a.len...
random
[ { "content": "#[allow(dead_code)]\n\npub fn read_json_file(filename: &str) -> String {\n\n // Create a path to the desired file\n\n let path = Path::new(filename);\n\n let display = path.display();\n\n\n\n let mut file = match File::open(&path) {\n\n Err(why) => panic!(\"couldn't open {}: {}\...
Rust
src/vpn_editor_plugin.rs
cathay4t/libnm-rs
99248bbc5a8b7b1adf62d99846312bfa8f770bcc
use crate::Connection; use crate::VpnEditor; use crate::VpnEditorPluginCapability; #[cfg(any(feature = "v1_4", feature = "dox"))] use crate::VpnPluginInfo; use glib; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GStri...
use crate::Connection; use crate::VpnEditor; use crate::VpnEditorPluginCapability; #[cfg(any(feature = "v1_4", feature = "dox"))] use crate::VpnPluginInfo; use glib; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GStri...
#[cfg(any(feature = "v1_4", feature = "dox"))] fn get_plugin_info(&self) -> Option<VpnPluginInfo> { unsafe { from_glib_none(nm_sys::nm_vpn_editor_plugin_get_plugin_info( self.as_ref().to_glib_none().0, )) } } fn get_suggested_filename<P: IsA<Con...
rror> { unsafe { let mut error = ptr::null_mut(); let ret = nm_sys::nm_vpn_editor_plugin_get_editor( self.as_ref().to_glib_none().0, connection.as_ref().to_glib_none().0, &mut error, ); if error.is_null() { ...
function_block-function_prefixed
[ { "content": "#[cfg(any(feature = \"v1_6\", feature = \"dox\"))]\n\npub fn utils_is_json_object(str: &str) -> Result<(), glib::Error> {\n\n unsafe {\n\n let mut error = ptr::null_mut();\n\n let _ = nm_sys::nm_utils_is_json_object(str.to_glib_none().0, &mut error);\n\n if error.is_null() ...
Rust
src/targets/mod.rs
Healer-fuzz/healer-fuzz
89b3bb04150042fc1ccefa186fdf7667921607b2
use crate::{ model::{SyscallRef, TypeRef}, utils::to_boxed_str, }; use rustc_hash::{FxHashMap, FxHashSet}; use thiserror::Error; pub mod sys_json; #[allow(clippy::type_complexity)] mod syscalls; pub struct Target { pub os: Box<str>, pub arch: Box<str>, pub revision: Box<str>, ...
use crate::{ model::{SyscallRef, TypeRef}, utils::to_boxed_str, }; use rustc_hash::{FxHashMap, FxHashSet}; use thiserror::Error; pub mod sys_json; #[allow(clippy::type_complexity)] mod syscalls; pub struct Target { pub os: Box<str>, pub arch: Box<str>, pub revision: Box<str>, ...
pub fn physical_addr(&self, addr: u64) -> u64 { self.data_offset + addr } fn is_subtype(dst: TypeRef, src: TypeRef) -> bool { let dst_desc = dst.res_desc().unwrap(); let src_desc = src.res_desc().unwrap(); if dst_desc.kinds.len() < src_desc.kinds.len() { *dst_d...
y() { return Err(Error::InvalidSyscalls(invalid_calls)); } let syscalls = all_syscalls .iter() .copied() .filter(|call| !disabled_calls.contains(&*call.name)) .collect::<Vec<_>>(); let call_map = syscalls .iter() ...
function_block-function_prefixed
[ { "content": "pub fn gen_seq(target: &Target, seq: &[SyscallRef]) -> Prog {\n\n let mut ctx = ProgContext::new(target);\n\n let mut calls = Vec::new();\n\n for call in seq {\n\n calls.push(call::gen(&mut ctx, call));\n\n }\n\n Prog::new(calls)\n\n}\n\n\n", "file_path": "src/gen/mod.rs"...
Rust
migration-engine/core/src/api.rs
otan-cockroach/prisma-engines
464ccfcca222190a624e29c8f9a1849021b53c84
use crate::{commands::*, CoreResult}; use migration_connector::{migrations_directory, MigrationConnector}; use std::path::Path; use tracing_futures::Instrument; #[async_trait::async_trait] pub trait GenericApi: Send + Sync + 'static { async fn version(&self) -> CoreResult<String>; async fn apply_m...
use crate::{commands::*, CoreResult}; use migration_connector::{migrations_directory, MigrationConnector}; use std::path::Path; use tracing_futures::Instrument; #[async_trait::async_trait] pub tr
lled_back( &self, input: &MarkMigrationRolledBackInput, ) -> CoreResult<MarkMigrationRolledBackOutput> { mark_migration_rolled_back(input, self) .instrument(tracing::info_span!( "MarkMigrationRolledBack", migration_name = input.migration_name.as_st...
ait GenericApi: Send + Sync + 'static { async fn version(&self) -> CoreResult<String>; async fn apply_migrations(&self, input: &ApplyMigrationsInput) -> CoreResult<ApplyMigrationsOutput>; async fn create_migration(&self, input: &CreateMigrationInput) -> CoreResult<CreateMigrationOutput>; ...
random
[ { "content": "#[async_trait::async_trait]\n\npub trait MigrationConnector: Send + Sync + 'static {\n\n /// If possible on the target connector, acquire an advisory lock, so multiple instances of migrate do not run concurrently.\n\n async fn acquire_lock(&self) -> ConnectorResult<()>;\n\n\n\n /// A stri...
Rust
source/rust_verify/src/rust_to_vir.rs
utaal/verus
429cacc61a312157a7e5935b7d23b1d8e9895b0b
/* Convert Rust HIR/THIR to VIR for verification. For soundness's sake, be as defensive as possible: - if we're not prepared to verify a feature of Rust, disallow the feature - explicitly match all fields of the Rust AST so we catch any features added in the future */ use crate::context::Context; use crate::rust_to_v...
/* Convert Rust HIR/THIR to VIR for verification. For soundness's sake, be as defensive as possible: - if we're not prepared to verify a feature of Rust, disallow the feature - explicitly match all fields of the Rust AST so we catch any features added in the future */ use crate::context::Context; use crate::rust_to_v...
"builtin::Structural", "non_eq_trait_impl", id ); } unsupported_unless!(proc_macros.len() == 0, "procedural macros", proc_macros); for (id, attr) in attrs { check_attr(ctxt.tcx, id, attr)?; } Ok(Arc::new(vir)) }
th, module, &mut item_to_module)?; vir.module_ids.push(path); } for (id, item) in foreign_items { check_foreign_item(ctxt, &mut vir, id, item)?; } for (id, item) in items { check_item(ctxt, &mut vir, &item_to_module[id], id, item)?; } unsupported_unless!(trait_items.len()...
function_block-random_span
[ { "content": "fn get_fn_path<'tcx>(tcx: TyCtxt<'tcx>, expr: &Expr<'tcx>) -> Result<vir::ast::Path, VirErr> {\n\n match &expr.kind {\n\n ExprKind::Path(QPath::Resolved(None, path)) => match path.res {\n\n Res::Def(DefKind::Fn, id) => Ok(def_id_to_vir_path(tcx, id)),\n\n res => uns...
Rust
vm/src/builtins/property.rs
rng-dynamics/RustPython
6165aadcc4e80e0f48f3e784e17b3c7f80d21a8a
/*! Python `property` descriptor class. */ use super::PyTypeRef; use crate::common::lock::PyRwLock; use crate::{ class::PyClassImpl, function::FuncArgs, types::{Constructor, GetDescriptor, Initializer}, AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, }; #[pyc...
/*! Python `property` descriptor class. */ use super::PyTypeRef; use crate::common::lock::PyRwLock; use crate::{ class::PyClassImpl, function::FuncArgs, types::{Constructor, GetDescriptor, Initializer}, AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, }; #[pyc...
let setter_abstract = match self.setter.read().to_owned() { Some(setter) => setter .get_attr("__isabstractmethod__", vm) .unwrap_or_else(|_| vm.ctx.new_bool(false).into()), _ => vm.ctx.new_bool(false).into(), }; vm._or(&setter_abstract, &g...
let getter_abstract = match self.getter.read().to_owned() { Some(getter) => getter .get_attr("__isabstractmethod__", vm) .unwrap_or_else(|_| vm.ctx.new_bool(false).into()), _ => vm.ctx.new_bool(false).into(), };
assignment_statement
[ { "content": "pub fn init(context: &Context) {\n\n PySet::extend_class(context, &context.types.set_type);\n\n PyFrozenSet::extend_class(context, &context.types.frozenset_type);\n\n PySetIterator::extend_class(context, &context.types.set_iterator_type);\n\n}\n", "file_path": "vm/src/builtins/set.rs"...
Rust
espr/src/parser/expression/primary.rs
ARCaide-Development/ruststep
1e3b5233a85bd5b808fdcec9d271deb471a160e2
use super::{ super::{combinator::*, identifier::*, literal::*}, aggregate_initializer::*, simple::*, }; use crate::ast::*; pub fn primary(input: &str) -> ParseResult<Expression> { alt(( literal.map(Expression::Literal), tuple((qualifiable_factor, many0(qualifier))) .map(|(fa...
use super::{ super::{combinator::*, identifier::*, literal::*}, aggregate_initializer::*, simple::*, }; use crate::ast::*; pub fn primary(input: &str) -> ParseResult<Expression> { alt(( literal.map(Expression::Literal), tuple((qualifiable_factor, many0(qualifier))) .map(|(fa...
assert_eq!(qualifiers.len(), 0); } else { panic!("Must be factor") } } #[test] fn function_call_builtin() { let (res, (q, _remarks)) = super::primary("VALUE_UNIQUE(x)").finish().unwrap(); assert_eq!(res, ""); dbg!(q); } #[test] f...
match factor { QualifiableFactor::FunctionCall { name, args } => { assert_eq!(name, FunctionCallName::Reference("f".to_string())); assert_eq!(args.len(), 1); } _ => panic!("Must be reference"), }
if_condition
[ { "content": "/// 217 factor = [simple_factor] \\[ `**` [simple_factor] \\] .\n\npub fn factor(input: &str) -> ParseResult<Expression> {\n\n tuple((simple_factor, opt(tuple((power_op, simple_factor)))))\n\n .map(|(arg1, opt)| {\n\n if let Some((op, arg2)) = opt {\n\n Expressi...
Rust
server/world/systems/chunk/pipelining.rs
iantheearl/voxelize
fda1af792e2eef298b25287fb3835cbba834638e
use nanoid::nanoid; use specs::{ReadExpect, System, WriteExpect}; use crate::{ Chunk, ChunkParams, ChunkUtils, Chunks, Pipeline, Registry, SeededNoise, SeededTerrain, Vec2, WorldConfig, }; pub struct ChunkPipeliningSystem; impl<'a> System<'a> for ChunkPipeliningSystem { type SystemData = ( ReadEx...
use nanoid::nanoid; use specs::{ReadExpect, System, WriteExpect}; use crate::{ Chunk, ChunkParams, ChunkUtils, Chunks, Pipeline, Registry, SeededNoise, SeededTerrain, Vec2, WorldConfig, }; pub struct ChunkPipeliningSystem; impl<'a> System<'a> for ChunkPipeliningSystem { type SystemData = ( ReadEx...
}
if !ready { break; } } if !ready { pipeline.postpone(&chunk.coords, index); continue; } if let Some(data) = stage.needs_space() { let mut space = ...
function_block-function_prefix_line
[ { "content": "pub fn round(n: f32, digits: i32) -> f32 {\n\n let scale = TEN.powi(digits);\n\n (n * scale).round() / scale\n\n}\n\n\n", "file_path": "server/libs/math.rs", "rank": 0, "score": 217130.0712698956 }, { "content": "fn floor_scale_coords(x: f32, y: f32, z: f32, factor: f32) ...
Rust
buttplug/src/device/protocol/vorze_sa.rs
felixonmars/buttplug-rs
cc08e959fe7971efd98c3ac2af52ca292093348d
use super::{ButtplugDeviceResultFuture, ButtplugProtocol, ButtplugProtocolCommandHandler}; use crate::{ core::messages::{self, ButtplugDeviceCommandMessageUnion, MessageAttributesMap}, device::{ protocol::{generic_command_manager::GenericCommandManager, ButtplugProtocolProperties}, DeviceImpl, DeviceWri...
use super::{ButtplugDeviceResultFuture, ButtplugProtocol, ButtplugProtocolCommandHandler}; use crate::{ core::messages::{self, ButtplugDeviceCommandMessageUnion, MessageAttributesMap}, device::{ protocol::{generic_command_manager::GenericCommandManager, ButtplugProtocolProperties}, DeviceImpl, DeviceWri...
.await; assert!(command_receiver.is_empty()); }); } #[test] pub fn test_vorze_sa_rotation_protocol() { async_manager::block_on(async move { let (device, test_device) = new_bluetoothle_test_device("CycSA").await.unwrap(); let command_receiver = test_device .get_endpoint_ch...
check_recv_value( &command_receiver, DeviceImplCommand::Write(DeviceWriteCmd::new( Endpoint::Tx, vec![0x06, 0x03, 0x0], false, )), )
call_expression
[ { "content": "fn serial_write_thread(mut port: Box<dyn SerialPort>, receiver: Receiver<Vec<u8>>) {\n\n let mut recv = receiver;\n\n while let Some(v) = async_manager::block_on(async { recv.next().await }) {\n\n port.write_all(&v).unwrap();\n\n }\n\n}\n\n\n", "file_path": "buttplug/src/server/comm_mana...
Rust
crates/sim1h/src/dht/bbdht/dynamodb/api/item/write.rs
jamesray1/sim1h
a3c7f43bd1fd45647d23667d451fecd07e144ce3
use crate::dht::bbdht::dynamodb::api::item::Item; use crate::dht::bbdht::dynamodb::client::Client; use crate::dht::bbdht::dynamodb::schema::cas::ADDRESS_KEY; use crate::dht::bbdht::dynamodb::schema::cas::CONTENT_KEY; use crate::dht::bbdht::dynamodb::schema::string_attribute_value; use crate::dht::bbdht::dynamodb::schem...
use crate::dht::bbdht::dynamodb::api::item::Item; use crate::dht::bbdht::dynamodb::client::Client; use crate::dht::bbdht::dynamodb::schema::cas::ADDRESS_KEY; use crate::dht::bbdht::dynamodb::schema::cas::CONTENT_KEY; use crate::dht::bbdht::dynamodb::schema::string_attribute_value; use crate::dht::bbdht::dynamodb::schem...
String::from(content.address())), ); item.insert( String::from(CONTENT_KEY), string_attribute_value(&String::from(content.content())), ); item } pub fn should_put_item_retry( log_context: &LogContext, put_item_result: Result<PutItemOutput, RusotoError<PutItemError>>, ) -> BbDhtR...
{ let mut item = HashMap::new(); item.insert( String::from(ADDRESS_KEY), string_attribute_value(&
function_block-random_span
[ { "content": "pub fn try_aspect_list_from_item(item: Item) -> BbDhtResult<Vec<Address>> {\n\n let addresses = match get_or_err(&item, ASPECT_LIST_KEY)?.ss.clone() {\n\n Some(addresses) => addresses.iter().map(|s| Address::from(s.clone())).collect(),\n\n None => {\n\n return Err(BbDht...
Rust
sdk/src/mfg_batch/store/diesel/operations/list_mfg_batches.rs
kjf64c/grid
f76c0fe8399db688d103c7073fd78d971ef01d65
use super::MfgBatchStoreOperations; use crate::{ error::InternalError, paging::Paging, mfg_batch::{ store::{ diesel::{ models::{MfgBatch as ModelMfgBatch, MfgBatchPropertyValue}, schema::{mfg_batch, mfg_batch_property_value}, }, ...
use super::MfgBatchStoreOperations; use crate::{ error::InternalError, paging::Paging, mfg_batch::{ store::{ diesel::{ models::{MfgBatch as ModelMfgBatch, MfgBatchPropertyValue}, schema::{mfg_batch, mfg_batch_property_value}, }, ...
pub fn get_root_values( conn: &SqliteConnection, mfg_batch_id: &str, ) -> QueryResult<Vec<MfgBatchPropertyValue>> { mfg_batch_property_value::table .select(mfg_batch_property_value::all_columns) .filter( mfg_batch_property_value::mfg_batch_id ...
t) .offset(offset) .filter(mfg_batch::end_commit_num.eq(MAX_COMMIT_NUM)); if let Some(service_id) = service_id { query = query.filter(mfg_batch::service_id.eq(service_id)); } else { query = query.filter(mfg_batch::service_id.is_null()); } ...
function_block-function_prefixed
[ { "content": "#[cfg(all(feature = \"postgres\", feature = \"diesel\"))]\n\npub fn run_migrations(conn: &PgConnection) -> Result<(), MigrationsError> {\n\n embedded_migrations::run(conn).map_err(|err| {\n\n MigrationsError::ResourceTemporarilyUnavailableError(\n\n ResourceTemporarilyUnavaila...
Rust
backends/carbide_glium/examples/list_select.rs
HolgerGottChriestensen/conrod
48b80a0c8915b2d478a445f1e5a8e0f396598652
#[macro_use] extern crate carbide_core; extern crate carbide_glium; #[macro_use] extern crate carbide_winit; extern crate find_folder; extern crate glium; use glium::Surface; mod support; const WIDTH: u32 = 600; const HEIGHT: u32 = 300; widget_ids! { struct Ids { canvas, list_select } } fn main() { le...
#[macro_use] extern crate carbide_core; extern crate carbide_glium; #[macro_use] extern crate carbide_winit; extern crate find_folder; extern crate glium; use glium::Surface; mod support; const WIDTH: u32 = 600; const HEIGHT: u32 = 300; widget_ids! { struct Ids { canvas, list_select } } fn main() { le...
} if let Some(s) = scrollbar { s.set(ui); } } if let Some((primitives, cprims)) = ui.draw_if_changed() { renderer.fill(&display.0, primitives, &image_map); let mut target = display.0.draw(); target.clea...
me(glium::glutin::VirtualKeyCode::Escape), .. }, .. } => break 'main, _ => (), }, _ => (), } } { use carbide_core::{ ...
random
[ { "content": "fn test_handling_basic_input_event(ui: &mut Ui, event: Input) {\n\n ui.handle_event(event.clone());\n\n assert_event_was_pushed(ui, event::Event::Raw(event));\n\n}\n\n\n", "file_path": "carbide_core/tests/ui.rs", "rank": 0, "score": 394307.1739174472 }, { "content": "/// ...
Rust
examples/transforms.rs
ggez-dev/ggez
f6c34de7a14859bef05d02aef8a2e12d2b6fc19e
use ggez::event; use ggez::graphics::{self, Color, DrawMode, DrawParam}; use ggez::input::keyboard; use ggez::{Context, GameResult}; use glam::*; use std::env; use std::path; struct MainState { pos_x: f32, gridmesh: graphics::Mesh, angle: graphics::Image, screen_bounds: Vec<graphics::Rect>, screen...
use ggez::event; use ggez::graphics::{self, Color, DrawMode, DrawParam}; use ggez::input::keyboard; use ggez::{Context, GameResult}; use glam::*; use std::env; use std::path; struct MainState { pos_x: f32, gridmesh: graphics::Mesh, angle: graphics::Image, screen_bounds: Vec<graphics::Rect>, screen...
} impl event::EventHandler<ggez::GameError> for MainState { fn update(&mut self, _ctx: &mut Context) -> GameResult { self.pos_x = self.pos_x % 800.0 + 1.0; Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult { let mut canvas = graphics::Canvas::from_frame(ctx, Color::from...
fn draw_coord_labels(&self, canvas: &mut graphics::Canvas) { for x in 0..Self::GRID_SIZE { for y in 0..Self::GRID_SIZE { let point = Vec2::new( x as f32 * Self::GRID_INTERVAL, y as f32 * Self::GRID_INTERVAL, ); l...
function_block-full_function
[ { "content": "#[deprecated(since = \"0.8.0-rc0\", note = \"Use `ctx.mouse.handle_move` instead\")]\n\npub fn handle_move(ctx: &mut Context, new_x: f32, new_y: f32) {\n\n ctx.mouse.handle_move(new_x, new_y)\n\n}\n\n\n", "file_path": "src/input/mouse.rs", "rank": 0, "score": 215113.98835486162 },...
Rust
crates/vm/src/chunk.rs
Measter/rlox
a8f8a88ea94b7db2c184164fefde3e7fefcb6e62
use std::io::Write; use codespan_reporting::{ diagnostic::{Diagnostic, Label}, files::Files, }; use lasso::Rodeo; use num_enum::{IntoPrimitive, TryFromPrimitive}; use rlox::{ source_file::{FileId, SourceLocation}, DiagnosticEmitter, }; use crate::value::Value; #[derive(Debug, Clone, Copy, PartialEq, ...
use std::io::Write; use codespan_reporting::{ diagnostic::{Diagnostic, Label}, files::Files, }; use lasso::Rodeo; use num_enum::{IntoPrimitive, TryFromPrimitive}; use rlox::{ source_file::{FileId, SourceLocation}, DiagnosticEmitter, }; use crate::value::Value; #[derive(Debug, Clone, Copy, PartialEq, ...
let op = self.code[offset]; match OpCode::try_from_primitive(op) { Ok( op @ OpCode::Constant | op @ OpCode::DefineGlobal | op @ OpCode::GetGlobal | op @ OpCode::SetGlobal, ) => { let constant_id = *s...
if Some(cur_loc) == prev_loc { write!(stream, "{:24}| ", "").unwrap(); } else { let source_location = emitter .sources() .location(cur_loc.file_id, cur_loc.source_start) .expect("ICE: Invalid file ID/byte index"); let source_nam...
if_condition
[ { "content": "fn get_ident_kind(ident: &str) -> TokenKind {\n\n match ident {\n\n \"and\" => TokenKind::And,\n\n \"class\" => TokenKind::Class,\n\n \"else\" => TokenKind::Else,\n\n \"false\" => TokenKind::BooleanLiteral(false),\n\n \"for\" => TokenKind::For,\n\n \"fu...
Rust
components/dada-execute/src/value.rs
mbrobbel/dada
b079cd821bb247b08d4388b69424cd95b3908686
use std::sync::Arc; use dada_ir::word::Word; use parking_lot::Mutex; use crate::{data::Data, interpreter::Interpreter, permission::Permission}; #[derive(Debug)] pub struct Value { permission: Permission, data: Arc<Mutex<Data>>, } impl Value { pub(crate) fn new(interpreter: &Interpreter<'_>, value: impl ...
use std::sync::Arc; use dada_ir::word::Word; use parking_lot::Mutex; use crate::{data::Data, interpreter::Interpreter, permission::Permission}; #[derive(Debug)] pub struct Value { permission: Permission, data: Arc<Mutex<Data>>, } impl Value { pub(crate) fn new(interpreter: &Interpreter<'_>, value: impl ...
ssion.is_valid() { std::mem::replace(&mut self.data, Arc::new(Mutex::new(Data::from(())))) } else { self.data.clone() }; Ok(Value { permission, data }) } pub(crate) fn lease_share(&self, interpreter: &Interpreter<'_>) -> eyre::Result<Value> { ...
-> Value { Value::new(interpreter, ()) } pub(crate) fn read<R>( &self, interpreter: &Interpreter<'_>, op: impl FnOnce(&Data) -> eyre::Result<R>, ) -> eyre::Result<R> { self.permission.perform_read(interpreter)?; op(&self.data.lock()) } ...
random
[ { "content": "#[track_caller]\n\npub fn poll_once<R>(mut future: Pin<Box<dyn Future<Output = R> + '_>>) -> R {\n\n fn panic_if_called<T>(_: *const ()) -> T {\n\n panic!(\n\n \"method from waker was unexpected called -- is a dada fn somehow awaiting something?\"\n\n );\n\n }\n\n ...
Rust
tokio/src/runtime/task/harness.rs
passcod/tokio
f2a06bff1be147a72d40cb01d8bb621fbdc242fc
use crate::future::Future; use crate::runtime::task::core::{Cell, Core, CoreStage, Header, Trailer}; use crate::runtime::task::state::Snapshot; use crate::runtime::task::waker::waker_ref; use crate::runtime::task::{JoinError, Notified, Schedule, Task}; use std::mem; use std::panic; use std::ptr::NonNull; use std::task...
use crate::future::Future; use crate::runtime::task::core::{Cell, Core, CoreStage, Header, Trailer}; use crate::runtime::task::state::Snapshot; use crate::runtime::task::waker::waker_ref; use crate::runtime::task::{JoinError, Notified, Schedule, Task}; use std::mem; use std::panic; use std::ptr::NonNull; use std::task...
enum PollFuture<T> { Complete(Result<T, JoinError>, bool), DropReference, Notified, None, } fn cancel_task<T: Future>(stage: &CoreStage<T>) -> JoinError { let res = panic::catch_unwind(panic::AssertUnwindSafe(|| { stage.drop_future_or_output(); })); if let Err(err) = res { ...
unsafe { trailer.set_waker(Some(waker)); } let res = header.state.set_join_waker(); if res.is_err() { unsafe { trailer.set_waker(None); } } res }
function_block-function_prefix_line
[ { "content": "struct Task(UnsafeCell<MaybeUninit<Waker>>);\n\n\n\nimpl Task {\n\n unsafe fn will_wake(&self, cx: &mut Context<'_>) -> bool {\n\n self.with_task(|w| w.will_wake(cx.waker()))\n\n }\n\n\n\n unsafe fn with_task<F, R>(&self, f: F) -> R\n\n where\n\n F: FnOnce(&Waker) -> R,\n...
Rust
filecoin-proofs/src/api/winning_post.rs
liangping/rust-fil-proofs
edc2b4db11f72ebb584024f237c6f0064a7796c5
use anyhow::{ensure, Context, Result}; use log::info; use filecoin_hashers::Hasher; use storage_proofs::compound_proof::{self, CompoundProof}; use storage_proofs::merkle::MerkleTreeTrait; use storage_proofs::multi_proof::MultiProof; use storage_proofs::post::fallback; use storage_proofs::sector::*; use crate::api::po...
use anyhow::{ensure, Context, Result}; use log::info; use filecoin_hashers::Hasher; use storage_proofs::compound_proof::{self, CompoundProof}; use storage_proofs::merkle::MerkleTreeTrait; use storage_proofs::multi_proof::MultiProof; use storage_proofs::post::fallback; use storage_proofs::sector::*; use crate::api::po...
pub fn generate_winning_post<Tree: 'static + MerkleTreeTrait>( post_config: &PoStConfig, randomness: &ChallengeSeed, replicas: &[(SectorId, PrivateReplicaInfo<Tree>)], prover_id: ProverId, ) -> Result<SnarkProof> { info!("generate_winning_post:start"); ensure!( post_config.typ == PoStT...
r { id: vanilla_proof.sector_id, comm_r: vanilla_proof.comm_r, }); } let pub_inputs = fallback::PublicInputs { randomness: randomness_safe, prover_id: prover_id_safe, sectors: &pub_sectors, k: None, }; let partitions = match pub_params.pa...
function_block-function_prefixed
[ { "content": "/// Generates a Window proof-of-spacetime with provided vanilla proofs.\n\npub fn generate_window_post_with_vanilla<Tree: 'static + MerkleTreeTrait>(\n\n post_config: &PoStConfig,\n\n randomness: &ChallengeSeed,\n\n prover_id: ProverId,\n\n vanilla_proofs: Vec<FallbackPoStSectorProof<T...
Rust
src/flags.rs
arcnmx/glib-serde
19e307a86786d385e655183c99212605e866d3dd
use glib::{ translate::{FromGlib, IntoGlib}, FlagsClass, StaticType, }; use std::marker::PhantomData; #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)] pub struct FlagsValue<T: StaticType + FromGlib<u32> + IntoGlib<GlibType = u32>> { value: u32, phantom: PhantomData<T>, } unsafe im...
use glib::{ translate::{FromGlib, IntoGlib}, FlagsClass, StaticType, }; use std::marker::PhantomData; #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)] pub struct FlagsValue<T: StaticType + FromGlib<u32> + IntoGlib<GlibType = u32>> { value: u32, phantom: PhantomData<T>, } unsafe im...
} pub struct ParseFlagsError { token: String, } impl std::fmt::Display for ParseFlagsError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Invalid flag value `{}`", self.token) } }
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::de::Deserializer<'de>, { struct FlagsVisitor(FlagsClass); impl<'de> serde::de::Visitor<'de> for FlagsVisitor { type Value = u32; fn expecting(&self, formatter: &mut std::fmt::Formatter)...
function_block-full_function
[ { "content": "#[proc_macro_derive(FlagsSerialize, attributes(glib_serde_repr))]\n\n#[proc_macro_error]\n\npub fn flags_serialize_derive(input: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(input as syn::DeriveInput);\n\n enums::impl_flags_serialize(input).into()\n\n}\n", "file_...
Rust
storage/backup/backup-service/src/handlers.rs
crpdev/Libra
607356087cf7f1bd9d96265e44b3c5714d88d6f8
use anyhow::Result; use bytes::Bytes; use futures::stream; use hyper::Body; use libra_crypto::hash::HashValue; use libra_logger::prelude::*; use libra_types::transaction::Version; use libradb::backup::BackupHandler; use serde::Serialize; use std::convert::Infallible; use warp::{ filters::BoxedFilter, reply::{...
use anyhow::Result; use bytes::Bytes; use futures::stream; use hyper::Body; use libra_crypto::hash::HashValue; use libra_logger::prelude::*; use libra_types::transaction::Version; use libradb::backup::BackupHandler; use serde::Serialize; use std::convert::Infallible; use warp::{ filters::BoxedFilter, reply::{...
.or(warp::path("state_range_proof").and(state_range_proof)) .or(warp::path("state_snapshot").and(state_snapshot)) .or(warp::path("state_root_proof").and(state_root_proof)); warp::get().and(routes).boxed() }
ersion) .map(move |version| get_state_snapshot(&bh, version)) .map(unwrap_or_500) .recover(handle_rejection); let bh = backup_handler; let state_root_proof = warp::path!(Version) .map(move |version| get_state_root_proof(&bh, version)) .map(unwrap_or_500) .re...
function_block-random_span
[ { "content": "/// Given an operation retries it successfully sleeping everytime it fails\n\n/// If the operation succeeds before the iterator runs out, it returns success\n\npub fn retry<I, O, T, E>(iterable: I, mut operation: O) -> Result<T, E>\n\nwhere\n\n I: IntoIterator<Item = Duration>,\n\n O: FnMut(...
Rust
src/lib.rs
djahandarie/fastping-rs
954e51340476c49a24ab26a6dbb9da6c5ec4a46f
extern crate pnet; extern crate pnet_macros_support; #[macro_use] extern crate log; extern crate rand; mod ping; use ping::{send_pings, Ping, ReceivedPing}; use pnet::packet::icmp::echo_reply::EchoReplyPacket; use pnet::packet::ip::IpNextHeaderProtocols; use pnet::packet::Packet; use pnet::packet::{icmp, icmpv6}; use...
extern crate pnet; extern crate pnet_macros_support; #[macro_use] extern crate log; extern crate rand; mod ping; use ping::{send_pings, Ping, ReceivedPing}; use pnet::packet::icmp::echo_reply::EchoReplyPacket; use pnet::packet::ip::IpNextHeaderProtocols; use pnet::packet::Packet; use pnet::packet::{icmp, icmpv6}; use...
s_key(&"127.0.0.1".parse::<IpAddr>().unwrap()), false ); } Err(e) => { println!("Test failed: {}", e); assert!(false) } } } #[test] fn test_stop() { match Pinger::new(None, None) { ...
().unwrap().remove(&valid_addr); } Err(e) => { error!("Error removing ip address {}. Error: {}", ipaddr, e); } }; } pub fn stop_pinger(&self) { let mut stop = self.stop.lock().unwrap(); *stop = true; } pub fn ping_on...
random
[ { "content": "pub fn send_pings(\n\n size: usize,\n\n timer: Arc<RwLock<Instant>>,\n\n stop: Arc<Mutex<bool>>,\n\n results_sender: Sender<PingResult>,\n\n thread_rx: Arc<Mutex<Receiver<ReceivedPing>>>,\n\n tx: Arc<Mutex<TransportSender>>,\n\n txv6: Arc<Mutex<TransportSender>>,\n\n target...
Rust
alacritty_terminal/src/url.rs
gentooboontoo/alacritty
6cd0f12efb7664bb99a4b79732b8f4f63e42b033
use unicode_width::UnicodeWidthChar; use crate::term::cell::{Cell, Flags}; const URL_SEPARATOR_CHARS: [char; 10] = ['<', '>', '"', ' ', '{', '}', '|', '\\', '^', '`']; const URL_DENY_END_CHARS: [char; 7] = ['.', ',', ';', ':', '?', '!', '(']; const URL_SCHEMES: [&str; 8] = ["http://", "https://", "mailto:", "ne...
use unicode_width::UnicodeWidthChar; use crate::term::cell::{Cell, Flags}; const URL_SEPARATOR_CHARS: [char; 10] = ['<', '>', '"', ' ', '{', '}', '|', '\\', '^', '`']; const URL_DENY_END_CHARS: [char; 7] = ['.', ',', ';', ':', '?', '!', '(']; const URL_SCHEMES: [&str; 8] = ["http://", "https://", "mailto:", "ne...
fn url_test(input: &str, expected: &str) { let term = url_create_term(input); let url = term.url_search(Point::new(0, Column(15))); assert_eq!(url.map(|u| u.text), Some(expected.into())); } #[test] fn url_skip_invalid() { let term = url_create_term("no url here"); ...
w(), Clipboard::new_nop()); let mut grid: Grid<Cell> = Grid::new(Line(1), Column(width), 0, Cell::default()); let mut i = 0; for c in input.chars() { grid[Line(0)][Column(i)].c = c; if c.width() == Some(2) { grid[Line(0)][Column(i)].flags.insert(Flags::W...
function_block-function_prefixed
[ { "content": "pub fn new<'a>(config: &Config, size: &SizeInfo, window_id: Option<usize>) -> Pty<'a> {\n\n if let Some(pty) = conpty::new(config, size, window_id) {\n\n info!(\"Using Conpty agent\");\n\n IS_CONPTY.store(true, Ordering::Relaxed);\n\n pty\n\n } else {\n\n info!(\"...
Rust
src/tools/compiletest/src/errors.rs
canaltinova/rust
7323ac4add33363a4bdee910b70b09ee82fef7bb
use self::WhichLine::*; use std::fmt; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::Path; use std::str::FromStr; #[derive(Clone, Debug, PartialEq)] pub enum ErrorKind { Help, Error, Note, Suggestion, Warning, } impl FromStr for ErrorKind { type Err = ();...
use self::WhichLine::*; use std::fmt; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::path::Path; use std::str::FromStr; #[derive(Clone, Debug, PartialEq)] pub enum ErrorKind { Help, Error, Note, Suggestion, Warning, } impl FromStr for ErrorKind { type Err = ();...
fn parse_expected(last_nonfollow_error: Option<usize>, line_num: usize, line: &str, tag: &str) -> Option<(WhichLine, Error)> { let start = match line.find(tag) { Some(i) => i, None => return None }; let (follow, adjusts) = if line[start + t...
function_block-full_function
[ { "content": "pub fn early_warn(output: config::ErrorOutputType, msg: &str) {\n\n let mut emitter: Box<Emitter> = match output {\n\n config::ErrorOutputType::HumanReadable(color_config) => {\n\n Box::new(BasicEmitter::stderr(color_config))\n\n }\n\n config::ErrorOutputType::Js...
Rust
woori-db/src/http/mod.rs
naomijub/wooridb
aefa200b4a2dec69166aa9de71126d277b4f8a1e
#[cfg(not(debug_assertions))] use crate::auth::{ controllers as auth, io::read_admin_info, middlewares::{history_validator, wql_validator}, }; #[cfg(not(debug_assertions))] use actix_web_httpauth::middleware::HttpAuthentication; use crate::{ actors::{scheduler::Scheduler, wql::Executor}, controller...
#[cfg(not(debug_assertions))] use crate::auth::{ controllers as auth, io::read_admin_info, middlewares::{history_validator, wql_validator}, }; #[cfg(not(debug_assertions))] use actix_web_httpauth::middleware::HttpAuthentication; use crate::{ actors::{scheduler::Scheduler, wql::Executor}, controller...
pub fn routes(config: &mut web::ServiceConfig) { let local_context = local_data().map_or(LocalContext::new(), |map| map); let encrypt_context = encryption().map_or(EncryptContext::new(), |e| e); let uniqueness = unique_data().map_or(UniquenessContext::new(), |u| u); let wql_context = Arc::new(Mutex::n...
output(); match process { Ok(_) => HttpResponse::Accepted(), Err(_) => HttpResponse::InternalServerError(), } }
function_block-function_prefix_line
[ { "content": "pub fn clear() {\n\n std::process::Command::new(\"rm\")\n\n .arg(\"-rf\")\n\n .arg(\"data/*.log\")\n\n .output()\n\n .expect(\"failed to execute process\")\n\n .stdout;\n\n}\n", "file_path": "woori-db/src/controllers/tx_test.rs", "rank": 0, "score"...
Rust
src/gui/window.rs
NyantasticUwU/nstd
5e48969f2cb25bc19fb83fc87b61655c527f53cf
use super::display::NSTDDisplay; use crate::{ core::{ def::{NSTDBool, NSTDErrorCode}, str::NSTDStr, }, events::{ def::{NSTDWindowPosition, NSTDWindowSize}, window_id::NSTDWindowID, NSTDEventLoop, }, image::NSTDImage, }; use winit::{ dpi::{PhysicalPosition...
use super::display::NSTDDisplay; use crate::{ core::{ def::{NSTDBool, NSTDErrorCode}, str::NSTDStr, }, events::{ def::{NSTDWindowPosition, NSTDWindowSize}, window_id::NSTDWindowID, NSTDEventLoop, }, image::NSTDImage, }; use winit::{ dpi::{PhysicalPosition...
e::new(size.width, size.height))); } else { (*window).set_max_inner_size::<PhysicalSize<u32>>(None); } } #[cfg_attr(feature = "clib", no_mangle)] pub unsafe extern "C" fn nstd_gui_window_set_title( window: NSTDWindow, title: &NSTDStr, ) -> NSTDErrorCode { if let Ok(title) = std::str::from_u...
ze: NSTDWindowSize) { (*window).set_inner_size(PhysicalSize::new(size.width, size.height)); } #[inline] #[cfg_attr(feature = "clib", no_mangle)] pub unsafe extern "C" fn nstd_gui_window_get_client_size(window: NSTDWindow) -> NSTDWindowSize { let size = (*window).inner_size(); NSTDWindowSize::new(size.width...
random
[ { "content": "NSTDAPI NSTDUSize nstd_core_char_types_size(const NSTDUnichar chr);\n", "file_path": "include/nstd/core/char_types.h", "rank": 0, "score": 113450.67297115066 }, { "content": "NSTDAPI NSTDBool nstd_core_float_types_f64_is_infinite(const NSTDFloat64 d);\n", "file_path": "incl...
Rust
wundergraph/src/helper/tuple.rs
mre/wundergraph
411534107748412a903dcc58d8792606eea8d07f
pub trait IsPrimaryKeyIndex { fn is_index(v: usize) -> bool; } pub trait TupleIndex<N> { type Value; fn get(&self) -> Self::Value; } pub trait ConcatTuples<Other> { type Out; } pub trait AppendToTuple<T> { type Out; const LENGHT: usize; } impl<T> AppendToTup...
pub trait IsPrimaryKeyIndex { fn is_index(v: usize) -> bool; } pub trait TupleIndex<N> { type Value; fn get(&self) -> Self::Value; } pub trait ConcatTuples<Other> { type Out; } pub trait AppendToTuple<T> { type Out; const LENGHT: usize; } impl<T> AppendToTup...
e, $($T,)*, $($idx)*); impl_multiple_tuple_index!{ index = {$($T,)*}, tuple = {$( $ST,)*}, } impl<$($T,)*> IsPrimaryKeyIndex for ($($T,)*) where $($T: IsPrimaryKeyIndex,)* { fn is_index(v: usize) -> bool { ...
:ident,)*) => { $d Target };)* } } } $( name_from_idx!($Tuple, create_tuple_index, $Tupl
random
[ { "content": "pub fn inner_ty_arg<'a>(ty: &'a Type, type_name: &str, index: usize) -> Option<&'a Type> {\n\n inner_ty_args(ty, type_name).and_then(|args| match args[index] {\n\n GenericArgument::Type(ref ty) => Some(ty),\n\n _ => None,\n\n })\n\n}\n\n\n", "file_path": "wundergraph_derive...
Rust
src/shm.rs
metaworm/easy-rpc
abdea55a0b278b68339a60ae6aba9b4d5f1d249b
use std::cell::{Cell, UnsafeCell}; use std::sync::atomic::{AtomicU32, Ordering}; use std::mem::{size_of, transmute}; use std::sync::{Arc, Mutex}; use std::time::{Instant, Duration}; use shared_memory::*; use crate::{Adaptor, RecvError}; pub use shared_memory::Timeout; struct Channel { data_ty: AtomicU32, da...
use std::cell::{Cell, UnsafeCell}; use std::sync::atomic::{AtomicU32, Ordering}; use std::mem::{size_of, transmute}; use std::sync::{Arc, Mutex}; use std::time::{Instant, Duration}; use shared_memory::*; use crate::{Adaptor, RecvError}; pub use shared_memory::Timeout; struct Channel { data_ty: AtomicU32, da...
} true } fn wait_send(&mut self) -> Option<(u32, u32)> { let begin = Instant::now(); loop { let sended = self.sended.load(Ordering::Relaxed); let recved = self.recved.load(Ordering::Relaxed); if sended > recved { return Some((sended, recved))...
match self.wait_recv() { Some(r) => { sended = r.0; _recved = r.1; } None => return false, }
if_condition
[ { "content": "fn recv_message(r: &mut Reader<TcpStream>, s: &Mutex<Writer<TcpStream>>) -> Result<Vec<u8>, WebSocketError> {\n\n loop {\n\n match r.recv_message()? {\n\n OwnedMessage::Close(_) => {\n\n s.lock().unwrap()\n\n .send_message(&OwnedMessage::Close(No...
Rust
vm/src/obj/objdict.rs
evilpie/RustPython
2d22a882ae642d4b2e66b44008378da63e71f78f
use super::super::pyobject::{ PyContext, PyFuncArgs, PyObject, PyObjectPayload, PyObjectRef, PyResult, TypeProtocol, }; use super::super::vm::{ReprGuard, VirtualMachine}; use super::objiter; use super::objstr; use super::objtype; use std::cell::{Ref, RefCell, RefMut}; use std::collections::HashMap; use std::ops::{D...
use super::super::pyobject::{ PyContext, PyFuncArgs, PyObject, PyObjectPayload, PyObjectRef, PyResult, TypeProtocol, }; use super::super::vm::{ReprGuard, VirtualMachine}; use super::objiter; use super::objstr; use super::objtype; use std::cell::{Ref, RefCell, RefMut}; use std::collections::HashMap; use std::ops::{D...
} pub fn create_type(type_type: PyObjectRef, object_type: PyObjectRef, dict_type: PyObjectRef) { (*dict_type.borrow_mut()).payload = PyObjectPayload::Class { name: String::from("dict"), dict: RefCell::new(HashMap::new()), mro: vec![object_type], }; (*dict_type.borrow_mut()).typ = S...
if elements.contains_key(&needle) { Ok(elements[&needle].1.clone()) } else { Err(vm.new_value_error(format!("Key not found: {}", needle))) }
if_condition
[ { "content": "pub fn get_mut_elements<'a>(obj: &'a PyObjectRef) -> impl DerefMut<Target = Vec<PyObjectRef>> + 'a {\n\n RefMut::map(obj.borrow_mut(), |x| {\n\n if let PyObjectPayload::Sequence { ref mut elements } = x.payload {\n\n elements\n\n } else {\n\n panic!(\"Cannot ...
Rust
src/schedule/queue.rs
omni-viral/gfx-chain
df38f1f362ce6cedec761707d0dc6b649f939e61
use std::iter::{DoubleEndedIterator, Enumerate, ExactSizeIterator}; use std::ops::{Index, IndexMut}; use std::slice::{Iter as SliceIter, IterMut as SliceIterMut}; use std::vec::IntoIter as VecIntoIter; use hal::queue::QueueFamilyId; use super::submission::{Submission, SubmissionId}; #[derive(Clone, Copy, Debug, Part...
use std::iter::{DoubleEndedIterator, Enumerate, ExactSizeIterator}; use std::ops::{Index, IndexMut}; use std::slice::{Iter as SliceIter, IterMut as SliceIterMut}; use std::vec::IntoIter as VecIntoIter; use hal::queue::QueueFamilyId; use super::submission::{Submission, SubmissionId}; #[derive(Clone, Copy, Debug, Part...
iter(self) -> QueueIterMut<'a, S> { self.iter_mut() } } impl<S> Index<SubmissionId> for Queue<S> { type Output = Submission<S>; fn index(&self, sid: SubmissionId) -> &Submission<S> { self.submission(sid).unwrap() } } impl<S> IndexMut<SubmissionId> for Queue<S> { fn index_mut(&mut ...
pub fn iter_mut(&mut self) -> QueueIterMut<S> { QueueIterMut { qid: self.id, iter: self.submissions.iter_mut().enumerate(), } } pub fn into_iter(self) -> QueueIntoIter<S> { QueueIntoIter { qid: self.id, iter: self.submissions.into_it...
random
[ { "content": "/// Defines resource type.\n\n/// Should be implemented for buffers and images.\n\npub trait Resource: Copy + Debug + Eq + Ord + Hash {\n\n /// Access type of the resource.\n\n type Access: Access;\n\n\n\n /// Layout type of the resource.\n\n type Layout: Layout;\n\n\n\n /// Usage t...
Rust
src/recent.rs
pkgw/slurm-rs
aef1f73eba07d6ac1f5b3d6f2420df4db5336b40
/*! Make a list of recent jobs belonging to this user. */ use chrono::{DateTime, Duration, Utc}; use colorio::ColorIo; use failure::Error; use itertools::Itertools; use slurm::{self, JobState, JobStepRecordSharedFields}; use std::cmp; use std::collections::HashMap; use users; use util; #[derive(Debug, StructOpt)] ...
/*! Make a list of recent jobs belonging to this user. */ use chrono::{DateTime, Duration, Utc}; use colorio::ColorIo; use failure::Error; use itertools::Itertools; use slurm::{self, JobState, JobStepRecordSharedFields}; use std::cmp; use std::collections::HashMap; use users; use util; #[derive(Debug, StructOpt)] ...
}
states = self.states.keys().sorted(); let mut first = true; for state in seen_states { if first { first = false; } else { cprint!(cio, pl, ","); } cprint!(cio, pl, " {} ", self.states.get(st...
function_block-function_prefixed
[ { "content": "/// Print out a shortcode for a job state with affective color.\n\npub fn colorize_state(cio: &mut ColorIo, state: JobState) {\n\n match state {\n\n JobState::Pending => {\n\n cprint!(cio, pl, \"{}\", state.shortcode());\n\n }\n\n\n\n JobState::Running => {\n\n ...
Rust
flo/src/editor/editor_controller.rs
adamnemecek/flowbetween
6c03b81d29dfc55bd46b4f686fdfb7f96efe38b2
use super::menu_controller::*; use super::canvas_controller::*; use super::toolbox_controller::*; use super::timeline_controller::*; use super::controlbar_controller::*; use super::super::model::*; use super::super::style::*; use flo_ui::*; use flo_ui_files::ui::*; use flo_binding::*; use flo_animation::*; use std::s...
use super::menu_controller::*; use super::canvas_controller::*; use super::toolbox_controller::*; use super::timeline_controller::*; use super::controlbar_controller::*; use super::super::model::*; use super::super::style::*; use flo_ui::*; use flo_ui_files::ui::*; use flo_binding::*; use flo_animation::*; use std::s...
pub fn ui() -> Control { use self::Position::*; let menu_bar = Self::menu_bar(); let timeline = Self::timeline(); let toolbar = Self::toolbox(); let canvas = Self::canvas(); let control_bar = Self::control_bar(); Control::cont...
l { Control::container() .with(Bounds::next_vert(28.0)) .with(Appearance::Background(TIMESCALE_BACKGROUND)) .with(Font::Size(12.0)) .with(Font::Weight(FontWeight::Light)) .with_controller(&serde_json::to_string(&SubController::ControlBar).unwrap()) ...
function_block-function_prefixed
[ { "content": "///\n\n/// Returns the drawing commands for a rectangle\n\n///\n\npub fn draw_rect(x1: f32, y1: f32, x2: f32, y2: f32) -> Vec<Draw> {\n\n use self::Draw::*;\n\n\n\n vec![\n\n Move(x1, y1),\n\n Line(x1, y2),\n\n Line(x2, y2),\n\n Line(x2, y1),\n\n Line(x1, y...
Rust
price_comparision_table/examples/chat/socket_io/ws_rs_compare_to_socket_io_folder/src/reference/main_equal_to_example_from_socket_io.rs
zacfrulloni/Rust-Full-Stack
2c242b2f249d2a3a3e62f84d21e58cfa00ceb1c8
extern crate ws; use ws::{listen, Handler, Message, Request, Response, Result, Sender, CloseCode, Error}; static INDEX_HTML: &'static [u8] = br#" <!doctype html> <html> <head> <title>Websocket Rust chat</title> <!-- <link rel="stylesheet" href="/main.css"> --> <style> * { margin: 0; padding: ...
extern crate ws; use ws::{listen, Handler, Message, Request, Response, Result, Sender, CloseCode, Error}; static INDEX_HTML: &'static [u8] = br#" <!doctype html> <html> <head> <title>Websocket Rust chat</title> <!-- <link rel="stylesheet" href="/main.css"> --> <style> * { margin: 0; padding: ...
} fn on_message(&mut self, msg: Message) -> Result<()> { println!("The message from the client is {:?}", &msg); self.out.broadcast(msg) } fn on_close(&mut self, code: CloseCode, reason: &str) { match code { CloseCode::Normal => pri...
match req.resource() { "/ws" => { let resp = Response::from_request(req); resp }, "/" => Ok(Response::new(200, "OK", INDEX_HTML.to_vec())), ...
if_condition
[ { "content": "#[catch(404)]\n\npub fn not_found(req: &Request) -> Template {\n\n let mut map = std::collections::HashMap::new();\n\n map.insert(\"path\", req.uri().path());\n\n Template::render(\"error/not-found\", &map)\n\n}\n\n\n\n// https://github.com/SergioBenitez/Rocket/tree/master/examples/tera_t...
Rust
common/functions/src/scalars/maths/trigonometric.rs
jackwener/databend
d9623a53e6fe11b9309b13354076ab75c4f94388
use std::fmt; use common_datavalues::prelude::*; use common_datavalues::DataSchema; use common_datavalues::DataType; use common_exception::ErrorCode; use common_exception::Result; use crate::scalars::function_factory::FunctionDescription; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::F...
use std::fmt; use common_datavalues::prelude::*; use common_datavalues::DataSchema; use common_datavalues::DataType; use common_exception::ErrorCode; use common_exception::Result; use crate::scalars::function_factory::FunctionDescription; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::F...
display) } } impl TrigonometricFunction { pub fn try_create_func(t: Trigonometric) -> Result<Box<dyn Function>> { Ok(Box::new(TrigonometricFunction { t })) } } impl Function for TrigonometricFunction { fn name(&self) -> &str { "TrigonometricFunction" } fn num_arguments(&self)...
n", Trigonometric::COS => "cos", Trigonometric::TAN => "tan", Trigonometric::COT => "cot", Trigonometric::ACOS => "acos", Trigonometric::ASIN => "asin", Trigonometric::ATAN => "atan", Trigonometric::ATAN2 => "atan2", }; ...
function_block-random_span
[ { "content": "// put_uvarint encodes a uint64 into buf and returns the number of bytes written.\n\n// If the buffer is too small, put_uvarint will panic.\n\npub fn put_uvarint(mut buffer: impl AsMut<[u8]>, x: u64) -> usize {\n\n let mut i = 0;\n\n let mut mx = x;\n\n let buf = buffer.as_mut();\n\n w...
Rust
base_layer/p2p/src/peer_seeds.rs
zhangcheng/tari
f5a034e19caa5a67ec667c8e971462b19a78c6d8
use std::str::FromStr; use anyhow::anyhow; use tari_common::DnsNameServer; use tari_comms::{ multiaddr::Multiaddr, peer_manager::{NodeId, Peer, PeerFeatures}, types::CommsPublicKey, }; use tari_utilities::hex::Hex; use super::dns::DnsClientError; use crate::dns::{default_trust_anchor, DnsClient}; #[der...
use std::str::FromStr; use anyhow::anyhow; use tari_common::DnsNameServer; use tari_comms::{ multiaddr::Multiaddr, peer_manager::{NodeId, Peer, PeerFeatures}, types::CommsPublicKey, }; use tari_utilities::hex::Hex; use super::dns::DnsClientError; use crate::dns::{default_trust_anchor, DnsClient}; #[der...
Ok(SeedPeer { public_key, addresses }) } } impl From<SeedPeer> for Peer { fn from(seed: SeedPeer) -> Self { let node_id = seed.derive_node_id(); Peer::new( seed.public_key, node_id, seed.addresses.into(), Default::default(), P...
if addresses.is_empty() || addresses.iter().any(|a| a.is_empty()) { return Err(anyhow!("Empty or invalid address in seed peer string")); }
if_condition
[ { "content": "pub fn to_short_str(peer: &Peer) -> String {\n\n format!(\"{}::{}\", peer.public_key, peer.addresses.first().unwrap())\n\n}\n\n\n", "file_path": "comms/examples/stress/prompt.rs", "rank": 0, "score": 443367.11360575166 }, { "content": "/// Returns a CommsPublicKey from eithe...
Rust
src/runner/graph.rs
jyn514/crater
a15793ed813d4e17c0082a6ab4de2feb39e41b4b
use crate::config::Config; use crate::crates::Crate; use crate::experiments::{Experiment, Mode}; use crate::prelude::*; use crate::results::{TestResult, WriteResults}; use crate::runner::{ tasks::{Task, TaskStep}, RunnerState, }; use petgraph::{dot::Dot, graph::NodeIndex, stable_graph::StableDiGraph, Directio...
use crate::config::Config; use crate::crates::Crate; use crate::experiments::{Experiment, Mode}; use crate::prelude::*; use crate::results::{TestResult, WriteResults}; use crate::runner::{ tasks::{Task, TaskStep}, RunnerState, }; use petgraph::{dot::Dot, graph::NodeIndex, stable_graph::StableDiGraph, Directio...
} #[derive(Debug)] pub(super) enum WalkResult { Task(NodeIndex, Arc<Task>), Blocked, NotBlocked, Finished, } impl WalkResult { pub(super) fn is_finished(&self) -> bool { if let WalkResult::Finished = self { true } else { false } } } #[derive(De...
if running { write!(f, "running: {:?}", task)?; } else { write!(f, "{:?}", task)?; } } Node::CrateCompleted => write!(f, "crate completed")?, Node::Root => write!(f, "root")?, } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn run(\n\n url: &str,\n\n token: &str,\n\n threads_count: usize,\n\n caps: &Capabilities,\n\n workspace: &Workspace,\n\n) -> Fallible<()> {\n\n let agent = Agent::new(url, token, caps)?;\n\n let db = results::ResultsUploader::new(&agent.api);\n\n\n\n run_heartbeat(url,...
Rust
apps/controller/src/system/modules/experiment/msg/add_event.rs
Patryk27/cr8r
fe7366866176909730212b82a5a3500fcb6360a7
use std::collections::BTreeMap; use std::sync::Arc; use anyhow::*; use chrono::Utc; use log::*; use lib_interop::models::{DEvent, DEventType, DJob, DReport, DRunnerId}; use lib_interop::models::job::{DJobId, DJobStatus}; use super::super::{ExperimentActor, ExperimentStatus}; pub fn add_event(actor: &mut ExperimentA...
use std::collections::BTreeMap; use std::sync::Arc; use anyhow::*; use chrono::Utc; use log::*; use lib_interop::models::{DEvent, DEventType, DJob, DReport, DRunnerId}; use lib_interop::models::job::{DJobId, DJobStatus}; use super::super::{ExperimentActor, ExperimentStatus}; pub fn add_event(actor: &mut ExperimentA...
::system_msg(event.at, "Experiment completed") } DEventType::JobStarted { id } => { if let Some(job) = jobs.get(&id) { DReport::system_msg(event.at, format!("Job `{}` started", job.name)) } else { warn!("Runner reported that it has started working...
result = Err(format!("job #{} failed: {}", id, err)); break; } } result }; actor.status = ExperimentStatus::Completed { ...
random
[ { "content": "pub fn claim(actor: &mut ExperimentActor, runner_id: DRunnerId) -> Result<()> {\n\n match &actor.status {\n\n ExperimentStatus::Idle { .. } => {\n\n actor.status = ExperimentStatus::Running {\n\n since: Utc::now(),\n\n last_heartbeat_at: Utc::now(...
Rust
src/visualizer/symmetry/penta_symmetry.rs
swaggy/rpi-music-visualizer
e962b2ebe17b815bec5364f6292e6349619ed77d
use audio; use gfx; use visualizer::symmetry::symmetry::SymmetryVisualizer; use visualizer::visualizer::SubVisualizer; pub struct PentaSymmetryVisualizer { symmetry_visualizer: SymmetryVisualizer, } impl SubVisualizer for PentaSymmetryVisualizer { fn new() -> PentaSymmetryVisualizer { PentaSymmetryVis...
use audio; use gfx; use visualizer::symmetry::symmetry::SymmetryVisualizer; use visualizer::visualizer::SubVisualizer; pub struct PentaSymmetryVisualizer { symmetry_visualizer: SymmetryVisualizer, } impl SubVisualizer for PentaSymmetryVisualizer { fn new() -> PentaSymmetryVisualizer { PentaSymmetryVis...
tation(t), vec2(0.6 * fract(t / 8.0)), vec2(fract(t) - 0.5)); if (all_in_wave(p1, p2, p3, p4, p5, wave, 0.05, 0.05)) { gl_FragColor = vec4(hsl2rgb(fract((t + TAU * 2.0 / 3.0) * 0.05 / TAU), 1.0, speed * 1.2), 1.0); return; } } gl_...
rotation(TAU / 5.0); vec2 p3 = p * rotation(TAU * 2.0 / 5.0); vec2 p4 = p * rotation(TAU * 3.0 / 5.0); vec2 p5 = p * rotation(TAU * 4.0 / 5.0); float phase_offset = 0.5; float min_phase = phase - phase_offset; float max_phase = phase + phase_offset; float phase_i...
random
[ { "content": "pub fn load_gl_window_as_context(gl_window: &glutin::GlWindow) -> gl::Gl {\n\n unsafe { gl_window.make_current() }.unwrap();\n\n let gl = gl::Gl::load_with(|ptr| gl_window.get_proc_address(ptr) as *const _);\n\n\n\n unsafe {\n\n gl.Enable(gl::BLEND);\n\n gl.BlendFunc(gl::SRC...
Rust
crates/peer-metrics/src/particle_executor.rs
ktzanida/fluence
51c44cbdb9a530aa986eb9f3af1d84508877dcec
use open_metrics_client::encoding::text::Encode; use open_metrics_client::metrics::counter::Counter; use open_metrics_client::metrics::family::Family; use open_metrics_client::metrics::gauge::Gauge; use open_metrics_client::metrics::histogram::Histogram; use open_metrics_client::registry::Registry; use std::time::Durat...
use open_metrics_client::encoding::text::Encode; use open_metrics_client::metrics::counter::Counter; use open_metrics_client::metrics::family::Family; use open_metrics_client::metrics::gauge::Gauge; use open_metrics_client::metrics::histogram::Histogram; use open_metrics_client::registry::Registry; use std::time::Durat...
} fn execution_time_buckets() -> Vec<f64> { vec![ 0.0001, 0.001, 0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 4.0, 7.0, 15.0, 30.0, 60.0, 120.0, ] }
call(&self, success: bool, kind: FunctionKind, run_time: Option<Duration>) { let label = FunctionKindLabel { function_kind: kind, }; if success { self.service_call_success.get_or_create(&label).inc(); } else { self.service_call_failure.get_or_create(&...
function_block-function_prefixed
[ { "content": "pub fn hash_dependencies(facade: Hash, mut deps: Vec<Hash>) -> Hash {\n\n let mut hasher = blake3::Hasher::new();\n\n deps.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));\n\n\n\n for d in deps.iter().chain(iter::once(&facade)) {\n\n hasher.update(d.as_bytes());\n\n }\n\n\n\n ...
Rust
radiate_matrix_tree/src/tree/node.rs
Neopallium/radiate
0c6b0528dcbcf14212aec37582dc2ba9cad897bc
use std::ops::{Deref, DerefMut}; use std::ptr; use std::cmp::max; use std::fmt; pub type Link<T> = Option<Box<Node<T>>>; pub struct Node<T: Clone> { elem: T, parent: *mut Node<T>, left_child: Link<T>, right_child: Link<T>, } impl<T: Clone> Node<T> { pub fn new(elem: T) -> Box<Self> { ...
use std::ops::{Deref, DerefMut}; use std::ptr; use std::cmp::max; use std::fmt; pub type Link<T> = Option<Box<Node<T>>>; pub struct Node<T: Clone> { elem: T, parent: *mut Node<T>, left_child: Link<T>, right_child: Link<T>, } impl<T: Clone> Node<T> { pub fn new(elem: T) -> Box<Self> { ...
pub fn insert_random(&mut self, node: Box<Node<T>>) { match rand::random() { true => { if let Some(child) = self.left_child_mut_opt() { child.insert_random(node); } else { self.set_left_child(Some(node)); ...
pub fn deepcopy(&self) -> Box<Node<T>> { let mut temp_copy = self.copy(); if let Some(child) = self.left_child_opt() { let child = child.deepcopy(); temp_copy.set_left_child(Some(child)); } if let Some(child) = self.right_child_opt() { let child = chil...
function_block-full_function
[ { "content": "/// Find the left most node in the tree.\n\nfn left_most<'a, T: Clone>(node: Option<&'a Node<T>>) -> Option<&'a Node<T>> {\n\n // The first node is the left most node in the tree.\n\n match node {\n\n Some(mut next) => {\n\n // find left most node from the root.\n\n ...
Rust
src/main.rs
artemsen/xvi
fb0c6cb524b36332cb56400d256cdfae2dfeb7b3
mod ascii; mod changes; mod config; mod controller; mod curses; mod cursor; mod editor; mod file; mod history; mod inifile; mod ui; mod view; use config::Config; use controller::Controller; use curses::Curses; const EFAULT: i32 = 14; const EINVAL: i32 = 22; fn main() { let args = CmdLineArgs::new().unwrap...
mod ascii; mod changes; mod config; mod controller; mod curses; mod cursor; mod editor; mod file; mod history; mod inifile; mod ui; mod view; use config::Config; use controller::Controller; use curses::Curses; const EFAULT: i32 = 14; const EINVAL: i32 = 22; fn main() { let args = CmdLineArgs::new().unwrap...
#[test] fn test_offset() { let args = ["--offset".to_string(), "0x12345678".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(!args.help); assert!(!args.version); assert!(args.files.is_empty()); assert_eq!(args.offset, Some(0x12345678)); let args = ["--offset".t...
fn test_simple() { let args = ["--help".to_string()]; let args = CmdLineArgs::parse(args.to_vec()).unwrap(); assert!(args.help); assert!(!args.version); assert!(args.offset.is_none()); assert!(args.files.is_empty()); let args = ["-v".to_string()]; let args = CmdLineArgs::parse(args.to_v...
function_block-full_function
[ { "content": "#[test]\n\nfn test_bool_keyval() {\n\n let mut ini = IniFile::new();\n\n ini.set_keyval(\"Section1\", \"MyKey\", \"1\");\n\n assert_eq!(ini.get_boolval(\"Section1\", \"MyKey\"), Some(true));\n\n ini.set_keyval(\"Section1\", \"MyKey\", \"0\");\n\n assert_eq!(ini.get_boolval(\"Section...
Rust
src/sc/src/k8/controllers/spg_stateful.rs
alphastrata/fluvio
f8af0c8d559ced0dedc65c0d75f01d7e4e676c7c
use std::{time::Duration}; use fluvio_stream_dispatcher::{store::K8ChangeListener}; use tracing::debug; use tracing::error; use tracing::trace; use tracing::warn; use tracing::instrument; use fluvio_future::task::spawn; use fluvio_future::timer::sleep; use k8_client::SharedK8Client; use k8_client::ClientError; use c...
use std::{time::Duration}; use fluvio_stream_dispatcher::{store::K8ChangeListener}; use tracing::debug; use tracing::error; use tracing::trace; use tracing::warn; use tracing::instrument; use fluvio_future::task::spawn; use fluvio_future::timer::sleep; use k8_client::SharedK8Client; use k8_client::ClientError; use c...
async fn dispatch_loop(mut self) { loop { if let Err(err) = self.inner_loop().await { error!("error with spg loop loop: {:#?}", err); debug!("sleeping 1 miniute to try again"); sleep(Duration::from_secs(60)).await; } } } ...
services: StoreContext<SpgServiceSpec>, tls: Option<TlsConfig>, ) { let controller = Self { client, namespace, groups, spus, statefulsets, spg_services, tls, }; spawn(controller.dispatch_loop()); ...
function_block-function_prefixed
[ { "content": "/// Generate a random client group key (50001 to 65535)\n\npub fn generate_group_id() -> String {\n\n format!(\"fluvio-consumer-{}\", thread_rng().gen_range(50001, 65535))\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/utils/src/generators.rs", "rank": 0, "score": 268056.0378...
Rust
src/configuration.rs
k0pernicus/gyro
7463240ffcc40aedb9bc3596790896da28045582
use {ConfigurationContent, ConfigurationFile, GROUPS_ENTRY_NAME, IGNORED_ENTRY_NAME, WATCHED_ENTRY_NAME}; use chrono::offset::utc::UTC; use rustc_serialize::Encodable; use std::error::Error; use std::fmt; use std::result; use toml; use toml::Value; #[derive(RustcDecodable, RustcEncodable)] pub struct Entry { ...
use {ConfigurationContent, ConfigurationFile, GROUPS_ENTRY_NAME, IGNORED_ENTRY_NAME, WATCHED_ENTRY_NAME}; use chrono::offset::utc::UTC; use rustc_serialize::Encodable; use std::error::Error; use std::fmt; use std::result; use toml; use toml::Value; #[derive(RustcDecodable, RustcEncodable)] pub struct Entry { ...
ConfigureContentError::DecodingError(ref e) => e.fmt(f), ConfigureContentError::EncodingError(ref e) => e.fmt(f), ConfigureContentError::InternalError(ref e) => e.fmt(f), ConfigureContentError::KeyAlreadyExists(ref e) => e.fmt(f), ConfigureContentError::UnknownKe...
on(String), DecodingError(String), EncodingError(String), InternalError(String), KeyAlreadyExists(String), UnknownKey(String), } impl fmt::Display for ConfigureContentError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConfigureContent...
random
[ { "content": "///\n\n/// Function to scan all directories from a single directory.\n\n///\n\n/// This function update a mutable vector of String, which represents each path for each git\n\n/// path for a given git repository.\n\n///\n\npub fn find_git_repositories(git_path: &mut Vec<String>, directory: &PathBuf...
Rust
diesel/src/query_builder/ast_pass.rs
NarrativeApp/diesel
daf1d331f941f759f8bf50ed807cce0b512c39a5
use std::{fmt, mem}; use crate::backend::Backend; use crate::query_builder::{BindCollector, QueryBuilder}; use crate::result::QueryResult; use crate::serialize::ToSql; use crate::sql_types::HasSqlType; #[allow(missing_debug_implementations)] pub struct AstPass<'a, DB> where DB: Backend, DB::QueryBuilder: 'a,...
use std::{fmt, mem}; use crate::backend::Backend; use crate::query_builder::{BindCollector, QueryBuilder}; use crate::result::QueryResult; use crate::serialize::ToSql; use crate::sql_types::HasSqlType; #[allow(missing_debug_implementations)] pub struct AstPass<'a, DB> where DB: Backend, DB::QueryBuilder: 'a,...
entifier)?, AstPassInternals::IsNoop(ref mut result) => **result = false, _ => {} } Ok(()) } pub fn push_bind_param<T, U>(&mut self, bind: &U) -> QueryResult<()> where DB: HasSqlType<T>, U: ToSql<T, DB>, { use self...
entifier(&mut self, identifier: &str) -> QueryResult<()> { match self.internals { AstPassInternals::ToSql(ref mut builder) => builder.push_identifier(id
function_block-random_span
[ { "content": "/// A type which manages serializing bind parameters during query construction.\n\n///\n\n/// The only reason you would ever need to interact with this trait is if you\n\n/// are adding support for a new backend to Diesel. Plugins which are extending\n\n/// the query builder will use [`AstPass::pu...
Rust
crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs
mengxy/swc
bcc3ae86ae0732979f9fbfef370ae729ba9af080
use swc_common::{util::take::Take, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::UsageFinder; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; pub fn block_scoped_functions() -> impl Fold + VisitMut { as_folder(BlockScopedFns) } #[derive(Clone, Copy)] struct Block...
use swc_common::{util::take::Take, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::UsageFinder; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; pub fn block_scoped_functions() -> impl Fold + VisitMut { as_folder(BlockScopedFns) } #[derive(Clone, Copy)] struct Block...
} #[cfg(test)] mod tests { use super::*; use swc_ecma_transforms_testing::test; test!( ::swc_ecma_parser::Syntax::default(), |_| block_scoped_functions(), hoisting, r#" { function fn1() { fn2(); } fn1(); function fn2() { } } "#, r#" { let fn1 = fu...
fn visit_mut_stmts(&mut self, items: &mut Vec<Stmt>) { let mut stmts = Vec::with_capacity(items.len()); let mut extra_stmts = Vec::with_capacity(items.len()); for mut stmt in items.take() { if let Stmt::Expr(ExprStmt { ref expr, .. }) = stmt { if let Expr::Lit(Lit::S...
function_block-full_function
[]
Rust
src/io/free_functions.rs
Sourav933/image
3250bd1c969d1fc2cc6ce16df484bcfb37a81ff5
use std::ffi::OsString; use std::fs::File; use std::io::{BufRead, BufReader, BufWriter, Seek}; use std::path::Path; use std::u32; #[cfg(feature = "bmp")] use crate::bmp; #[cfg(feature = "gif")] use crate::gif; #[cfg(feature = "hdr")] use crate::hdr; #[cfg(feature = "ico")] use crate::ico; #[cfg(feature = "jpeg")] use ...
use std::ffi::OsString; use std::fs::File; use std::io::{BufRead, BufReader, BufWriter, Seek}; use std::path::Path; use std::u32; #[cfg(feature = "bmp")] use crate::bmp; #[cfg(feature = "gif")] use crate::gif; #[cfg(feature = "hdr")] use crate::hdr; #[cfg(feature = "ico")] use crate::ico; #[cfg(feature = "jpeg")] use ...
} #[allow(unused_variables)] pub(crate) fn save_buffer_impl( path: &Path, buf: &[u8], width: u32, height: u32, color: color::ColorType, ) -> ImageResult<()> { let fout = &mut BufWriter::new(File::create(path)?); let ext = path.extension() .and_then(|s| s.to_str()) .map_or(...
Ok(match format { #[cfg(feature = "jpeg")] image::ImageFormat::Jpeg => jpeg::JpegDecoder::new(fin)?.dimensions(), #[cfg(feature = "png")] image::ImageFormat::Png => png::PngDecoder::new(fin)?.dimensions(), #[cfg(feature = "gif")] image::ImageFormat::Gif => gif::GifDecoder...
call_expression
[ { "content": "/// Read the dimensions of the image located at the specified path.\n\n/// This is faster than fully loading the image and then getting its dimensions.\n\n///\n\n/// Try [`io::Reader`] for more advanced uses, including guessing the format based on the file's\n\n/// content before its path or manua...
Rust
src/librustc_typeck/variance/terms.rs
sylvestre/rust
1b6a182cf1e400b63ae8692e3183beabe541ea6c
use arena::TypedArena; use rustc::ty::{self, TyCtxt}; use std::fmt; use std::rc::Rc; use syntax::ast; use rustc::hir; use rustc::hir::itemlikevisit::ItemLikeVisitor; use util::nodemap::NodeMap; use self::VarianceTerm::*; pub type VarianceTermPtr<'a> = &'a VarianceTerm<'a>; #[derive(Copy, Clone, Debug)] pub struct ...
use arena::TypedArena; use rustc::ty::{self, TyCtxt}; use std::fmt; use std::rc::Rc; use syntax::ast; use rustc::hir; use rustc::hir::itemlikevisit::ItemLikeVisitor; use util::nodemap::NodeMap; use self::VarianceTerm::*; pub type VarianceTermPtr<'a> = &'a VarianceTerm<'a>; #[derive(Copy, Clone, Debug)] pub struct ...
lobalAsm(..) | hir::ItemTy(..) => {} } } fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) { } fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) { } }
Contravariant]), (tcx.lang_items.invariant_type(), vec![ty::Invariant]), (tcx.lang_items.covariant_lifetime(), vec![ty::Covariant]), (tcx.lang_items.contravariant_lifetime(), vec![ty::Contravariant]), (tcx.lang_items.invariant_lifetime(), vec![ty::Invariant]), ]; all.into_i...
random
[ { "content": "// same as cci_iter_lib, more-or-less, but not marked inline\n\npub fn iter<F>(v: Vec<usize> , mut f: F) where F: FnMut(usize) {\n\n let mut i = 0;\n\n let n = v.len();\n\n while i < n {\n\n f(v[i]);\n\n i += 1;\n\n }\n\n}\n", "file_path": "src/test/run-pass/auxiliary...
Rust
diesel/src/pg/connection/result.rs
GiGainfosystems/diesel
95823085f68d35e16266ef1b15afd6e7ab743b85
extern crate pq_sys; use self::pq_sys::*; use std::ffi::{CStr, CString}; use std::num::NonZeroU32; use std::os::raw as libc; use std::{slice, str}; use super::raw::RawResult; use super::row::PgRow; use crate::result::{DatabaseErrorInformation, DatabaseErrorKind, Error, QueryResult}; pub struct PgResult { interna...
extern crate pq_sys; use self::pq_sys::*; use std::ffi::{CStr, CString}; use std::num::NonZeroU32; use std::os::raw as libc; use std::{slice, str}; use super::raw::RawResult; use super::row::PgRow; use crate::result::{DatabaseErrorInformation, DatabaseErrorKind, Error, QueryResult}; pub struct PgResult { interna...
pub fn is_null(&self, row_idx: usize, col_idx: usize) -> bool { unsafe { 0 != PQgetisnull( self.internal_result.as_ptr(), row_idx as libc::c_int, col_idx as libc::c_int, ) } } pub fn column_type(&self, col_idx: usize)...
idx = row_idx as libc::c_int; let col_idx = col_idx as libc::c_int; unsafe { let value_ptr = PQgetvalue(self.internal_result.as_ptr(), row_idx, col_idx) as *const u8; let num_bytes = PQgetlength(self.internal_result.as_ptr(), row_idx, col_idx);...
function_block-function_prefixed
[ { "content": "pub fn edit_string(s: &str) -> Result<String, Box<dyn Error>> {\n\n let mut file = NamedTempFile::new()?;\n\n file.write_all(s.as_bytes())?;\n\n editor_output(&mut file)\n\n}\n\n\n", "file_path": "examples/postgres/advanced-blog-cli/src/editor.rs", "rank": 0, "score": 281146.4...
Rust
components/test_raftstore/src/node.rs
suryatmodulus/tikv
f85a6d3407c3aa0bee8e24d0e75157f054b4a56b
use std::path::Path; use std::sync::{Arc, Mutex, RwLock}; use tempfile::{Builder, TempDir}; use kvproto::metapb; use kvproto::raft_cmdpb::*; use kvproto::raft_serverpb::{self, RaftMessage}; use raft::eraftpb::MessageType; use raft::SnapshotStatus; use super::*; use collections::{HashMap, HashSet}; use concurrency_...
use std::path::Path; use std::sync::{Arc, Mutex, RwLock}; use tempfile::{Builder, TempDir}; use kvproto::metapb; use kvproto::raft_cmdpb::*; use kvproto::raft_serverpb::{self, RaftMessage}; use raft::eraftpb::MessageType; use raft::SnapshotStatus; use super::*; use collections::{HashMap, HashSet}; use concurrency_...
fn get_node_ids(&self) -> HashSet<u64> { self.nodes.keys().cloned().collect() } fn async_command_on_node_with_opts( &self, node_id: u64, request: RaftCmdRequest, cb: Callback<RocksSnapshot>, opts: RaftCmdExtraOpts, ) -> Result<()> { if !self ...
d) { node.stop(); } self.trans .core .lock() .unwrap() .routers .remove(&node_id) .unwrap(); }
function_block-function_prefixed
[ { "content": "/// Deletes given path from file system. Returns `true` on success, `false` if the directory doesn't\n\n/// exist. Otherwise the raw error will be returned.\n\npub fn delete_dir_if_exist<P: AsRef<Path>>(dir: P) -> io::Result<bool> {\n\n match remove_dir_all(&dir) {\n\n Ok(_) => Ok(true),...
Rust
src/tree/ops.rs
mappum/merk
a2e46ed40c7b7eeaaed7a94654c18413728f7b8d
use super::{Fetch, Link, Tree, Walker}; use crate::error::{Error, Result}; use std::collections::LinkedList; use std::fmt; use Op::*; pub enum Op { Put(Vec<u8>), Delete, } impl fmt::Debug for Op { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!( f, "{}", ...
use super::{Fetch, Link, Tree, Walker}; use crate::error::{Error, Result}; use std::collections::LinkedList; use std::fmt; use Op::*; pub enum Op { Put(Vec<u8>), Delete, } impl fmt::Debug for Op { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!( f, "{}", ...
est] fn simple_insert() { let batch = [(b"foo2".to_vec(), Op::Put(b"bar2".to_vec()))]; let tree = Tree::new(b"foo".to_vec(), b"bar".to_vec()); let (maybe_walker, deleted_keys) = Walker::new(tree, PanicSource {}) .apply(&batch) .expect("apply errored"); let wal...
left)?)))? } else { self }; tree.rotate(left) } fn rotate(self, left: bool) -> Result<Self> { let (tree, child) = self.detach_expect(left)?; let (child, maybe_grandchild) = child.detach(!left)?; let tree = tree.attach(left, maybe_...
random
[ { "content": "pub fn apply_memonly(tree: Tree, batch: &Batch) -> Tree {\n\n let tree = apply_memonly_unchecked(tree, batch);\n\n assert_tree_invariants(&tree);\n\n tree\n\n}\n\n\n", "file_path": "src/test_utils/mod.rs", "rank": 0, "score": 179811.64296630022 }, { "content": "pub fn ...
Rust
amethyst_network/src/simulation/timing.rs
OscarTHZhang/amethyst
6b32f69356581835ac8d1e2a411c22c7112b5a16
use std::{ops::RangeInclusive, time::Duration}; use amethyst_core::{ecs::*, timing::Time}; const DEFAULT_SIM_FRAME_RATE: u32 = 30; pub struct NetworkSimulationTimeSystem; impl System for NetworkSimulationTimeSystem { fn build(self) -> Box<dyn ParallelRunnable> { Box::new( SystemBuilder::ne...
use std::{ops::RangeInclusive, time::Duration}; use amethyst_core::{ecs::*, timing::Time}; const DEFAULT_SIM_FRAME_RATE: u32 = 30; pub struct NetworkSimulationTimeSystem; impl System for NetworkSimulationTimeSystem { fn build(self) -> Box<dyn ParallelRunnable> { Box::new( SystemBuilder::ne...
}
let mut time = NetworkSimulationTime::default(); let elapsed_time = Duration::from_millis(500); time.update_elapsed(elapsed_time); assert_eq!(time.elapsed_duration(), elapsed_time) }
function_block-function_prefix_line
[]
Rust
rust/cubesql/cubesql/src/compile/engine/df/columar.rs
AlbanCrepel/cube.js
49f47a6344889af74a8f3004d3925b2e3ba69535
use datafusion::{ arrow::{ array::{self, *}, datatypes::DataType, }, error::{DataFusionError, Result}, }; use std::sync::Arc; macro_rules! if_then_else { ($BUILDER_TYPE:ty, $ARRAY_TYPE:ty, $BOOLS:expr, $TRUE:expr, $FALSE:expr) => {{ let true_values = $TRUE .as_ref() ...
use datafusion::{ arrow::{ array::{self, *}, datatypes::DataType, }, error::{DataFusionError, Result}, }; use std::sync::Arc; macro_rules! if_then_else { ($BUILDER_TYPE:ty, $ARRAY_TYPE:ty, $BOOLS:expr, $TRUE:expr, $FALSE:expr) => {{ let true_values = $TRUE .as_ref() ...
_values ), DataType::Float32 => if_then_else!( array::Float32Builder, array::Float32Array, bools, true_values, false_values ), DataType::Float64 => if_then_else!( array::Float64Builder, array::Float64Arra...
::UInt32Builder, array::UInt32Array, bools, true_values, false_values ), DataType::UInt64 => if_then_else!( array::UInt64Builder, array::UInt64Array, bools, true_values, false_values ), ...
random
[ { "content": "pub fn append_value(b: &mut dyn ArrayBuilder, c: &ColumnType, v: &TableValue) {\n\n let is_null = matches!(v, TableValue::Null);\n\n macro_rules! convert_value {\n\n (Decimal, $v: expr) => {{\n\n $v.raw_value()\n\n }};\n\n (Float, $v: expr) => {{\n\n ...
Rust
probe-rs/src/probe/daplink/commands/general/info.rs
hargoniX/probe-rs
fa3fc404f54c5f4fe9d37eeb95a2d37c968b233a
use super::super::{Category, CmsisDapError, Request, Response, Result}; use scroll::{Pread, LE}; #[allow(unused)] #[derive(Copy, Clone)] pub enum Command { VendorID = 0x01, ProductID = 0x02, SerialNumber = 0x03, FirmwareVersion = 0x04, TargetDeviceVendor = 0x05, TargetDeviceName = 0x06, Ca...
use super::super::{Category, CmsisDapError, Request, Response, Result}; use scroll::{Pread, LE}; #[allow(unused)] #[derive(Copy, Clone)] pub enum Command { VendorID = 0x01, ProductID = 0x02, SerialNumber = 0x03, FirmwareVersion = 0x04, TargetDeviceVendor = 0x05, TargetDeviceName = 0x06, Ca...
is is a bug. Please report it."); Ok(constructor(res.to_owned())) }
R> { let string_len = buffer[dbg!(offset)] as usize; let string_start = offset + 1; let string_end = string_start + string_len; let res = std::str::from_utf8(&buffer[string_start..string_end]) .expect("Th
function_block-random_span
[ { "content": "/// Determine if an AP exists with the given AP number.\n\npub fn access_port_is_valid<AP>(debug_port: &mut AP, access_port: GenericAP) -> bool\n\nwhere\n\n AP: APAccess<GenericAP, IDR>,\n\n{\n\n if let Ok(idr) = debug_port.read_ap_register(access_port, IDR::default()) {\n\n u32::from...
Rust
crates/robot-panic/src/report.rs
lqc/rover
c8783b80ac920e9fe55d834015b7c3dbdf14412f
use std::borrow::Cow; use std::convert::TryFrom; use std::error::Error; use std::fmt::Write as FmtWrite; use std::mem; use std::{env, fs::File, io::Write}; use backtrace::Backtrace; use camino::Utf8PathBuf; use serde::Serialize; use url::Url; use uuid::Uuid; #[derive(Debug, Serialize, Clone, Copy)] pub enum Method ...
use std::borrow::Cow; use std::convert::TryFrom; use std::error::Error; use std::fmt::Write as FmtWrite; use std::mem; use std::{env, fs::File, io::Write}; use backtrace::Backtrace; use camino::Utf8PathBuf; use serde::Serialize; use url::Url; use uuid::Uuid; #[derive(Debug, Serialize, Clone, Copy)] pub enum Method ...
Ok(url) } }
let url = match crash_report { Some(crash_report) => Url::parse_with_params( &new_issue, &[ ("title", "bug: crashed while <insert description here>"), ( "body", &format!( ...
assignment_statement
[ { "content": "/// this fn takes 2 args: the first, an enum describing where to look to load\n\n/// a schema - from stdin or a file's Utf8PathBuf, and the second, the reference to\n\n/// stdin to load from, should it be needed.\n\npub fn load_schema_from_flag(loc: &SchemaSource, mut stdin: impl Read) -> Result<S...
Rust
src/data.rs
tko/critcmp
83040b4dcf98c9d74a7a5b23b8cc83626b200ba9
use std::collections::BTreeMap; use std::fs::File; use std::io; use std::path::Path; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json as json; use walkdir::WalkDir; use crate::Result; #[derive(Clone, Debug, Default)] pub struct Benchmarks { pub by_baseline: BTreeMap<String, Ba...
use std::collections::BTreeMap; use std::fs::File; use std::io; use std::path::Path; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json as json; use walkdir::WalkDir; use crate::Result; #[derive(Clone, Debug, Default)] pub struct Benchmarks { pub by_baseline: BTreeMap<String, Ba...
} impl Benchmark { fn from_path<P: AsRef<Path>>(path: P) -> Result<Option<Benchmark>> { let path = path.as_ref(); Benchmark::from_path_imp(path).map_err(|err| { if let Some(parent) = path.parent() { err!("{}: {}", parent.display(), err) } else { ...
pub fn gather<P: AsRef<Path>>(criterion_dir: P) -> Result<Benchmarks> { let mut benchmarks = Benchmarks::default(); for result in WalkDir::new(criterion_dir) { let dent = result?; let b = match Benchmark::from_path(dent.path())? { None => continue, ...
function_block-full_function
[ { "content": "fn throughput(bytes_per_second: Option<f64>) -> String {\n\n const MIN_KB: f64 = (2 * (1 << 10) as u64) as f64;\n\n const MIN_MB: f64 = (2 * (1 << 20) as u64) as f64;\n\n const MIN_GB: f64 = (2 * (1 << 30) as u64) as f64;\n\n\n\n let per = match bytes_per_second {\n\n None => re...
Rust
pkcs5/src/lib.rs
stefunctional/formats
866fe0c983fc023cd89ca609ebabab166e07c2ab
#![doc = include_str!("../README.md")] #![no_std] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_root_url = "https://docs.rs/pkcs...
#![doc = include_str!("../README.md")] #![no_std] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_root_url = "https://docs.rs/pkcs...
)?; encoder.sequence(seq_len, |seq| { seq.encode(&pbes2::PBES2_OID)?; seq.encode(pbes2) }) } } } } impl<'a> From<pbes1::Parameters> for EncryptionScheme<'a> { fn from(params: pbes1::Parameters) -> EncryptionScheme<'a> {...
r<'a>) -> der::Result<Self> { AlgorithmIdentifier::decode(decoder)?.try_into() } } impl<'a> Encodable for EncryptionScheme<'a> { fn encoded_len(&self) -> der::Result<Length> { match self { Self::Pbes1(pbes1) => pbes1.encoded_len(), Self::Pbes2(pbes2) => { ...
random
[ { "content": "#[inline(always)]\n\nfn decode_padding(input: &[u8]) -> Result<(usize, i16), InvalidEncodingError> {\n\n if input.len() % 4 != 0 {\n\n return Err(InvalidEncodingError);\n\n }\n\n\n\n let unpadded_len = match *input {\n\n [.., b0, b1] => {\n\n let pad_len = is_pad_...
Rust
src/vendor/fragile/sticky.rs
chathaway-codes/relm
7cd86826e7602044393d4d72e9edac2c8ad10015
use std::cell::UnsafeCell; use std::cmp; use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use super::errors::InvalidThreadAccess; fn next_item_id() -> usize { static mut COUNTER: AtomicUsize = ATOMIC_USIZE_I...
use std::cell::UnsafeCell; use std::cmp; use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use super::errors::InvalidThreadAccess; fn next_item_id() -> usize { static mut COUNTER: AtomicUsize = ATOMIC_USIZE_I...
) .unwrap(); } assert_eq!(was_called.load(Ordering::SeqCst), true); } #[test] fn test_rc_sending() { use std::rc::Rc; use std::thread; let val = Sticky::new(Rc::new(true)); thread::spawn(move || { assert!(val.try_get().is_err()); }).join().unwrap(); }
se std::sync::Arc; let was_called = Arc::new(AtomicBool::new(false)); struct X(Arc<AtomicBool>); impl Drop for X { fn drop(&mut self) { self.0.store(true, Ordering::SeqCst); } } let val = Sticky::new(X(was_called.clone())); drop(val); assert_eq!(was_called.load(Or...
random
[ { "content": "/// After `duration` ms, emit `msg`.\n\npub fn timeout<F: Fn() -> MSG + 'static, MSG: 'static>(stream: &EventStream<MSG>, duration: u32, constructor: F) {\n\n let stream = stream.clone();\n\n gtk::timeout_add(duration, move || {\n\n let msg = constructor();\n\n stream.emit(msg)...
Rust
core/src/avm1/globals/color_transform.rs
xzfc/ruffle
178178d9dd2bdc31f3962e18ee254e12d4541060
use crate::avm1::activation::Activation; use crate::avm1::error::Error; use crate::avm1::function::{Executable, FunctionObject}; use crate::avm1::{AvmString, Object, TObject, Value}; use enumset::EnumSet; use gc_arena::MutationContext; use crate::avm1::object::color_transform_object::ColorTransformObject; use crate:...
use crate::avm1::activation::Activation; use crate::avm1::error::Error; use crate::avm1::function::{Executable, FunctionObject}; use crate::avm1::{AvmString, Object, TObject, Value}; use enumset::EnumSet; use gc_arena::MutationContext; use crate::avm1::object::color_transform_object::ColorTransformObject; use crate:...
pub fn get_rgb<'gc>( _activation: &mut Activation<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let ct = this.as_color_transform_object().unwrap(); let rgb = ((ct.get_red_offset() as u32) << 16) | ((ct.get_green_offset() as u32) << 8) ...
activation)? .coerce_to_f64(activation)? as f32; let blue_offset = object .get("blueOffset", activation)? .coerce_to_f64(activation)? as f32; let alpha_offset = object .get("alphaOffset", activation)? .coerce_to_f64(activation)? as f32; Ok(ColorTransform { r_...
function_block-function_prefixed
[ { "content": "pub fn root_error_handler<'gc>(activation: &mut Activation<'_, 'gc, '_>, error: Error<'gc>) {\n\n if let Error::ThrownValue(error) = &error {\n\n let string = error\n\n .coerce_to_string(activation)\n\n .unwrap_or_else(|_| \"undefined\".into());\n\n log::info...
Rust
src/pipeline/world/collision_groups.rs
jojolepro/ncollide
e098f0eb6d884432e20a9abb6f338db7398eeafc
use na::Real; use crate::pipeline::broad_phase::BroadPhasePairFilter; use crate::pipeline::world::CollisionObject; const SELF_COLLISION: u32 = 1 << 31; const ALL_GROUPS: u32 = (1 << 30) - 1; const NO_GROUP: u32 = 0; #[derive(Clone, Debug, Copy)] pub struct CollisionGroups { membership: u32, whitelist: u32, ...
use na::Real; use crate::pipeline::broad_phase::BroadPhasePairFilter; use crate::pipeline::world::CollisionObject; const SELF_COLLISION: u32 = 1 << 31; const ALL_GROUPS: u32 = (1 << 30) - 1; const NO_GROUP: u32 = 0; #[derive(Clone, Debug, Copy)] pub struct CollisionGroups { membership: u32, whitelist: u32, ...
} } impl Default for CollisionGroups { #[inline] fn default() -> Self { CollisionGroups::new() } }
if co1.handle() == co2.handle() { co1.collision_groups().can_interact_with_self() } else { co1.collision_groups() .can_interact_with_groups(co2.collision_groups()) }
if_condition
[ { "content": "/// Given an index buffer, remove from `points` every point that is not indexed.\n\npub fn remove_unused_points<N: Real>(points: &mut Vec<Point<N>>, idx: &mut [Point3<u32>]) {\n\n let mut used: Vec<bool> = iter::repeat(false).take(points.len()).collect();\n\n let mut remap: Vec<usize> = (0.....
Rust
src/lib.rs
callmeahab/sqs_listener
b3f6c7277ec8ef8707325f809a2f1a0497ef0b92
/*! ### Simple Example Simple example: [examples/simple.rs](https://github.com/avencera/sqs_listener/blob/master/examples/simple.rs) ```rust,ignore use sqs_listener::{Region, SQSListener, SQSListenerClientBuilder}; #[tokio::main] async fn main() -> eyre::Result<()> { env_logger::init(); color_eyre::install(...
/*! ### Simple Example Simple example: [examples/simple.rs](https://github.com/avencera/sqs_listener/blob/master/examples/simple.rs) ```rust,ignore use sqs_listener::{Region, SQSListener, SQSListenerClientBuilder}; #[tokio::main] async fn main() -> eyre::Result<()> { env_logger::init(); color_eyre::install(...
}
p); println!("{:#?}", message) }); let config = ConfigBuilder::default() .check_interval(Duration::from_millis(1000)) .auto_ack(false) .build(); let client = SQSListenerClientBuilder::new(Region::UsEast1) .listener(listener) ...
function_block-function_prefixed
[ { "content": "use sqs_listener::{Region, SQSListener, SQSListenerClientBuilder};\n\n\n\n#[tokio::main]\n\nasync fn main() -> eyre::Result<()> {\n\n env_logger::init();\n\n color_eyre::install()?;\n\n\n\n let listener = SQSListener::new(\"\".to_string(), |message| {\n\n println!(\"Message receive...
Rust
lychee-bin/src/options.rs
fauust/lychee
476a048350a50a367955404411cbcf8d2f88da4b
use std::{convert::TryFrom, fs, io::ErrorKind, path::PathBuf, str::FromStr, time::Duration}; use anyhow::{anyhow, Error, Result}; use const_format::{concatcp, formatcp}; use lychee_lib::{ Base, Input, DEFAULT_MAX_REDIRECTS, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, }; use serde::Deserialize; use st...
use std::{convert::TryFrom, fs, io::ErrorKind, path::PathBuf, str::FromStr, time::Duration}; use anyhow::{anyhow, Error, Result}; use const_format::{concatcp, formatcp}; use lychee_lib::{ Base, Input, DEFAULT_MAX_REDIRECTS, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, }; use serde::Deserialize; use st...
} }; Ok(Some(toml::from_slice(&contents)?)) } pub(crate) fn merge(&mut self, toml: Config) { fold_in! { self, toml; verbose: false; cache: false; no_progress: false; max_redirects: ...
match e.kind() { ErrorKind::NotFound => Ok(None), _ => Err(Error::from(e)), }
if_condition
[ { "content": "fn read_header(input: &str) -> Result<(String, String)> {\n\n let elements: Vec<_> = input.split('=').collect();\n\n if elements.len() != 2 {\n\n return Err(anyhow!(\n\n \"Header value should be of the form key=value, got {}\",\n\n input\n\n ));\n\n }\n...
Rust
crates/core/src/schedule/system_runner.rs
gents83/INOX
8ff4f851ab6493b9d613fce4a08bb0ba58dee568
use std::{ collections::HashMap, sync::{ atomic::{AtomicBool, AtomicU8, Ordering}, Arc, RwLock, }, }; use crate::{JobHandlerRw, JobHandlerTrait, JobPriority, System, SystemId, SystemRw}; const STATE_READY: u8 = 0; const STATE_WAITING: u8 = 1; const STATE_RUNNING: u8 = 2; const STATE_EXECUT...
use std::{ collections::HashMap, sync::{ atomic::{AtomicBool, AtomicU8, Ordering}, Arc, RwLock, }, }; use crate::{JobHandlerRw, JobHandlerTrait, JobPriority, System, SystemId, SystemRw}; const STATE_READY: u8 = 0; const STATE_WAITING: u8 = 1; const STATE_RUNNING: u8 = 2; const STATE_EXECUT...
self.state.store(STATE_EXECUTED, Ordering::SeqCst); } pub fn execute_as_job(&mut self, can_continue: Arc<AtomicBool>, is_focused: bool) { if self.is_executed() || self.is_running() { return; } let should_run_when_not_focused = self.should_run_when_not_focused(); ...
if is_focused || should_run_when_not_focused { self.state.store(STATE_RUNNING, Ordering::SeqCst); let result = can_continue.load(Ordering::SeqCst) && self.system.write().unwrap().run(); can_continue.store(result, Ordering::SeqCst); }
if_condition
[]
Rust
termwiz/src/escape/parser/mod.rs
ony/wezterm
a26a94b5bb0f8f872f9a2ee7a7c1b414cd2bbda4
use crate::escape::{Action, DeviceControlMode, Esc, OperatingSystemCommand, CSI}; use log::error; use num; use std::cell::RefCell; use vtparse::{VTActor, VTParser}; pub struct Parser { state_machine: VTParser, } impl Default for Parser { fn default() -> Self { Self::new() } } impl Parser { pu...
use crate::escape::{Action, DeviceControlMode, Esc, OperatingSystemCommand, CSI}; use log::error; use num; use std::cell::RefCell; use vtparse::{VTActor, VTParser}; pub struct Parser { state_machine: VTParser, } impl Default for Parser { fn default() -> Self { Self::new() } } impl Parser { pu...
}
e_as_vec(b"\x1b%H"); assert_eq!( vec![Action::Esc(Esc::Unspecified { intermediate: Some(b'%'), control: b'H', })], actions ); assert_eq!(encode(&actions), "\x1b%H"); }
function_block-function_prefixed
[ { "content": "/// A little helper to convert i64 -> u8 if safe\n\nfn to_u8(v: i64) -> Result<u8, ()> {\n\n if v <= i64::from(u8::max_value()) {\n\n Ok(v as u8)\n\n } else {\n\n Err(())\n\n }\n\n}\n\n\n", "file_path": "termwiz/src/escape/csi.rs", "rank": 1, "score": 291804.5162...
Rust
src/report/coveralls.rs
sameer/tarpaulin
60fe0eba97d4a73258f9960a046622a3dab62bea
use crate::config::Config; use crate::errors::RunError; use crate::traces::{CoverageStat, TraceMap}; use coveralls_api::*; use log::{info, trace, warn}; use std::collections::HashMap; use std::fs; use std::path::Path; fn get_git_info(manifest_path: &Path) -> Result<GitInfo, String> { let dir_path = manifest_path ...
use crate::config::Config; use crate::errors::RunError; use crate::traces::{CoverageStat, TraceMap}; use coveralls_api::*; use log::{info, trace, warn}; use std::collections::HashMap; use std::fs; use std::path::Path; fn get_git_info(manifest_path: &Path) -> Result<GitInfo, String> { let dir_path = manifest_path ...
report.set_detailed_git_info(git_info); info!("Git info collected"); } Err(err) => warn!("Failed to collect git info: {}", err), } let res = match config.report_uri { Some(ref uri) => { info!("Sending report to endpoint: {}", uri); ...
function_block-function_prefix_line
[ { "content": "/// Reports the test coverage using the users preferred method. See config.rs\n\n/// or help text for details.\n\npub fn report_coverage(config: &Config, result: &TraceMap) -> Result<(), RunError> {\n\n if !result.is_empty() {\n\n info!(\"Coverage Results:\");\n\n if config.verbos...
Rust
tokio/src/util/slab/tests/loom_slab.rs
goriunov/tokio
3ecaa6d91cef271b4c079a2e28bc3270280bcee6
use crate::io::driver::ScheduledIo; use crate::util::slab::{Address, Slab}; use loom::sync::{Arc, Condvar, Mutex}; use loom::thread; #[test] fn local_remove() { loom::model(|| { let slab = Arc::new(Slab::new()); let s = slab.clone(); let t1 = thread::spawn(move || { let idx = ...
use crate::io::driver::ScheduledIo; use crate::util::slab::{Address, Slab}; use loom::sync::{Arc, Condvar, Mutex}; use loom::thread; #[test] fn local_remove() { loom::model(|| { let slab = Arc::new(Slab::new()); let s = slab.clone(); let t1 = thread::spawn(move || { let idx = ...
fn store_when_free(slab: &Arc<Slab<ScheduledIo>>, readiness: usize) -> Address { let key = loop { if let Some(key) = slab.alloc() { break key; } thread::yield_now(); }; if let Some(slot) = slab.get(key) { slot.set_readiness(key, |_| readiness) .exp...
let key = slab.alloc().expect("allocate slot"); if let Some(slot) = slab.get(key) { slot.set_readiness(key, |_| readiness) .expect("generation should still be valid!"); } else { panic!("slab did not contain a value for {:?}", key); } key }
function_block-function_prefix_line
[ { "content": "#[test]\n\n#[ignore]\n\nfn lock() {\n\n let mut lock = Mutex::new(false);\n\n\n\n let mut lock2 = lock.clone();\n\n std::thread::spawn(move || {\n\n let l = lock2.lock();\n\n pin_mut!(l);\n\n\n\n let mut task = MockTask::new();\n\n let mut g = assert_ready!(tas...
Rust
plasma-store/src/ffi/mod.rs
novifinancial/rust-plasma
628bbacbfb6cb542e9c456b493a70fc771e7d58f
#[cfg(test)] mod tests; #[allow(clippy::all)] #[cxx::bridge(namespace = plasma)] pub(crate) mod ffi { struct ObjectBuffer { data: SharedPtr<Buffer>, metadata: SharedPtr<Buffer>, device_num: i32, } #[derive(Debug)] pub struct ArrowStatus { ...
#[cfg(test)] mod tests; #[allow(clippy::all)] #[cxx::bridge(namespace = plasma)] pub(crate) mod ffi { struct ObjectBuffer { data: SharedPtr<Buffer>, metadata: SharedPtr<Buffer>, device_num: i32, } #[derive(Debug)] pub struct ArrowStatus { ...
: &PlasmaClient, oid: &ObjectID) -> ArrowStatus; #[allow(dead_code)] fn multi_delete(pc: &PlasmaClient, oid: &CxxVector<ObjectID>) -> ArrowStatus; #[allow(dead_code)] fn refresh(pc: &PlasmaClient, oid: &CxxVector<ObjectID>) -> ArrowStatus; fn disconnect(pc: &...
: &[u8], ) -> ArrowStatus; fn create_and_seal( pc: &PlasmaClient, oid: &ObjectID, data: &[u8], metadata: &[u8], ) -> ArrowStatus; fn get( pc: &PlasmaClient, oid: &ObjectID, timeout_ms: i64, ...
random
[ { "content": "fn flex_code_check(s: ffi::StatusCode) -> bool {\n\n // the race condition is irrelevant for these purposes\n\n s == ffi::StatusCode::AlreadyExists || s == ffi::StatusCode::OK\n\n}\n\n\n", "file_path": "plasma-store/src/ffi/tests.rs", "rank": 0, "score": 161074.67046910524 }, ...
Rust
src/dist/pkg.rs
woss/cachepot
42f0557f40adfacd1ee56edf91229bd558f06002
use crate::dist; use crate::util::fs; use std::io; use std::path::{Component, Path, PathBuf}; use std::str; use crate::errors::*; pub use self::toolchain_imp::*; pub trait ToolchainPackager: Send { fn write_pkg(self: Box<Self>, f: fs::File) -> Result<()>; } pub trait InputsPackager: Send { fn write_inputs...
use crate::dist; use crate::util::fs; use std::io; use std::path::{Component, Path, PathBuf}; use std::str; use crate::errors::*; pub use self::toolchain_imp::*; pub trait ToolchainPackager: Send { fn write_pkg(self: Box<Self>, f: fs::File) -> Result<()>; } pub trait InputsPackager: Send { fn write_inputs...
} pub fn make_tar_header(src: &Path, dest: &str) -> io::Result<tar::Header> { let metadata_res = fs::metadata(&src); let mut file_header = tar::Header::new_ustar(); if let Ok(metadata) = metadata_res { file_header.set_metadata(&metadata); } else { warn!( "Cou...
1 (0x00007ffddc1f6000) \tlibcap.so.2 => /usr/lib/libcap.so.2 (0x00007f4980989000) \tlibc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f69ca6a1000) \tlibc.so.6 => /usr/lib/libc.so.6 (0x00007f49807c2000) \t/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007f49809e9000) "; assert_eq!( ...
function_block-function_prefixed
[ { "content": "pub fn create_file<F>(dir: &Path, path: &str, fill_contents: F) -> io::Result<PathBuf>\n\nwhere\n\n F: FnOnce(File) -> io::Result<()>,\n\n{\n\n let b = dir.join(path);\n\n let parent = b.parent().unwrap();\n\n fs::create_dir_all(&parent)?;\n\n let f = fs::File::create(&b)?;\n\n f...
Rust
src/rustc/middle/trans/reflect.rs
dckc/rust
07edf9036715bde27cc7bbc0feb3ee6e461130da
use std::map::HashMap; use driver::session::session; use lib::llvm::{TypeRef, ValueRef}; use syntax::ast; use back::abi; use common::*; use build::*; use base::*; use type_of::*; use ast::def_id; use util::ppaux::ty_to_str; use datum::*; use callee::{ArgVals, DontAutorefArg}; use expr::SaveIn; enum reflector = { v...
use std::map::HashMap; use driver::session::session; use lib::llvm::{TypeRef, ValueRef}; use syntax::ast; use back::abi; use common::*; use build::*; use base::*; use type_of::*; use ast::def_id; use util::ppaux::ty_to_str; use datum::*; use callee::{ArgVals, DontAutorefArg}; use expr::SaveIn; enum reflector = { v...
fn c_tydesc(t: ty::t) -> ValueRef { let bcx = self.bcx; let static_ti = get_tydesc(bcx.ccx(), t); glue::lazily_emit_all_tydesc_glue(bcx.ccx(), static_ti); PointerCast(bcx, static_ti.tydesc, T_ptr(self.tydesc_ty)) } fn c_mt(mt: ty::mt) -> ~[ValueRef] { ~[self.c_uint...
e_of(self.bcx.ccx(), t); let s = shape::llsize_of_real(self.bcx.ccx(), tr); let a = shape::llalign_of_min(self.bcx.ccx(), tr); return ~[self.c_uint(s), self.c_uint(a)]; }
function_block-function_prefixed
[ { "content": "// Use this when creating a block for the inside of a landing pad.\n\nfn lpad_block(bcx: block, n: ~str) -> block {\n\n new_block(bcx.fcx, Some(bcx), block_non_scope, true, n, None)\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 0, "score": 483845.4519201966 }...
Rust
examples/postgres/advanced-blog-cli/src/main.rs
goncalor/diesel
72bfb356b8038e993634f095b57e54fdf1cfd8f9
#![deny(warnings)] mod auth; mod cli; mod comment; mod editor; mod pagination; mod post; mod schema; #[cfg(test)] mod test_helpers; use diesel::prelude::*; use structopt::StructOpt; use std::error::Error; use self::cli::Cli; use self::pagination::*; use self::post::*; use self::schema::*; fn main() { let matc...
#![deny(warnings)] mod auth; mod cli; mod comment; mod editor; mod pagination; mod post; mod schema; #[cfg(test)] mod test_helpers; use diesel::prelude::*; use structopt::StructOpt; use std::error::Error; use self::cli::Cli; use self::pagination::*; use self::post::*; use self::schema::*; fn main() { let matc...
fn register_user(conn: &mut PgConnection) -> Result<(), Box<dyn Error>> { use auth::AuthenticationError as Auth; use diesel::result::DatabaseErrorKind::UniqueViolation; use diesel::result::Error::DatabaseError; match auth::register_user_from_env(conn) { Ok(_) => Ok(()), Err(Auth::Data...
fn current_user(conn: &mut PgConnection) -> Result<auth::User, Box<dyn Error>> { match auth::current_user_from_env(conn) { Ok(Some(user)) => Ok(user), Ok(None) => Err("No user found with the given username".into()), Err(e) => Err(convert_auth_error(e)), } }
function_block-function_prefix_line
[ { "content": "pub fn create_post(conn: &mut PgConnection, title: &str, body: &str) -> Post {\n\n use crate::schema::posts;\n\n\n\n let new_post = NewPost { title, body };\n\n\n\n diesel::insert_into(posts::table)\n\n .values(&new_post)\n\n .get_result(conn)\n\n .expect(\"Error savi...
Rust
tonic-web/tonic-web/src/cors.rs
KaiserKarel/tonic
b29fedc602655aab0955a2a32e7ca1cf5bf8b138
use std::sync::Arc; use http::{header, HeaderMap, HeaderValue, Method}; use tracing::debug; use self::headers::*; use crate::config::Config; pub(crate) mod headers { pub(crate) use http::header::ACCESS_CONTROL_ALLOW_CREDENTIALS as ALLOW_CREDENTIALS; pub(crate) use http::header::ACCESS_CONTROL_ALLOW_HEADERS a...
use std::sync::Arc; use http::{header, HeaderMap, HeaderValue, Method}; use tracing::debug; use self::headers::*; use crate::config::Config; pub(crate) mod headers { pub(crate) use http::header::ACCESS_CONTROL_ALLOW_CREDENTIALS as ALLOW_CREDENTIALS; pub(crate) use http::header::ACCESS_CONTROL_ALLOW_HEADERS a...
fn is_origin_allowed(&self, origin: &HeaderValue) -> bool { self.cache.config.allowed_origins.is_allowed(origin) } #[cfg(test)] pub(crate) fn __check_preflight(&self, headers: &HeaderMap) -> Result<HeaderMap, Error> { self.preflight( headers, headers.get(ORIGIN...
f.cache.expose_headers.clone()); if self.cache.config.allow_credentials { headers.insert(ALLOW_CREDENTIALS, self.cache.allow_credentials.clone()); } headers }
function_block-function_prefixed
[ { "content": "fn invalid_header_value_byte<Error: fmt::Display>(err: Error) -> Status {\n\n debug!(\"Invalid header: {}\", err);\n\n Status::new(\n\n Code::Internal,\n\n \"Couldn't serialize non-text grpc status header\".to_string(),\n\n )\n\n}\n\n\n\n#[cfg(feature = \"transport\")]\n\nim...
Rust
vendor/xz2/src/bufread.rs
riscv-android-src/toolchain-rustc
bcf972c0208490b0eb3ce3c170c2db486ba945b3
use std::io::prelude::*; use std::io; use lzma_sys; #[cfg(feature = "tokio")] use futures::Poll; #[cfg(feature = "tokio")] use tokio_io::{AsyncRead, AsyncWrite}; use stream::{Stream, Check, Action, Status}; pub struct XzEncoder<R> { obj: R, data: Stream, } pub struct XzDecoder<R> { obj: R, data: S...
use std::io::prelude::*; use std::io; use lzma_sys; #[cfg(feature = "tokio")] use futures::Poll; #[cfg(feature = "tokio")] use tokio_io::{AsyncRead, AsyncWrite}; use stream::{Stream, Check, Action, Status}; pub struct XzEncoder<R> { obj: R, data: Stream, } pub struct XzDecoder<R> { obj: R, data: S...
read = (self.data.total_out() - before_out) as usize; consumed = (self.data.total_in() - before_in) as usize; } self.obj.consume(consumed); let status = ret?; if read > 0 || eof || buf.len() == 0 { if read == 0 && status != Status::StreamE...
} } impl<R: BufRead> XzDecoder<R> { pub fn new(r: R) -> XzDecoder<R> { let stream = Stream::new_stream_decoder(u64::max_value(), 0).unwrap(); XzDecoder::new_stream(r, stream) } pub fn new_multi_decoder(r: R) -> XzDecoder<R> { let stream = Stream::new_auto_dec...
random
[]
Rust
src/pprint.rs
sminez/roc
575e5b42f06cfae23dfa0a72ba8e9a78edfe6f28
/*! * Formatted output and pretty printing */ use colored::*; use std::cmp; use term_size; pub(crate) const CRATE_LIST_HEADING_COLOR: &'static str = "blue"; pub(crate) const SECTION_HEADING_COLOR: &'static str = "yellow"; pub(crate) const ENUM_HEADING_COLOR: &'static str = "green"; const SPACER: &'static str = " "...
/*! * Formatted output and pretty printing */ use colored::*; use std::cmp; use term_size; pub(crate) const CRATE_LIST_HEADING_COLOR: &'static str = "blue"; pub(crate) const SECTION_HEADING_COLOR: &'static str = "yellow"; pub(crate) const ENUM_HEADING_COLOR: &'static str = "green"; const SPACER: &'static str = " "...
let max = max_width(); if column_widths.iter().sum::<usize>() + SPACER.len() <= max { return self.formatted(&column_widths); } let mut buf = String::new(); let mut current = String::new(); let offset = vec![" "; column_widths[0] + SPACER.len() + 1].join("")...
if self.cells.len() != 2 { panic!( "two_column_wrapped called on row with {} columns", self.cells.len() ); }
if_condition
[ { "content": "fn matching_lines(s: String, pattern: &str) -> Result<String, Box<dyn Error>> {\n\n let matcher = RegexMatcher::new(pattern)?;\n\n let mut matches: Vec<String> = vec![];\n\n let lines: Vec<&str> = s.split('\\n').collect();\n\n\n\n Searcher::new().search_slice(\n\n &matcher,\n\n ...
Rust
vpp-api-gen/src/bin/api-gen/basetypes.rs
pepinns/vpp-api
a5a8e0cf6f70a3150135f317d27771ebeb2da9de
#![allow( dead_code, unused_mut, unused_variables, unused_must_use, non_camel_case_types, unused_imports, non_snake_case )] use crate::alias::VppJsApiAlias; use crate::enums::VppJsApiEnum; use crate::file_schema::VppJsApiFile; use crate::types::VppJsApiMessageFieldDef; use crate::types::Vpp...
#![allow( dead_code, unused_mut, unused_variables, unused_must_use, non_camel_case_types, unused_imports, non_snake_case )] use crate::alias::VppJsApiAlias; use crate::enums::VppJsApiEnum; use crate::file_schema::VppJsApiFile; use crate::types::VppJsApiMessageFieldDef; use crate::types::Vpp...
pub fn sizeof_alias(alias: &VppJsApiAlias, file: &VppJsApiFile) -> u8 { if alias.ctype.starts_with("vl_api_") { find_type(&file, &alias.ctype) } else { match alias.length { Some(len) => { let typ = basetypes::ctoSizeR(&alias.ctype); let totalsize = t...
pub fn sizeof_struct(file: &VppJsApiFile, structs: &VppJsApiType) -> u8 { structs.fields.iter().fold(0, |mut totalsize, x| { totalsize = totalsize + field_size(&x, &file); totalsize }) }
function_block-full_function
[ { "content": "pub trait AsU32 {\n\n fn as_u32(data: Self) -> u32;\n\n}\n\n\n\n/* FIXME: add deserializer for SizedEnum */\n\n\n\n#[derive(Clone, Default, Debug)]\n\npub struct VariableSizeArray<T>(pub Vec<T>);\n\n\n\nuse serde::ser::{SerializeSeq, SerializeTuple, Serializer};\n\n\n\nimpl<T: Debug + Serialize...
Rust
protocol/src/reqres.rs
HashWarlock/robonomics
6fa124f674d9536f060b0562c463594435bc8df0
use async_trait::async_trait; use futures::{AsyncRead, AsyncWrite, FutureExt}; use libp2p::core::upgrade::{read_one, write_one}; use libp2p::core::ProtocolName; use libp2p::core::{ identity, muxing::StreamMuxerBox, transport::{self, Transport}, upgrade, PeerId, }; use libp2p::noise::{Keypair, NoiseCon...
use async_trait::async_trait; use futures::{AsyncRead, AsyncWrite, FutureExt}; use libp2p::core::upgrade::{read_one, write_one}; use libp2p::core::ProtocolName; use libp2p::core::{ identity, muxing::StreamMuxerBox, transport::{self, Transport}, upgrade, PeerId, }; use libp2p::noise::{Keypair, NoiseCon...
authenticate(NoiseConfig::xx(noise_keys).into_authenticated()) .multiplex(YamuxConfig::default()) .boxed(), ) }
function_block-function_prefix_line
[ { "content": "/// Generate random ED25519 keypair for node identity.\n\npub fn random() -> Keypair {\n\n let key = Keypair::generate_ed25519();\n\n let peer_id = PeerId::from(key.public());\n\n log::info!(target: \"robonomics-identity\",\n\n \"Generated random peer id: {}\", peer_id.to_ba...
Rust
tests/consumer.rs
Syfaro/faktory-rs
2d8191ddcc583f534ae0d4c79d3486ab125f7981
extern crate failure; extern crate faktory; extern crate mockstream; extern crate serde_json; extern crate url; mod mock; use faktory::*; use std::io; use std::thread; use std::time::Duration; #[test] fn hello() { let mut s = mock::Stream::default(); let mut c = ConsumerBuilder::default(); c.hostname("h...
extern crate failure; extern crate faktory; extern crate mockstream; extern crate serde_json; extern crate url; mod mock; use faktory::*; use std::io; use std::thread; use std::time::Duration; #[test] fn hello() { let mut s = mock::Stream::default(); let mut c = ConsumerBuilder::default(); c.hostname("h...
73318394Z\",\ \"reserve_for\":600,\ \"retry\":25\ }\r\n", ); let jh = thread::spawn(move || c.run(&["default"])); s.push_bytes_to_read(0, b"+{\"state\":\"quiet\"}\r\n"); s.ok(1); s.push_bytes_to_read(0, b"+{\"state\":\"terminate\"}\r\n...
tring()); c.register("foobar", |_| -> io::Result<()> { thread::sleep(Duration::from_secs(7)); Ok(()) }); let mut c = c.connect_with(s.clone(), None).unwrap(); s.ignore(0); s.push_bytes_to_read( 1, b"$0\r\n\r\n$182\r\n\ {\ \"jid\"...
function_block-random_span
[ { "content": "type JobRunner<E> = dyn Fn(Job) -> Result<(), E> + Send + Sync;\n", "file_path": "src/consumer/mod.rs", "rank": 0, "score": 109180.84650433416 }, { "content": "#[test]\n\nfn hello() {\n\n let mut s = mock::Stream::default();\n\n\n\n let p = Producer::connect_with(s.clone(...
Rust
src/memory.rs
appsignal/probes
61069b9d0d8f5c52a6e22c3be3e02810b7039d76
use super::Result; #[derive(Debug, PartialEq)] pub struct Memory { total: u64, free: u64, used: u64, buffers: u64, cached: u64, swap_total: u64, swap_free: u64, swap_used: u64, } const PROC_MEMORY_NUMBER_OF_FIELDS: usize = 6; const SYS_MEMORY_NUMBER_OF_FIELDS: usize = 1; impl Memory {...
use super::Result; #[derive(Debug, PartialEq)] pub struct Memory { total: u64, free: u64, used: u64, buffers: u64, cached: u64, swap_total: u64, swap_free: u64, swap_used: u64, } const PROC_MEMORY_NUMBER_OF_FIELDS: usize = 6; const SYS_MEMORY_NUMBER_OF_FIELDS: usize = 1; impl Memory {...
tal - memory.free; memory.swap_used = memory.swap_total - memory.swap_free; Ok(memory) } pub fn read_and_parse_sys_memory(path: &Path) -> Result<Memory> { let mut memory = Memory { total: 0, free: 0, used: 0, buffers: 0, cache...
let message = format!( "Directory `{}` not found", sys_fs_dir.to_str().unwrap_or("unknown path") ); Err(ProbeError::UnexpectedContent(message)) } } #[inline] pub fn read_and_parse_proc_memory(path: &Path) -> Result<Memory> { let mut...
random
[ { "content": "#[cfg(target_os = \"linux\")]\n\npub fn current_rss() -> Result<u64> {\n\n os::current_rss()\n\n}\n\n\n\n/// Get the current RSS memory of a process with given pid in KB\n", "file_path": "src/process_memory.rs", "rank": 1, "score": 148863.53883086663 }, { "content": "#[cfg(t...
Rust
src/decoding/mod.rs
Enet4/oxydicom
15d86fac0b8679420294650330d92a6f749ae923
use std::convert::TryInto; use jpeg2000::decode::{Codec, DecodeConfig}; use anyhow::{Result, anyhow}; use crate::utils::{Dicom, EncodedImage, RawImage, Encoding, Format, Palettes}; mod dicom_parsing; use dicom_parsing::get_encoded_image_data; pub fn get_image(dicom: &Dicom) -> Result<RawImage> { let encoded_image...
use std::convert::TryInto; use jpeg2000::decode::{Codec, DecodeConfig}; use anyhow::{Result, anyhow}; use crate::utils::{Dicom, EncodedImage, RawImage, Encoding, Format, Palettes}; mod dicom_parsing; use dicom_parsing::get_encoded_image_data; pub fn get_image(dicom: &Dicom) -> Result<RawImage> { let encoded_image...
} Ok(decoded_segment) }
if header_val > 129 { let n: usize = (258 - header_val).try_into()?; let rep_byte = segment_data[i]; decoded_segment.append(&mut vec![rep_byte; n]); i += 1; } else if header_val < 129 { let n: usize = header_val.try_into()?; if i+n > N {...
if_condition
[ { "content": "pub fn get_encoded_image_data(dicom: &Dicom) -> Result<EncodedImage> {\n\n\n\n let get_int_value = |tag| match dicom.element(tag)?.value() {\n\n\n\n Value::Primitive(primitive_val) => match primitive_val {\n\n PrimitiveValue::U16(val) => Ok(val[0].into()),\n\n _ => ...
Rust
compiler/crates/relay-compiler/src/watchman/file_source.rs
HeroicHitesh/relay
b96329c9c90d28b4c2336cb4f1cdcae7f9c6f846
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use super::query_builder::{get_all_roots, get_watchman_expr}; use super::{Clock, WatchmanFile}; use crate::errors::{Error, Result};...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use super::query_builder::{get_all_roots, get_watchman_expr}; use super::{Clock, WatchmanFile}; use crate::errors::{Error, Result};...
async fn try_saved_state( &self, perf_logger: &impl PerfLogger, perf_logger_event: &impl PerfLogEvent, saved_state_config: ScmAwareClockData, saved_state_loader: &Box<dyn SavedStateLoader + Send + Sync>, ) -> std::result::Result<Result<CompilerState>...
async fn query_file_result( &self, since_clock: Option<Clock>, perf_logger_event: &impl PerfLogEvent, ) -> Result<FileSourceResult> { let expression = get_watchman_expr(&self.config); let query_timer = perf_logger_event.start("watchman_query_time"); ...
function_block-full_function
[ { "content": "/// Returns root directories that contain GraphQL schema files.\n\nfn get_schema_file_roots(config: &Config) -> impl Iterator<Item = PathBuf> {\n\n get_schema_file_paths(config)\n\n .into_iter()\n\n .map(|schema_path| {\n\n schema_path\n\n .parent()\n\n ...
Rust
crates/kitsune_p2p/kitsune_p2p/src/spawn/actor/discover.rs
pjkundert/holochain
e0681530633b07c6cfe49948ef653a77a043bdbe
#![allow(dead_code)] use super::*; use crate::agent_store::AgentInfo; use ghost_actor::dependencies::must_future::MustBoxFuture; use std::collections::HashSet; use std::convert::TryFrom; pub(crate) enum PeerDiscoverResult { OkShortcut, OkRemote { url: url2::Url2, con_hnd: Tx2ConHnd<wire::Wire>,...
#![allow(dead_code)] use super::*; use crate::agent_store::AgentInfo; use ghost_actor::dependencies::must_future::MustBoxFuture; use std::collections::HashSet; use std::convert::TryFrom; pub(crate) enum PeerDiscoverResult { OkShortcut, OkRemote { url: url2::Url2, con_hnd: Tx2ConHnd<wire::Wire>,...
pub(crate) fn get_5_or_less_non_local_agents_near_basis( space: Arc<KitsuneSpace>, from_agent: Arc<KitsuneAgent>, _basis: Arc<KitsuneBasis>, i_s: ghost_actor::GhostSender<SpaceInternal>, evt_sender: futures::channel::mpsc::Sender<KitsuneP2pEvent>, bootstrap_service: Option<url2::Url2>, ) ...
c::Mutex::new(Vec::new())); let mut sent_to = HashSet::new(); let start_time = std::time::Instant::now(); let mut interval_ms = 50; loop { let fetched_count = out.lock().await.len();...
function_block-function_prefixed
[ { "content": "type WriteLenCb = Box<dyn Fn(&'static str, usize) + 'static + Send + Sync>;\n\n\n\n/// Metrics callback manager to be injected into the endpoint\n\npub struct Tx2ApiMetrics {\n\n write_len: Option<WriteLenCb>,\n\n}\n\n\n\nimpl Default for Tx2ApiMetrics {\n\n fn default() -> Self {\n\n ...
Rust
src/membership/client.rs
ShisoftResearch/bifrost
4c6901bd35d59767a4345ce154f4e0268b9ec990
use crate::membership::raft::client::SMClient; use crate::membership::DEFAULT_SERVICE_ID; use crate::raft::client::{RaftClient, SubscriptionError, SubscriptionReceipt}; use crate::raft::state_machine::master::ExecError; use bifrost_hasher::hash_str; use futures::future::BoxFuture; use serde::{Deserialize, Serialize}; u...
use crate::membership::raft::client::SMClient; use crate::membership::DEFAULT_SERVICE_ID; use crate::raft::client::{RaftClient, SubscriptionError, SubscriptionReceipt}; use crate::raft::state_machine::master::ExecError; use bifrost_hasher::hash_str; use futures::future::BoxFuture; use serde::{Deserialize, Serialize}; u...
F: Fn((Option<Member>, Option<Member>, u64)) -> BoxFuture<'static, ()> + 'static + Send + Sync, { self.sm_client .on_group_leader_changed(f, &hash_str(group)) .await } }
} } pub struct ObserverClient { pub sm_client: Arc<SMClient>, } impl ObserverClient { pub fn new(raft_client: &Arc<RaftClient>) -> ObserverClient { ObserverClient { sm_client: Arc::new(SMClient::new(DEFAULT_SERVICE_ID, &raft_client)), } } pub fn new_from_sm(sm_client: &Arc...
random
[ { "content": " def cmd join_group(group_name: String, id: u64) -> bool;\n", "file_path": "src/membership/mod.rs", "rank": 0, "score": 244661.37930010766 }, { "content": " def cmd leave_group(group: u64, id: u64) -> bool;\n", "file_path": "src/membership/mod.rs", "rank":...
Rust
src/generate/impl_for.rs
tguichaoua/virtue
1754e8f4c0521a08b0261be804b9c09707c8aaac
use super::{generate_fn::FnParent, FnBuilder, Parent, StreamBuilder}; use crate::{ parse::{GenericConstraints, Generics}, prelude::{Delimiter, Result}, }; #[must_use] pub struct ImplFor<'a, P: Parent> { generator: &'a mut P, trait_name: String, lifetimes: Option<Vec<String>>, custom_generic_co...
use super::{generate_fn::FnParent, FnBuilder, Parent, StreamBuilder}; use crate::{ parse::{GenericConstraints, Generics}, prelude::{Delimiter, Result}, }; #[must_use] pub struct ImplFor<'a, P: Parent> { generator: &'a mut P, trait_name: String, lifetimes: Option<Vec<String>>, custom_generic_co...
mes: &[String]) { for (idx, lt) in lifetimes.iter().enumerate() { builder.punct(if idx == 0 { '<' } else { ',' }); builder.lifetime_str(lt); } builder.punct('>'); }
function_block-function_prefixed
[ { "content": "pub fn consume_ident(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Option<Ident> {\n\n match input.peek() {\n\n Some(TokenTree::Ident(_)) => Some(super::utils::assume_ident(input.next())),\n\n Some(TokenTree::Group(group)) => {\n\n // When calling from a mac...
Rust
src_testbed/box2d_backend.rs
sebcrozet/rapier
b61bec83487224c285a1e95ac58d48885254285b
use std::collections::HashMap; use na::{Isometry2, Vector2}; use rapier::counters::Counters; use rapier::dynamics::{ IntegrationParameters, JointParams, JointSet, RigidBodyHandle, RigidBodySet, }; use rapier::geometry::{Collider, ColliderSet}; use std::f32; use wrapped2d::b2; use wrapped2d::dynamics::joints::{Pri...
use std::collections::HashMap; use na::{Isometry2, Vector2}; use rapier::counters::Counters; use rapier::dynamics::{ IntegrationParameters, JointParams, JointSet, RigidBodyHandle, RigidBodySet, }; use rapier::geometry::{Collider, ColliderSet}; use std::f32; use wrapped2d::b2; use wrapped2d::dynamics::joints::{Pri...
; let linear_damping = 0.0; let angular_damping = 0.0; let def = b2::BodyDef { body_type, position: na_vec_to_b2_vec(body.position().translation.vector), ...
if !body.is_dynamic() { b2::BodyType::Static } else { b2::BodyType::Dynamic }
if_condition
[ { "content": "pub fn init_world(testbed: &mut Testbed) {\n\n /*\n\n * World\n\n */\n\n let mut bodies = RigidBodySet::new();\n\n let mut colliders = ColliderSet::new();\n\n let mut joints = JointSet::new();\n\n\n\n let rad = 0.4;\n\n let num = 5;\n\n let shift = 1.0;\n\n\n\n let ...
Rust
rust_bridge/src/main.rs
masap/rust_cni
14329913c9f489cc857bc5bea2c31904cd6d2ee1
extern crate rust_bridge; extern crate scopeguard; use std::fs::File; use std::io::{Error, ErrorKind}; use std::os::unix::prelude::*; use std::result::Result; use std::thread; use nix::{fcntl, sched}; use rand::Rng; use serde_json::{json, Value}; use rust_bridge::{cni_utils, iptables_utils, CniArgs, CniConf}; fn cm...
extern crate rust_bridge; extern crate scopeguard; use std::fs::File; use std::io::{Error, ErrorKind}; use std::os::unix::prelude::*; use std::result::Result; use std::thread; use nix::{fcntl, sched}; use rand::Rng; use serde_json::{json, Value}; use rust_bridge::{cni_utils, iptables_utils, CniArgs, CniConf}; fn cm...
if let Err(err) = cni_utils::configure_netns_interface(&cni_ifname, &netns_ipv4_addr, &ipv4_mask, &gw_ipv4_addr) { return Err(err) } match cni_utils::get_hardware_addr(&cni_ifname) { Ok(addr) => Ok(addr), Err(...
if let Err(err) = sched::setns(netns_fd, sched::CloneFlags::CLONE_NEWNET) { panic!(format!("failed to setns to fd={}: {}", netns_fd, err)); }
if_condition
[ { "content": "# Rust CNI\n\nThis is a Kubernetes CNI plugin written with [Rust](https://www.rust-lang.org/).\n\n\n\nThis is a re-write of [bridge plugin](https://github.com/containernetworking/plugins/tree/master/plugins/main/bridge).\n\n\n\nThis CNI plugin depends on [host-local](https://github.com/containerne...
Rust
examples/acipher/ta/src/main.rs
mssun/incubator-teaclave-trustzone-sdk
c97dee27d662788bffcba5f84517a29f1c6d0481
#![no_main] use optee_utee::{ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, }; use optee_utee::{AlgorithmId, Asymmetric, OperationMode}; use optee_utee::{Error, ErrorKind, Parameters, Result}; use optee_utee::{TransientObject, TransientObjectType}; use proto::Command...
#![no_main] use optee_utee::{ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, }; use optee_utee::{AlgorithmId, Asymmetric, OperationMode}; use optee_utee::{Error, ErrorKind, Parameters, Result}; use optee_utee::{TransientObject, TransientObjectType}; use proto::Command...
} #[ta_invoke_command] fn invoke_command(sess_ctx: &mut RsaCipher, cmd_id: u32, params: &mut Parameters) -> Result<()> { trace_println!("[+] TA invoke command"); match Command::from(cmd_id) { Command::GenKey => gen_key(sess_ctx, params), Command::GetSize => get_size(sess_ctx, params), ...
match Asymmetric::allocate( AlgorithmId::RsaesPkcs1V15, OperationMode::Decrypt, key_info.object_size(), ) { Err(e) => Err(e), Ok(cipher) => { cipher.set_key(&rsa.key)?; match cipher.decrypt(&mut [], &mut cipher_text) { Err(e) => Err(e),...
if_condition
[]
Rust
src/additional_zones.rs
skurfuerst/cosmogony
117ef033ab2e523e87ccc958d7e40daff65279b6
use crate::hierarchy_builder::ZonesTree; use crate::is_place; use cosmogony::{Zone, ZoneIndex, ZoneType}; use geo::prelude::BoundingRect; use geo_types::{Coordinate, MultiPolygon, Point, Rect}; use geos::{Geom, Geometry}; use osmpbfreader::{OsmId, OsmObj}; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use ...
use crate::hierarchy_builder::ZonesTree; use crate::is_place; use cosmogony::{Zone, ZoneIndex, ZoneType}; use geo::prelude::BoundingRect; use geo_types::{Coordinate, MultiPolygon, Point, Rect}; use geos::{Geom, Geometry}; use osmpbfreader::{OsmId, OsmObj}; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use ...
fn convert_to_geo(geom: Geometry<'_>) -> Option<MultiPolygon<f64>> { match match geom.try_into() { Ok(c) => c, Err(e) => { println!("convert_to_geo: conversion to geo failed: {}", e); return None; } } { geo::Geometry::Polygon(x) => Some(MultiPolygon(vec!...
zone.zone_type = Some(ZoneType::City); zone.center = Some(Point::<f64>::new(node.lon(), node.lat())); zone.bbox = zone.center.as_ref().map(|p| { Rect::new( Coordinate { x: p.0.x - std::f64::EPSILO...
function_block-function_prefix_line
[ { "content": "pub fn is_place(obj: &OsmObj) -> bool {\n\n match *obj {\n\n OsmObj::Node(ref node) => node\n\n .tags\n\n .get(\"place\")\n\n .map_or(false, |v| v == \"city\" || v == \"town\" || v == \"village\"),\n\n _ => false,\n\n }\n\n}\n\n\n", "file_pa...