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/an_ok_binary_tree/src/lib.rs
shen-jinhao/Rust-With-Linked-Lists
924b6fe896192d1e3fc4757080027ae12baad28a
use an_ok_stack::List as Stack; use an_unsafe_queue::List as Queue; use std::fmt::Debug; #[derive(Clone)] pub struct BinaryTree<T> { root: Link<T>, } type Link<T> = Option<Box<Node<T>>>; #[derive(Eq, PartialEq, Clone)] struct Node<T> { elem: T, left: Link<T>, right: Link<T>, } impl<T> Node<T> { ...
use an_ok_stack::List as Stack; use an_unsafe_queue::List as Queue; use std::fmt::Debug; #[derive(Clone)] pub struct BinaryTree<T> { root: Link<T>, } type Link<T> = Option<Box<Node<T>>>; #[derive(Eq, PartialEq, Clone)] struct Node<T> { elem: T, left: Link<T>, right: Link<T>, } impl<T> Node<
()); } let mut flag = true; while !queue.is_empty() { let head = queue.pop().unwrap(); if head.left.is_some() { if !flag { return false; } queue.push(head.left.as_ref().unwrap()); } ...
T> { pub fn new(elem: T) -> Self { Self { elem, left: None, right: None, } } } impl<T: Debug + PartialEq + Clone> BinaryTree<T> { pub fn new(val: &[T], invalid: T) -> Self { let mut index: usize = 0; Self { root: Self::cre...
random
[ { "content": "struct Node {\n\n elem: i32,\n\n next: Link,\n\n}\n\n\n", "file_path": "src/a_bad_stack/src/lib.rs", "rank": 0, "score": 126590.78467837354 }, { "content": "struct Node<T> {\n\n elem: T,\n\n next: Link<T>,\n\n}\n\n\n\nimpl<T> List<T> {\n\n pub fn new() -> Self {\...
Rust
server/prisma-rs/query-engine/native-bridge/src/error.rs
otrebu/prisma
298be5c919119847bb8d102d6b16672edd06b2c5
use crate::protobuf; use connector::error::{ConnectorError, NodeSelectorInfo}; use failure::{Error, Fail}; use prisma_models::DomainError; use prost::DecodeError; use serde_json; #[derive(Debug, Fail)] pub enum BridgeError { #[fail(display = "Error in connector.")] ConnectorError(ConnectorError), #[fail(di...
use crate::protobuf; use connector::error::{ConnectorError, NodeSelectorInfo}; use failure::{Error, Fail}; use prisma_models::DomainError; use prost::DecodeError; use serde_json; #[derive(Debug, Fail)] pub enum BridgeError { #[fail(display = "Error in connector.")] ConnectorError(ConnectorError), #[fail(di...
protobuf::prisma::error::Value::NodeNotFoundForWhere(node_selector) } BridgeError::ConnectorError(ConnectorError::NodesNotConnected { relation_name, parent_name, parent_where, child_name, child_whe...
let node_selector = protobuf::prisma::NodeSelector { model_name: info.model, field_name: info.field, value: info.value.into(), };
assignment_statement
[ { "content": "pub fn parse_and_validate(input: &str) -> dml::Schema {\n\n let ast = datamodel::parser::parse(&String::from(input)).expect(\"Unable to parse datamodel.\");\n\n let validator = datamodel::validator::Validator::new();\n\n validator.validate(&ast).expect(\"Validation error\")\n\n}\n", "...
Rust
main/src/devices/stepper.rs
Alexander89/Stepper-Feedback-Driver
4e698750d75d79ec77b9845374cc9ebf741c4422
use atsamd_hal::{ delay::Delay, gpio::v2::{Pin, PushPullOutput, PA04, PA10, PA11}, prelude::_atsamd_hal_embedded_hal_digital_v2_OutputPin, }; use embedded_hal::digital::v2::PinState; use utils::time::{Microseconds, U32Ext}; use crate::settings::{DT_MIN_U32, STEPS_PER_RESOLUTION_I16, STEPS_PER_RESOLUTION_I1...
use atsamd_hal::{ delay::Delay, gpio::v2::{Pin, PushPullOutput, PA04, PA10, PA11}, prelude::_atsamd_hal_embedded_hal_digital_v2_OutputPin, }; use embedded_hal::digital::v2::PinState; use utils::time::{Microseconds, U32Ext}; use crate::settings::{DT_MIN_U32, STEPS_PER_RESOLUTION_I16, STEPS_PER_RESOLUTION_I1...
self.filtered_dt_per_step = ((self.filtered_dt_per_step + dt_per_step) / 2).min(DT_MIN_U32); let stuck = motor_dt.0 < self.filtered_dt_per_step - 1280; let dif = self.current_step - self.real_step; match dif.abs() { 1 => { ...
let dt_per_step = if dif == 0 { DT_MIN_U32 } else { (dt.0 / dif.abs() as u32).min(DT_MIN_U32) };
assignment_statement
[ { "content": "fn enabled_changed(state: bool) {\n\n unsafe { HARDWARE.as_mut() }.map(|hw| {\n\n if state {\n\n hw.stepper_enable();\n\n hw.led1.on()\n\n } else {\n\n hw.stepper_disable();\n\n hw.led1.off()\n\n }\n\n });\n\n}\n", "file_pa...
Rust
fruity_core/fruity_ecs/src/entity/entity_query/serialized/mod.rs
DoYouRockBaby/fruity_game_engine
299a8fe641efb142a551640f6d1aa4868e1ad670
use crate::entity::archetype::Archetype; use crate::entity::archetype::ArchetypeArcRwLock; use crate::entity::entity_query::serialized::params::With; use crate::entity::entity_query::serialized::params::WithEnabled; use crate::entity::entity_query::serialized::params::WithEntity; use crate::entity::entity_query::serial...
use crate::entity::archetype::Archetype; use crate::entity::archetype::ArchetypeArcRwLock; use crate::entity::entity_query::serialized::params::With; use crate::entity::entity_query::serialized::params::WithEnabled; use crate::entity::entity_query::serialized::params::WithEntity; use crate::entity::entity_query::serial...
fn get_field_infos(&self) -> Vec<FieldInfo> { vec![] } }
fn get_method_infos(&self) -> Vec<MethodInfo> { vec![ MethodInfo { name: "with_entity".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_entity(); ...
function_block-full_function
[ { "content": "pub fn use_global<'a, T: Send + Sync + 'static>() -> &'a mut T {\n\n let mut globals = GLOBALS.lock();\n\n let globals = globals.get_mut(&TypeId::of::<T>()).unwrap().deref_mut();\n\n let result = globals.downcast_mut::<T>().unwrap();\n\n\n\n // TODO: Try to find a way to remove that\n\...
Rust
src/beatmap/mod.rs
LunarCoffee/osurate
06684a4ddef5a579903e794245d98cea5d9883c8
use std::io::BufRead; pub use crate::beatmap::parser::ParseError; use crate::beatmap::parser::Parser; mod parser; #[derive(Clone, Debug)] pub struct Beatmap { pub general_info: GeneralInfo, pub editor_info: EditorInfo, pub metadata: Metadata, pub difficulty: DifficultyInfo, pub events: Events, ...
use std::io::BufRead; pub use crate::beatmap::parser::ParseError; use crate::beatmap::parser::Parser; mod parser; #[derive(Clone, Debug)] pub struct Beatmap { pub general_info: GeneralInfo, pub editor_info: EditorInfo, pub metadata: Metadata, pub difficulty: DifficultyInfo, pub events: Events, ...
pub fn into_string(self) -> String { format!( "osu file format v14\n\n{}\n{}\n{}\n{}\n{}\n[TimingPoints]\n{}\n\n{}\n[HitObjects]\n{}", self.general_info.into_string(), self.editor_info.into_string(), self.metadata.into_string(), self.difficu...
pub fn change_rate(&mut self, rate: f64) -> bool { let transform_f64 = |n| n / rate + 75.; let transform = |n| transform_f64(n as f64) as i32; let preview = self.general_info.preview_time; self.general_info.preview_time = if preview >= 0 { transform(preview) } else { p...
function_block-full_function
[ { "content": "// Stretches the audio associated with the given `map` by a factor of `rate`, updating metadata.\n\npub fn stretch_beatmap_audio(map: &mut Beatmap, dir: &Path, rate: f64) -> Result<()> {\n\n let old_path = dir.join(&map.general_info.audio_file);\n\n let old_audio = File::open(&old_path).or(E...
Rust
all-is-cubes/benches/space_bench.rs
kpreid/all-is-cubes
81e0fb8fbd5a0557f0f9002085f4160bce37174a
use criterion::{ black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput, }; use all_is_cubes::content::make_some_blocks; use all_is_cubes::space::{Grid, Space, SpaceTransaction}; use all_is_cubes::transaction::Transaction; pub fn space_bulk_mutation(c: &mut Criterion) { le...
use criterion::{ black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput, }; use all_is_cubes::content::make_some_blocks; use all_is_cubes::space::{Grid, Space, SpaceTransaction}; use all_is_cubes::transac
function( BenchmarkId::new("fill_uniform() entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { space.fill_uniform(space.grid...
tion::Transaction; pub fn space_bulk_mutation(c: &mut Criterion) { let mut group = c.benchmark_group("space-bulk-mutation"); for &mutation_size in &[1, 4, 64] { let grid = Grid::new([0, 0, 0], [mutation_size, mutation_size, mutation_size]); let bigger_grid = grid.multiply(2); let size_...
random
[]
Rust
Katalon_OrangeHRMS/Object Repository/Header_Menu/Performance/a_Manage Reviews.rs
girishbhangale416/Katalon_Docker
a3f8ada90afac9e0b71454366ca93ff8a09dffe4
<?xml version="1.0" encoding="UTF-8"?> <WebElementEntity> <description></description> <name>a_Manage Reviews</name> <tag></tag> <elementGuidId>a9d86c40-dd16-4349-9cf7-4fb26ece97a5</elementGuidId> <selectorCollection> <entry> <key>XPATH</key> <value> </entry> </selectorCol...
<?xml version="1.0" encoding="UTF-8"?> <WebElementEntity> <description></description> <name>a_Manage Reviews</name> <tag></tag> <elementGuidId>a9d86c40-dd16-4349-9cf7-4fb26ece97a5</elementGuidId> <selectorCollection> <entry> <key>XPATH</key> <value> </entry> </selectorCol...
ondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:href</name> <type>Main</type> <value>( </webElementX...
>tag</name> <type>Main</type> <value>a</value> </webElementProperties> <webElementProperties> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>href</name> <type>Main</type> <value>#</value> </webElementProperties> <webElementProperties> ...
random
[ { "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<WebElementEntity>\n\n <description></description>\n\n <name>input_Middle Name_middleName</name>\n\n <tag></tag>\n\n <elementGuidId>a02d298f-e2ee-48f3-8efe-dc1f9953b202</elementGuidId>\n\n <selectorCollection>\n\n <entry>\n\n <ke...
Rust
unsafe_collection/src/bytes/uninit.rs
HFQR/xitca-web
ee2d4fa9e88b2be149c9ca3454bc14d90f8f9ca2
use std::{io::IoSlice, mem::MaybeUninit}; use bytes_crate::{buf::Chain, Buf, Bytes}; use crate::uninit; use super::buf_list::{BufList, EitherBuf}; mod sealed { pub trait Sealed {} } pub trait ChunkVectoredUninit: sealed::Sealed { unsafe fn chunks_vectored_uninit<'a>(&'a s...
use std::{io::IoSlice, mem::MaybeUninit}; use bytes_crate::{buf::Chain, Buf, Bytes}; use crate::uninit; use super::buf_list::{BufList, EitherBuf}; mod sealed { pub trait Sealed {} } pub trait ChunkVectoredUninit: sealed::Sealed { unsafe fn chunks_vectored_uninit<'a>(&'a s...
} impl<L, R> sealed::Sealed for EitherBuf<L, R> where L: ChunkVectoredUninit, R: ChunkVectoredUninit, { } impl<L, R> ChunkVectoredUninit for EitherBuf<L, R> where L: ChunkVectoredUninit, R: ChunkVectoredUninit, { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit...
f, dst: &'s mut [MaybeUninit<IoSlice<'a>>], ) -> &'s mut [IoSlice<'a>] { unsafe { let len = self.chunks_vectored_uninit(dst); uninit::slice_assume_init_mut(&mut dst[..len]) } }
function_block-function_prefixed
[ { "content": " pub trait Sealed {}\n\n}\n\n\n\nimpl<T> sealed::Sealed for &mut [MaybeUninit<T>] {}\n\n\n", "file_path": "unsafe_collection/src/uninit.rs", "rank": 2, "score": 266279.3679360628 }, { "content": "/// Trait for safely initialize an unit slice.\n\npub trait PartialInit: sealed...
Rust
mayastor/tests/reconfigure.rs
gahag/MayaStor
0a2f01b04d75203e5ec19b3037703ee8967ec9e7
#![feature(async_await)] #![allow(clippy::cognitive_complexity)] use mayastor::{ bdev::{ nexus::nexus_bdev::{nexus_create, nexus_lookup}, Bdev, }, descriptor::Descriptor, mayastor_start, spdk_stop, }; use std::process::Command; static DISKNAME1: &str = "/tmp/disk1.img"; static BDEV...
#![feature(async_await)] #![allow(clippy::cognitive_complexity)] use mayastor::{ bdev::{ nexus::nexus_bdev::{nexus_create, nexus_lookup}, Bdev, }, descriptor::Descriptor, mayastor_start, spdk_stop, }; use std::process::Command; static DISKNAME1: &str = "/tmp/disk1.img"; static BDEV...
let stats1 = first.stats().await.unwrap(); let stats2 = second.stats().await.unwrap(); assert_eq!(stats1.num_write_ops, stats2.num_write_ops); } async fn works() { let child1 = BDEVNAME1.to_string(); let child2 = BDEVNAME2.to_string(); let children = vec![child1.clone(), child2.clone()]; n...
ert_eq!(rc, 0); let output = Command::new("rm") .args(&["-rf", DISKNAME1, DISKNAME2]) .output() .expect("failed delete test file"); assert_eq!(output.status.success(), true); } fn buf_compare(first: &[u8], second: &[u8]) { for i in 0 .. first.len() { assert_eq!(first[i], s...
random
[ { "content": "/// lookup a bdev by its name or one of its alias\n\npub fn bdev_lookup_by_name(name: &str) -> Option<Bdev> {\n\n let name = std::ffi::CString::new(name.to_string()).unwrap();\n\n unsafe {\n\n let b = spdk_sys::spdk_bdev_get_by_name(name.as_ptr());\n\n if b.is_null() {\n\n ...
Rust
src/main.rs
falzberger/ddlog_bench
261fc5598353c648708088eb3b36d1e2082fd869
use clap::{App, Arg, ArgMatches}; use csv::{ReaderBuilder, StringRecord}; use ordered_float::OrderedFloat; use std::fs::File; use std::io::prelude::*; use query_ddlog::api::HDDlog; use query_ddlog::relid2name; use query_ddlog::typedefs::*; use query_ddlog::Relations; use differential_datalog::ddval::{DDValConvert, DD...
use clap::{App, Arg, ArgMatches}; use csv::{ReaderBuilder, StringRecord}; use ordered_float::OrderedFloat; use std::fs::File; use std::io::prelude::*; use query_ddlog::api::HDDlog; use query_ddlog::relid2name; use query_ddlog::typedefs::*; use query_ddlog::Relations; use differential_datalog::ddval::{DDValConvert, DD...
fn main() -> Result<(), String> { let matches = get_cli_arg_matches(); println!("Instantiating DDlog program..."); let start = std::time::Instant::now(); let (hddlog, init_state) = HDDlog::run(1, false)?; println!( "Instantiating program took {} µs", ...
fn get_cli_arg_matches<'a>() -> ArgMatches<'a> { App::new("DDlog Benchmark CLI") .arg( Arg::with_name("input") .short("i") .help("Specifies a CSV input file for a relation. We expect CSVs to have headers.") .takes_value(true) .numbe...
function_block-full_function
[ { "content": "def to_entity_str(entity_id: int):\n", "file_path": "generator.py", "rank": 7, "score": 12004.358802751458 }, { "content": "# Differential Datalog Benchmarks\n\n\n\nThis repository contains some simple benchmarks based on artificially generated datasets for\n\nthe [Differential...
Rust
src/main.rs
caperaven/svg-to-js
07a2f5962d878d183c4aac2fd5e75f91e78982cc
mod path_to_path; extern crate lyon; extern crate glob; use std::env; use glob::glob; use std::fs; use lyon::tessellation::{FillOptions, FillTessellator, StrokeTessellator, StrokeOptions}; use lyon::path::math::{Point}; use lyon::path::Path; use lyon::tessellation::geometry_builder::{VertexBuffers, simple_builder}; ...
mod path_to_path; extern crate lyon; extern crate glob; use std::env; use glob::glob; use std::fs; use lyon::tessellation::{FillOptions, FillTessellator, StrokeTessellator, StrokeOptions}; use lyon::path::math::{Point}; use lyon::path::Path; use lyon::tessellation::geometry_builder::{VertexBuffers, simple_builder}; ...
fn main() { let (files, target_folder) = get_svg_in_folder(); for entry in files { match entry { Ok(path) => { let file_name = format!("{}", path.display()); let (fill_buffer, _stroke_buffer) = process_file(&file_name); save_buffer(&file_name...
function_block-full_function
[]
Rust
utils/test-env/src/utils.rs
hboshnak/casper-nft-cep47
09b40b0caf4cfc6f73d1e5f7d5b9c868228f7621
use std::path::PathBuf; use casper_engine_test_support::{ DeployItemBuilder, ExecuteRequestBuilder, InMemoryWasmTestBuilder, ARG_AMOUNT, DEFAULT_ACCOUNT_ADDR, DEFAULT_PAYMENT, }; use casper_execution_engine::core::engine_state::ExecuteRequest; use casper_types::{ account::AccountHash, bytesrepr::FromBytes,...
use std::path::PathBuf; use casper_engine_test_support::{ DeployItemBuilder, ExecuteRequestBuilder, InMemoryWasmTestBuilder, ARG_AMOUNT, DEFAULT_ACCOUNT_ADDR, DEFAULT_PAYMENT, }; use casper_execution_engine::core::engine_state::ExecuteRequest; use casper_types::{ account::AccountHash, bytesrepr::FromBytes,...
let named_keys = match &stored_value { StoredValue::Account(account) => account.named_keys(), StoredValue::Contract(contract) => contract.named_keys(), _ => { return Err( "Provided base key is nether an accou...
function_block-function_prefix_line
[ { "content": "pub fn key_and_value_to_str<T: CLTyped + ToBytes>(key: &Key, value: &T) -> String {\n\n let mut bytes_a = key.to_bytes().unwrap_or_revert();\n\n let mut bytes_b = value.to_bytes().unwrap_or_revert();\n\n\n\n bytes_a.append(&mut bytes_b);\n\n\n\n let bytes = runtime::blake2b(bytes_a);\n...
Rust
src/main.rs
rcarmo/rrss2imap
1fff615262bcf5f98ae74bfacec6f902f732b9de
extern crate structopt; #[macro_use] extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate flexi_logger; extern crate treexml; extern crate chrono; extern crate rfc822_sanitizer; extern crate unidecode; extern crate tera; #[macro_use] exter...
extern crate structopt; #[macro_use] extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate flexi_logger; extern crate treexml; extern crate chrono; extern crate rfc822_sanitizer; extern crate unidecode; extern crate tera; #[macro_use] exter...
flexi_logger::colored_with_thread, }) .start() .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e)); openssl_probe::init_ssl_cert_env_vars(); let store_path = store::find_store(); let store_result = store::Store::load(&store_path); match store_result { ...
function_block-function_prefix_line
[ { "content": "fn group_feeds(to_store: &Store) -> HashMap<String, Vec<Feed>> {\n\n to_store.feeds.iter().fold(HashMap::new(), |mut map, feed| {\n\n let feed = feed.clone();\n\n let folder = feed.config.get_folder(&to_store.settings.config);\n\n if !map.contains_key(&folder) {\n\n ...
Rust
src/loading/util.rs
zmbush/budgetron
3403a020abbea635e156d2245226120ee87843c6
use { crate::loading::{ alliant, generic::{Genericize, Transaction}, logix, mint, }, budgetronlib::error::{BResult, BudgetError}, csv::Reader, log::info, serde::de::DeserializeOwned, std::{ cmp::min, fmt::Display, fs::File, io::{self,...
use { crate::loading::{ alliant, generic::{Genericize, Transaction}, logix, mint, }, budgetronlib::error::{BResu
read(buf), Source::Stdin(ref mut source) => { if source.loc >= source.buf.len() { let ret = source.stdin.read(buf); if let Ok(size) = ret { source.buf.extend_from_slice(&buf[..size]); source.loc += size; ...
lt, BudgetError}, csv::Reader, log::info, serde::de::DeserializeOwned, std::{ cmp::min, fmt::Display, fs::File, io::{self, Read, Seek, Stdin, StdinLock}, path::Path, }, }; fn from_reader<TransactionType, R>(file: &mut R) -> BResult<Vec<Transaction>> where ...
random
[ { "content": "CREATE TABLE transactions (\n\n id SERIAL PRIMARY KEY,\n\n date DATE NOT NULL,\n\n person VARCHAR NOT NULL,\n\n description VARCHAR NOT NULL,\n\n original_description VARCHAR,\n\n amount DOUBLE PRECISION NOT NULL,\n\n transaction_type VARCHAR NOT NULL,\n\n category VARCHAR NOT NULL,\n\n o...
Rust
guacamole-runner/src/map.rs
EllenNyan/guacamole-runner
aa17fdaf763e415ff9531e42ae946b503f9cbfb9
use crate::{ shipyard::{ *, }, consts::{ *, }, tetra::{ math::{ Vec3, Vec2, }, graphics::{ Color, }, }, }; use vermarine_lib::{ rendering::{ draw_buffer::{ DrawBuffer, DrawCom...
use crate::{ shipyard::{ *, }, consts::{ *, }, tetra::{ math::{ Vec3, Vec2, }, graphics::{ Color, }, }, }; use vermarine_lib::{ rendering::{ draw_buffer::{ DrawBuffer, DrawCom...
pub fn render_hex_map(mut draw_buffer: UniqueViewMut<DrawBuffer>, drawables: NonSendSync<UniqueViewMut<Drawables>>, mut map: UniqueViewMut<HexMap>) { draw_buffer.new_command_pool(true); let command_pool = draw_buffer.get_command_pool(); let (q, r) = map.pixel_to_hex_raw(Vec2::zero(), 0.); let startx...
mut qi = q.round() as i32; let mut ri = r.round() as i32; let mut si = s.round() as i32; let q_diff = f64::abs(qi as f64 - q as f64); let r_diff = f64::abs(ri as f64 - r as f64); let s_diff = f64::abs(si as f64 - s as f64); if q_diff > r_diff && q_diff > s_diff { qi = -ri - si; } e...
function_block-function_prefixed
[ { "content": "pub fn player_height_visualiser(player: View<Player>, height: View<Height>, mut sprite: ViewMut<Sprite>) {\n\n let (_, height, sprite) = (&player, &height, &mut sprite).iter().next().unwrap();\n\n let mut percent = height.0 / START_HEIGHT;\n\n percent *= percent;\n\n let start = 1.;\n\...
Rust
src/grammar/grammar.rs
zuyumi/compiler-course-helper
093b0d37073703d8e87e29e140a7bec29008c93b
use std::collections::{HashMap, HashSet}; #[derive(Debug, Clone)] pub struct NonTerminal { pub index: usize, pub name: String, pub first: HashSet<usize>, pub follow: HashSet<usize>, pub nullable: bool, pub productions: Vec<Vec<usize>>, } impl NonTerminal { pub fn new(index: usize, name: St...
use std::collections::{HashMap, HashSet}; #[derive(Debug, Clone)] pub struct NonTerminal { pub index: usize, pub name: String, pub first: HashSet<usize>, pub follow: HashSet<usize>, pub nullable: bool, pub productions: Vec<Vec<usize>>, } impl NonTerminal { pub fn new(index: usize, name: St...
}
pub fn production_to_vec_str(&self, production: &Vec<usize>) -> Vec<&str> { production .iter() .map(|idx| self.get_symbol_name(*idx)) .collect() }
function_block-full_function
[ { "content": "#[wasm_bindgen]\n\npub fn wasm_grammar_to_output(json: &str) -> String {\n\n let args: WasmArgs = serde_json::from_str(json).unwrap();\n\n let result = grammar_to_output(&args.grammar, &args.actions, &args.outputs);\n\n serde_json::to_string(&result).unwrap()\n\n}\n\n\n\n#[derive(Clone, C...
Rust
src/services/paste.rs
zeroqn/pastebin-actix
269693f99be1d9a7cc010bf7e4392f61909659b8
use std::time::SystemTime; use actix::prelude::*; use diesel::{self, prelude::*}; use crate::common::error::ServerError; use crate::models::{ executor::DatabaseExecutor as DbExecutor, paste::{NewPaste, Paste}, }; pub struct CreatePasteMsg { pub title: String, pub body: String, pub created_at: Sys...
use std::time::SystemTime; use actix::prelude::*; use diesel::{self, prelude::*}; use crate::common::error::ServerError; use crate::models::{ executor::DatabaseExecutor as DbExecutor, paste::{NewPaste, Paste}, }; pub struct CreatePasteMsg { pub title: String, pub body: String, pub created_at: Sys...
} pub struct DelPasteByIdMsg { pub id: i64, } impl Message for DelPasteByIdMsg { type Result = Result<usize, ServerError>; } impl Handler<DelPasteByIdMsg> for DbExecutor { type Result = Result<usize, ServerError>; fn handle(&mut self, msg: DelPasteByIdMsg, _: &mut Self::Context) -> Self::Result { ...
fn handle(&mut self, msg: GetPasteListMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; let mut query = pastes.into_boxed(); if let Some(title_pat) = msg.title_pat { query = query.filter(title.ilike(title_pat.to_owned() + "%")); } ...
function_block-full_function
[ { "content": "pub fn get_paste_list(\n\n (req, conds): (HttpRequest<State>, Query<GetPasteListConds>),\n\n) -> FutureJsonResponse {\n\n let db_chan = req.state().db_chan.clone();\n\n let created_at = conds\n\n .cmp_created_at\n\n .to_owned()\n\n .map_or(Ok(None), |cmp_created_at| {...
Rust
day-21/src/main.rs
Shriram-Balaji/rust-advent-of-code-2020
a1002a2f50d12eff744f7cb0db1f7271b9020c3a
#[macro_use] extern crate lazy_static; use regex::Regex; use std::{ collections::{BTreeMap, HashMap, HashSet}, env, fs, }; #[derive(Debug)] struct Food<'a> { ingredients: HashSet<&'a str>, allergens: Vec<&'a str>, } fn process_food(food: &str) -> Food { lazy_static! { static ref FOOD_REGEX...
#[macro_use] extern crate lazy_static; use regex::Regex; use std::{ collections::{BTreeMap, HashMap, HashSet}, env, fs, }; #[derive(Debug)] struct Food<'a> { ingredients: HashSet<&'a str>, allergens: Vec<&'a str>, } fn process_food(food: &str) -> Food { lazy_static! { static ref FOOD_REGEX...
}
fn should_process_food_items_list() { let input = r#"mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish)"#; process_food_items(input); }
function_block-full_function
[ { "content": "fn process(input: &str) -> (u64, Vec<&str>) {\n\n let notes: Vec<&str> = input.split('\\n').collect();\n\n let timestamp = notes[0].parse::<u64>().expect(\"Invalid timestamp\");\n\n let bus_ids: Vec<&str> = notes[1].split(',').collect();\n\n (timestamp, bus_ids)\n\n}\n\n\n", "file_...
Rust
src/macos/aarch64/vcpu.rs
RWTH-OS/uhyve
14e8ea129a82910c13e5a12b7893cd1badb5f380
#![allow(non_snake_case)] #![allow(clippy::identity_op)] use crate::aarch64::{ mair, tcr_size, MT_DEVICE_nGnRE, MT_DEVICE_nGnRnE, MT_DEVICE_GRE, MT_NORMAL, MT_NORMAL_NC, PSR, TCR_FLAGS, TCR_TG1_4K, VA_BITS, }; use crate::consts::*; use crate::vm::HypervisorResult; use crate::vm::SysExit; use crate::vm::VcpuStopReaso...
#![allow(non_snake_case)] #![allow(clippy::identity_op)] use crate::aarch64::{ mair, tcr_size, MT_DEVICE_nGnRE, MT_DEVICE_nGnRnE, MT_DEVICE_GRE, MT_NORMAL, MT_NORMAL_NC, PSR, TCR_FLAGS, TCR_TG1_4K, VA_BITS, }; use crate::consts::*; use crate::vm::HypervisorResult; use crate::vm::SysExit; use crate::vm::VcpuStopReaso...
} impl VirtualCPU for UhyveCPU { fn init(&mut self, entry_point: u64) -> HypervisorResult<()> { debug!("Initialize VirtualCPU"); /* pstate = all interrupts masked */ let pstate: PSR = PSR::D_BIT | PSR::A_BIT | PSR::I_BIT | PSR::F_BIT | PSR::MODE_EL1H; self.vcpu.write_register(Register::CPSR, pstate.bits())?...
pub fn new(id: u32, kernel_path: PathBuf, args: Vec<OsString>, vm_start: usize) -> UhyveCPU { Self { id, kernel_path, args, vcpu: xhypervisor::VirtualCpu::new().unwrap(), vm_start, } }
function_block-full_function
[ { "content": "/// Uses Cargo to build a kernel in the `tests/test-kernels` directory.\n\n/// Returns a path to the build binary.\n\npub fn build_hermit_bin(kernel: impl AsRef<Path>) -> PathBuf {\n\n\tlet kernel = kernel.as_ref();\n\n\tprintln!(\"Building Kernel {}\", kernel.display());\n\n\tlet kernel_src_path ...
Rust
gcode/src/words.rs
Michael-F-Bryan/gcode-rs
3cfd2fe1787fcd234bf135bbc7250aa1b5b67ca6
use crate::{ lexer::{Lexer, Token, TokenType}, Comment, Span, }; use core::fmt::{self, Display, Formatter}; #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr( feature = "serde-1", derive(serde_derive::Serialize, serde_derive::Deserialize) )] #[repr(C)] pub struct Word { pub letter: char, ...
use crate::{ lexer::{Lexer, Token, TokenType}, Comment, Span, }; use core::fmt::{self, Display, Formatter}; #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr( feature = "serde-1", derive(serde_derive::Serialize, serde_derive::Deserialize) )] #[repr(C)] pub struct Word { pub letter: char, ...
() { let mut words = WordsOrComments::new(Lexer::new("(this is a comment) 3.14")); let got = words.next().unwrap(); let comment = "(this is a comment)"; let expected = Atom::Comment(Comment { value: comment, span: Span { start: 0, ...
fn next(&mut self) -> Option<Self::Item> { while let Some(token) = self.tokens.next() { let Token { kind, value, span } = token; match kind { TokenType::Unknown => return Some(Atom::Unknown(token)), TokenType::Comment => { return Some...
random
[ { "content": "/// Parse each [`GCode`] in some text, ignoring any errors that may occur or\n\n/// [`Comment`]s that are found.\n\n///\n\n/// This function is probably what you are looking for if you just want to read\n\n/// the [`GCode`] commands in a program. If more detailed information is needed,\n\n/// have...
Rust
src/lib.rs
JIghtuse/rs-release
e96f2441c02ed1d54ee939856fca87c9bc2b7459
#![deny(missing_docs)] use std::collections::HashMap; use std::convert::From; use std::error::Error; use std::fmt; use std::fs::File; use std::io::{BufReader, BufRead}; use std::path::Path; use std::borrow::Cow; const PATHS: [&'static str; 2] = ["/etc/os-release", "/usr/lib/os-release"]; const QUOTES: [&'static str...
#![deny(missing_docs)] use std::collections::HashMap; use std::convert::From; use std::error::Error; use std::fmt; use std::fs::File; use std::io::{BufReader, BufRead}; use std::path::Path; use std::borrow::Cow; const PATHS: [&'static str; 2] = ["/etc/os-release", "/usr/lib/os-release"]; const QUOTES: [&'static str...
fn extract_variable_and_value(s: &str) -> Result<(Cow<'static, str>, String)> { if let Some(equal) = s.chars().position(|c| c == '=') { let var = &s[..equal]; let var = var.trim(); let val = &s[equal + 1..]; let val = trim_quotes(val.trim()).to_string(); if let Some(key) =...
fn trim_quotes(s: &str) -> &str { if QUOTES.iter().any(|q| s.starts_with(q) && s.ends_with(q)) { &s[1..s.len() - 1] } else { s } }
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nenum Error {\n\n UnknownOs,\n\n ReadError,\n\n}\n\n\n", "file_path": "examples/who_eats_my_hard_drive.rs", "rank": 5, "score": 70185.70182749387 }, { "content": "fn get_os_id() -> Result<String, Error> {\n\n match rs_release::get_os_release() {\n\n ...
Rust
crates/tm4c129x/src/emac0/vlantg.rs
m-labs/ti2svd
30145706b658136c35c90290701de3f02a4b8ef2
#[doc = "Reader of register VLANTG"] pub type R = crate::R<u32, super::VLANTG>; #[doc = "Writer for register VLANTG"] pub type W = crate::W<u32, super::VLANTG>; #[doc = "Register VLANTG `reset()`'s with value 0"] impl crate::ResetValue for super::VLANTG { type Type = u32; #[inline(always)] fn reset_value() ...
#[doc = "Reader of register VLANTG"] pub type R = crate::R<u32, super::VLANTG>; #[doc = "Writer for register VLANTG"] pub type W = crate::W<u32, super::VLANTG>; #[doc = "Register VLANTG `reset()`'s with value 0"] impl crate::ResetValue for super::VLANTG { type Type = u32; #[inline(always)] fn reset_value() ...
elf) -> ETV_R { ETV_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - VLAN Tag Inverse Match Enable"] #[inline(always)] pub fn vtim(&self) -> VTIM_R { VTIM_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - Enable S-VLAN"] #[inline(always)] pub fn esvl(...
s)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
crates/core/src/graph/mod.rs
rustatian/rock
664825fe85b3649de669d5e498f64267c7676e79
#![warn(missing_debug_implementations)] #![allow(dead_code)] use crate::profile::line::Line; use crate::profile::Profile; use crate::profile::{self}; use std::{collections::HashMap, vec}; use std::{ hash::{Hash, Hasher}, path::PathBuf, }; #[cfg(target_os = "windows")] const SEPARATOR: &str = "\\"; #[cfg(tar...
#![warn(missing_debug_implementations)] #![allow(dead_code)] use crate::profile::line::Line; use crate::profile::Profile; use crate::profile::{self}; use std::{collections::HashMap, vec}; use std::{ hash::{Hash, Hasher}, path::PathBuf, }; #[cfg(target_os = "windows")] const SEPARATOR: &str = "\\"; #[cfg(tar...
fn create_nodes<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( prof: &Profile, o: Options<T, U>, ) -> Option<(Nodes, HashMap<u64, Nodes>)> { let mut locations: HashMap<u64, Nodes> = HashMap::new(); let nm = NodeMap::new(); for l in prof.location.iter() { ...
fn init_graph<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( &self, prof: Profile, o: Options<T, U>, ) -> Self { Graph { nodes: vec![] } }
function_block-full_function
[ { "content": "#[inline]\n\n#[allow(unused_assignments)]\n\npub fn decode_field(buf: &mut Buffer, data: &mut Vec<u8>) -> Result<Vec<u8>, RockError> {\n\n let result = decode_varint(data);\n\n match result {\n\n Ok(varint) => {\n\n // decode\n\n // 90 -> 1011010\n\n /...
Rust
src/args.rs
anthraxx/dfrs
ea645d6a9d36510005a08dc6729884e1171cc068
#![allow(clippy::use_self)] use structopt::clap::{AppSettings, Shell}; use structopt::StructOpt; use std::io::stdout; use anyhow::Result; use lazy_static::lazy_static; use std::path::PathBuf; use strum::VariantNames; use strum_macros::{EnumString, EnumVariantNames, ToString}; #[derive(Debug, StructOpt)] #[structopt(...
#![allow(clippy::use_self)] use structopt::clap::{AppSettings, Shell}; use structopt::StructOpt; use std::io::stdout; use anyhow::Result; use lazy_static::lazy_static; use std::path::PathBuf; use strum::VariantNames; use strum_macros::{EnumString, EnumVariantNames, ToString}; #[derive(Debug, StructOpt)] #[structopt(...
ble_values=&Shell::variants())] pub shell: Shell, } pub fn gen_completions(args: &Completions) -> Result<()> { Args::clap().gen_completions_to("dfrs", args.shell, &mut stdout()); Ok(()) }
atch self { Self::Base10 => 1000_f64, Self::Base2 => 1024_f64, } } } #[derive(Debug, StructOpt, ToString, EnumString, EnumVariantNames)] #[strum(serialize_all = "snake_case")] pub enum ColumnType { Filesystem, Type, Bar, Used, UsedPercentage, Available, A...
random
[ { "content": "pub fn parse_mounts(f: File) -> Result<Vec<Mount>> {\n\n BufReader::new(f)\n\n .lines()\n\n .map(|line| {\n\n parse_mount_line(&line?)\n\n .context(\"Failed to parse mount line\")\n\n .map_err(Error::from)\n\n })\n\n .collect:...
Rust
rust/k210-shared/src/soc/sysctl/pll_compute.rs
egcd32/k210-sdk-stuff
ab95e18ba81e011f721237472b1f5434506fd7fb
use core::convert::TryInto; use libm::F64Ext; /** PLL configuration */ #[derive(Debug, PartialEq, Eq)] pub struct Params { pub clkr: u8, pub clkf: u8, pub clkod: u8, pub bwadj: u8, } /* constants for PLL frequency computation */ const VCO_MIN: f64 = 3.5e+08; const VCO_MAX: f64 = 1.75e+09; const REF_MI...
use core::convert::TryInto; use libm::F64Ext; /** PLL configuration */ #[derive(Debug, PartialEq, Eq)] pub struct Params { pub clkr: u8, pub clkf: u8, pub clkod: u8, pub bwadj: u8, } /* constants for PLL frequency computation */ const VCO_MIN: f64 = 3.5e+08; const VCO_MAX: f64 = 1.75e+09; const REF_MI...
}
fn test_ompute_params() { /* check against output of C implementation */ assert_eq!(compute_params(26_000_000, 1_500_000_000), Some(Params { clkr: 0, clkf: 57, clkod: 0, bwadj: 57 })); assert_eq!(compute_params(26_000_000, 1_000_000_000), Some(Params { clkr: 0, clkf: 37, clkod: 0, bwadj: 37 }));...
function_block-full_function
[ { "content": "pub fn set_bit(inval: u32, bit: u8, state: bool) -> u32 {\n\n if state {\n\n inval | (1 << u32::from(bit))\n\n } else {\n\n inval & !(1 << u32::from(bit))\n\n }\n\n}\n\n\n", "file_path": "rust/k210-shared/src/soc/utils.rs", "rank": 1, "score": 305117.4159386919 ...
Rust
src/support/mod.rs
Twinklebear/tobj_viewer
c6f59993eb4bf0a7b1262602fec17884ec48c1f3
#![allow(dead_code)] extern crate clock_ticks; extern crate tobj; use glium::vertex::VertexBufferAny; use glium::{self, Display}; use std::f32; use std::path::Path; use std::thread; use std::time::{Duration, Instant}; pub mod camera; pub enum Action { Stop, Continue, } pub fn start_loop<F>(mut callback: F)...
#![allow(dead_code)] extern crate clock_ticks; extern crate tobj; use glium::vertex::VertexBufferAny; use glium::{self, Display}; use std::f32; use std::path::Path; use std::thread; use std::time::{Duration, Instant}; pub mod camera; pub enum Action { Stop, Continue, } pub fn start_loop<F>(mut callback: F)...
f32::powf(max_pos[1] - min_pos[1], 2.0) + f32::powf(max_pos[2] - min_pos[2], 2.0); let scale = f32::sqrt(diagonal_len / current_len); println!("Model scaled by {} to fit", scale); ( glium::vertex::VertexBuffer::new(display, &vertex_data) .unwrap() .into_vertex_buffer_...
function_block-function_prefix_line
[ { "content": "fn show_test_window<'a>(ui: &Ui<'a>, state: &mut State, opened: &mut bool) {\n\n if state.show_app_metrics {\n\n ui.show_metrics_window(&mut state.show_app_metrics);\n\n }\n\n if state.show_app_main_menu_bar { show_example_app_main_menu_bar(ui, state) }\n\n if state.show_app_aut...
Rust
src/ast/pp_visitor.rs
ffwff/iro
2e92ab30bee7f3ab9036726e383edd8ec788fdd9
use crate::ast::*; use crate::compiler::sources; use bit_set::BitSet; use std::path::PathBuf; pub struct PreprocessState { imported: BitSet<u32>, total_imported_statements: Vec<NodeBox>, prelude: Option<PathBuf>, } impl PreprocessState { pub fn new(prelude: Option<PathBuf>) -> Self { Self { ...
use crate::ast::*; use crate::compiler::sources; use bit_set::BitSet; use std::path::PathBuf; pub struct PreprocessState { imported: BitSet<u32>, total_imported_statements: Vec<NodeBox>, prelude: Option<PathBuf>, } impl PreprocessState { pub fn new(prelude: Option<PathBuf>) -> Self { Self { ...
} impl<'a> Visitor for PreprocessVisitor<'a> { fn visit_program(&mut self, n: &mut Program) -> VisitorResult { for node in &n.exprs { Self::ungenerate_retvar(node); node.visit(self)?; } if self.file == 0 { if let Some(state_cell) = self.state { ...
fn import(&mut self, working_path: PathBuf) -> VisitorResult { if let Some(mut state) = self.state.as_ref().map(|x| x.borrow_mut()) { let sources = &mut self.sources; let (index, _) = sources .read(&working_path) .map_err(|error| compiler::Error::io_error...
function_block-full_function
[ { "content": "pub fn mangle_string(source: &str, dest: &mut String) {\n\n for ch in source.chars() {\n\n assert!((0x20..0x7e).contains(&(ch as _)));\n\n dest.push(ch);\n\n }\n\n}\n\n\n", "file_path": "src/codegen/mangler.rs", "rank": 0, "score": 158156.51224327856 }, { "c...
Rust
contracts/pylon/gov/src/executions/mod.rs
kyscott18/interest_split
e24541f6ecfb228ab1397a1f058bb45149c413a9
use cosmwasm_std::{ from_binary, to_binary, CanonicalAddr, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Order, Response, Uint128, WasmMsg, }; use cosmwasm_storage::{ReadonlyBucket, ReadonlySingleton}; use cw20::Cw20ReceiveMsg; use pylon_token::gov_msg::{ AirdropMsg, Cw20HookMsg, ExecuteMsg, InstantiateMsg...
use cosmwasm_std::{ from_binary, to_binary, CanonicalAddr, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Order, Response, Uint128, WasmMsg, }; use cosmwasm_storage::{ReadonlyBucket, ReadonlySingleton}; use cw20::Cw20ReceiveMsg; use pylon_token::gov_msg::{ AirdropMsg, Cw20HookMsg, ExecuteMsg, InstantiateMsg...
pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> ExecuteResult { match msg { MigrateMsg::State {} => { let state: LegacyState = ReadonlySingleton::new(deps.storage, b"state") .load() .unwrap(); State::save( deps.storage, ...
function_block-full_function
[ { "content": "pub fn claim(deps: DepsMut, env: Env, info: MessageInfo, sender: Option<String>) -> ExecuteResult {\n\n let sender = sender\n\n .map(|x| deps.api.addr_validate(x.as_str()).unwrap())\n\n .unwrap_or(info.sender);\n\n\n\n let state = State::load(deps.storage).unwrap();\n\n let ...
Rust
src/util/conversions.rs
paigereeves/mmtk-core
d45c5155d3f20bdc4f667c3b08a78f641507966c
use crate::util::constants::*; use crate::util::heap::layout::vm_layout_constants::*; use crate::util::Address; /* Alignment */ pub fn is_address_aligned(addr: Address) -> bool { addr.is_aligned_to(BYTES_IN_ADDRESS) } pub fn page_align_down(address: Address) -> Address { address.align_down(BYTES_IN_PAGE) } ...
use crate::util::constants::*; use crate::util::heap::layout::vm_layout_constants::*; use crate::util::Address; /* Alignment */ pub fn is_address_aligned(addr: Address) -> bool { addr.is_aligned_to(BYTES_IN_ADDRESS) } pub fn page_align_down(ad
o_chunk_index(addr: Address) -> usize { addr >> LOG_BYTES_IN_CHUNK } pub fn chunk_index_to_address(chunk: usize) -> Address { unsafe { Address::from_usize(chunk << LOG_BYTES_IN_CHUNK) } } pub const fn raw_align_up(val: usize, align: usize) -> usize { val.wrapping_add(align).wrapping_sub(1) & !align.w...
dress: Address) -> Address { address.align_down(BYTES_IN_PAGE) } pub fn is_page_aligned(address: Address) -> bool { address.is_aligned_to(BYTES_IN_PAGE) } pub const fn chunk_align_up(addr: Address) -> Address { addr.align_up(BYTES_IN_CHUNK) } pub const fn chunk_align_down(addr: Address) -> Address { ...
random
[ { "content": "/// Is the address in the mapped memory? The runtime can use this function to check\n\n/// if an address is mapped by MMTk. Note that this is different than is_mapped_object().\n\n/// For malloc spaces, MMTk does not map those addresses (malloc does the mmap), so\n\n/// this function will return f...
Rust
src/threaded.rs
jneem/dfa-runner
b3e926f79274e0254ecc61c86ec7d8b9874948b9
use Engine; use prefix::{Prefix, PrefixSearcher}; use program::{Program, Instructions}; use std::mem; use std::cell::RefCell; use std::ops::DerefMut; #[derive(Clone, Debug, PartialEq)] struct Thread { state: usize, start_idx: usize, } #[derive(Clone, Debug, PartialEq)] struct Threads { threads: Vec<Thre...
use Engine; use prefix::{Prefix, PrefixSearcher}; use program::{Program, Instructions}; use std::mem; use std::cell::RefCell; use std::ops::DerefMut; #[derive(Clone, Debug, PartialEq)] struct Thread { state: usize, start_idx: usize, } #[derive(Clone, Debug, PartialEq)] struct Threads { threads: Vec<Thre...
_bytes(); let mut searcher = self.prefix.make_searcher(s); self.shortest_match_from_searcher(s, &mut *searcher) } fn clone_box(&self) -> Box<Engine> { Box::new(self.clone()) } }
ads.cur.threads[i].state; let start_idx = threads.cur.threads[i].start_idx; threads.cur.states[state] = 0; let (next_state, accept) = self.prog.step(state, &input[pos..]); if let Some(bytes_ago) = accept { let acc_idx = start_idx.saturating_sub(byte...
random
[ { "content": "fn loop_searcher<'i, 'lo>(loop_while: &'lo [bool], input: &'i [u8])\n\n-> SimpleSearcher<'i, LoopWhile<'lo>> {\n\n SimpleSearcher {\n\n skip_fn: LoopWhile(loop_while),\n\n input: input,\n\n pos: 0,\n\n }\n\n}\n\n\n\nimpl<'a, Sk: SkipFn> PrefixSearcher for SimpleSearcher<...
Rust
src/graph/stage/source/refreshable.rs
dmrolfs/proctor
9b2fac5e80e4a8874906a85302af7b34b4433f46
use std::fmt::{self, Debug}; use std::future::Future; use async_trait::async_trait; use cast_trait_object::dyn_upcast; use tokio::sync::mpsc; use crate::graph::shape::SourceShape; use crate::graph::{stage, Outlet, Port, Stage, PORT_DATA}; use crate::{AppData, ProctorResult, SharedString}; pub struct RefreshableSourc...
use std::fmt::{self, Debug}; use std::future::Future; use async_trait::async_trait; use cast_trait_object::dyn_upcast; use tokio::sync::mpsc; use crate::graph::shape::SourceShape; use crate::graph::{stage, Outlet, Port, Stage, PORT_DATA}; use crate::{AppData, ProctorResult, SharedString}; pub struct RefreshableSourc...
async fn close(mut self: Box<Self>) -> ProctorResult<()> { tracing::info!("closing refreshable source outlet."); self.outlet.close().await; Ok(()) } } impl<Ctrl, Out, A, F> Debug for RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<O...
async fn run(&mut self) -> ProctorResult<()> { let mut done = false; let op = &self.action; let operation = op(None); tokio::pin!(operation); let outlet = &self.outlet; let rx = &mut self.rx_control; loop { let _timer = stage::start_stage_eval_time(...
function_block-full_function
[ { "content": "#[dyn_upcast]\n\n#[async_trait]\n\npub trait Stage: fmt::Debug + Send + Sync {\n\n fn name(&self) -> SharedString;\n\n async fn check(&self) -> ProctorResult<()>;\n\n async fn run(&mut self) -> ProctorResult<()>;\n\n async fn close(self: Box<Self>) -> ProctorResult<()>;\n\n}\n\n\n", ...
Rust
logpack-derive/src/encode_derive.rs
da-x/logpack
4c95c05a415a94d41ff562cde38d77b3e55516c1
use std::collections::HashSet; use proc_macro2::{TokenStream as Tokens, Span}; use syn::{Data, DeriveInput, Fields, DataEnum, Ident}; use quote::quote; pub fn derive(input: &DeriveInput) -> Tokens { let name = &input.ident; let generics = super::add_trait_bounds( input.generics.clone(), &HashS...
use std::collections::HashSet; use proc_macro2::{TokenStream as Tokens, Span}; use syn::{Data, DeriveInput, Fields, DataEnum, Ident}; use quote::quote; pub fn derive(input: &DeriveInput) -> Tokens { let name = &input.ident; let generics = super::add_trait_bounds( input.generics.clone(), &HashS...
fn encoder_for_struct_kind(fields: Option<&[&syn::Field]>, named: bool, sizer: bool) -> Tokens { let unit = fields.is_none(); let fields: Vec<_> = fields.unwrap_or(&[]).iter() .enumerate().map(|(i, f)| FieldExt::new(f, i, named)).collect(); if unit { if sizer { quote![ 0 ] ...
t; let prefix = if sizer { quote! {} } else { quote! { let idx : #idx_type = #idx as #idx_type; idx.logpack_encode(_buf)?; } }; idx += 1; match v.fields { ...
function_block-function_prefixed
[ { "content": "fn bintype_for_enum(data_enum: &DataEnum) -> Tokens {\n\n let impls = data_enum.variants.iter().map(|v| {\n\n let fields = bintype_for_struct(&v.fields);\n\n let ident = &v.ident;\n\n quote! { (stringify!(#ident), #fields) }\n\n });\n\n\n\n quote!(vec![#(#impls),*])\n...
Rust
src/main.rs
icefoxen/otter
518de550ea792ce1c16f7cf353b8dd97bcd4ff57
extern crate pencil; #[macro_use] extern crate log; extern crate env_logger; extern crate hoedown; extern crate git2; use std::collections::BTreeMap; use std::fs; use std::io; use std::io::Read; use pencil::helpers; use pencil::{Pencil, Request, Response, PencilResult, PencilError}; use pencil::http_errors; use git2...
extern crate pencil; #[macro_use] extern crate log; extern crate env_logger; extern crate hoedown; extern crate git2; use std::collections::BTreeMap; use std::fs; use std::io; use std::io::Read; use pencil::helpers; use pencil::{Pencil, Request, Response, PencilResult, PencilError}; use pencil::http_errors; use git2...
::from(contents.as_bytes()); let mut html = hoedown::Html::new(hoedown::renderer::html::Flags::empty(), 0); let buffer = html.render(&md); let rendered_markdown = buffer.to_str().unwrap(); let mut ctx = BTreeMap::new(); ctx.insert("pagename".to_string(), page.to_string()); ...
let page = request.view_args.get("page").unwrap(); let contents = load_page_file(page)?; let md = hoedown::Markdown
function_block-random_span
[ { "content": "pub fn clone(repo_url: &str, into_directory: &str) -> Result<String, Error> {\n\n let output = try!(Command::new(\"git\")\n\n .arg(\"clone\")\n\n .arg(repo_url)\n\n .arg(into_directory)\n\n .outp...
Rust
sw/linalg/src/im4.rs
yupferris/xenowing
0762908cba96bdd695c9af07f494bf34736b3288
use crate::fixed::*; use crate::iv4::*; use trig::*; use core::ops::{Mul, MulAssign}; #[derive(Clone, Copy)] pub struct Im4<const FRACT_BITS: u32> { pub columns: [Iv4<FRACT_BITS>; 4], } impl<const FRACT_BITS: u32> Im4<FRACT_BITS> { pub fn identity() -> Self { Self { columns: [ ...
use crate::fixed::*; use crate::iv4::*; use trig::*; use core::ops::{Mul, MulAssign}; #[derive(Clone, Copy)] pub struct Im4<const FRACT_BITS: u32> { pub columns: [Iv4<FRACT_BITS>; 4], } impl<const FRACT_BITS: u32> Im4<FRACT_BITS> { pub fn identity() -> Self { Self { columns: [ ...
( rows[0].dot(other.columns[0]), rows[1].dot(other.columns[0]), rows[2].dot(other.columns[0]), rows[3].dot(other.columns[0]), ), Iv4::new( rows[0].dot(other.columns[1]), ...
[ Iv4::new(2.0 / (right - left), 0.0, 0.0, 0.0), Iv4::new(0.0, 2.0 / (top - bottom), 0.0, 0.0), Iv4::new(0.0, 0.0, -2.0 / (z_far - z_near), 0.0), Iv4::new(tx, ty, tz, 1.0), ] } } pub fn perspective(fov_degrees: f32, aspect: f32...
random
[ { "content": "pub fn sin(x: f32) -> f32 {\n\n let phase_scale = 1.0 / core::f32::consts::TAU;\n\n let phase = x * phase_scale;\n\n let phase = phase - unsafe { intrinsics::floorf32(phase) };\n\n let phase_with_offset = phase + 1.0;\n\n let bits = phase_with_offset.to_bits();\n\n const NUM_SIGN...
Rust
memscanner/src/signature/mod.rs
garlond/memscanner
dcc322a6c83133dcc494472933b6be410ca46583
mod parser; use super::MemReader; use failure::{format_err, Error}; #[derive(Clone, Debug, PartialEq, Eq)] enum Match { Any, Position, Literal(u8), } #[derive(Clone, Debug, PartialEq, Eq)] enum Op { Asm(Vec<Match>), Ptr(i32), } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Signature { op...
mod parser; use super::MemReader; use failure::{format_err, Error}; #[derive(Clone, Debug, PartialEq, Eq)] enum Match { Any, Position, Literal(u8), } #[derive(Clone, Debug, PartialEq, Eq)] enum Op { Asm(Vec<Match>), Ptr(i32), } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Signature { op...
}
fn single_lea() { #[rustfmt::skip] let mem = TestMemReader { mem: vec![ 0xff, 0xff, 0xff, 0xff, 0x00, 0x11, 0x22, 0x33, 0x04, 0x00, 0x00, 0x00, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, ], s...
function_block-full_function
[ { "content": "fn parse_position(input: &str) -> IResult<&str, Match> {\n\n value(Match::Position, tag(\"^^\"))(input)\n\n}\n\n\n", "file_path": "memscanner/src/signature/parser.rs", "rank": 6, "score": 111181.45690729145 }, { "content": "fn parse_i32(input: &str) -> IResult<&str, i32> {\n...
Rust
src/utils.rs
ruoshui-git/mks66-w11_animation
2324fb210b1b88c44e712d7a5a9790b975223069
use std::fs::File; use std::path::Path; use indicatif::ProgressStyle; use crate::{ canvas::Canvas, light::{self, LightProps}, }; pub(crate) fn create_file(filepath: &str) -> File { let path = Path::new(filepath); let display = path.display(); match File::create(&path) { Err(why) => panic...
use std::fs::File; use std::path::Path; use indicatif::ProgressStyle; use crate::{ canvas::Canvas, light::{self, LightProps}, }; pub(crate) fn create_file(filepath: &str) -> File { let path = Path::new(filepath); let display = path.display(); match File::create(&path) { Err(why) => panic...
]) }
img.render_ndc_edges_n1to1(m, color); } else { img.render_edge_matrix(m, color); } display_ppm(&img); } pub(crate) fn display_polygon_matrix(m: &Matrix, ndc: bool) { let mut img = PPMImg::with_bg(500, 500, 225, RGB::BLACK); if ndc { unimplemented!("Displaying polygon matrix in...
random
[ { "content": "// generate transformation matrices\n\n/// Generate a translation matrix with (dx, dy, dz)\n\npub fn mv(dx: f64, dy: f64, dz: f64) -> Matrix {\n\n let mut m = Matrix::ident(4);\n\n\n\n m.set(3, 0, dx);\n\n m.set(3, 1, dy);\n\n m.set(3, 2, dz);\n\n m\n\n}\n\n\n", "file_path": "sr...
Rust
src/cluster/cluster.rs
MilesBreslin/Chunky-Bits
2338a32b9fd8fbae75173c4e667b4b509128dad3
use std::{ convert::TryInto, path::Path, }; use futures::stream::Stream; use serde::{ Deserialize, Serialize, }; use tokio::{ io, io::AsyncRead, }; use crate::{ cluster::{ ClusterNodes, ClusterProfile, ClusterProfiles, Destination, DestinationInner, ...
use std::{ convert::TryInto, path::Path, }; use futures::stream::Stream; use serde::{ Deserialize, Serialize, }; use tokio::{ io, io::AsyncRead, }; use crate::{ cluster::{ ClusterNodes, ClusterProfile, ClusterProfiles, Destination, DestinationInner, ...
parity_chunks(profile.get_parity_chunks()) .write(reader) .await; match result { Ok(mut file_ref) => { file_ref.content_type = content_type; self.metadata.write(path, &file_ref).await.unwrap(); (reporter.profile().await, Ok(()))...
fn from_location( location: impl TryInto<Location, Error = impl Into<LocationParseError>>, ) -> Result<Cluster, MetadataReadError> { MetadataFormat::Yaml.from_location(location).await } pub fn get_file_writer(&self, profile: &ClusterProfile) -> FileWriteBuilder<Destination> { let de...
random
[ { "content": "#[derive(Serialize, Deserialize)]\n\nstruct MetadataGitSerde {\n\n #[serde(default)]\n\n pub format: MetadataFormat,\n\n pub path: PathBuf,\n\n}\n\n\n\nimpl From<MetadataGitSerde> for MetadataGit {\n\n fn from(meta: MetadataGitSerde) -> Self {\n\n let MetadataGitSerde { format, ...
Rust
azul-layout/src/style.rs
dignifiedquire/azul
de204bf2770286866c4da5d049827e04dab22347
use crate::geometry::{Offsets, Size}; use crate::number::Number; use azul_css::PixelValue; #[derive(Copy, Clone, PartialEq, Debug)] pub enum AlignItems { FlexStart, FlexEnd, Center, Baseline, Stretch, } impl Default for AlignItems { fn default() -> AlignItems { AlignItems::Stretch ...
use crate::geometry::{Offsets, Size}; use crate::number::Number; use azul_css::PixelValue; #[derive(Copy, Clone, PartialEq, Debug)] pub enum AlignItems { FlexStart, FlexEnd, Center, Baseline, Stretch, } impl Default for AlignItems { fn default() -> AlignItems { AlignItems::Stretch ...
pub(crate) fn cross_margin_end(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.bottom, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.right, } } pub(crate) fn align...
pub(crate) fn cross_margin_start(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.top, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.left, } }
function_block-full_function
[ { "content": "/// For a given line number (**NOTE: 0-indexed!**), calculates the Y\n\n/// position of the bottom left corner\n\npub fn get_line_y_position(line_number: usize, font_size_px: f32, line_height_px: f32) -> f32 {\n\n ((font_size_px + line_height_px) * line_number as f32) + font_size_px\n\n}\n\n\n"...
Rust
polars/polars-arrow/src/builder.rs
Spirans/polars
7774f419fdbf79bc4c4ec3bd6f0f72d87b32a70c
use crate::bit_util; use crate::vec::AlignedVec; pub use arrow::array::LargeStringBuilder; use arrow::array::{ ArrayBuilder, ArrayData, ArrayRef, BooleanArray, LargeStringArray, PrimitiveArray, }; use arrow::buffer::{Buffer, MutableBuffer}; use arrow::datatypes::{ArrowPrimitiveType, DataType}; use std::any::Any; us...
use crate::bit_util; use crate::vec::AlignedVec; pub use arrow::array::LargeStringBuilder; use arrow::array::{ ArrayBuilder, ArrayData, ArrayRef, BooleanArray, LargeStringArray, PrimitiveArray, }; use arrow::buffer::{Buffer, MutableBuffer}; use arrow::datatypes::{ArrowPrimitiveType, DataType}; use std::any::Any; us...
extend_from_slice(values); self.offsets.extend_from_slice(offsets); } #[inline] pub fn append_value(&mut self, value: &str) { self.values.extend_from_slice(value.as_bytes()); self.offsets.push(self.values.len() as i64); } pub fn finish(&mut self) -> LargeStringArray { ...
y(&self) -> bool { self.values_builder.is_empty() } fn finish(&mut self) -> ArrayRef { Arc::new(self.finish()) } } pub struct PrimitiveArrayBuilder<T> where T: ArrowPrimitiveType, T::Native: Default, { values: AlignedVec<T::Native>, bitmap_builder: BooleanBufferBuilder...
random
[ { "content": "#[inline]\n\npub fn slice_offsets(offset: i64, length: usize, array_len: usize) -> (usize, usize) {\n\n let abs_offset = offset.abs() as usize;\n\n\n\n // The offset counted from the start of the array\n\n // negative index\n\n if offset < 0 {\n\n if abs_offset <= array_len {\n\...
Rust
crates/holochain/tests/authored_test/mod.rs
MCYBA/holochain
74a9ac250285d38985fad9d41de3955646549606
use std::convert::TryFrom; use std::convert::TryInto; use std::time::Duration; use holo_hash::AnyDhtHash; use holo_hash::EntryHash; use holochain_state::prelude::fresh_reader_test; use holochain_wasm_test_utils::TestWasm; use holochain_zome_types::Entry; use holochain::test_utils::conductor_setup::ConductorTestData; ...
use std::convert::TryFrom; use std::convert::TryInto; use std::time::Duration; use holo_hash::AnyDhtHash; use holo_hash::EntryHash; use holochain_state::prelude::fresh_reader_test; use holochain_wasm_test_utils::TestWasm; use holochain_zome_types::Entry; use holochain::test_utils::conductor_setup::ConductorTestData; ...
.await; let triggers = handle.get_cell_triggers(&alice_call_data.cell_id).unwrap(); triggers.publish_dht_ops.trigger(); fresh_reader_test(alice_call_data.authored_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_authored_entry: bool = txn ...
estData::two_agents(zomes, true).await; let handle = conductor_test.handle(); let alice_call_data = conductor_test.alice_call_data(); let bob_call_data = conductor_test.bob_call_data().unwrap(); let entry = Post("Hi there".into()); let entry_hash = EntryHash::with_data_sync(&Entry::try_from(entry.c...
random
[ { "content": "fn consistency(bench: &mut Criterion) {\n\n observability::test_run().ok();\n\n let mut group = bench.benchmark_group(\"consistency\");\n\n group.sample_size(\n\n std::env::var_os(\"BENCH_SAMPLE_SIZE\")\n\n .and_then(|s| s.to_string_lossy().parse::<usize>().ok())\n\n ...
Rust
src/soft_f32/soft_f32_add.rs
Inokinoki/softfpu-rs
152f71f131d5d38a4112bf5d2e2c2975af2c1e15
use super::util::{ f32_shift_right_jam, f32_norm_round_and_pack, f32_round_and_pack, f32_pack_raw, f32_pack, f32_propagate_nan, f32_sign, f32_exp, f32_frac, }; use crate::soft_f32::f32_sub; pub fn f32_add(a: u32, b: u32) -> u32 { let mut a_sign = f32_sign(a); let mut b_sign = f32_...
use super::util::{ f32_shift_right_jam, f32_norm_round_and_pack, f32_round_and_pack, f32_pack_raw, f32_pack, f32_propagate_nan, f32_sign, f32_exp, f32_frac, }; use crate::soft_f32::f32_sub; pub fn f32_add(a: u32, b: u32) -> u32 { let mut a_sign = f32_sign(a); let mut b_sign = f32_...
}
fn test_f32_add_inf_nan() { assert_eq!(crate::soft_f32::f32_add(0x7F800000, 0x3F800000), 0x7F800000); assert_eq!(crate::soft_f32::f32_add(0xFF800000, 0x3F800000), 0xFF800000); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFF800000, 0x7F800000)), t...
function_block-full_function
[ { "content": "pub fn f32_div(a: u32, b: u32) -> u32 {\n\n // Sign\n\n let mut a_sign = f32_sign(a);\n\n let mut b_sign = f32_sign(b);\n\n let mut r_sign = a_sign ^ b_sign;\n\n\n\n // Exp\n\n let mut a_exp = f32_exp(a);\n\n let mut b_exp = f32_exp(b);\n\n let mut r_exp;\n\n\n\n // Frac...
Rust
third_party/rust_crates/vendor/tokio-executor/src/park.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
use std::marker::PhantomData; use std::rc::Rc; use std::sync::Arc; use std::time::Duration; use crossbeam_utils::sync::{Parker, Unparker}; pub trait Park { type Unpark: Unpark; type Error; fn unpark(&self) -> Self::Unpark; ...
use std::marker::PhantomData; use std::rc::Rc; use std::sync::Arc; use std::time::Duration; use crossbeam_utils::sync::{Parker, Unparker}; pub trait Park { type Unpark: Unpark; type Error; fn unpark(&self) -> Self::Unpark; ...
} impl Park for ParkThread { type Unpark = UnparkThread; type Error = ParkError; fn unpark(&self) -> Self::Unpark { let inner = self.with_current(|inner| inner.unparker().clone()); UnparkThread { inner } } fn park(&mut self) -> Result<(), Self::Error> { self.with_current(...
fn with_current<F, R>(&self, f: F) -> R where F: FnOnce(&Parker) -> R, { CURRENT_PARKER.with(|inner| f(inner)) }
function_block-function_prefix_line
[]
Rust
src/db.rs
lovesh/merkle_trees
0db6b68bbfb219d584a96d503e2d6e4e4c7147a6
use crate::errors::{MerkleTreeError, MerkleTreeErrorKind}; use num_bigint::BigUint; use std::collections::HashMap; use std::iter::FromIterator; pub trait HashValueDb<H, V: Clone> { fn put(&mut self, hash: H, value: V) -> Result<(), MerkleTreeError>; fn get(&self, hash: &H) -> Result<V, MerkleTreeError>; } #[...
use crate::errors::{MerkleTreeError, MerkleTreeErrorKind}; use num_bigint::BigUint; use std::collections::HashMap; use std::iter::FromIterator; pub trait HashValueDb<H, V: Clone> { fn put(&mut self, hash: H, value: V) -> Result<(), MerkleTreeError>; fn get(&self, hash: &H) -> Result<V, MerkleTreeError>; } #[...
} impl<T: Clone> InMemoryBigUintHashDb<T> { pub fn new() -> Self { let db = HashMap::<Vec<u8>, T>::new(); Self { db } } } #[cfg(test)] pub mod unqlite_db { use super::{HashValueDb, MerkleTreeError, MerkleTreeErrorKind}; extern crate unqlite; use unqlite::{Config, Cursor, UnQ...
fn get(&self, hash: &BigUint) -> Result<V, MerkleTreeError> { let b = hash.to_bytes_be(); match self.db.get(&b) { Some(val) => Ok(val.clone()), None => Err(MerkleTreeErrorKind::HashNotFoundInDB { hash: b }.into()), } }
function_block-full_function
[ { "content": "/// Interface for the database used to store the leaf and node hashes\n\npub trait HashDb<H> {\n\n /// The database stores all leaves\n\n fn add_leaf(&mut self, leaf_hash: H) -> Result<(), MerkleTreeError>;\n\n\n\n /// The database stores roots of all full subtrees of the datbase\n\n f...
Rust
crates/volta-core/src/tool/node/resolve.rs
gregjopa/volta
18f6b061d9fe5205010291f586518b93533a2f6f
use std::fs::File; use std::io::Write; use std::str::FromStr; use std::time::{Duration, SystemTime}; use super::super::registry_fetch_error; use super::metadata::{NodeEntry, NodeIndex, RawNodeIndex}; use crate::error::{Context, ErrorKind, Fallible}; use crate::fs::{create_staging_file, read_file}; use crate::hook::T...
use std::fs::File; use std::io::Write; use std::str::FromStr; use std::time::{Duration, SystemTime}; use super::super::registry_fetch_error; use super::metadata::{NodeEntry, NodeIndex, RawNodeIndex}; use crate::error::{Context, ErrorKind, Fallible}; use crate::fs::{create_staging_file, read_file}; use crate::hook::T...
let index: NodeIndex = resolve_node_versions(url)?.into(); let mut entries = index.entries.into_iter(); Ok(entries .find(predicate) .map(|NodeEntry { version, .. }| version)) } fn read_cached_opt(url: &str) -> Fallible<Option<RawNodeIndex>> { let expiry_file = volta_home()?.node_index_ex...
o::SERVER_URL) } } else { fn public_node_version_index() -> String { "https://nodejs.org/dist/index.json".to_string() } } } pub fn resolve(matching: VersionSpec, session: &mut Session) -> Fallible<Version> { let hooks = session.hooks()?.node(); match matchin...
random
[ { "content": "fn resolve_semver_legacy(matching: VersionReq, url: String) -> Fallible<Version> {\n\n let spinner = progress_spinner(&format!(\"Fetching public registry: {}\", url));\n\n let releases: RawYarnIndex = attohttpc::get(&url)\n\n .send()\n\n .and_then(Response::error_for_status)\n\...
Rust
ethers-solc/src/hh.rs
alxiong/ethers-rs
133c32d64a53a8ae38e0c8c8a10753e423127782
use crate::{ artifacts::{ Bytecode, BytecodeObject, CompactContract, CompactContractBytecode, Contract, ContractBytecode, DeployedBytecode, LosslessAbi, Offsets, }, ArtifactOutput, }; use serde::{Deserialize, Serialize}; use std::collections::btree_map::BTreeMap; const HH_ARTIFACT_VERSION...
use crate::{ artifacts::{ Bytecode, BytecodeObject, CompactContract, CompactContractBytecode, Contract, ContractBytecode, DeployedBytecode, LosslessAbi, Offsets, }, ArtifactOutput, }; use serde::{Deserialize, Serialize}; use std::collections::btree_map::BTreeMap; const HH_ARTIFACT_VERSION...
} #[cfg(test)] mod tests { use super::*; use crate::Artifact; #[test] fn can_parse_hh_artifact() { let s = include_str!("../test-data/hh-greeter-artifact.json"); let artifact = serde_json::from_str::<HardhatArtifact>(s).unwrap(); let compact = artifact.into_compact_contract();...
fn contract_to_artifact(&self, file: &str, name: &str, contract: Contract) -> Self::Artifact { let (bytecode, link_references, deployed_bytecode, deployed_link_references) = if let Some(evm) = contract.evm { let (deployed_bytecode, deployed_link_references) = if l...
function_block-full_function
[ { "content": "/// Strips the identifier of field declaration from the input and returns it\n\nfn strip_field_identifier(input: &mut &str) -> Result<String> {\n\n let mut iter = input.trim_end().rsplitn(2, is_whitespace);\n\n let name = iter\n\n .next()\n\n .ok_or_else(|| format_err!(\"Expect...
Rust
language/bytecode-verifier/src/abstract_state.rs
meenxio/libra
da94f03225f93709f18d614a72337e41ba54b3fd
use crate::{ absint::{AbstractDomain, JoinResult}, borrow_graph::BorrowGraph, nonce::Nonce, }; use mirai_annotations::{checked_postcondition, checked_precondition, checked_verify}; use std::collections::{BTreeMap, BTreeSet}; use vm::{ file_format::{ CompiledModule, FieldDefinitionIndex, Kind, ...
use crate::{ absint::{AbstractDomain, JoinResult}, borrow_graph::BorrowGraph, nonce::Nonce, }; use mirai_annotations::{checked_postcondition, checked_precondition, checked_verify}; use std::collections::{BTreeMap, BTreeSet}; use vm::{ file_format::{ CompiledModule, FieldDefinitionIndex, Kind, ...
fn split_locals( locals: &BTreeMap<LocalIndex, TypedAbstractValue>, values: &mut BTreeMap<LocalIndex, Kind>, references: &mut BTreeMap<LocalIndex, Nonce>, ) { for (idx, abs_type) in locals { match abs_type.value { AbstractValue::Reference(nonce) => {...
state1.locals.keys().any(|idx| { state1.locals[idx].value.is_value() && state1.is_local_borrowed(*idx) && !state2.locals.contains_key(idx) }) }
function_block-function_prefix_line
[ { "content": "/// Get the StructTag for a StructDefinition defined in a published module.\n\npub fn resource_storage_key(module: &impl ModuleAccess, idx: StructDefinitionIndex) -> StructTag {\n\n let resource = module.struct_def_at(idx);\n\n let res_handle = module.struct_handle_at(resource.struct_handle)...
Rust
dynomite/src/ext.rs
sbruton/dynomite
0f3e5a045a0bbd6fd5ae6b1f83c66ccbb0ac6376
use crate::dynamodb::{ AttributeValue, BackupSummary, DynamoDb, ListBackupsError, ListBackupsInput, ListTablesError, ListTablesInput, QueryError, QueryInput, ScanError, ScanInput, }; use futures::{stream, Stream, TryStreamExt}; #[cfg(feature = "default")] use rusoto_core_default::RusotoError; #[cfg(feature = ...
use crate::dynamodb::{ AttributeValue, BackupSummary, DynamoDb, ListBackupsError, ListBackupsInput, ListTablesError, ListTablesInput, QueryError, QueryInput, ScanError, ScanInput, }; use futures::{stream, Stream, TryStreamExt}; #[cfg(feature = "default")] use rusoto_core_default::RusotoError; #[cfg(feature = ...
; Ok(Some(( stream::iter(resp.items.unwrap_or_default().into_iter().map(Ok)), next_state, ))) } }, ) .try_flatten(), ) } }
match resp.last_evaluated_key.filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }
if_condition
[ { "content": "#[proc_macro_error::proc_macro_error]\n\n#[proc_macro_derive(Attributes, attributes(dynomite))]\n\npub fn derive_attributes(input: TokenStream) -> TokenStream {\n\n let ast = syn::parse_macro_input!(input);\n\n\n\n let gen = match expand_attributes(ast) {\n\n Ok(g) => g,\n\n Er...
Rust
language/bytecode-verifier/src/control_flow.rs
GreyHyphen/dijets
8c94c5c079fd025929dbd0455fc0e76d62e418c2
use move_binary_format::{ errors::{PartialVMError, PartialVMResult}, file_format::{Bytecode, CodeOffset, CodeUnit, FunctionDefinitionIndex}, }; use move_core_types::vm_status::StatusCode; use std::{collections::HashSet, convert::TryInto}; pub fn verify( current_function_opt: Option<FunctionDefinitionInde...
use move_binary_format::{ errors::{PartialVMError, PartialVMResult}, file_format::{Bytecode, CodeOffset, CodeUnit, FunctionDefinitionIndex}, }; use move_core_types::vm_status::StatusCode; use std::{collections::HashSet, convert::TryInto}; pub fn verify( current_function_opt: Option<FunctionDefinitionInde...
Err(context.error(StatusCode::INVALID_LOOP_BREAK, i)) } _ => Ok(()), } } _ => Ok(()), } }) } fn check_no_loop_splits(context: &ControlFlowVerifier, labels: &[Label]) -> PartialVMResult<()> { let is_break = |loop_s...
op_stack, i, instr| { match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j > i => { match loop_stack.last() { Some((_cur_loop, last_continue)) if j > last_continue && *j != last_continue + 1 => ...
function_block-random_span
[ { "content": "fn remap_branch_offsets(code: &mut Vec<Bytecode>, fake_to_actual: &HashMap<u16, u16>) {\n\n for instr in code {\n\n match instr {\n\n Bytecode::BrTrue(offset) | Bytecode::BrFalse(offset) | Bytecode::Branch(offset) => {\n\n *offset = fake_to_actual[offset]\n\n ...
Rust
src/systems/collision.rs
Jazarro/evoli
fe817899c4381bc98b294ae124f12301a711c664
use amethyst::renderer::{debug_drawing::DebugLinesComponent, palette::Srgba}; use amethyst::shrev::{EventChannel, ReaderId}; use amethyst::{core::math::Point3, core::Transform, ecs::prelude::*}; use log::info; use std::f32; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use crate::components::collide...
use amethyst::renderer::{debug_drawing::DebugLinesComponent, palette::Srgba}; use amethyst::shrev::{EventChannel, ReaderId}; use amethyst::{core::math::Point3, core::Transform, ecs::prelude::*}; use log::info; use std::f32; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use crate::components::collide...
if pos.y > bounds.top { local.translation_mut().y = bounds.top; } else if pos.y < bounds.bottom { local.translation_mut().y = bounds.bottom; } } } } #[derive(Debug, Clone)] pub struct CollisionEvent { pub entity_a: Entity, pub entity_b: En...
al.translation().clone(); if pos.x > bounds.right { local.translation_mut().x = bounds.right; } else if pos.x < bounds.left { local.translation_mut().x = bounds.left; }
function_block-random_span
[ { "content": "// Once the prefabs are loaded, this function is called to update the ekeys in the CreaturePrefabs struct.\n\n// We use the Named component of the entity to determine which key to use.\n\npub fn update_prefabs(world: &mut World) {\n\n let updated_prefabs = {\n\n let creature_prefabs = wo...
Rust
src/operation/aggregate/change_stream.rs
moy2010/mongo-rust-driver
dc085119dac3943773115bf4a0f923d17156dd06
use crate::{ bson::{doc, Document}, change_stream::{event::ResumeToken, ChangeStreamData, WatchArgs}, cmap::{Command, RawCommandResponse, StreamDescription}, cursor::CursorSpecification, error::Result, operation::{append_options, Operation, Retryability}, options::{ChangeStreamOptions, Selec...
use crate::{ bson::{doc, Document}, change_stream::{event::ResumeToken, ChangeStreamData, WatchArgs}, cmap::{Command, RawCommandResponse, StreamDescription}, cursor::CursorSpecification, error::Result, operation::{append_options, Operation, Retryability}, options::{ChangeStreamOptions, Selec...
fn handle_response( &self, response: RawCommandResponse, description: &StreamDescription, ) -> Result<Self::O> { let op_time = response .raw_body() .get("operationTime")? .and_then(bson::RawBsonRef::as_timestamp); let spec = self.inne...
fn extract_at_cluster_time( &self, response: &bson::RawDocument, ) -> Result<Option<bson::Timestamp>> { self.inner.extract_at_cluster_time(response) }
function_block-full_function
[ { "content": "fn build_test(db_name: &str, mut list_collections: ListCollections, mut expected_body: Document) {\n\n let mut cmd = list_collections\n\n .build(&StreamDescription::new_testing())\n\n .expect(\"build should succeed\");\n\n assert_eq!(cmd.name, \"listCollections\");\n\n asser...
Rust
sync/src/synchronizer/headers_process.rs
Taem42/ckb
9d43dee13a350fe75f62b75915c3c932f129a3f5
use crate::block_status::BlockStatus; use crate::synchronizer::Synchronizer; use crate::types::{ActiveChain, SyncShared}; use crate::{Status, StatusCode, MAX_HEADERS_LEN}; use ckb_error::{Error, ErrorKind}; use ckb_logger::{debug, log_enabled, warn, Level}; use ckb_network::{CKBProtocolContext, PeerIndex}; use ckb_trai...
use crate::block_status::BlockStatus; use crate::synchronizer::Synchronizer; use crate::types::{ActiveChain, SyncShared}; use crate::{Status, StatusCode, MAX_HEADERS_LEN}; use ckb_error::{Error, ErrorKind}; use ckb_logger::{debug, log_enabled, warn, Level}; use ckb_network::{CKBProtocolContext, PeerIndex}; use ckb_trai...
.nc .disconnect(self.peer, "useless outbound peer in IBD") { return StatusCode::Network.with_context(format!("Disconnect error: {:?}", err)); } } Status::ok() } } #[derive(Clone)] pub struct HeaderAcceptor<'a, V: Verifier> { head...
N { shared.state().misbehavior(self.peer, 20); warn!("HeadersProcess is_oversize"); return Status::ok(); } if headers.is_empty() { self.synchronizer .peers() .state .write() .get...
random
[ { "content": "pub fn inherit_block(shared: &Shared, parent_hash: &Byte32) -> BlockBuilder {\n\n let snapshot = shared.snapshot();\n\n let parent = snapshot.get_block(parent_hash).unwrap();\n\n let parent_epoch = snapshot.get_block_epoch(parent_hash).unwrap();\n\n let parent_number = parent.header()....
Rust
src/linux/mod.rs
8176135/InputBot
e54b3a04cccbcdead0141a42688d2cf7e89fd6d4
use crate::{common::*, linux::inputs::*, public::*}; use input::{ event::{ keyboard::{ KeyState, {KeyboardEvent, KeyboardEventTrait}, }, pointer::{ButtonState, PointerEvent::*}, Event::{self, *}, }, Libinput, LibinputInterface, }; use nix::{ fcntl::{open, OFla...
use crate::{common::*, linux::inputs::*, public::*}; use input::{ event::{ keyboard::{ KeyState, {KeyboardEvent, KeyboardEventTrait}, }, pointer::{ButtonState, PointerEvent::*}, Event::{self, *}, }, Libinput, LibinputInterface, }; use nix::{ fcntl::{open, OFla...
&LibinputInterfaceRaw.seat()) .unwrap(); while !MOUSE_BINDS.lock().unwrap().is_empty() || !KEYBD_BINDS.lock().unwrap().is_empty() { libinput_context.dispatch().unwrap(); while let Some(event) = libinput_context.next() { handle_input_event(event); } sleep(Duration:...
ss(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device .write(0x01, key_to_scan_code(self), 1) .unwrap(); device.synchronize().unwrap(); } pub fn release(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device .write(0x...
random
[ { "content": "pub fn handle_input_events() {\n\n if !MOUSE_BINDS.lock().unwrap().is_empty() {\n\n set_hook(WH_MOUSE_LL, &*MOUSE_HHOOK, mouse_proc);\n\n };\n\n if !KEYBD_BINDS.lock().unwrap().is_empty() {\n\n set_hook(WH_KEYBOARD_LL, &*KEYBD_HHOOK, keybd_proc);\n\n };\n\n let mut msg...
Rust
src/wayland/output/xdg.rs
rano-oss/smithay
a06e8b231e305cda37f68c63f872d468d673d598
use std::{ ops::Deref as _, sync::{Arc, Mutex}, }; use slog::{o, trace}; use wayland_protocols::unstable::xdg_output::v1::server::{ zxdg_output_manager_v1::{self, ZxdgOutputManagerV1}, zxdg_output_v1::ZxdgOutputV1, }; use wayland_server::{protocol::wl_output::WlOutput, Display, Filter, Global, Main};...
use std::{ ops::Deref as _, sync::{Arc, Mutex}, }; use slog::{o, trace}; use wayland_protocols::unstable::xdg_output::v1::server::{ zxdg_output_manager_v1::{self, ZxdgOutputManagerV1}, zxdg_output_v1::ZxdgOutputV1, }; use wayland_server::{protocol::wl_output::WlOutput, Display, Filter, Global, Main};...
L: Into<Option<::slog::Logger>>, { let log = crate::slog_or_fallback(logger).new(o!("smithay_module" => "xdg_output_handler")); display.create_global( 3, Filter::new(move |(manager, _version): (Main<ZxdgOutputManagerV1>, _), _, _| { let log = log.clone(); manager.quick_a...
function_block-function_prefix_line
[ { "content": "/// Initialize a tablet manager global.\n\npub fn init_tablet_manager_global(display: &mut Display) -> Global<ZwpTabletManagerV2> {\n\n display.create_global::<ZwpTabletManagerV2, _>(\n\n MANAGER_VERSION,\n\n Filter::new(\n\n move |(manager, _version): (Main<ZwpTabletMa...
Rust
src/list.rs
mantono/giss
867d2143196e631a875207684c5be45abb3feae7
use crate::search::{GraphQLQuery, SearchIssues, SearchQuery, Type}; use crate::{ api::ApiError, cfg::Config, issue::{Issue, Root}, project::Project, sort::Sorting, AppErr, }; use crate::{user::Username, Target}; use core::fmt; use std::{ sync::mpsc::{SendError, SyncSender}, time::Instant...
use crate::search::{GraphQLQuery, SearchIssues, SearchQuery, Type}; use crate::{ api::ApiError, cfg::Config, issue::{Issue, Root}, project::Project, sort::Sorting, AppErr, }; use crate::{user::Username, Target}; use core::fmt; use std::{ sync::mpsc::{SendError, SyncSender}, time::Instant...
impl From<SendError<Issue>> for AppErr { fn from(_: SendError<Issue>) -> Self { AppErr::ChannelError } } impl From<ApiError> for AppErr { fn from(err: ApiError) -> Self { log::error!("{:?}", err); match err { ApiError::NoResponse(_) => AppErr::ApiError, Api...
fn create_query(kind: Type, user: &Option<String>, targets: &[Target], config: &FilterConfig) -> SearchIssues { let assignee: Option<String> = match config.assigned_only { false => None, true => match kind { Type::Issue | Type::PullRequest => user.clone(), Type::ReviewRequest...
function_block-full_function
[ { "content": "fn save_username(token: &str, username: &str) -> Result<(), std::io::Error> {\n\n let token_hash: String = hash_token(token);\n\n let mut path: PathBuf = get_users_dir();\n\n std::fs::create_dir_all(&path)?;\n\n path.push(token_hash);\n\n let mut file: File = File::create(&path)?;\n...
Rust
osm2lanes/src/transform/tags_to_lanes/counts.rs
a-b-street/osm2lanes
e24d9762dc50f8d83b57f0a0737e2626823133a4
use super::{Infer, Oneway}; use crate::locale::Locale; use crate::tag::{Highway, TagKey, Tags}; use crate::transform::tags_to_lanes::modes::BusLaneCount; use crate::transform::{RoadWarnings, TagsToLanesMsg}; #[derive(Debug)] pub enum Counts { One, Directional { forward: Infer<usize>, backward:...
use super::{Infer, Oneway}; use crate::locale::Locale; use crate::tag::{Highway, TagKey, Tags}; use crate::transform::tags_to_lanes::modes::BusLaneCount; use crate::transform::{RoadWarnings, TagsToLanesMsg}; #[derive(Debug)] pub enum Counts { One, Directional { forward: Infer<usize>, backward:...
l / 2), centre_turn_lane, } } else { let remaining_lanes = l - both_ways - bus.forward - bus.backward; if remaining_lanes % 2 != 0 { warnings.push(...
"lanes:both_ways", "lanes:backward", ]))); } if let Some(total) = lanes.total { let forward = total - both_ways - bus.backward; let result = Self::Dire...
random
[ { "content": "fn set_cycleway(lanes: &[Lane], tags: &mut Tags, oneway: bool) -> Result<(), LanesToTagsMsg> {\n\n let left_cycle_lane: Option<Direction> = lanes\n\n .iter()\n\n .take_while(|lane| !lane.is_motor())\n\n .find(|lane| lane.is_bicycle())\n\n .and_then(Lane::direction);\...
Rust
src/options.rs
sunsided/realsense-rust
6908a3d6ca172b8d7f388c10434b1800ceefafbe
use crate::{ common::*, error::{ErrorChecker, Result as RsResult}, kind::Rs2Option, }; pub trait ToOptions { fn to_options(&self) -> RsResult<HashMap<Rs2Option, OptionHandle>> { let options_ptr = self.get_options_ptr(); unsafe { let list_ptr = { let mut check...
use crate::{ common::*, error::{ErrorChecker, Result as RsResult}, kind::Rs2Option, }; pub trait ToOptions { fn to_options(&self) -> RsResult<HashMap<Rs2Option, OptionHandle>> { let options_ptr = self.get_options_ptr(); unsafe { let list_ptr = { let mut check...
let mut checker = ErrorChecker::new(); let val = realsense_sys::rs2_is_option_read_only( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; Ok(val != 0) ...
n = realsense_sys::rs2_get_options_list_size(list_ptr, checker.inner_mut_ptr()); checker.check()?; len }; let handles = (0..len) .map(|index| { let mut checker = ErrorChecker::new(); let ...
random
[ { "content": "#[cfg(all(feature = \"with-image\", feature = \"with-nalgebra\"))]\n\nfn main() -> Result<()> {\n\n example::main()\n\n}\n\n\n", "file_path": "examples/capture_images.rs", "rank": 1, "score": 91129.60982840325 }, { "content": "fn main() -> Result<()> {\n\n println!(\"Look...
Rust
src/main.rs
mbaumfalk/scheme
a00669a59d127d24b7bab87c5abe369f7a2a8ddf
extern crate nom; use nom::{ branch::alt, bytes::streaming::{tag, take_until, take_while1}, character::streaming::{ anychar, char, digit1, hex_digit1, line_ending, multispace0, none_of, oct_digit1, }, combinator::opt, error::{Error, ErrorKind::Char}, multi::{many0, many1}, sequen...
extern crate nom; use nom::{ branch::alt, bytes::streaming::{tag, take_until, take_while1}, character::streaming::{ anychar, char, digit1, hex_digit1, line_ending, multispace0, none_of, oct_digit1, }, combinator::opt, error::{Error, ErrorKind::Char}, multi::{many0, many1}, sequen...
} fn lisptoken(input: &str) -> IResult<&str, char> { none_of("'()# \"\r\n")(input) } fn cons(input: &str) -> IResult<&str, LispData> { let (input, _) = char('(')(input)?; let (input, _) = multispace0(input)?; let (input, middle) = many0(terminated(lisp_data, multispace0))(input)?; let (input, dot...
a, b) => { write!(f, "({}", a)?; write_cdr(&b, f)?; write!(f, ")") } } }
function_block-function_prefixed
[]
Rust
day-12/src/main.rs
kecors/AoC-2018
dd213e9087639ace4788c94daa4a85fedc635162
use pom::parser::*; use pom::Error; use std::collections::HashMap; use std::collections::VecDeque; use std::io::{stdin, Read}; #[derive(Debug)] struct Pot { number: i32, plant: bool, } #[derive(Debug)] struct Note { neighbors: Vec<bool>, next_generation: bool, } #[derive(Debug)] struct Engine { p...
use pom::parser::*; use pom::Error; use std::collections::HashMap; use std::collections::VecDeque; use std::io::{stdin, Read}; #[derive(Debug)] struct Pot { number: i32, plant: bool, } #[derive(Debug)] struct Note { neighbors: Vec<bool>, next_generation: bool, } #[derive(Debug)] struct Engine { p...
engine_p2.next_generation(); println!("[{}] sum = {}", x, engine_p2.sum()); engine_p2.display(); println!(); } println!("patterns = {:#?}", patterns); let part2: u64 = (50_000_000_000 - 158) * 86 + 16002; println!( "Part 2: After fifty billion generations, the sum of the...
number: front_number - x, plant: false, }); self.pots.push_back(Pot { number: back_number + x, plant: false, }); } let mut new_pots = VecDeque::new(); for j in 0..self.pots.len(...
random
[ { "content": "fn number<'a>() -> Parser<'a, u8, i32> {\n\n let integer = (one_of(b\"123456789\") - one_of(b\"0123456789\").repeat(0..)) | sym(b'0');\n\n let number = sym(b'-').opt() + integer;\n\n number\n\n .collect()\n\n .convert(str::from_utf8)\n\n .convert(|s| i32::from_str_rad...
Rust
ruma-events/tests/pdu.rs
ignatenkobrain/ruma
1c47963befcf241f1dbd0e9ad12ab3dfd7ef54cc
#![cfg(not(feature = "unstable-pre-spec"))] use std::{ collections::BTreeMap, time::{Duration, SystemTime}, }; use ruma_events::{ pdu::{EventHash, Pdu, RoomV1Pdu, RoomV3Pdu}, EventType, }; use ruma_identifiers::{event_id, room_id, server_name, server_signing_key_id, user_id}; use serde_json::{from_val...
#![cfg(not(feature = "unstable-pre-spec"))] use std::{ collections::BTreeMap, time::{Duration, SystemTime}, }; use ruma_events::{ pdu::{EventHash, Pdu, RoomV1Pdu, RoomV3Pdu}, EventType, }; use ruma_identifiers::{event_id, room_id, server_name, server_signing_key_id, user_id}; use serde_json::{from_val...
rg")), unsigned, hashes: EventHash { sha256: "1233543bABACDEF".into() }, signatures, }; let pdu_stub = Pdu::RoomV3Pdu(v3_pdu); let json = json!({ "room_id": "!n8f893n9:example.com", "sender": "@sender:example.com", "origin": "matrix.org", "origin_serve...
2_u32.into(), auth_events: vec![( event_id!("$someauthevent:matrix.org"), EventHash { sha256: "21389CFEDABC".into() }, )], redacts: Some(event_id!("$9654:matrix.org")), unsigned, hashes: EventHash { sha256: "1233543bABACDEF".into() }, signatures, ...
random
[ { "content": "fn aliases_event_with_prev_content() -> JsonValue {\n\n json!({\n\n \"content\": {\n\n \"aliases\": [ \"#somewhere:localhost\" ]\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"prev_content\": {\n\n ...
Rust
src/graphics/shader.rs
mooman219/glpaly
7731c705614ee2de8bc8685dc28361caa050a0af
use crate::graphics::{ graphics, resource, std140::Std140Struct, Buffer, DrawMode, Texture, Uniform, VertexDescriptor, }; use crate::{App, Context}; use alloc::format; use core::iter::IntoIterator; use core::marker::PhantomData; pub trait ShaderDescriptor<const TEXTURES: usize> { const VERTEX_SHADER: &'static ...
use crate::graphics::{ graphics, resource, std140::Std140Struct, Buffer, DrawMode, Texture, Uniform, VertexDescriptor, }; use crate::{App, Context}; use alloc::format; use core::iter::IntoIterator; use core::marker::PhantomData; pub trait ShaderDescriptor<const TEXTURES: usize> { const VERTEX_SHADER: &'static ...
fn draw_instanced<'a, Item, Iter>( &self, mode: DrawMode, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES], buffers: Iter, count: i32, ) where Item: AsRef<Buffer<T::VertexDescriptor>> + ...
let instancing = T::VertexDescriptor::INSTANCING; if instancing.is_instanced() { self.draw_instanced(mode, uniform, textures, buffers, instancing.count); } else { self.draw_non_instanced(mode, uniform, textures, buffers); } }
function_block-function_prefix_line
[ { "content": "/// Type that holds all of your application state and handles events.\n\npub trait App: 'static + Sized {\n\n /// Function to create the app from a context.\n\n /// # Arguments\n\n ///\n\n /// * `ctx` - The engine context. This can be used to call various API functions.\n\n fn new(_...
Rust
src/find.rs
jqnatividad/csvlens
5d9f82e4e17145f0df324dfff39b29a257aab6bd
use crate::csv; use anyhow::Result; use regex::Regex; use std::cmp::min; use std::sync::{Arc, Mutex, MutexGuard}; use std::thread::{self}; use std::time::Instant; pub struct Finder { internal: Arc<Mutex<FinderInternalState>>, cursor: Option<usize>, row_hint: usize, target: Regex, } #[derive(Clone, Deb...
use crate::csv; use anyhow::Result; use regex::Regex; use std::cmp::min; use std::sync::{Arc, Mutex, MutexGuard}; use std::thread::{self}; use std::time::Instant; pub struct Finder { internal: Arc<Mutex<FinderInternalState>>, cursor: Option<usize>, row_hint: usize, target: Regex, } #[derive(Clone, Deb...
pub fn prev(&mut self) -> Option<FoundRecord> { let m_guard = self.internal.lock().unwrap(); if let Some(n) = self.cursor { self.cursor = Some(n.saturating_sub(1)); } else { let count = m_guard.count; if count > 0 { self.cursor = Some(m_g...
let m_guard = self.internal.lock().unwrap(); let count = m_guard.count; if let Some(n) = self.cursor { if n + 1 < count { self.cursor = Some(n + 1); } } else if count > 0 { self.cursor = Some(m_guard.next_from(self.row_hint)); } ...
function_block-function_prefix_line
[ { "content": "struct ReaderInternalState {\n\n total_line_number: Option<usize>,\n\n total_line_number_approx: Option<usize>,\n\n pos_table: Vec<Position>,\n\n done: bool,\n\n}\n\n\n\nimpl ReaderInternalState {\n\n fn init_internal(config: Arc<CsvConfig>) -> (Arc<Mutex<ReaderInternalState>>, Join...
Rust
arrow/src/buffer/ops.rs
zhaox1n/arrow-rs
d2cec2ccef6adf92754883bd58a7fdd4858c02a9
#[cfg(feature = "simd")] use crate::util::bit_util; #[cfg(feature = "simd")] use packed_simd::u8x64; #[cfg(feature = "avx512")] use crate::arch::avx512::*; use crate::util::bit_util::ceil; #[cfg(any(feature = "simd", feature = "avx512"))] use std::borrow::BorrowMut; use super::{Buffer, MutableBuffer}; #[cfg(featur...
#[cfg(feature = "simd")] use crate::util::bit_util; #[cfg(feature = "simd")] use packed_simd::u8x64; #[cfg(feature = "avx512")] use crate::arch::avx512::*; use crate::util::bit_util::ceil; #[cfg(any(feature = "simd", feature = "avx512"))] use std::borrow::BorrowMut; use super::{Buffer, MutableBuffer}; #[cfg(featur...
#[cfg(all(target_arch = "x86_64", feature = "avx512"))] pub fn buffer_bin_and( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bi...
pub fn bitwise_unary_op_helper<F>( left: &Buffer, offset_in_bits: usize, len_in_bits: usize, op: F, ) -> Buffer where F: Fn(u64) -> u64, { let mut result = MutableBuffer::new(ceil(len_in_bits, 8)).with_bitset(len_in_bits / 64 * 8, false); let left_chunks = left.bit_chunks(offse...
function_block-full_function
[ { "content": "fn bench_buffer_and(left: &Buffer, right: &Buffer) {\n\n criterion::black_box((left & right).unwrap());\n\n}\n\n\n", "file_path": "arrow/benches/buffer_bit_ops.rs", "rank": 2, "score": 380009.3854061781 }, { "content": "fn bench_buffer_or(left: &Buffer, right: &Buffer) {\n\n...
Rust
sdk/program/src/entrypoint_deprecated.rs
rob-ti/SAFE
315d06c27d3923472ef8f94f04be4bfe762dd91a
extern crate alloc; use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey}; use alloc::vec::Vec; use std::{ cell::RefCell, mem::size_of, rc::Rc, result::Result as ResultGeneric, slice::{from_raw_parts, from_raw_parts_mut}, }; pub type ProgramResult = ResultGeneri...
extern crate alloc; use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey}; use alloc::vec::Vec; use std::{ cell::RefCell, mem::size_of, rc::Rc, result::Result as ResultGeneric, slice::{from_raw_parts, from_raw_parts_mut}, }; pub type ProgramResult = ResultGeneri...
let mut accounts = Vec::with_capacity(num_accounts); for _ in 0..num_accounts { let dup_info = *(input.add(offset) as *const u8); offset += size_of::<u8>(); if dup_info == std::u8::MAX { #[allow(clippy::cast_ptr_alignment)] let is_signer = *(input.add(offset) as *cons...
function_block-function_prefix_line
[ { "content": "/// Create `AccountInfo`s\n\npub fn create_account_infos(accounts: &mut [(Pubkey, Account)]) -> Vec<AccountInfo> {\n\n accounts.iter_mut().map(Into::into).collect()\n\n}\n\n\n", "file_path": "sdk/src/account.rs", "rank": 0, "score": 425486.5331603654 }, { "content": "pub fn ...
Rust
src/config.rs
AmaranthineCodices/whimsy
e46684a0e66277a18694324268e8635cdc22f054
use std::default::Default; use std::path::{Path, PathBuf}; use crate::keybind; lazy_static::lazy_static! { pub static ref DEFAULT_CONFIG_PATH: PathBuf = { let mut cfg_dir = dirs::config_dir().expect("Could not find user configuration directory."); cfg_dir.push("whimsy"); cfg_dir.push("whim...
use std::default::Default; use std::path::{Path, PathBuf}; use crate::keybind; lazy_static::lazy_static! { pub static ref DEFAULT_CONFIG_PATH: PathBuf = { let mut cfg_dir = dirs::config_dir().expect("Could not find user configuration directory."); cfg_dir.push("whimsy"); cfg_dir.push("whim...
} pub fn read_config_from_file(path: &dyn AsRef<Path>) -> Result<Option<Config>, ConfigReadError> { if !path.as_ref().exists() { return Ok(None); } let config_string = std::fs::read_to_string(path).map_err(|e| ConfigReadError::IoError(e))?; serde_yaml::from_str(&config_string).map_err(|e| Con...
fn default() -> Self { Config { directives: ConfigDirectives::default(), bindings: vec![ Binding { key: keybind::Key::Left, modifiers: vec![keybind::Modifier::Super, keybind::Modifier::Shift], action: Action::Pus...
function_block-full_function
[ { "content": "fn modifier_to_flag_code(modifier: &Modifier) -> isize {\n\n match modifier {\n\n Modifier::Control => winuser::MOD_CONTROL,\n\n Modifier::Alt => winuser::MOD_ALT,\n\n Modifier::Shift => winuser::MOD_SHIFT,\n\n Modifier::Super => winuser::MOD_WIN,\n\n }\n\n}\n\n\n...
Rust
src/codegen.rs
tamaroning/ironcc
c75f6dfc300ee44154cd68b5d7f3801bfeb40279
extern crate llvm_sys as llvm; use self::llvm::core::*; use self::llvm::prelude::*; use crate::node; use crate::types; /* use self::llvm::execution_engine; use self::llvm::target::*; use llvm::execution_engine::LLVMCreateExecutionEngineForModule; use llvm::execution_engine::LLVMDisposeExecutionEngine; use llvm::executi...
extern crate llvm_sys as llvm; use self::llvm::core::*; use self::llvm::prelude::*; use crate::node; use crate::types; /* use self::llvm::execution_engine; use self::llvm::target::*; use llvm::execution_engine::LLVMCreateExecutionEngineForModule; use llvm::execution_engine::LLVMDisposeExecutionEngine; use llvm::executi...
pub unsafe fn gen_load(&mut self, ast: &AST) -> Option<(LLVMValueRef, Option<Type>)> { match ast { AST::Variable(ref name) => { let (val, ty) = self.gen(ast).unwrap(); let ty = ty.unwrap(); let ret = LLVMBuildLoad(self.builder, val, cstr...
cstr("ne").as_ptr(), ), BinaryOps::Lt => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntSLT, *lhs_val, *rhs_val, cstr("lt").as_ptr(), ), BinaryOps::Le => LLVMBuildICmp( ...
function_block-function_prefix_line
[ { "content": "pub fn error(line: u32, msg: &str) {\n\n println!(\" Error: line:{} {}\", line, msg);\n\n process::exit(-1);\n\n}", "file_path": "src/error.rs", "rank": 0, "score": 81268.38232700378 }, { "content": "pub fn run(filepath: String, tokens: Vec<Token>) -> Vec<AST> {\n\n le...
Rust
day07/src/main.rs
pkusensei/adventofcode2020
116b462afa8f5d05d221d312644a7b870954fc92
use std::{collections::HashMap, str::FromStr}; fn main() { let input = tools::read_input("input.txt").unwrap(); let rules = parse_rules(&input); println!("To Shiny gold: {}", count_shiny_gold(&rules)); println!( "Shiny gold contains: {}", count_contained(&rules, "shiny gold") - 1 ) ...
use std::{collections::HashMap, str::FromStr}; fn main() { let input = tools::read_input("input.txt").unwrap(); let rules = parse_rules(&input); println!("To Shiny gold: {}", count_shiny_gold(&rules)); println!( "Shiny gold contains: {}", count_contained(&rules, "shiny gold") - 1 ) ...
s); assert_eq!(126, count_contained(&rules, "shiny gold") - 1); } } }
ontain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags."# .split('\n') ...
function_block-random_span
[ { "content": "fn group_answers(lines: &[String]) -> Vec<Vec<&str>> {\n\n let mut groups = vec![];\n\n let mut one_group = vec![];\n\n for line in lines {\n\n if line.trim().is_empty() {\n\n groups.push(one_group.clone());\n\n one_group.clear()\n\n } else {\n\n ...
Rust
azure_sdk_cosmos/src/resource_quota.rs
guywaldman/azure-sdk-for-rust
638d0322d1f397be253b609963cc1961324bdf04
use crate::errors::TokenParsingError; #[derive(Debug, Clone, PartialEq, PartialOrd)] pub enum ResourceQuota { Databases(u64), StoredProcedures(u64), Collections(u64), DocumentSize(u64), DocumentsSize(u64), DocumentsCount(i64), CollectionSize(u64), Users(u64), Permissions(u64), T...
use crate::errors::TokenParsingError; #[derive(Debug, Clone, PartialEq, PartialOrd)] pub enum ResourceQuota { Databases(u64), StoredProcedures(u64), Collections(u64), DocumentSize(u64), DocumentsSize(u64), DocumentsCount(i64), CollectionSize(u64), Users(u64), Permissions(u64), T...
}
fn parse_resource_quota() { let resource_quota = resource_quotas_from_str("storedProcedures=25;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::StoredProcedures(25)]); let resource_quota = resource_quotas_from_str( "databases=100;collections=5000;users=500000;permissions=...
function_block-full_function
[ { "content": "pub fn with_azure_sas(account: &str, sas_token: &str) -> KeyClient {\n\n let client = hyper::Client::builder().build(HttpsConnector::new());\n\n let params = get_sas_token_parms(sas_token);\n\n\n\n KeyClient::new(\n\n account.to_owned(),\n\n String::new(),\n\n Some(pa...
Rust
eir-fmm/src/entry_functions.rs
ein-lang/eir
70d59589efeb1f6a7e881abb28ce7aebb862018f
use super::error::CompileError; use crate::{closures, expressions, reference_count, types}; use std::collections::HashMap; const CLOSURE_NAME: &str = "_closure"; pub fn compile( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpre...
use super::error::CompileError; use crate::{closures, expressions, reference_count, types}; use std::collections::HashMap; const CLOSURE_NAME: &str = "_closure"; pub fn compile( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpre...
}, )?; Ok(instruction_builder.unreachable()) }, types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, fmm::ir::Linkage::Internal, ) } fn compile_normal_thunk_entry( module_builder: &fmm::build::ModuleBui...
Ok(instruction_builder.return_( instruction_builder.call( instruction_builder.atomic_load( compile_entry_function_pointer(definition, types)?, fmm::ir::AtomicOrdering::Acquire, ...
call_expression
[ { "content": "fn infer_in_let(let_: &Let, variables: &HashMap<String, Type>) -> Let {\n\n Let::new(\n\n let_.name(),\n\n let_.type_().clone(),\n\n infer_in_expression(let_.bound_expression(), variables),\n\n infer_in_expression(\n\n let_.expression(),\n\n &va...
Rust
src/kgen/src/ast/functions/mod.rs
capra314cabra/kaprino
7b4ce32631194955e9a9cd4e206edadbc5110da4
use inkwell::types::BasicTypeEnum; use inkwell::types::FunctionType; use inkwell::values::FunctionValue; use crate::ast::CodeGen; use crate::ast::functions::expr_function::ExprFunction; use crate::ast::functions::external_function::ExternalFunction; use crate::ast::functions::statement_function::StatementFunction; use ...
use inkwell::types::BasicTypeEnum; use inkwell::types::FunctionType; use inkwell::values::FunctionValue; use crate::ast::CodeGen; use crate::ast::functions::expr_function::ExprFunction; use crate::ast::functions::external_function::ExternalFunction; use crate::ast::functions::statement_function::StatementFunction; use ...
fn get_func_type<'ctx>(&self, gen: &CodeGen<'ctx>, pos: FilePosition) -> Result<FunctionType<'ctx>, ErrorToken> { let arg_types = self.get_arg_types(gen, pos.clone())?; let ret_type = self.get_ret_type(gen, pos)?; let ret_type = match ret_type { BasicTypeEnum::A...
ere used in declaration of return value of the function named {}.", self.get_info().name ) ))?; Ok(ret_type.get_type(gen)) }
function_block-function_prefixed
[ { "content": "///\n\n/// Execute a function Just In Time.\n\n///\n\npub fn execute_function(text: &str, func_name: &str, arg: u32) -> Result<u32, ()> {\n\n type TestFunc = unsafe extern \"C\" fn(u32) -> u32;\n\n\n\n let context = &Context::create();\n\n let gen = CodeGen::new(context, \"test\");\n\n\n\...
Rust
async-coap/src/message/write.rs
Luro02/rust-async-coap
6a7b592a23de0c9d86ca399bf40ecfbf0bff6e62
use super::*; pub trait MessageWrite: OptionInsert { fn set_msg_type(&mut self, tt: MsgType); fn set_msg_id(&mut self, msg_id: MsgId); fn set_msg_code(&mut self, code: MsgCode); fn set_msg_token(&mut self, token: MsgToken); ...
use super::*; pub trait MessageWrite: OptionInsert { fn set_msg_type(&mut self, tt: MsgType); fn set_msg_id(&mut self, msg_id: MsgId); fn set_msg_code(&mut self, code: MsgCode); fn set_msg_token(&mut self, token: MsgToken); ...
Ok(()) } fn write_char(&mut self, c: char) -> Result<(), core::fmt::Error> { self.append_payload_char(c)?; Ok(()) } } impl<'a> std::io::Write for dyn MessageWrite + 'a { fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { self.append_payload_bytes(buf) ...
.as_bytes()) } fn append_payload_u8(&mut self, b: u8) -> Result<(), Error> { self.append_payload_bytes(&[b]) } fn append_payload_char(&mut self, c: char) -> Result<(), Error> { self.append_payload_string(c.encode_utf8(&mut [0; 4])) } fn ...
random
[ { "content": "/// Extension trait for option iterators that provide additional convenient accessors.\n\npub trait OptionIteratorExt<'a>: Iterator<Item = Result<(OptionNumber, &'a [u8]), Error>> {\n\n /// Moves the iterator forward until it finds a matching key or the\n\n /// spot where it should have been...
Rust
src/client.rs
shichaoyuan/mini-redis
cefca5377af54520904c55764d16fc7c0a291902
use crate::cmd::{Get, Publish, Set, Subscribe, Unsubscribe}; use crate::{Connection, Frame}; use async_stream::try_stream; use bytes::Bytes; use std::io::{Error, ErrorKind}; use std::time::Duration; use tokio::net::{TcpStream, ToSocketAddrs}; use tokio::stream::Stream; use tracing::{debug, instrument}; pub struct C...
use crate::cmd::{Get, Publish, Set, Subscribe, Unsubscribe}; use crate::{Connection, Frame}; use async_stream::try_stream; use bytes::Bytes; use std::io::{Error, ErrorKind}; use std::time::Duration; use tokio::net::{TcpStream, ToSocketAddrs}; use tokio::stream::Stream; use tracing::{debug, instrument}; pub struct C...
#[instrument(skip(self))] pub async fn unsubscribe(&mut self, channels: &[String]) -> crate::Result<()> { let frame = Unsubscribe::new(&channels).into_frame(); debug!(request = ?frame); self.client.connection.write_frame(&frame).await?; ...
t?; self.subscribed_channels .extend(channels.iter().map(Clone::clone)); Ok(()) }
function_block-function_prefixed
[ { "content": "/// Creates a message informing the client about a new message on a channel that\n\n/// the client subscribes to.\n\nfn make_message_frame(channel_name: String, msg: Bytes) -> Frame {\n\n let mut response = Frame::array();\n\n response.push_bulk(Bytes::from_static(b\"message\"));\n\n resp...
Rust
crates/nomination/src/lib.rs
gregdhill/interbtc
88e53a7d46c437fdd58ef232973388469186ecf9
#![deny(warnings)] #![cfg_attr(test, feature(proc_macro_hygiene))] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod mock; #[cfg(test)] mod tests; mod ext; mod types; mod default_weights; use ext::vault_registry::{DefaultVault, SlashingError, TryDepositCollateral, TryWithdrawCollateral}; use frame_supp...
#![deny(warnings)] #![cfg_attr(test, feature(proc_macro_hygiene))] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod mock; #[cfg(test)] mod tests; mod ext; mod types; mod default_weights; use ext::vault_registry::{DefaultVault, SlashingError, TryDepositCollateral, TryWithdrawCollateral}; use frame_supp...
pub fn _opt_in_to_nomination(vault_id: &T::AccountId) -> DispatchResult { ensure!(Self::is_nomination_enabled(), Error::<T>::VaultNominationDisabled); ensure!( ext::vault_registry::vault_exists::<T>(&vault_id), Error::<T>::VaultNotFound ); ...
e!( new_nominated_collateral <= Self::get_max_nominatable_collateral(vault_backing_collateral)?, Error::<T>::DepositViolatesMaxNominationRatio ); ext::fee::withdraw_all_vault_rewards::<T>(&vault_id)?; Self::deposit_pool_stake::<<T as pallet::Config>::Va...
function_block-function_prefixed
[ { "content": "pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::Origin {\n\n <Runtime as frame_system::Config>::Origin::signed(account_id)\n\n}\n\n\n", "file_path": "parachain/runtime/tests/mock/mod.rs", "rank": 0, "score": 354341.9938808502 }, { "content": "pu...
Rust
adafruit-feather-nrf52840-express/examples/feather-express-listener.rs
blueluna/nrf52840-dk-experiments
bbe34a24b9002f9f446e949d7b8013d2e8dae484
#![no_main] #![no_std] use panic_itm as _; use cortex_m::{iprintln, peripheral::ITM}; use rtic::app; use bbqueue::{self, BBBuffer}; use nrf52840_hal::{clocks, gpio, uarte}; use nrf52840_pac as pac; use psila_nrf52::radio::{Radio, MAX_PACKET_LENGHT}; const PACKET_BUFFER_SIZE: usize = 2048; static PKT_BUFFER: BB...
#![no_main] #![no_std] use panic_itm as _; use cortex_m::{iprintln, peripheral::ITM}; use rtic::app; use bbqueue::{self, BBBuffer}; use nrf52840_hal::{clocks, gpio, uarte}; use nrf52840_pac as pac; use psila_nrf52::radio::{Radio, MAX_PACKET_LENGHT}; const PACKET_BUFFER_SIZE: usize = 2048; static PKT_BUFFER: BB...
let mut buffer = [0u8; MAX_PACKET_LENGHT]; let _ = radio.receive(&mut buffer); } } } #[idle(resources = [rx_consumer, uart, itm])] fn idle(cx: idle::Context) -> ! { let mut host_packet = [0u8; MAX_PACKET_LENGHT * 2]; let queue =...
= cx.resources.rx_producer; match queue.grant_exact(MAX_PACKET_LENGHT) { Ok(mut grant) => { if grant.buf().len() < MAX_PACKET_LENGHT { grant.commit(0); } else { if let Ok(packet_len) = radio.receive_slice(grant.buf()) { ...
function_block-random_span
[ { "content": "fn clear(slice: &mut [u8]) {\n\n for v in slice.iter_mut() {\n\n *v = 0;\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum EncryptDecrypt {\n\n /// Encryp operation\n\n Encrypt = 0,\n\n /// Decryp operation\n\n Decrypt = 1,\n\n}\n\n\n\n/// Block cipher key t...
Rust
src/elastic/src/types/string/macros.rs
reinfer/elastic
78191a70d3774295ba66e1cf35f72e216e9fbf2a
macro_rules! impl_string_type { ($wrapper_ty:ident, $mapping_ty:ident, $field_type:ident) => { impl<TMapping> $field_type<TMapping> for $wrapper_ty<TMapping> where TMapping: $mapping_ty {} impl_mapping_type!(String, $wrapper_ty, $mapping_ty); impl<'a, TMapping> From<$wrapper_ty<TMapping>> ...
macro_rules! impl_string_type { ($wrapper_ty:ident, $mapping_ty:ident, $field_type:ident) => { impl<TMapping> $field_type<TMapping> for $wrapper_ty<TMapping> where TMapping: $mapping_ty {} impl_mapping_type!(String, $wrapper_ty, $mapping_ty); impl<'a, TMapping> From<$wrapper_ty<TMapping>> ...
orrow::Cow<'a, str> where TMapping: $mapping_ty, { fn from(wrapper: &'a $wrapper_ty<TMapping>) -> Self { wrapper.as_ref().into() } } impl<'a, TMapping> From<&'a $wrapper_ty<TMapping>> for &'a str where TMapping: $ma...
_ty<TMapping>) -> Self { wrapper.value } } impl<'a, TMapping> From<&'a $wrapper_ty<TMapping>> for std::b
random
[ { "content": "fn dedup_urls(endpoint: (String, Endpoint)) -> (String, Endpoint) {\n\n let (name, mut endpoint) = endpoint;\n\n\n\n let mut deduped_paths = BTreeMap::new();\n\n\n\n for path in endpoint.url.paths {\n\n let key = path.params().join(\"\");\n\n\n\n deduped_paths.insert(key, pa...
Rust
examples/src/bin/orientable_subclass.rs
elmarco/gtk4-rs
a1f7bcc611584c542308bd062ceda0103f96a69a
use std::cell::RefCell; use std::env; use gtk::glib; use gtk::prelude::*; use gtk::subclass::prelude::ObjectSubclass; mod imp { use super::*; use gtk::{glib::translate::ToGlib, subclass::prelude::*}; #[derive(Debug)] pub struct CustomOrientable { first_label: RefCell<Option<gtk::Widget>>, ...
use std::cell::RefCell; use std::env; use gtk::glib; use gtk::prelude::*; use gtk::subclass::prelude::ObjectSubclass; mod imp { use super::*; use gtk::{glib::translate::ToGlib, subclass::prelude::*}; #[derive(Debug)] pub struct CustomOrientable { first_label: RefCell<Option<gtk::Widget>>, ...
bx.append(&orientable); bx.append(&button); bx.set_margin_top(18); bx.set_margin_bottom(18); bx.set_margin_start(18); bx.set_margin_end(18); window.set_child(Some(&bx)); window.show(); }); application.run(&env::args().collect::<Vec<_>>()); }
button.connect_clicked(glib::clone!(@weak orientable => move |_| { match orientable.get_orientation() { gtk::Orientation::Horizontal => orientable.set_orientation(gtk::Orientation::Vertical), gtk::Orientation::Vertical => orientable.set_orientation(gtk::Orientation::Horizo...
function_block-random_span
[ { "content": "pub trait ApplicationWindowImpl: WindowImpl + 'static {}\n\n\n\nunsafe impl<T: ApplicationWindowImpl> IsSubclassable<T> for ApplicationWindow {\n\n fn class_init(class: &mut glib::Class<Self>) {\n\n <Window as IsSubclassable<T>>::class_init(class);\n\n }\n\n\n\n fn instance_init(in...
Rust
packages/vm/src/middleware/deterministic.rs
slave5vw/cosmwasm
220e39c8977eb0f0391a429c146872ad59b16426
use wasmer::wasmparser::Operator; use wasmer::{ FunctionMiddleware, LocalFunctionIndex, MiddlewareError, MiddlewareReaderState, ModuleMiddleware, }; #[derive(Debug)] pub struct Deterministic {} impl Deterministic { pub fn new() -> Self { Self {} } } impl ModuleMiddleware for Deterministic { ...
use wasmer::wasmparser::Operator; use wasmer::{ FunctionMiddleware, LocalFunctionIndex, MiddlewareError, MiddlewareReaderState, ModuleMiddleware, }; #[derive(Debug)] pub struct Deterministic {} impl Deterministic { pub fn new() -> Self { Self {} } } impl ModuleMiddleware for Deterministic { ...
let deterministic = Arc::new(Deterministic::new()); let mut compiler_config = Cranelift::default(); compiler_config.push_middleware(deterministic); let store = Store::new(&JIT::new(compiler_config).engine()); let result = Module::new(&store, &wasm); assert!(result.is_ok...
let wasm = wat::parse_str( r#" (module (func (export "sum") (param i32 i32) (result i32) get_local 0 get_local 1 i32.add )) "#, ) .unwrap();
assignment_statement
[ { "content": "pub fn config(storage: &mut dyn Storage) -> Singleton<State> {\n\n singleton(storage, CONFIG_KEY)\n\n}\n\n\n", "file_path": "contracts/reflect/src/state.rs", "rank": 0, "score": 281227.80228281906 }, { "content": "#[entry_point]\n\npub fn init(deps: DepsMut, _env: Env, info:...
Rust
strum_macros/src/macros/enum_iter.rs
orenbenkiki/strum
d5f660a3737ca0db3a5d8384a772e2b92e4ec0ed
use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{Data, DeriveInput, Fields, Ident}; use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties}; pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; l...
use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{Data, DeriveInput, Fields, Ident}; use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let type_properties = ast.get_type_properties()?; let strum_module_path = type_proper...
function_block-full_function
[ { "content": "struct Prop(Ident, LitStr);\n\n\n\nimpl Parse for Prop {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n use syn::ext::IdentExt;\n\n\n\n let k = Ident::parse_any(input)?;\n\n let _: Token![=] = input.parse()?;\n\n let v = input.parse()?;\n\n\n\n Ok...
Rust
cargo-spatial/src/download.rs
randomPoison/spatialos-sdk-rs
6a0149a21a7de40fd4ff127820d6f04f87173454
#[cfg(target_os = "linux")] pub use self::linux::*; #[cfg(target_os = "macos")] pub use self::macos::*; #[cfg(target_os = "windows")] pub use self::windows::*; use crate::{config::Config, opt::DownloadSdk}; use log::*; use reqwest::get; use std::fs::File; use std::io::copy; use std::{ fs, path::{Path, PathBuf...
#[cfg(target_os = "linux")] pub use self::linux::*; #[cfg(target_os = "macos")] pub use self::macos::*; #[cfg(target_os = "windows")] pub use self::windows::*; use crate::{config::Config, opt::DownloadSdk}; use log::*; use reqwest::get; use std::fs::File; use std::io::copy; use std::{ fs, path::{Path, PathBuf...
} #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialPackageSource { WorkerSdk(SpatialWorkerSdkPackage), Tools(SpatialToolsPackage), Schema(SpatialSchemaPackage), } impl SpatialPackageSource { fn package_name(self) -> Vec<&'static str> { match self { SpatialPackageSour...
ative_target_directory(self) -> &'static str { match self { SpatialSchemaPackage::StandardLibrary => "std-lib", SpatialSchemaPackage::ExhaustiveTestSchema => "test-schema", } }
function_block-function_prefixed
[ { "content": "/// Formats an key-value pair into an argument string.\n\npub fn format_arg<S: AsRef<OsStr>>(prefix: &str, value: S) -> OsString {\n\n let mut arg = OsString::from(format!(\"--{}=\", prefix));\n\n arg.push(value.as_ref());\n\n arg\n\n}\n", "file_path": "cargo-spatial/src/lib.rs", ...
Rust
rg3d-ui/src/check_box.rs
vigdail/rg3d
b65bfdab350f8c1d48bcc288a8449cc74653ef51
use crate::grid::{Column, GridBuilder, Row}; use crate::message::MessageDirection; use crate::vector_image::{Primitive, VectorImageBuilder}; use crate::{ border::BorderBuilder, brush::Brush, core::{color::Color, pool::Handle}, message::{CheckBoxMessage, UiMessage, UiMessageData, WidgetMessage}, widg...
use crate::grid::{Column, GridBuilder, Row}; use crate::message::MessageDirection; use crate::vector_image::{Primitive, VectorImageBuilder}; use crate::{ border::BorderBuilder, brush::Brush, core::{color::Color, pool::Handle}, message::{CheckBoxMessage, UiMessage, UiMessageData, WidgetMessage}, widg...
} #[cfg(test)] mod test { use crate::{ check_box::CheckBoxBuilder, core::algebra::Vector2, message::{CheckBoxMessage, MessageDirection}, widget::WidgetBuilder, UserInterface, }; #[test] fn check_box() { let mut ui = UserInterface::new(Vector2::new(1000....
pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> { let check_mark = self.check_mark.unwrap_or_else(|| { VectorImageBuilder::new( WidgetBuilder::new() .with_vertical_alignment(VerticalAlignment::Center) .with_horizontal_alignment(Hor...
function_block-full_function
[ { "content": "pub fn make_default_anchor(ctx: &mut BuildContext, row: usize, column: usize) -> Handle<UiNode> {\n\n let default_anchor_size = 30.0;\n\n BorderBuilder::new(\n\n WidgetBuilder::new()\n\n .with_width(default_anchor_size)\n\n .with_height(default_anchor_size)\n\n ...
Rust
src/resource/model.rs
Jytesh/rg3d
5cc1017f9a9b3e5d461fbb6247675bf0df4d6d00
#![warn(missing_docs)] use crate::{ animation::Animation, core::{ pool::Handle, visitor::{Visit, VisitError, VisitResult, Visitor}, }, engine::resource_manager::ResourceManager, resource::{ fbx::{self, error::FbxError}, Resource, ResourceData, }, scene::{node...
#![warn(missing_docs)] use crate::{ animation::Animation, core::{ pool::Handle, visitor::{Visit, VisitError, VisitResult, Visitor}, }, engine::resource_manager::ResourceManager, resource::{ fbx::{self, error::FbxError}, Resource, ResourceData, }, scene::{node...
xtension = path .as_ref() .extension() .unwrap_or_default() .to_string_lossy() .as_ref() .to_lowercase(); let (scene, mapping) = match extension.as_ref() { "fbx" => { let mut scene = Scene::new(); ...
ata = self.data_ref(); let (root, old_to_new) = data.scene.graph.copy_node( data.scene.graph.get_root(), &mut dest_scene.graph, &mut |_, _| true, ); dest_scene.graph[root].is_resource_instance_root = true; let mut stack = vec![root]; ...
random
[ { "content": "/// Tries to load and convert FBX from given path.\n\n///\n\n/// Normally you should never use this method, use resource manager to load models.\n\npub fn load_to_scene<P: AsRef<Path>>(\n\n scene: &mut Scene,\n\n resource_manager: ResourceManager,\n\n path: P,\n\n) -> Result<(), FbxError>...
Rust
packages/sycamore-macro/src/component/mod.rs
alsuren/sycamore
df16d18ad29933316aa666185e7e2dd7002eb662
use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::parse::{Parse, ParseStream}; use syn::{ Attribute, Block, FnArg, GenericParam, Generics, Ident, Item, ItemFn, Result, ReturnType, Type, Visibility, }; pub struct ComponentFunctionName { pub component_name: Ident, pub generics: Generic...
use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::parse::{Parse, ParseStream}; use syn::{ Attribute, Block, FnArg, GenericParam, Generics, Ident, Item, ItemFn, Result, ReturnType, Type, Visibility, }; pub struct ComponentFunctionName { pub component_name: Ident, pub generics: Generic...
pub fn component_impl( attr: ComponentFunctionName, component: ComponentFunction, ) -> Result<TokenStream> { let ComponentFunctionName { component_name, generics: generic_node_ty, } = attr; let component_name_str = component_name.to_string(); let generic_node_ty = generic_node_t...
function_block-full_function
[ { "content": "pub fn route_impl(input: DeriveInput) -> syn::Result<TokenStream> {\n\n let mut quoted = TokenStream::new();\n\n let mut err_quoted = TokenStream::new();\n\n let mut has_error_handler = false;\n\n\n\n match &input.data {\n\n syn::Data::Enum(de) => {\n\n let ty_name = ...
Rust
starky/src/constraint_consumer.rs
mfaulk/plonky2
2cedd1b02a718d19115560647ba1f741eab83260
use std::marker::PhantomData; use plonky2::field::extension_field::Extendable; use plonky2::field::packed_field::PackedField; use plonky2::hash::hash_types::RichField; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; use plonky2::plonk::circuit_builder::CircuitBuilder; pub struct Const...
use std::marker::PhantomData; use plonky2::field::extension_field::Extendable; use plonky2::field::packed_field::PackedField; use plonky2::hash::hash_types::RichField; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; use plonky2::plonk::circuit_builder::CircuitBuilder; pub struct Const...
pub fn constraint_first_row(&mut self, constraint: P) { self.constraint(constraint * self.lagrange_basis_first); } pub fn constraint_last_row(&mut self, constraint: P) { self.constraint(constraint * self.lagrange_basis_last); } } pub struct RecursiveConstraintCons...
onstraint(&mut self, constraint: P) { for (&alpha, acc) in self.alphas.iter().zip(&mut self.constraint_accs) { *acc *= alpha; *acc += constraint; } }
function_block-function_prefixed
[]
Rust
starchart/src/action/result.rs
starlite-project/starchart
c0f8cd6774596d45bf9a603aa3a37aa5dcde5d3a
use std::{ fmt::{Debug, Display, Formatter, Result as FmtResult}, hint::unreachable_unchecked, iter::FromIterator, }; use crate::Entry; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[must_use = "an ActionResult should be asserted"] pub enum ActionResult<R> { Create, SingleRead(...
use std::{ fmt::{Debug, Display, Formatter, Result as FmtResult}, hint::unreachable_unchecked, iter::FromIterator, }; use crate::Entry; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[must_use = "an ActionResult should be asserted"] pub enum ActionResult<R> { Create, SingleRead(...
#[track_caller] #[inline] pub fn unwrap_multi_read<I: FromIterator<R>>(self) -> I { if let Self::MultiRead(v) = self { v.into_iter().collect() } else { panic!("called `ActionResult::multi_read` on a `{}` value", self) } } pub unsafe fn unwrap_multi_read_unchecked<I: FromI...
pub unsafe fn unwrap_single_read_unchecked(self) -> Option<R> { debug_assert!(self.is_single_read()); if let Self::SingleRead(v) = self { v } else { unreachable_unchecked() } }
function_block-full_function
[ { "content": "#[cfg(not(feature = \"metadata\"))]\n\npub fn is_metadata(_: &str) -> bool {\n\n\tfalse\n\n}\n\n\n\npub unsafe trait InnerUnwrap<T> {\n\n\tunsafe fn inner_unwrap(self) -> T;\n\n}\n\n\n\n#[cfg(not(has_unwrap_unchecked))]\n\nunsafe impl<T> InnerUnwrap<T> for Option<T> {\n\n\t#[inline]\n\n\t#[track_c...
Rust
src/connectivity/bluetooth/profiles/bt-hfp-audio-gateway/src/peer/procedure/nrec.rs
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
use super::{Procedure, ProcedureError, ProcedureMarker, ProcedureRequest}; use crate::peer::{service_level_connection::SlcState, slc_request::SlcRequest, update::AgUpdate}; use at_commands as at; #[derive(Debug, PartialEq, Clone, Copy)] enum State { Start, SetRequest, Terminated, } impl ...
use super::{Procedure, ProcedureError, ProcedureMarker, ProcedureRequest}; use crate::peer::{service_level_connection::SlcState, slc_request::SlcRequest, update::AgUpdate}; use at_commands as at; #[derive(Debug, PartialEq, Clone, Copy)] enum State { Start, SetRequest, Terminated, } impl ...
eRequest::Error(ProcedureError::UnexpectedAg(_)) ); } #[test] fn updates_produce_expected_requests() { let mut proc = NrecProcedure::new(); let mut state = SlcState::default(); let req = proc.hf_update(at::Command::Nrec { nrec: true }, &mut state); let update = matc...
, ProcedureRequest::Error(ProcedureError::UnexpectedHf(_)) ); } #[test] fn unexpected_ag_update_returns_error() { let mut proc = NrecProcedure::new(); let mut state = SlcState::default(); let random_ag = AgUpdate::ThreeWaySupport; assert_matches!...
random
[]
Rust
src/sstable/writer.rs
ikatson/rust-sstb
8f2996d4e330dd1e98a16154e5bb38c6f7b81576
use std::convert::TryFrom; use std::fs::File; use std::io::BufWriter; use std::io::{Seek, SeekFrom, Write}; use std::path::Path; use bincode; use bloomfilter::Bloom; use super::compress_ctx_writer::*; use super::compression; use super::ondisk_format::*; use super::options::*; use super::poswriter::PosWriter; use su...
use std::convert::TryFrom; use std::fs::File; use std::io::BufWriter; use std::io::{Seek, SeekFrom, Write}; use std::path::Path; use bincode; use bloomfilter::Bloom; use super::compress_ctx_writer::*; use super::compression; use super::ondisk_format::*; use super::options::*; use super::poswriter::PosWriter; use su...
} impl RawSSTableWriter for SSTableWriterV2 { #[allow(clippy::collapsible_if)] fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> { let approx_msg_len = key.len() + 5 + value.len(); if self.meta.items == 0 { self.sparse_index.push((key.to_owned(),...
pub fn finish(self) -> Result<()> { match self { SSTableWriterV2 { file, mut meta, meta_start, data_start, sparse_index, bloom, .. } => { let mut writer = file....
function_block-full_function
[ { "content": "/// Find the key in the chunk by scanning sequentially.\n\n///\n\n/// This assumes the chunk was fetched from disk and has V1 ondisk format.\n\n///\n\n/// Returns the start and end index of the value.\n\n///\n\n/// TODO: this probably belongs in \"ondisk\" for version V1.\n\npub fn find_value_offs...
Rust
fifteen_min/src/isochrone.rs
balbok0/abstreet
3af15fefdb2772c83864c08724318418da8190a9
use std::collections::{HashMap, HashSet}; use abstutil::MultiMap; use geom::{Duration, Polygon}; use map_gui::tools::Grid; use map_model::{ connectivity, AmenityType, BuildingID, BuildingType, LaneType, Map, Path, PathConstraints, PathRequest, }; use widgetry::{Color, Drawable, EventCtx, GeomBatch}; use crate...
use std::collections::{HashMap, HashSet}; use abstutil::MultiMap; use geom::{Duration, Polygon}; use map_gui::tools::Grid; use map_model::{ connectivity, AmenityType, BuildingID, BuildingType, LaneType, Map, Path, PathConstraints, PathRequest, }; use widgetry::{Color, Drawable, EventCtx, GeomBatch}; use crate...
pub fn path_to(&self, map: &Map, to: BuildingID) -> Option<Path> { if !self.time_to_reach_building.contains_key(&to) { return None; } let req = PathRequest::between_buildings( map, self.start, to, match self.options { ...
pub fn new(ctx: &mut EventCtx, app: &App, start: BuildingID, options: Options) -> Isochrone { let time_to_reach_building = options.clone().time_to_reach_building(&app.map, start); let mut amenities_reachable = MultiMap::new(); let mut population = 0; let mut all_roads = HashSet::new(); ...
function_block-full_function
[ { "content": "pub fn pathfind(req: PathRequest, params: &RoutingParams, map: &Map) -> Option<(Path, Duration)> {\n\n if req.constraints == PathConstraints::Pedestrian {\n\n pathfind_walking(req, map)\n\n } else {\n\n let graph = build_graph_for_vehicles(map, req.constraints);\n\n calc...
Rust
src/objects/mod.rs
hinton-lang/hinton
796ae395ce45240676875b7ddeddb9b5e54016b2
use crate::built_in::{NativeBoundMethod, NativeFn}; use crate::core::chunk::Chunk; use crate::objects::class_obj::*; use crate::objects::dictionary_obj::*; use crate::objects::iter_obj::IterObject; use std::cell::RefCell; use std::fmt; use std::fmt::Formatter; use std::rc::Rc; pub mod class_obj; pub mod dictionary_obj...
use crate::built_in::{NativeBoundMethod, NativeFn}; use crate::core::chunk::Chunk; use crate::objects::class_obj::*; use crate::objects::dictionary_obj::*; use crate::objects::iter_obj::IterObject; use std::cell::RefCell; use std::fmt; use std::fmt::Formatter; use std::rc::Rc; pub mod class_obj; pub mod dictionary_obj...
} #[derive(Clone)] pub enum UpValRef { Open(usize), Closed(Object), } impl UpValRef { pub fn is_open_at(&self, index: usize) -> bool { match self { UpValRef::Closed(_) => false, UpValRef::Open(i) => *i == index, } } } #[derive(Clone)] pub enum Object { Array(Rc<RefCe...
pub fn into_bound_method(self, c: Rc<RefCell<InstanceObject>>) -> Object { Object::BoundMethod(BoundMethod { receiver: c, method: self, }) }
function_block-full_function
[ { "content": "#[cfg(feature = \"show_bytecode\")]\n\npub fn disassemble_func_scope(chunk: &Chunk, natives: &[String], primitives: &[String], name: &str) {\n\n // prints this chunk's name\n\n println!(\"==== {} ====\", name);\n\n\n\n let mut current_line = 0;\n\n\n\n let mut idx = 0;\n\n while idx < ch...
Rust
crates/eww/src/script_var_handler.rs
RianFuro/eww
e1558965ff45f72c35b7aeed15774381f32e0165
use std::collections::HashMap; use crate::{ app, config::{create_script_var_failed_warn, script_var}, }; use anyhow::*; use app::DaemonCommand; use eww_shared_util::VarName; use nix::{ sys::signal, unistd::{setpgid, Pid}, }; use simplexpr::dynval::DynVal; use tokio::{ io::{AsyncBufReadExt, BufRead...
use std::collections::HashMap; use crate::{ app, config::{create_script_var_failed_warn, script_var}, }; use anyhow::*; use app::DaemonCommand; use eww_shared_util::VarName; use nix::{ sys::signal, unistd::{setpgid, Pid}, }; use simplexpr::dynval::DynVal; use tokio::{ io::{AsyncBufReadExt, BufRead...
pub fn stop_for_variable(&self, name: VarName) { crate::print_result_err!( "while forwarding instruction to script-var handler", self.msg_send.send(ScriptVarHandlerMsg::Stop(name)), ); } pub fn stop_all(&self) { crate::print_result_err!( ...
pub fn add(&self, script_var: ScriptVarDefinition) { crate::print_result_err!( "while forwarding instruction to script-var handler", self.msg_send.send(ScriptVarHandlerMsg::AddVar(script_var)) ); }
function_block-function_prefix_line
[ { "content": "pub fn initial_value(var: &ScriptVarDefinition) -> Result<DynVal> {\n\n match var {\n\n ScriptVarDefinition::Poll(x) => match &x.initial_value {\n\n Some(value) => Ok(value.clone()),\n\n None => match &x.command {\n\n VarSource::Function(f) => f()\n\n...
Rust
src/engine/mod.rs
mersinvald/xsecurelock-saver-rs
e4c064918271a165657e52c4a22d20eb383e9e6a
use std::sync::Arc; use rayon::ThreadPoolBuilder; use sfml::graphics::{ Color, RenderTarget, RenderWindow, View as SfView, }; use sfml::system::{Clock, SfBox, Time, Vector2f}; use specs::{Component, System}; use shred::Resource; use physics::{ self, resources::{PhysicsDeltaTime, PhysicsElaps...
use std::sync::Arc; use rayon::ThreadPoolBuilder; use sfml::graphics::{ Color, RenderTarget, RenderWindow, View as SfView, }; use sfml::system::{Clock, SfBox, Time, Vector2f}; use specs::{Component, System}; use shred::Resource; use physics::{ self, resources::{PhysicsDeltaTime, PhysicsElaps...
pub fn with_update_sys<S>(mut self, sys: S, name: &str, dep: &[&str]) -> Self where S: for<'c> System<'c> + Send + 'a { self.add_update_sys(sys, name, dep); self } pub fn add_update_sys<S>(&mut self, sys: S, name: &str, dep: &[&str]) where S: for<...
pub fn new() -> Self { let thread_pool = Arc::new(ThreadPoolBuilder::new().build().unwrap()); Self { world: { let mut world = ::specs::World::new(); physics::register(&mut world); scene_management::register(&mut world); componen...
function_block-full_function
[ { "content": "pub trait SpecializedSystem<'a, T> {\n\n type SystemData: SystemData<'a>;\n\n\n\n fn run_special(&mut self, specialized: T, data: Self::SystemData);\n\n\n\n fn setup_special(&mut self, _specialized: T, res: &mut Resources) {\n\n Self::SystemData::setup(res);\n\n }\n\n}\n\n\n\npu...
Rust
src/clock_control/config.rs
reitermarkus/esp32-hal
95c7596c78a8e380b858d34f4f0ad1170a5b259a
use super::Error; use crate::prelude::*; use core::fmt; use super::{ dfs, CPUSource, ClockControlConfig, FastRTCSource, SlowRTCSource, CLOCK_CONTROL, CLOCK_CONTROL_MUTEX, }; impl<'a> super::ClockControlConfig { pub fn cpu_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref()....
use super::Error; use crate::prelude::*; use core::fmt; use super::{ dfs, CPUSource, ClockControlConfig, FastRTCSource, SlowRTCSource, CLOCK_CONTROL, CLOCK_CONTROL_MUTEX, }; impl<'a> super::ClockControlConfig { pub fn cpu_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref()....
{ CLOCK_CONTROL.as_mut().unwrap().rtc_nanoseconds() } } } impl fmt::Debug for ClockControlConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { CLOCK_CONTROL.as_ref().unwrap().fmt(f) } } }
where F: Fn(), { unsafe { CLOCK_CONTROL.as_mut().unwrap().add_callback(f) } } pub fn get_lock_count(&self) -> dfs::Locks { unsafe { CLOCK_CONTROL.as_mut().unwrap().get_lock_count() } } pub unsafe fn park_core(&mut self, core: crate::Core) { (&CLOCK...
random
[ { "content": "#[ram]\n\npub fn enable(interrupt: Interrupt) -> Result<(), Error> {\n\n match interrupt_to_cpu_interrupt(interrupt) {\n\n Ok(cpu_interrupt) => {\n\n unsafe { interrupt::enable_mask(1 << cpu_interrupt.0) };\n\n return Ok(());\n\n }\n\n Err(_) => enable...
Rust
src/lib.rs
gimli-rs/cpp_demangle
a8afba1db064469278c4530ad9bad28ec4d6c161
#![deny(missing_docs)] #![deny(missing_debug_implementations)] #![deny(unsafe_code)] #![allow(unknown_lints)] #![allow(clippy::inline_always)] #![allow(clippy::redundant_field_names)] #![cfg_attr(all(not(feature = "std"), feature = "alloc"), no_std)] #![cfg_attr(all(not(feature = "std"), feature = "alloc"), feature(...
#![deny(missing_docs)] #![deny(missing_debug_implementations)] #![deny(unsafe_code)] #![allow(unknown_lints)] #![allow(clippy::inline_always)] #![allow(clippy::redundant_field_names)] #![cfg_attr(all(not(feature = "std"), feature = "alloc"), no_std)] #![cfg_attr(all(not(feature = "std"), feature = "alloc"), feature(...
}; let symbol = Symbol { raw: raw, substitutions: substitutions, parsed: parsed, }; log!( "Successfully parsed '{}' as AST = {:#?} substitutions = {:#?}", String::from_utf8_lossy(symbol.raw.as_ref()), symbol.par...
if tail.is_empty() { parsed } else { return Err(Error::UnexpectedText); }
if_condition
[ { "content": "#[allow(unsafe_code)]\n\nfn parse_number(base: u32, allow_signed: bool, mut input: IndexStr) -> Result<(isize, IndexStr)> {\n\n if input.is_empty() {\n\n return Err(error::Error::UnexpectedEnd);\n\n }\n\n\n\n let num_is_negative = if allow_signed && input.as_ref()[0] == b'n' {\n\n ...
Rust
crates/nodes/src/logic_data.rs
gents83/NRG
62743a54ac873a8dea359f3816e24c189a323ebb
use sabi_serialize::{Deserialize, Serialize, SerializeFile}; use crate::{LogicContext, LogicExecution, NodeExecutionType, NodeState, NodeTree, PinId}; #[derive(Default, PartialEq, Eq, Hash, Clone)] struct LinkInfo { node: usize, pin: PinId, } #[derive(Default, Clone)] struct PinInfo { id: PinId, links...
use sabi_serialize::{Deserialize, Serialize, SerializeFile}; use crate::{LogicContext, LogicExecution, NodeExecutionType, NodeState, NodeTree, PinId}; #[derive(Default, PartialEq, Eq, Hash, Clone)] struct LinkInfo { node: usize, pin: PinId, } #[derive(Default, Clone)] struct PinInfo { id: PinId, links...
}
fn execute_node( tree: &mut NodeTree, context: &LogicContext, link_info: &LinkInfo, nodes_info: &[NodeInfo], execution_state: &mut [NodeState], ) -> Vec<LinkInfo> { let mut new_nodes_to_execute = Vec::new(); let info = &nodes_info[link_info.node]; inf...
function_block-full_function
[]
Rust
components/resource_metering/src/recorder/cpu.rs
lroolle/tikv
f3f02d7fc6cf7e94abcf8cdb9b9ff52b110a72ba
use crate::localstorage::LocalStorage; use crate::recorder::SubRecorder; use crate::utils; use crate::utils::Stat; use crate::{RawRecord, RawRecords, SharedTagPtr}; use collections::HashMap; use fail::fail_point; use lazy_static::lazy_static; lazy_static! { static ref STAT_TASK_COUNT: prometheus::IntCounter = p...
use crate::localstorage::LocalStorage; use crate::recorder::SubRecorder; use crate::utils; use crate::utils::Stat; use crate::{RawRecord, RawRecords, SharedTagPtr}; use collections::HashMap; use fail::fail_point; use lazy_static::lazy_static; lazy_static! { static ref STAT_TASK_COUNT: prometheus::IntCounter = p...
#[test] fn test_record() { let info = Arc::new(TagInfos { store_id: 0, region_id: 0, peer_id: 0, extra_attachment: b"abc".to_vec(), }); let shared_ptr = SharedTagPtr { ptr: Arc::new(AtomicPtr::new(Arc::into_raw(info) as _)), ...
fn heavy_job() -> u64 { let m: u64 = rand::random(); let n: u64 = rand::random(); let m = m ^ n; let n = m.wrapping_mul(n); let m = m.wrapping_add(n); let n = m & n; let m = m | n; m.wrapping_sub(n) }
function_block-full_function
[ { "content": "#[cfg(target_os = \"linux\")]\n\npub fn stat_task(pid: usize, tid: usize) -> std::io::Result<Stat> {\n\n procinfo::pid::stat_task(pid as _, tid as _).map(Into::into)\n\n}\n\n\n\n/// Get the [Stat] of the thread (tid) in the process (pid).\n", "file_path": "components/resource_metering/src/u...
Rust
alvr/experiments/graphics_tests/src/compositor/convert.rs
glegoo/ALVR
76d087fdb05f2035486626551c9ab9022ba645c6
use super::{Compositor, Context, Swapchain, TextureType}; use alvr_common::prelude::*; use ash::{extensions::khr, vk}; use openxr_sys as sys; use std::{ffi::CStr, slice}; use wgpu::{ DeviceDescriptor, Extent3d, Features, Texture, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, }; use wgpu_hal...
use super::{Compositor, Context, Swapchain, TextureType}; use alvr_common::prelude::*; use ash::{extensions::khr, vk}; use openxr_sys as sys; use std::{ffi::CStr, slice}; use wgpu::{ DeviceDescriptor, Extent3d, Features, Texture, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, }; use wgpu_hal...
pub fn new(adapter_index: Option<usize>) -> StrResult<Self> { let entry = unsafe { trace_err!(ash::Entry::new())? }; let vk_instance = trace_err!(create_vulkan_instance( &entry, &vk::InstanceCreateInfo::builder() .application_info( ...
pub fn from_vulkan( owned: bool, entry: ash::Entry, version: u32, vk_instance: ash::Instance, adapter_index: Option<usize>, vk_device: ash::Device, queue_family_index: u32, queue_index: u32, ) -> StrResult<Self> { let mut flags = hal::Instance...
function_block-full_function
[ { "content": "#[cfg(target_os = \"macos\")]\n\npub fn get_screen_size() -> StrResult<(u32, u32)> {\n\n Ok((0, 0))\n\n}\n", "file_path": "alvr/server/src/graphics_info.rs", "rank": 0, "score": 257298.96087876664 }, { "content": "pub fn version() -> String {\n\n let manifest_path = packa...
Rust
gtk/src/auto/text_tag_table.rs
pop-os/gtk-rs
0a0e50a2f5ea8f816c005bd8c3d145a5a9581d8c
use crate::Buildable; use crate::TextTag; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct TextTagTable(Object<ffi::GtkTextTagTab...
use crate::Buildable; use crate::TextTag; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct TextTagTable(Object<ffi::GtkTextTagTab...
fn connect_tag_removed<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn tag_removed_trampoline<P, F: Fn(&P, &TextTag) + 'static>( this: *mut ffi::GtkTextTagTable, tag: *mut ffi::GtkTextTag, f: glib::ffi::gpointer, ) where ...
let f: &F = &*(f as *const F); f( &TextTagTable::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(tag), from_glib(size_changed), ) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( ...
function_block-function_prefix_line
[ { "content": "/// Adds a closure to be called by the main loop the return `Source` is attached to when it's idle.\n\n///\n\n/// `func` will be called repeatedly until it returns `Continue(false)`.\n\npub fn idle_source_new<F>(name: Option<&str>, priority: Priority, func: F) -> Source\n\nwhere\n\n F: FnMut() ...
Rust
python/src/expression.rs
boaz-codota/ballista
75f5f79bdcf18ac897d9ab9e11035040d932fc5e
/* A great deal of this files source code was pulled more or less verbatim from https://github.com/jorgecarleitao/datafusion-python/commit/688f0d23504704cfc2be3fca33e2707e964ea5bc which is dual liscensed as MIT or Apache-2.0. */ /* MIT License Copyright (c) 2020 Jorge Leitao Permission is hereby granted, free of char...
/* A great deal of this files source code was pulled more or less verbatim from https://github.com/jorgecarleitao/datafusion-python/commit/688f0d23504704cfc2be3fca33e2707e964ea5bc which is dual liscensed as MIT or Apache-2.0. */ /* MIT License Copyright (c) 2020 Jorge Leitao Permission is hereby granted, free of char...
} #[pyproto] impl PyNumberProtocol for BPyExpr { fn __add__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr + rhs_expr, }) } fn __sub__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let r...
if let Ok(expr) = any.extract::<BPyExpr>() { Ok(expr.expr) } else if let Ok(scalar_value) = any.extract::<crate::scalar::Scalar>() { Ok(Expr::Literal(scalar_value.scalar)) } else { let type_name = util::object_class_name(any) .unwrap_or_else(|err| format!("<Could not get clas...
if_condition
[ { "content": "#[pyfunction]\n\npub fn count(value: BPyExpr) -> BPyExpr {\n\n BPyExpr {\n\n expr: logical_plan::count(value.expr),\n\n }\n\n}\n\n\n", "file_path": "python/src/functions.rs", "rank": 0, "score": 210292.79264307546 }, { "content": "#[pyfunction]\n\npub fn min(value:...
Rust
zebra-chain/src/serialization/read_zcash.rs
ebfull/zebra
e61b5e50a2f00ebc6e16ac1de10031897acd71cc
use std::io; use std::net::{IpAddr, SocketAddr}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt}; use super::SerializationError; pub trait ReadZcashExt: io::Read { ...
use std::io; use std::net::{IpAddr, SocketAddr}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt}; use super::SerializationError; pub trait ReadZcashExt: io::Read { ...
#[inline] fn read_4_bytes(&mut self) -> io::Result<[u8; 4]> { let mut bytes = [0; 4]; self.read_exact(&mut bytes)?; Ok(bytes) } #[inline] fn read_12_bytes(&mut self) -> io::Result<[u8; 12]> { let mut bytes = [0; 12]; self.read_exact(&mut bytes)?; ...
ring(&mut self) -> Result<String, SerializationError> { let len = self.read_compactsize()?; let mut buf = vec![0; len as usize]; self.read_exact(&mut buf)?; String::from_utf8(buf).map_err(|_| SerializationError::Parse("invalid utf-8")) }
function_block-function_prefixed
[ { "content": "/// Check that if there are no Spends or Outputs, that valueBalance is also 0.\n\n///\n\n/// https://zips.z.cash/protocol/canopy.pdf#consensusfrombitcoin\n\npub fn shielded_balances_match(\n\n shielded_data: &ShieldedData,\n\n value_balance: Amount,\n\n) -> Result<(), TransactionError> {\n\n...
Rust
src/de/mod.rs
RoccoDev/bson-rust
9781781212056c619464be8444a27587c7dc5de9
mod error; mod raw; mod serde; pub use self::{ error::{Error, Result}, serde::Deserializer, }; use std::io::Read; use crate::{ bson::{Array, Binary, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp}, oid::{self, ObjectId}, ser::write_i32, spec::{self, BinarySubtype}, ...
mod error; mod raw; mod serde; pub use self::{ error::{Error, Result}, serde::Deserializer, }; use std::io::Read; use crate::{ bson::{Array, Binary, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp}, oid::{self, ObjectId}, ser::write_i32, spec::{self, BinarySubtype}, ...
pub(crate) fn deserialize_bson_kvp<R: Read + ?Sized>( reader: &mut R, tag: u8, utf8_lossy: bool, ) -> Result<(String, Bson)> { use spec::ElementType; let key = read_cstring(reader)?; let val = match ElementType::from(tag) { Some(ElementType::Double) => Bson::Double(read_f64(reader)?),...
break; } let (_, val) = deserialize_bson_kvp(cursor, tag, utf8_lossy)?; arr.push(val) } Ok(()) }, )?; Ok(arr) }
function_block-function_prefix_line
[ { "content": "/// Attempts to serialize a u64 as an i32. Errors if an exact conversion is not possible.\n\npub fn serialize_u64_as_i32<S: Serializer>(val: &u64, serializer: S) -> Result<S::Ok, S::Error> {\n\n match i32::try_from(*val) {\n\n Ok(val) => serializer.serialize_i32(val),\n\n Err(_) =...
Rust
src/shared/crossterm.rs
jojolepro/crossterm
f4d2ab4feb520e687540e8917793f4fb32f0fe34
use super::super::cursor; use super::super::style; use super::super::terminal::terminal; use Context; use std::fmt::Display; use std::mem; use std::rc::Rc; use std::sync::Arc; use std::convert::From; pub struct Crossterm { context: Rc<Context> } impl From<Rc<Context>> for Crossterm { fn from(context: Rc<Co...
use super::super::cursor; use super::super::style; use super::super::terminal::terminal; use Context; use std::fmt::Display; use std::mem; use std::rc::Rc; use std::sync::Arc; use std::convert::From; pub struct Crossterm { context: Rc<Context> } impl From<Rc<Context>> for Crossterm { fn from(context: Rc<Co...
paint<'a, D: Display>(&'a self, value: D) -> style::StyledObject<D> { self.terminal().paint(value) } pub fn write<D: Display>(&self, value: D) { self.terminal().write(value) } pub fn context(&self) -> Rc<Context...
} pub fn
random
[ { "content": "/// print wait screen on alternate screen, then swich back.\n\npub fn print_wait_screen_on_alternate_window(context: Rc<Context>) {\n\n // create scope. If this scope ends the screen will be switched back to mainscreen.\n\n // because `AlternateScreen` switches back to main screen when switc...
Rust
nrf-softdevice/src/flash.rs
timokroeger/nrf-softdevice
6a01c4ceb7d1f1d9fc06e74e9a264037ac1159c5
use core::future::Future; use core::marker::PhantomData; use core::sync::atomic::{AtomicBool, Ordering}; use embassy::traits::flash::Error as FlashError; use crate::raw; use crate::util::{DropBomb, Signal}; use crate::{RawError, Softdevice}; pub struct Flash { _private: PhantomData<*mut ()>, } static FLASH_...
use core::future::Future; use core::marker::PhantomData; use core::sync::atomic::{AtomicBool, Ordering}; use embassy::traits::flash::Error as FlashError; use crate::raw; use crate::util::{DropBomb, Signal}; use crate::{RawError, Softdevice}; pub struct Flash { _private: PhantomData<*mut ()>, } static FLASH_...
a.as_ptr(); let data_len = data.len() as u32; if address % 4 != 0 { return Err(FlashError::AddressMisaligned); } if (data_ptr as u32) % 4 != 0 || data_len % 4 != 0 { return Err(FlashError::BufferMisaligned); } ...
ing::AcqRel, Ordering::Acquire) .is_err() { panic!("nrf_softdevice::Softdevice::take_flash() called multiple times.") } Flash { _private: PhantomData, } } } static SIGNAL: Signal<Result<(), FlashError>> = Signal::new(); pub(crate) fn on_flash_su...
random
[ { "content": "pub fn gen_bindings(\n\n tmp_dir: &PathBuf,\n\n src_dir: &PathBuf,\n\n dst: &PathBuf,\n\n mut f: impl FnMut(String) -> String,\n\n) {\n\n let mut wrapper = String::new();\n\n\n\n for entry in WalkDir::new(src_dir)\n\n .follow_links(true)\n\n .into_iter()\n\n ...