text stringlengths 8 4.13M |
|---|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_catalog::catalog_kind::CATALOG_DEFAULT;
use common_catalog::table::Table;
use common_catalog::table_context::TableContext;
use common_exception::Result;
use common_expression::types::StringType;
use common_expression::utils::FromData;
use common_expression::DataBlock;
use common_expression::TableDataType;
use common_expression::TableField;
use common_expression::TableSchemaRefExt;
use common_meta_app::schema::TableIdent;
use common_meta_app::schema::TableInfo;
use common_meta_app::schema::TableMeta;
use common_storages_view::view_table::VIEW_ENGINE;
use crate::table::AsyncOneBlockSystemTable;
use crate::table::AsyncSystemTable;
pub struct ColumnsTable {
table_info: TableInfo,
}
#[async_trait::async_trait]
impl AsyncSystemTable for ColumnsTable {
const NAME: &'static str = "system.columns";
fn get_table_info(&self) -> &TableInfo {
&self.table_info
}
async fn get_full_data(&self, ctx: Arc<dyn TableContext>) -> Result<DataBlock> {
let rows = self.dump_table_columns(ctx).await?;
let mut names: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
let mut tables: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
let mut databases: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
let mut types: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
let mut data_types: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
let mut default_kinds: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
let mut default_exprs: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
let mut is_nullables: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
let mut comments: Vec<Vec<u8>> = Vec::with_capacity(rows.len());
for (database_name, table_name, field) in rows.into_iter() {
names.push(field.name().clone().into_bytes());
tables.push(table_name.into_bytes());
databases.push(database_name.into_bytes());
types.push(field.data_type().wrapped_display().into_bytes());
let data_type = field.data_type().remove_recursive_nullable().sql_name();
data_types.push(data_type.into_bytes());
let mut default_kind = "".to_string();
let mut default_expr = "".to_string();
if let Some(expr) = field.default_expr() {
default_kind = "DEFAULT".to_string();
default_expr = expr.to_string();
}
default_kinds.push(default_kind.into_bytes());
default_exprs.push(default_expr.into_bytes());
if field.is_nullable() {
is_nullables.push("YES".to_string().into_bytes());
} else {
is_nullables.push("NO".to_string().into_bytes());
}
comments.push("".to_string().into_bytes());
}
Ok(DataBlock::new_from_columns(vec![
StringType::from_data(names),
StringType::from_data(databases),
StringType::from_data(tables),
StringType::from_data(types),
StringType::from_data(data_types),
StringType::from_data(default_kinds),
StringType::from_data(default_exprs),
StringType::from_data(is_nullables),
StringType::from_data(comments),
]))
}
}
impl ColumnsTable {
pub fn create(table_id: u64) -> Arc<dyn Table> {
let schema = TableSchemaRefExt::create(vec![
TableField::new("name", TableDataType::String),
TableField::new("database", TableDataType::String),
TableField::new("table", TableDataType::String),
// inner wrapped display style
TableField::new("type", TableDataType::String),
// mysql display style for 3rd party tools
TableField::new("data_type", TableDataType::String),
TableField::new("default_kind", TableDataType::String),
TableField::new("default_expression", TableDataType::String),
TableField::new("is_nullable", TableDataType::String),
TableField::new("comment", TableDataType::String),
]);
let table_info = TableInfo {
desc: "'system'.'columns'".to_string(),
name: "columns".to_string(),
ident: TableIdent::new(table_id, 0),
meta: TableMeta {
schema,
engine: "SystemColumns".to_string(),
..Default::default()
},
..Default::default()
};
AsyncOneBlockSystemTable::create(ColumnsTable { table_info })
}
async fn dump_table_columns(
&self,
ctx: Arc<dyn TableContext>,
) -> Result<Vec<(String, String, TableField)>> {
let tenant = ctx.get_tenant();
let catalog = ctx.get_catalog(CATALOG_DEFAULT)?;
let databases = catalog.list_databases(tenant.as_str()).await?;
let mut rows: Vec<(String, String, TableField)> = vec![];
for database in databases {
for table in catalog
.list_tables(tenant.as_str(), database.name())
.await?
{
let fields = if table.engine() == VIEW_ENGINE {
// information_schema.columns is a view that will query system.columns
// 1. if query information_schema.columns will call dump_table_columns and
// information_schema also in CATALOG_DEFAULT, will recursion
continue;
} else {
table.schema().fields().clone()
};
for field in fields {
rows.push((database.name().into(), table.name().into(), field.clone()))
}
}
}
Ok(rows)
}
}
|
use projecteuler::factorial;
fn main() {
dbg!(solve(1, vec![0, 1, 2]));
dbg!(solve(1_000_000, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
}
fn solve(mut n: usize, mut digits: Vec<usize>) -> usize {
n -= 1;
let mut ret = 0;
while digits.len() > 0 {
let m: usize = factorial::factorial(digits.len() - 1);
let i = n / m;
n -= i * m;
let d = digits.remove(i);
ret *= 10;
ret += d;
}
ret
}
|
extern crate progress_streams;
use progress_streams::ProgressWriter;
use std::io::{Cursor, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
fn main() {
let total = Arc::new(AtomicUsize::new(0));
let mut file = Cursor::new(Vec::new());
let mut writer = ProgressWriter::new(&mut file, |progress: usize| {
total.fetch_add(progress, Ordering::SeqCst);
});
{
let total = total.clone();
thread::spawn(move || {
loop {
println!("Written {} Kib", total.load(Ordering::SeqCst) / 1024);
thread::sleep(Duration::from_millis(16));
}
});
}
let buffer = [0u8; 8192];
while total.load(Ordering::SeqCst) < 1000 * 1024 * 1024 {
writer.write(&buffer).unwrap();
}
} |
//! Models for sonar go here
use auth::pw::SaltyPassword;
use chrono::NaiveDateTime;
use db::Connection;
use diesel;
use diesel::prelude::*;
use diesel::result::QueryResult;
use schema::{users, pings, auth_tokens};
#[derive(Identifiable, Queryable)]
pub struct User {
pub id: i32,
pub username: String,
password: String,
pub real_name: String,
pub blurb: String,
}
impl User {
/// Validated a given username and plaintext password
///
/// Return `true` if the given username exists and matches the given password
fn validate(conn: &Connection, username: &str, password: &str) -> bool {
unimplemented!()
}
/// Get the User object corresponding to a given username and plaintext password
fn get_validated(conn: &Connection, username: &str, password: &str) -> QueryResult<User> {
unimplemented!()
}
}
#[derive(Insertable)]
#[table_name = "users"]
pub struct NewUser {
username: String,
password: String,
real_name: String,
blurb: String,
}
impl NewUser {
pub fn new(username: String, password: String, real_name: String, blurb: String) -> NewUser {
NewUser {
username: username,
password: SaltyPassword::new(&password).to_string(),
real_name: real_name,
blurb: blurb,
}
}
pub fn insert(self, conn: &Connection) -> QueryResult<User> {
use schema::users::dsl::*;
diesel::insert(&self)
.into(users)
// ideally we'd use .get_result(conn) here instead of
// .execute(conn), because we'd prefer to fetch the
// newly inserted row immediately. Unfortunately,
// SQLite doesn't support that, so we're stuck making
// another query to fetch it.
.execute(conn)?;
users.filter(username.eq(&self.username)).first::<User>(
conn,
)
}
}
#[derive(Identifiable, Queryable, Associations)]
#[belongs_to(User)]
pub struct Ping {
pub id: i32,
pub user_id: i32,
pub timestamp: NaiveDateTime,
pub content: String,
pub likes: u32,
pub echoes: u32,
}
#[derive(Insertable)]
#[table_name = "pings"]
pub struct NewPing<'a> {
pub user_id: i32,
pub content: &'a str,
}
#[derive(Identifiable, Queryable, Associations)]
#[belongs_to(User)]
#[table_name = "auth_tokens"]
pub struct Token {
pub id: i32,
pub user_id: i32,
pub timestamp: NaiveDateTime,
pub key: String,
}
#[derive(Insertable)]
#[table_name = "auth_tokens"]
pub struct NewToken<'a> {
pub user_id: i32,
pub key: &'a str,
}
|
pub extern crate glium;
extern crate cgmath;
mod types;
pub mod camera;
pub mod transform;
pub mod graphics;
pub mod mesh;
pub use graphics::{Target, Shader, Renderer};
pub use mesh::Mesh;
pub use types::{Mat4, Scalar};
#[macro_export]
macro_rules! implement_uniforms {
($tyname: ty, $( $field: ident ),*) => {
impl $crate::glium::uniforms::Uniforms for $tyname {
fn visit_values<'a, F>(&'a self, mut f: F)
where F: FnMut(&str, $crate::glium::uniforms::UniformValue<'a>)
{
use $crate::glium::uniforms::AsUniformValue;
$(f(stringify!($field), (&self.$field).as_uniform_value());)*
}
}
};
} |
use crate::base::misc::util::{downcast_to_usize};
use crate::api::account_info;
use std::cell::Cell;
use std::rc::Rc;
use crate::api::config::Config;
pub fn get_account_sequence(config: &Config, account: String) -> u32 {
let seq_rc = Rc::new(Cell::new(0u64));
account_info::api::request(config, account, |x| match x {
Ok(response) => {
let seq = seq_rc.clone();
seq.set(response.sequence);
},
Err(_) => { }
});
downcast_to_usize(seq_rc)
} |
use anyhow::Result;
use hxcmp::{matrix, tests};
// fn main() -> Result<()> {
// matrix::run()?;
// Ok(())
// }
use clap::{load_yaml, App};
fn main() -> Result<()> {
// The YAML file is found relative to the current file, similar to how modules are found
let yaml = load_yaml!("cli.yaml");
let matches = App::from(yaml).get_matches();
println!("{:?}", matches);
env_logger::init();
match matches.subcommand() {
("test", Some(sub_m)) => {
let cli_files = sub_m.values_of("FILE");
let input = sub_m.value_of("input-file");
if input.is_some() {
return Ok(());
}
if input.is_none() && cli_files.is_none() {
println!("Error: no provided input files");
return Ok(());
}
for file in cli_files.unwrap() {
let data = std::fs::read_to_string(file)?;
// preview file
// println!("{}", data.chars().into_iter().take(100).collect::<String>());
matrix::run_matrix(
std::io::stdout(),
vec![tests::Test {
name: file,
input: tests::Input::AString(data),
}],
)?;
}
}
("builtin", Some(sub_m)) => matrix::run_matrix(std::io::stdout(), tests::get_tests())?,
_ => println!("No command provided"),
}
Ok(())
}
|
use std::time::Instant;
use std::io;
use std::env;
trait Futoshiki {
fn blocking_indexes(&self, r: u32, c: u32) -> Vec<usize>;
fn next_index(&self, flag: char) -> Option<(u32, u32)>;
fn forward_check(&self, value: u32, blocking_indexes_vec: &Vec<usize>, flag: char) -> bool;
fn can_put_num(&self, r: u32, c: u32, num: u32, blocking_indexes_vec: &Vec<usize>) -> bool;
fn solve(&mut self, r: u32, c: u32, flag: char) -> bool;
}
struct Matrix {
rows: u32,
cols: u32,
data: Vec<u32>,
mvr: Vec<Vec<u32>>,
cell_restriction: Vec<(u8, Box<(Fn(usize) -> i8)>)>,
attributions: u64,
}
impl Matrix {
fn new(dim: u32) -> Matrix {
Matrix {
rows: dim,
cols: dim,
data: Vec::new(),
mvr: Vec::new(),
cell_restriction: Vec::new(),
attributions: 0,
}
}
fn set(&mut self, r: u32, c: u32, value: u32) {
self.data[(c + r * self.rows) as usize] = value;
self.attributions += 1;
}
}
impl Futoshiki for Matrix {
fn blocking_indexes(&self, row: u32, col: u32) -> Vec<usize> {
let mut indexes: Vec<usize> = Vec::new();
for r in 0..self.rows {
if r == row {
continue;
}
indexes.push((col + r * self.cols) as usize);
}
for c in 0..self.cols {
if c == col {
continue;
}
indexes.push((c + row * self.cols) as usize);
}
indexes
}
fn next_index(&self, flag: char) -> Option<(u32, u32)> {
if flag == 'c' {
match self.mvr
.iter()
.enumerate()
.filter(|&(index, _)| self.data[index] == 0)
.min_by_key(|&(_, v)| v.len()) {
None => return None,
Some((index, _)) => {
let index = index as u32;
return Some((index / self.rows, index % self.cols));
}
}
}
match self.data.iter().position(|&x| x == 0) {
None => None,
Some(index) => {
let index = index as u32;
Some((index / self.rows, index % self.cols))
}
}
}
fn forward_check(&self, value: u32, blocking_indexes_vec: &Vec<usize>, flag: char) -> bool {
if flag == 'a' {
return true;
}
for index in blocking_indexes_vec {
if self.data[*index] == 0 {
continue;
}
let index_mvr = &self.mvr[*index];
if index_mvr.contains(&value) && index_mvr.len() == 1 {
return false;
}
}
return true;
}
fn can_put_num(&self, r: u32, c: u32, num: u32, blocking_indexes_vec: &Vec<usize>) -> bool {
for index in blocking_indexes_vec {
let index = *index;
if self.data[index] == 0 {
continue;
}
if self.data[index] == num {
return false;
}
let (valid, ref fn_restrict) = self.cell_restriction[index];
if valid == 1 {
let check = fn_restrict((c + r * self.cols) as usize);
if check == 1 && self.data[index] > num {
return false;
} else if check == -1 && self.data[index] < num {
return false;
}
}
}
return true;
}
fn solve(&mut self, r: u32, c: u32, flag: char) -> bool {
let possible_nums;
if flag != 'c' {
possible_nums = (1..self.cols + 1).collect();
} else {
let index = c + r * self.cols;
possible_nums = self.mvr[index as usize].clone();
}
let mut removed_stack = Vec::new();
for possible_num in possible_nums {
let blocking_indexes_vec = self.blocking_indexes(r, c);
if self.can_put_num(r, c, possible_num, &blocking_indexes_vec) &&
self.forward_check(possible_num, &blocking_indexes_vec, flag) {
if self.attributions > 1000000 {
return false;
}
self.set(r, c, possible_num);
if flag == 'c' {
for index in &blocking_indexes_vec {
if let Some(possible_num_index) = self.mvr[*index]
.iter()
.position(|&x| x == possible_num) {
removed_stack.push(*index);
self.mvr[*index].swap_remove(possible_num_index);
};
}
}
match self.next_index(flag) {
None => return true,
Some((next_r, next_c)) => {
if self.solve(next_r, next_c, flag) {
return true;
}
}
}
if flag == 'c' {
for index in &removed_stack {
self.mvr[*index].push(possible_num);
}
removed_stack.clear();
}
}
}
self.set(r, c, 0);
return false;
}
}
fn restriction_func(maybe_old_f: (u8, Box<(Fn(usize) -> i8)>),
cell: usize,
value: i8)
-> Box<(Fn(usize) -> i8)> {
let (valid, old_f) = maybe_old_f;
Box::new(move |index: usize| -> i8 {
if valid == 1 {
let ret = old_f(index);
if ret != 0 {
return ret;
}
}
if index == cell {
value
} else {
0
}
})
}
fn main() {
let line_or_panic = || -> String {
let mut line = String::new();
if let Err(error) = io::stdin().read_line(&mut line) {
panic!("Couldn't read line. Error: {}", error);
}
String::from(line.trim())
};
let u32_values = |line: String| -> Vec<u32> {
line.trim().split(" ").map(|s| s.parse::<u32>().unwrap_or(0)).collect::<Vec<u32>>()
};
let flag;
match env::var("FLAG") {
Ok(val) => flag = val.chars().next().unwrap_or('a'),
Err(_) => flag = 'a',
}
let n_cases_line = line_or_panic();
let test_cases = n_cases_line.parse::<u32>().unwrap_or(0);
println!("{}", n_cases_line);
for _ in 0..test_cases {
let first_line = u32_values(line_or_panic());
let matrix_dim = first_line[0];
let restrictions = first_line[1];
let mut matrix = Matrix::new(matrix_dim);
let mvr_vec = (1..matrix_dim + 1).collect::<Vec<u32>>();
for i in 0..(matrix_dim * matrix_dim) {
if i < matrix_dim {
let mut row = u32_values(line_or_panic());
matrix.data.append(&mut row);
}
matrix.mvr.push(mvr_vec.clone());
matrix.cell_restriction.push((0, Box::new(|_: usize| -> i8 { 0 })));
}
for _ in 0..restrictions {
let restriction = u32_values(line_or_panic());
let (r1, c1) = (restriction[0] - 1, restriction[1] - 1);
let (r2, c2) = (restriction[2] - 1, restriction[3] - 1);
let index1 = (c1 + r1 * matrix_dim) as usize;
let index2 = (c2 + r2 * matrix_dim) as usize;
let index_max = std::cmp::max(index1, index2);
let index_min = std::cmp::min(index1, index2);
let old_f1 = matrix.cell_restriction.remove(index_max);
let old_f2 = matrix.cell_restriction.remove(index_min);
let index_min_fn = restriction_func(old_f1,
index_max,
if index_max == index2 {
1
} else {
-1
});
let index_max_fn = restriction_func(old_f2,
index_min,
if index_min == index2 {
1
} else {
-1
});
matrix.cell_restriction.insert(index_min, (1, index_min_fn));
matrix.cell_restriction.insert(index_max, (1, index_max_fn));
}
// consume \n at the end of each case
line_or_panic();
let now = Instant::now();
if !matrix.solve(0, 0, flag) {
println!("Numero de atribuicoes excede o limite");
println!("{}\n", now.elapsed().subsec_nanos());
continue;
}
println!("{}", now.elapsed().subsec_nanos());
for (i, num) in matrix.data.into_iter().enumerate() {
if (i as u32) % matrix_dim == 0 && i != 0 {
print!("\n");
}
print!("{} ", num);
}
println!("\n");
}
}
|
use std::path::{Path, PathBuf};
use std::process;
use crate::config::mimetype;
pub fn stringify_mode(mode: u32) -> String {
const LIBC_FILE_VALS: [(libc::mode_t, char); 7] = [
(libc::S_IFREG, '-'),
(libc::S_IFDIR, 'd'),
(libc::S_IFLNK, 'l'),
(libc::S_IFSOCK, 's'),
(libc::S_IFBLK, 'b'),
(libc::S_IFCHR, 'c'),
(libc::S_IFIFO, 'f'),
];
const LIBC_PERMISSION_VALS: [(libc::mode_t, char); 9] = [
(libc::S_IRUSR, 'r'),
(libc::S_IWUSR, 'w'),
(libc::S_IXUSR, 'x'),
(libc::S_IRGRP, 'r'),
(libc::S_IWGRP, 'w'),
(libc::S_IXGRP, 'x'),
(libc::S_IROTH, 'r'),
(libc::S_IWOTH, 'w'),
(libc::S_IXOTH, 'x'),
];
let mut mode_str: String = String::with_capacity(10);
let mode_shifted = mode >> 9;
for (val, ch) in LIBC_FILE_VALS.iter() {
let val: u32 = (*val >> 9) as u32;
if mode_shifted & val == mode_shifted {
mode_str.push(*ch);
break;
}
}
for (val, ch) in LIBC_PERMISSION_VALS.iter() {
let val: u32 = (*val) as u32;
if mode & val != 0 {
mode_str.push(*ch);
} else {
mode_str.push('-');
}
}
mode_str
}
pub fn set_mode(path: &Path, mode: u32) {
let os_path = path.as_os_str();
if let Some(s) = os_path.to_str() {
let svec: Vec<libc::c_char> = s.bytes().map(|ch| ch as libc::c_char).collect();
unsafe {
libc::chmod(svec.as_ptr(), mode as libc::mode_t);
}
}
}
pub fn open_with_entry(paths: &[&PathBuf], entry: &mimetype::LllMimetypeEntry) {
let program = entry.program.clone();
let mut command = process::Command::new(program);
if entry.silent {
command.stdout(process::Stdio::null());
command.stderr(process::Stdio::null());
}
if let Some(args) = entry.args.as_ref() {
command.args(args.clone());
}
command.args(paths.iter().map(|path| path.as_os_str()));
match command.spawn() {
Ok(mut handle) => {
if !entry.fork {
match handle.wait() {
Ok(_) => {}
Err(e) => eprintln!("{}", e),
}
}
}
Err(e) => eprintln!("{}", e),
};
}
pub fn open_with_args(paths: &[&PathBuf], args: &[String]) {
let program = args[0].clone();
let mut command = process::Command::new(program);
command.args(args[1..].iter().cloned());
command.args(paths.iter().map(|path| path.as_os_str()));
match command.spawn() {
Ok(mut handle) => match handle.wait() {
Ok(_) => {}
Err(e) => eprintln!("{}", e),
},
Err(e) => eprintln!("{}", e),
}
}
|
extern crate piston;
extern crate glutin_window;
extern crate graphics;
extern crate opengl_graphics;
// extern crate blas_src;
extern crate openblas_src;
use piston::window::WindowSettings;
use piston::event_loop::{Events, EventLoop, EventSettings};
use piston::input::RenderEvent;
use glutin_window::GlutinWindow;
use opengl_graphics::{OpenGL, GlGraphics};
use ndarray_npy::read_npy;
extern crate lib;
use lib::simulation::colony::Colony;
use lib::simulation::environment::Environment;
use lib::simulation::world_view::{WorldView, WorldViewSettings};
use lib::neural_network::mlp::MLP;
const NUM_ANTS: usize = 50;
const ARENA_SIZE: usize = 100;
const DIFFUSION_RATE: f64 = 0.999;
const PIXEL_SIZE: usize = 4;
const RESOLUTION: usize = PIXEL_SIZE * ARENA_SIZE;
fn main() {
let opengl = OpenGL::V3_2;
let settings = WindowSettings::new("Ant Colony Simulation", [RESOLUTION as f64; 2])
.graphics_api(opengl)
.exit_on_esc(true);
let mut window: GlutinWindow = settings.build()
.expect("Could not create window");
let event_settings: EventSettings = EventSettings::new()
.max_fps(100)
.ups(100);
let mut events = Events::new(event_settings);
let mut gl = GlGraphics::new(opengl);
//let weights = read_npy("/home/reeldata/Documents/ant_sim/src/visualize_simulation/trial_3.npy").unwrap();
let decision_network: MLP = MLP::new(38, vec![16, 1]);
let mut colony = Colony::new(NUM_ANTS, decision_network);
let mut environment = Environment::new(ARENA_SIZE, DIFFUSION_RATE);
let world_view = WorldView::new(WorldViewSettings::new());
while let Some(e) = events.next(&mut window) {
environment.update_piston(&e);
colony.update_piston(&mut environment, &e);
if let Some(args) = e.render_args() {
gl.draw(args.viewport(), |c, g| {
use graphics::{clear};
clear([0.0; 4], g);
world_view.draw(&environment, &c, g);
});
}
}
} |
//! Implementation details of the `#[sabi_extern_fn]` attribute.
use std::mem;
use as_derive_utils::return_spanned_err;
use proc_macro::TokenStream as TokenStream1;
use proc_macro2::{Span, TokenStream as TokenStream2, TokenTree};
use quote::{quote, ToTokens};
use syn::{Expr, ItemFn};
use crate::parse_or_compile_err;
#[doc(hidden)]
pub fn sabi_extern_fn(attr: TokenStream1, item: TokenStream1) -> TokenStream1 {
parse_or_compile_err(item, move |item| sabi_extern_fn_inner(attr.into(), item)).into()
}
#[cfg(test)]
pub(crate) fn sabi_extern_fn_str(attr: &str, item: &str) -> Result<TokenStream2, syn::Error> {
syn::parse_str(item).and_then(move |item| {
let attr = syn::parse_str::<TokenStream2>(attr)?;
sabi_extern_fn_inner(attr, item)
})
}
/// Whether the function contains an early return or not.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum WithEarlyReturn {
No,
Yes,
}
/// Converts a function into an `extern "C" fn` which aborts on panic.
pub(crate) fn convert_to_sabi_extern_fn(with_early_return: WithEarlyReturn, item: &mut ItemFn) {
let no_early_return = match with_early_return {
WithEarlyReturn::No => Some(quote!( no_early_return; )),
WithEarlyReturn::Yes => None,
};
item.sig.abi = Some(syn::Abi {
extern_token: Default::default(),
name: Some(syn::LitStr::new("C", Span::call_site())),
});
let statements = mem::take(&mut item.block.stmts);
let x = quote! {
::abi_stable::extern_fn_panic_handling!(
#no_early_return
#(#statements)*
)
};
let x = Expr::Verbatim(x);
let x = syn::Stmt::Expr(x);
let x = vec![x];
item.block.stmts = x;
}
fn sabi_extern_fn_inner(attr: TokenStream2, mut item: ItemFn) -> Result<TokenStream2, syn::Error> {
let with_early_return = match attr.into_iter().next() {
Some(TokenTree::Ident(ref ident)) if ident == "no_early_return" => WithEarlyReturn::No,
Some(tt) => return_spanned_err!(tt, "Unrecognized `#[sabi_extern_fn]` parameter",),
None => WithEarlyReturn::Yes,
};
convert_to_sabi_extern_fn(with_early_return, &mut item);
Ok(item.into_token_stream())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_output() {
let list = vec![
(
"",
r##"
pub fn hello()->RString{
println!("{}",HELLO);
println!(",");
println!("{}",WORLD);
}
"##,
quote!(
pub extern "C" fn hello() -> RString {
::abi_stable::extern_fn_panic_handling!(
println!("{}",HELLO);
println!(",");
println!("{}",WORLD);
)
}
),
),
(
"no_early_return",
r##"
pub(crate) extern "Rust" fn hello()->RStr<'_>{
println!("{}",HELLO);
println!(",");
println!("{}",WORLD);
"stuff".into()
}
"##,
quote!(
pub(crate) extern "C" fn hello() -> RStr<'_> {
::abi_stable::extern_fn_panic_handling!(
no_early_return;
println!("{}",HELLO);
println!(",");
println!("{}",WORLD);
"stuff".into()
)
}
),
),
];
for (attr, item, expected) in list {
assert_eq!(
sabi_extern_fn_str(attr, item).unwrap().to_string(),
expected.to_string()
);
}
}
}
|
use crate::{rendering::Display, simulation::Simulation, timing::TIMING_DATABASE};
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
pub struct PerfApp;
impl PerfApp {
pub fn update(&mut self, ctx: &egui::CtxRef, _display: &Display, _simulation: &Simulation) {
egui::SidePanel::right("Performance Info").show(ctx, |ui| {
ui.style_mut().wrap = Some(false);
ui.heading("Performance");
self.physics(ui);
self.sim_render(ui);
});
}
fn physics(&self, ui: &mut egui::Ui) {
let database = TIMING_DATABASE.read();
ui.separator();
ui.heading("Physics");
ui.label(format!("Full Step {}", database.physics.step.res_str));
ui.label(format!("\t{}", database.physics.step));
ui.label(format!("Pos Update {}", database.physics.pos_update.res_str));
ui.label(format!("\t{}", database.physics.pos_update));
ui.label(format!("Col Detection {}", database.physics.col_detect.res_str));
ui.label(format!("\t{}", database.physics.col_detect));
}
fn sim_render(&self, ui: &mut egui::Ui) {
let database = TIMING_DATABASE.read();
ui.separator();
ui.heading("Sim Render");
ui.label(format!(
"Vertex Update {}",
database.sim_render.vertex_buffer_update.res_str
));
ui.label(format!("\t{}", database.sim_render.vertex_buffer_update));
ui.label(format!("Render {}", database.sim_render.render.res_str));
ui.label(format!("\t{}", database.sim_render.render));
}
}
|
use super::window::Window;
use std::borrow::Borrow;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::Arc;
use vulkano::command_buffer::DynamicState;
use vulkano::device::{Device, DeviceExtensions, Queue};
use vulkano::framebuffer::{Framebuffer, FramebufferAbstract, RenderPassAbstract};
use vulkano::image;
use vulkano::instance::{Instance, InstanceCreationError, InstanceExtensions, PhysicalDevice};
use vulkano::pipeline::viewport::Viewport;
use vulkano::swapchain::{
ColorSpace, PresentMode, Surface, SurfaceCreationError, SurfaceTransform, Swapchain,
};
const WIDTH: u32 = 500;
const HEIGHT: u32 = 500;
pub struct VkSession {
pub device: Arc<Device>,
pub instance: Arc<Instance>,
pub queue: Arc<Queue>,
pub draw_surface: Arc<Surface<Window>>,
pub swapchain: Arc<Swapchain<Window>>,
pub images: Vec<Arc<image::SwapchainImage<Window>>>,
pub dynamic_state: DynamicState,
}
#[derive(Debug)]
pub enum VkSessionError {
PhysicalDeviceIdNotFound(usize),
Todo(Box<dyn std::error::Error>),
}
impl From<InstanceCreationError> for VkSessionError {
fn from(e: InstanceCreationError) -> Self {
Self::Todo(Box::new(e))
}
}
pub unsafe trait SafeBorrow<T>: Borrow<T> {}
unsafe impl<T> SafeBorrow<T> for T {}
unsafe impl<'a, T> SafeBorrow<T> for &'a T {}
unsafe impl<'a, T> SafeBorrow<T> for &'a mut T {}
unsafe impl<T> SafeBorrow<T> for Rc<T> {}
unsafe impl<T> SafeBorrow<T> for Arc<T> {}
unsafe impl<T> SafeBorrow<T> for Box<T> {}
pub fn create_vk_surface<W>(
window: W,
instance: Arc<Instance>,
) -> Result<Arc<Surface<W>>, SurfaceCreationError>
where
W: SafeBorrow<super::window::Window>,
{
unsafe {
Surface::from_wayland(
instance,
window.borrow().display.c_ptr() as *mut _,
window.borrow().surface.as_ref().c_ptr() as *mut _,
window,
)
}
}
impl<'a> VkSession {
pub fn initialize(physical_device_id: usize, window: Window) -> Result<Self, VkSessionError> {
let extensions = InstanceExtensions {
khr_wayland_surface: true,
khr_surface: true,
..InstanceExtensions::none()
};
let instance = Instance::new(None, &extensions, None)?;
let physical = PhysicalDevice::from_index(&instance, physical_device_id)
.ok_or_else(|| VkSessionError::PhysicalDeviceIdNotFound(physical_device_id))?;
let queue_family = physical
.queue_families()
.find(|&q| q.supports_graphics())
.expect("Could not find a graphical queue family of physical vulkan device");
let (device, mut queues) = {
Device::new(
physical,
physical.supported_features(),
&DeviceExtensions {
khr_swapchain: true,
..DeviceExtensions::none()
},
[(queue_family, 0.5)].iter().cloned(),
)
.expect("Failed to create device")
};
let queue = queues.next().unwrap();
let vksurface = create_vk_surface(window, instance.clone()).unwrap();
let caps = vksurface.capabilities(physical).unwrap();
let dimensions = caps.current_extent.unwrap_or([WIDTH, HEIGHT]);
let alpha = caps.supported_composite_alpha.iter().next().unwrap();
let format = caps.supported_formats[0].0;
let (swapchain, images) = Swapchain::new(
device.clone(),
vksurface.clone(),
caps.min_image_count,
format,
dimensions,
1,
caps.supported_usage_flags,
&queue,
SurfaceTransform::Identity,
alpha,
PresentMode::Fifo,
true,
ColorSpace::SrgbNonLinear,
)
.unwrap();
let dynamic_state = DynamicState {
line_width: None,
viewports: None,
scissors: None,
..DynamicState::default()
};
Ok(Self {
device,
instance,
queue,
draw_surface: vksurface,
swapchain,
images,
dynamic_state,
})
}
pub fn new_framebuffers(
&mut self,
) -> (
Vec<Arc<dyn FramebufferAbstract + Send + Sync>>,
Arc<dyn RenderPassAbstract + Send + Sync>,
) {
let viewport = Viewport {
origin: [0.0, 0.0],
dimensions: [500.0, 500.0],
depth_range: 0.0..1.0,
};
self.dynamic_state.viewports = Some(vec![viewport]);
let render_pass = Arc::new(
vulkano::single_pass_renderpass!(
self.device.clone(),
attachments: {
color: {
load: Clear,
store: Store,
format: self.swapchain.format(),
samples: 1,
}
},
pass: {
color: [color],
depth_stencil: {}
}
)
.unwrap(),
);
let buffers = self
.images
.iter()
.map(|image| {
Arc::new(
Framebuffer::start(render_pass.clone())
.add(image.clone())
.unwrap()
.build()
.unwrap(),
) as Arc<dyn FramebufferAbstract + Send + Sync>
})
.collect::<Vec<_>>();
(buffers, render_pass)
}
}
|
#![allow(unused_imports, non_camel_case_types, non_snake_case)]
extern crate libc;
extern crate glib;
extern crate glib_sys;
pub mod kb;
pub mod nvti;
pub mod ast;
pub use self::kb::*;
pub use self::nvti::*;
pub use self::ast::*;
// https://developer.gnome.org/glib/stable/glib-Basic-Types.html#D
pub type gchar = std::os::raw::c_char;
pub type gint = std::os::raw::c_int;
pub type guint = std::os::raw::c_uint;
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct __BindgenBitfieldUnit<Storage, Align>
where
Storage: AsRef<[u8]> + AsMut<[u8]>,
{
storage: Storage,
align: [Align; 0],
}
impl<Storage, Align> __BindgenBitfieldUnit<Storage, Align>
where
Storage: AsRef<[u8]> + AsMut<[u8]>,
{
#[inline]
pub fn new(storage: Storage) -> Self {
Self { storage, align: [] }
}
#[inline]
pub fn get_bit(&self, index: usize) -> bool {
debug_assert!(index / 8 < self.storage.as_ref().len());
let byte_index = index / 8;
let byte = self.storage.as_ref()[byte_index];
let bit_index = index % 8;
let mask = 1 << bit_index;
byte & mask == mask
}
#[inline]
pub fn set_bit(&mut self, index: usize, val: bool) {
debug_assert!(index / 8 < self.storage.as_ref().len());
let byte_index = index / 8;
let byte = &mut self.storage.as_mut()[byte_index];
let bit_index = index % 8;
let mask = 1 << bit_index;
if val {
*byte |= mask;
} else {
*byte &= !mask;
}
}
#[inline]
pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len());
let mut val = 0;
for i in 0..(bit_width as usize) {
if self.get_bit(i + bit_offset) {
val |= 1 << i;
}
}
val
}
#[inline]
pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len());
for i in 0..(bit_width as usize) {
let mask = 1 << i;
let val_bit_is_set = val & mask == mask;
self.set_bit(i + bit_offset, val_bit_is_set);
}
}
}
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub fn new() -> Self {
__IncompleteArrayField(::std::marker::PhantomData)
}
#[inline]
pub unsafe fn as_ptr(&self) -> *const T {
::std::mem::transmute(self)
}
#[inline]
pub unsafe fn as_mut_ptr(&mut self) -> *mut T {
::std::mem::transmute(self)
}
#[inline]
pub unsafe fn as_slice(&self, len: usize) -> &[T] {
::std::slice::from_raw_parts(self.as_ptr(), len)
}
#[inline]
pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] {
::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)
}
}
impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
fmt.write_str("__IncompleteArrayField")
}
}
impl<T> ::std::clone::Clone for __IncompleteArrayField<T> {
#[inline]
fn clone(&self) -> Self {
Self::new()
}
}
impl<T> ::std::marker::Copy for __IncompleteArrayField<T> {}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::any::Any;
use std::cell::UnsafeCell;
use std::sync::Arc;
use common_exception::ErrorCode;
use common_exception::Result;
use futures::future::BoxFuture;
use futures::FutureExt;
use petgraph::graph::node_index;
use petgraph::prelude::NodeIndex;
#[derive(Debug)]
pub enum Event {
NeedData,
NeedConsume,
Sync,
Async,
Finished,
}
// The design is inspired by ClickHouse processors
#[async_trait::async_trait]
pub trait Processor: Send {
fn name(&self) -> String;
/// Reference used for downcast.
fn as_any(&mut self) -> &mut dyn Any;
fn event(&mut self) -> Result<Event>;
// When the synchronization task needs to run for a long time, the interrupt function needs to be implemented.
fn interrupt(&self) {}
// Synchronous work.
fn process(&mut self) -> Result<()> {
Err(ErrorCode::Unimplemented("Unimplemented process."))
}
// Asynchronous work.
async fn async_process(&mut self) -> Result<()> {
Err(ErrorCode::Unimplemented("Unimplemented async_process."))
}
}
#[derive(Clone)]
pub struct ProcessorPtr {
id: Arc<UnsafeCell<NodeIndex>>,
inner: Arc<UnsafeCell<Box<dyn Processor>>>,
}
unsafe impl Send for ProcessorPtr {}
unsafe impl Sync for ProcessorPtr {}
impl ProcessorPtr {
pub fn create(inner: Box<dyn Processor>) -> ProcessorPtr {
ProcessorPtr {
id: Arc::new(UnsafeCell::new(node_index(0))),
inner: Arc::new(UnsafeCell::new(inner)),
}
}
/// # Safety
pub unsafe fn as_any(&mut self) -> &mut dyn Any {
(*self.inner.get()).as_any()
}
/// # Safety
pub unsafe fn id(&self) -> NodeIndex {
*self.id.get()
}
/// # Safety
pub unsafe fn set_id(&self, id: NodeIndex) {
*self.id.get() = id;
}
/// # Safety
pub unsafe fn name(&self) -> String {
(*self.inner.get()).name()
}
/// # Safety
pub unsafe fn event(&self) -> Result<Event> {
(*self.inner.get()).event()
}
/// # Safety
pub unsafe fn interrupt(&self) {
(*self.inner.get()).interrupt()
}
/// # Safety
pub unsafe fn process(&self) -> Result<()> {
(*self.inner.get()).process()
}
/// # Safety
pub unsafe fn async_process(&self) -> BoxFuture<'static, Result<()>> {
(*self.inner.get()).async_process().boxed()
}
}
#[async_trait::async_trait]
impl<T: Processor + ?Sized> Processor for Box<T> {
fn name(&self) -> String {
(**self).name()
}
fn as_any(&mut self) -> &mut dyn Any {
(**self).as_any()
}
fn event(&mut self) -> Result<Event> {
(**self).event()
}
fn interrupt(&self) {
(**self).interrupt()
}
fn process(&mut self) -> Result<()> {
(**self).process()
}
async fn async_process(&mut self) -> Result<()> {
(**self).async_process().await
}
}
|
use sourcerenderer_core::Platform;
use sourcerenderer_core::platform::FileWatcher;
use std::sync::Arc;
use sourcerenderer_core::platform::{Window, ThreadHandle};
use std::error::Error;
use sourcerenderer_vulkan::{VkBackend, VkInstance, VkSurface, VkDevice, VkSwapchain};
use ndk::native_window::NativeWindow;
use ndk_sys::{ANativeWindow_release, ANativeWindow_getWidth, ANativeWindow_getHeight};
use ash::extensions::khr::AndroidSurface;
use ash::extensions::khr::Surface;
use ash::vk;
use std::os::raw::c_void;
use crate::io::AndroidIO;
pub struct AndroidPlatform {
window: AndroidWindow
}
impl AndroidPlatform {
pub fn new(native_window: NativeWindow) -> Self {
Self {
window: AndroidWindow::new(native_window)
}
}
pub(crate) fn change_window(&mut self, window: AndroidWindow) {
self.window = window;
}
}
impl Platform for AndroidPlatform {
type GraphicsBackend = VkBackend;
type Window = AndroidWindow;
type IO = AndroidIO;
type ThreadHandle = StdThreadHandle;
fn window(&self) -> &Self::Window {
&self.window
}
fn create_graphics(&self, debug_layers: bool) -> Result<Arc<VkInstance>, Box<dyn Error>> {
Ok(Arc::new(VkInstance::new(&["VK_KHR_surface", "VK_KHR_android_surface"], debug_layers)))
}
fn start_thread<F>(&self, name: &str, callback: F) -> Self::ThreadHandle
where
F: FnOnce(),
F: Send + 'static {
StdThreadHandle(std::thread::Builder::new()
.name(name.to_string())
.spawn(callback)
.unwrap())
}
}
pub struct AndroidFileWatcher {}
impl FileWatcher for AndroidFileWatcher {
fn watch<P: AsRef<std::path::Path>>(&mut self, _path: P) {
// It's probably possible to implement this, but not super useful.
}
fn unwatch<P: AsRef<std::path::Path>>(&mut self, _path: P) {
// It's probably possible to implement this, but not super useful.
}
}
pub struct AndroidWindow {
native_window: NativeWindow
}
impl AndroidWindow {
pub fn new(native_window: NativeWindow) -> Self {
Self {
native_window
}
}
pub(crate) fn native_window(&self) -> &NativeWindow {
&self.native_window
}
}
impl Drop for AndroidWindow {
fn drop(&mut self) {
unsafe {
ANativeWindow_release(self.native_window.ptr().as_ptr());
}
}
}
impl Window<AndroidPlatform> for AndroidWindow {
fn create_surface(&self, graphics_instance: Arc<VkInstance>) -> Arc<VkSurface> {
// thankfully, VkSurfaceKHR keeps a reference to the NativeWindow internally so I dont have to deal with that
let instance_raw = graphics_instance.raw();
let android_surface_loader = AndroidSurface::new(&instance_raw.entry, &instance_raw.instance);
let surface = unsafe { android_surface_loader.create_android_surface(&vk::AndroidSurfaceCreateInfoKHR {
flags: vk::AndroidSurfaceCreateFlagsKHR::empty(),
window: self.native_window.ptr().as_ptr() as *mut c_void,
..Default::default()
}, None).unwrap() };
let surface_loader = Surface::new(&instance_raw.entry, &instance_raw.instance);
Arc::new(VkSurface::new(instance_raw, surface, surface_loader))
}
fn create_swapchain(&self, vsync: bool, device: &VkDevice, surface: &Arc<VkSurface>) -> Arc<VkSwapchain> {
let device_inner = device.inner();
return VkSwapchain::new(vsync, self.native_window.width() as u32, self.native_window.height() as u32, device_inner, surface).unwrap();
}
fn width(&self) -> u32 {
unsafe {
ANativeWindow_getWidth(self.native_window.ptr().as_ptr()) as u32
}
}
fn height(&self) -> u32 {
unsafe {
ANativeWindow_getHeight(self.native_window.ptr().as_ptr()) as u32
}
}
}
pub struct StdThreadHandle(std::thread::JoinHandle<()>);
impl ThreadHandle for StdThreadHandle {
fn join(self) -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
self.0.join()
}
}
|
use std::io::BufRead;
fn get_input() -> std::vec::Vec<[bool; 31]> {
std::io::BufReader::new(std::fs::File::open("input.txt").unwrap_or_else(|_| {
panic!(
"current dir: {}",
std::env::current_dir().unwrap().display()
)
}))
.lines()
.map(|s| -> [bool; 31] {
#[allow(clippy::uninit_assumed_init)]
let mut arr: [bool; 31] = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
s.unwrap()
.as_bytes()
.iter()
.map(|c| -> bool { *c == b'#' })
.enumerate()
.for_each(|x| arr[x.0] = x.1);
arr
})
.collect()
}
fn trees_encountered(right: usize, down: usize) -> usize {
get_input()
.iter()
.enumerate()
.filter(|(ix, _)| -> bool { ix % down == 0 })
.filter(|(ix, arr)| -> bool { arr[(*ix * right / down) % 31] })
.count()
}
fn main() {
println!("part one: {}", trees_encountered(3, 1));
println!(
"part two: {}",
trees_encountered(1, 1)
* trees_encountered(3, 1)
* trees_encountered(5, 1)
* trees_encountered(7, 1)
* trees_encountered(1, 2)
);
}
|
pub use crate::{Type, Ty};
use intern::Intern;
pub struct LayoutCtx<'t, 'l> {
pub defaults: DefaultLayouts<'t, 'l>,
interner: &'l LayoutInterner<'t, 'l>,
types: &'t crate::ty::TyCtx<'t>,
}
pub struct DefaultLayouts<'t, 'l> {
pub unit: TyLayout<'t, 'l>,
pub bool: TyLayout<'t, 'l>,
pub char: TyLayout<'t, 'l>,
pub str: TyLayout<'t, 'l>,
pub ratio: TyLayout<'t, 'l>,
pub u8: TyLayout<'t, 'l>,
pub u16: TyLayout<'t, 'l>,
pub u32: TyLayout<'t, 'l>,
pub u64: TyLayout<'t, 'l>,
pub u128: TyLayout<'t, 'l>,
pub usize: TyLayout<'t, 'l>,
pub i8: TyLayout<'t, 'l>,
pub i16: TyLayout<'t, 'l>,
pub i32: TyLayout<'t, 'l>,
pub i64: TyLayout<'t, 'l>,
pub i128: TyLayout<'t, 'l>,
pub isize: TyLayout<'t, 'l>,
pub f32: TyLayout<'t, 'l>,
pub f64: TyLayout<'t, 'l>,
pub fsize: TyLayout<'t, 'l>,
pub proc: TyLayout<'t, 'l>,
pub ptr_u8: TyLayout<'t, 'l>,
}
impl<'t, 'l> LayoutCtx<'t, 'l> {
pub fn new(types: &'t crate::ty::TyCtx<'t>, interner: &'l LayoutInterner<'t, 'l>, triple: &target_lexicon::Triple) -> LayoutCtx<'t, 'l> {
use target_lexicon::PointerWidth;
let ptr_width = triple.pointer_width().unwrap_or(PointerWidth::U32);
let ptr_size = ptr_width.bytes() as usize;
let u8 = TyLayout { ty: types.defaults.u8, details: Details { size: 1, align: 1, ..Details::default() }.intern(interner) };
let u16 = TyLayout { ty: types.defaults.u16, details: Details { size: 2, align: 2, ..Details::default() }.intern(interner) };
let u32 = TyLayout { ty: types.defaults.u32, details: Details { size: 4, align: 4, ..Details::default() }.intern(interner) };
let u64 = TyLayout { ty: types.defaults.u64, details: Details { size: 8, align: 8, ..Details::default() }.intern(interner) };
let usize = match ptr_width {
PointerWidth::U16 => u16,
PointerWidth::U32 => u32,
PointerWidth::U64 => u64,
};
let i16 = TyLayout { ty: types.defaults.i16, details: Details { size: 2, align: 2, ..Details::default() }.intern(interner) };
let i32 = TyLayout { ty: types.defaults.i32, details: Details { size: 4, align: 4, ..Details::default() }.intern(interner) };
let i64 = TyLayout { ty: types.defaults.i64, details: Details { size: 8, align: 8, ..Details::default() }.intern(interner) };
let isize = match ptr_width {
PointerWidth::U16 => i16,
PointerWidth::U32 => i32,
PointerWidth::U64 => i64,
};
let f32 = TyLayout { ty: types.defaults.f32, details: Details { size: 4, align: 4, ..Details::default() }.intern(interner) };
let f64 = TyLayout { ty: types.defaults.f64, details: Details { size: 8, align: 8, ..Details::default() }.intern(interner) };
let ptr_u8 = TyLayout { ty: types.defaults.ptr_u8, details: Details {
size: ptr_size,
align: alignment(ptr_size),
pointee: Some(u8),
..Details::default()
}.intern(interner) };
LayoutCtx {
defaults: DefaultLayouts {
unit: TyLayout { ty: types.defaults.unit, details: Details::default().intern(interner) },
bool: TyLayout { ty: types.defaults.bool, details: Details { size: 1, align: 1, ..Details::default() }.intern(interner) },
char: TyLayout { ty: types.defaults.char, details: Details { size: 4, align: 4, ..Details::default() }.intern(interner) },
str: TyLayout { ty: types.defaults.str, details: Details {
size: 2 * ptr_size,
align: alignment(2 * ptr_size),
idx: Some(u8),
fields: Box::new([
(0, ptr_u8),
(ptr_size, usize),
]),
..Details::default()
}.intern(interner) },
ratio: TyLayout { ty: types.defaults.ratio, details: Details {
size: 2 * isize.details.size,
align: 2 * isize.details.align,
fields: Box::new([
(0, isize),
(isize.details.size, isize),
]),
..Details::default()
}.intern(interner) },
u8, u16, u32, u64,
u128: TyLayout { ty: types.defaults.u128, details: Details::default().intern(interner) },
usize,
i8: TyLayout { ty: types.defaults.i8, details: Details::default().intern(interner) },
i16, i32, i64,
i128: TyLayout { ty: types.defaults.i128, details: Details::default().intern(interner) },
isize, f32, f64,
fsize: match ptr_width {
PointerWidth::U16 => f32,
PointerWidth::U32 => f32,
PointerWidth::U64 => f64,
},
proc: TyLayout { ty: Type::Proc(Default::default()).intern(types), details: Details {
size: ptr_size,
align: alignment(ptr_size),
..Details::default()
}.intern(interner) },
ptr_u8,
},
interner,
types,
}
}
}
#[derive(Clone, Copy)]
pub struct TyLayout<'t, 'l> {
pub ty: Ty<'t>,
pub details: Layout<'t, 'l>,
}
pub struct Details<'t, 'l> {
pub size: usize,
pub align: usize,
pub pointee: Option<TyLayout<'t, 'l>>,
pub idx: Option<TyLayout<'t, 'l>>,
pub fields: Box<[(usize, TyLayout<'t, 'l>)]>,
}
impl<'t, 'l> Default for Details<'t, 'l> {
fn default() -> Details<'t, 'l> {
Details {
size: 0,
align: 1,
pointee: None,
idx: None,
fields: Box::new([]),
}
}
}
impl<'t, 'l> TyLayout<'t, 'l> {
pub fn sign(&self) -> bool {
match &*self.ty {
Type::Int(_) => true,
_ => false,
}
}
}
impl<'t, 'l> Ty<'t> {
pub fn layout(self, ctx: &LayoutCtx<'t, 'l>) -> TyLayout<'t, 'l> {
use crate::{IntSize, FloatSize};
TyLayout {
ty: self,
details: match &*self {
Type::Param(_) => unreachable!(),
Type::Unit => ctx.defaults.unit.details,
Type::Bool => ctx.defaults.bool.details,
Type::Char => ctx.defaults.char.details,
Type::Str => ctx.defaults.str.details,
Type::Ratio => ctx.defaults.ratio.details,
Type::Int(IntSize::Bits8) => ctx.defaults.i8.details,
Type::Int(IntSize::Bits16) => ctx.defaults.i16.details,
Type::Int(IntSize::Bits32) => ctx.defaults.i32.details,
Type::Int(IntSize::Bits64) => ctx.defaults.i64.details,
Type::Int(IntSize::Bits128) => ctx.defaults.i128.details,
Type::Int(IntSize::Size) => ctx.defaults.isize.details,
Type::UInt(IntSize::Bits8) => ctx.defaults.u8.details,
Type::UInt(IntSize::Bits16) => ctx.defaults.u16.details,
Type::UInt(IntSize::Bits32) => ctx.defaults.u32.details,
Type::UInt(IntSize::Bits64) => ctx.defaults.u64.details,
Type::UInt(IntSize::Bits128) => ctx.defaults.u128.details,
Type::UInt(IntSize::Size) => ctx.defaults.usize.details,
Type::Float(FloatSize::Bits32) => ctx.defaults.f32.details,
Type::Float(FloatSize::Bits64) => ctx.defaults.f64.details,
Type::Float(FloatSize::Size) => ctx.defaults.fsize.details,
Type::Ref(to) => Details {
size: ctx.defaults.ptr_u8.details.size,
align: ctx.defaults.ptr_u8.details.align,
pointee: Some(to.layout(ctx)),
..Default::default()
}.intern(ctx.interner),
Type::Array(of, len) => {
let of_layout= of.layout(ctx);
Details {
size: of_layout.details.size * len,
align: alignment(of_layout.details.size * len),
idx: Some(of_layout),
..Default::default()
}.intern(ctx.interner)
},
Type::Slice(of) => {
let of_layout = of.layout(ctx);
Details {
size: ctx.defaults.ptr_u8.details.size * 2,
align: ctx.defaults.ptr_u8.details.align * 2,
idx: Some(of_layout),
fields: Box::new([
(0, TyLayout {
ty: Type::Ref(*of).intern(ctx.types),
details: Details {
size: ctx.defaults.ptr_u8.details.size,
align: ctx.defaults.ptr_u8.details.align,
pointee: Some(of_layout),
.. Default::default()
}.intern(ctx.interner)
}),
(ctx.defaults.ptr_u8.details.size, ctx.defaults.usize),
]),
..Default::default()
}.intern(ctx.interner)
},
Type::Vector(of, len) => {
let of_layout= of.layout(ctx);
Details {
size: of_layout.details.size * len,
align: alignment(of_layout.details.size * len),
idx: Some(of_layout),
..Default::default()
}.intern(ctx.interner)
},
Type::Proc(_) => ctx.defaults.proc.details,
Type::Tuple(packed, types) => {
let mut size = 0;
let mut fields = Vec::new();
for ty in types {
let layout = ty.layout(ctx);
if !*packed {
let align = layout.details.align;
while size % align != 0 {
size += 1;
}
}
fields.push((size, layout));
size += layout.details.size;
}
while !pow2(size) {
size += 1;
}
Details {
size,
align: alignment(size),
fields: fields.into_boxed_slice(),
..Default::default()
}.intern(ctx.interner)
},
Type::Union(tagged, types) => {
let mut fields = Vec::new();
let mut size = 0;
for ty in types {
let s = ty.layout(ctx).details.size;
size = usize::max(size, s);
}
if *tagged {
let layout = TyLayout {
ty: Type::Union(false, types.clone()).intern(ctx.types),
details: Details {
size,
align: alignment(size),
..Default::default()
}.intern(ctx.interner)
};
fields.push((0, ctx.defaults.usize));
fields.push((ctx.defaults.usize.details.size, layout));
size += ctx.defaults.usize.details.size;
Details {
size,
align: alignment(size),
fields: fields.into_boxed_slice(),
..Default::default()
}.intern(ctx.interner)
} else {
Details {
size,
align: alignment(size),
..Default::default()
}.intern(ctx.interner)
}
},
Type::Tagged(_tag, _ty) => {
unimplemented!();
},
}
}
}
}
fn pow2(x: usize) -> bool {
(x & (x - 1)) == 0
}
fn alignment(size: usize) -> usize {
if size % 2 == 1 || size == 0 {
return 1;
}
let mut bytes = 1;
loop {
if size % bytes != 0 || bytes > size {
bytes /= 2;
break;
}
bytes *= 2;
};
bytes
}
pub struct LayoutInterner<'t, 'l> {
storage: intern::typed_arena::Arena<Details<'t, 'l>>,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Layout<'t, 'l>(*mut Details<'t, 'l>, ::std::marker::PhantomData<&'l mut Details<'t, 'l>>);
impl<'t, 'l> LayoutInterner<'t, 'l> {
pub fn new() -> LayoutInterner<'t, 'l> {
LayoutInterner {
storage: intern::typed_arena::Arena::new(),
}
}
}
impl<'t, 'l> intern::Intern<'l> for Details<'t, 'l> {
type Key = Layout<'t, 'l>;
fn intern<I: intern::Interner<'l, Self> + 'l>(self, i: &I) -> Layout<'t, 'l> {
i.intern(self)
}
}
impl<'t, 'l> intern::Interner<'l, Details<'t, 'l>> for LayoutInterner<'t, 'l> {
fn intern(&self, value: Details<'t, 'l>) -> Layout<'t, 'l> {
Layout(self.storage.alloc(value), ::std::marker::PhantomData)
}
}
impl<'t, 'l> ::std::default::Default for Layout<'t, 'l> {
fn default() -> Layout<'t, 'l> {
Layout(::std::ptr::null_mut(), ::std::marker::PhantomData)
}
}
impl<'t, 'l> ::std::ops::Deref for Layout<'t, 'l> {
type Target = Details<'t, 'l>;
fn deref(&self) -> &Details<'t, 'l> {
unsafe { &*self.0 }
}
}
impl<'t, 'l> ::std::ops::DerefMut for Layout<'t, 'l> {
fn deref_mut(&mut self) -> &mut Details<'t, 'l> {
unsafe { &mut *self.0 }
}
}
|
mod helloTriangleApplication;
fn main() {
let mut app = helloTriangleApplication::HelloTriangleApplication::init();
app.main_loop();
} |
//! The module implements an HTTP/2 client driven by Tokio's async IO.
//!
//! It exports the `H2Client` struct, which exposes the main client API.
use std::io;
use std::fmt;
use std::error::Error;
use solicit::http::{self as http2, StaticHeader};
mod tokio_layer;
mod client_wrapper;
mod connectors;
mod tls;
pub use self::client_wrapper::H2Client;
/// An enum of errors that can arise due to the Tokio layer becoming out-of-sync from the http2
/// session state.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TokioSyncError {
/// An error that would arise if we got a data chunk from Tokio for a request whose body was
/// previously marked as complete.
DataChunkAfterEndOfBody,
/// An error that would arise if we got a Tokio request with an ID that doesn't have a matching
/// HTTP/2 stream, when one would be expected.
UnmatchedRequestId,
}
impl fmt::Display for TokioSyncError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "TokioSyncError: {}", self.description())
}
}
impl Error for TokioSyncError {
fn description(&self) -> &str {
match *self {
TokioSyncError::DataChunkAfterEndOfBody =>
"received a data chunk for a request previously marked complete",
TokioSyncError::UnmatchedRequestId =>
"received a request id that doesn't have a matching h2 stream",
}
}
}
/// An enum of errors that can be raised by the http/2 Transport/Protocol.
#[derive(Debug)]
pub enum Http2Error {
/// An http/2 protocol error
Protocol(http2::HttpError),
/// An IO error (except WouldBlock)
IoError(io::Error),
/// Errors due to Tokio and the Transport going out of sync.
TokioSync(TokioSyncError),
}
impl fmt::Display for Http2Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"Http2Error::{}: {}",
match *self {
Http2Error::Protocol(_) => "Protocol",
Http2Error::IoError(_) => "IoError",
Http2Error::TokioSync(_) => "TokioSync",
},
self.description())
}
}
impl Error for Http2Error {
fn description(&self) -> &str {
match *self {
Http2Error::Protocol(ref err) => err.description(),
Http2Error::IoError(ref err) => err.description(),
Http2Error::TokioSync(ref err) => err.description(),
}
}
}
impl From<http2::HttpError> for Http2Error {
fn from(err: http2::HttpError) -> Http2Error {
Http2Error::Protocol(err)
}
}
impl From<io::Error> for Http2Error {
fn from(err: io::Error) -> Http2Error {
Http2Error::IoError(err)
}
}
// Tokio needs us to return `io::Error`s from the Transport (and its associated Sink + Stream
// impls). So, we'll use `Http2Error` internally and using this impl finally convert back to
// `io::Error` at the boundary, while still keeping any http2 protocol errors as
// `ErrorKind::Other`.
//
// Hopefully, Tokio will lift this limitation and use something like requiring the used error to
// impl `From<io::Error>` at which point it won't be necessary to wrap/box the http2 error.
impl From<Http2Error> for io::Error {
fn from(err: Http2Error) -> io::Error {
match err {
Http2Error::Protocol(err) => io::Error::new(io::ErrorKind::Other, err),
Http2Error::IoError(err) => err,
Http2Error::TokioSync(err) => io::Error::new(io::ErrorKind::Other, err),
}
}
}
/// A struct representing the headers used to start a new HTTP request.
///
/// Theoretically, this same struct could be used regardless whether the underlying protocol is
/// h2 or h11.
#[derive(Debug)]
pub struct HttpRequestHeaders {
headers: Vec<StaticHeader>,
}
impl HttpRequestHeaders {
pub fn new() -> HttpRequestHeaders {
HttpRequestHeaders {
headers: Vec::new(),
}
}
pub fn with_headers(headers: Vec<StaticHeader>) -> HttpRequestHeaders {
HttpRequestHeaders {
headers: headers,
}
}
}
/// Represents a chunk of the body of an HTTP request.
///
/// Currently requires the chunk to be owned.
#[derive(Debug)]
pub struct HttpRequestBody {
body: Vec<u8>,
}
impl HttpRequestBody {
/// Create a new `HttpRequestBody` that will contain the bytes in the given `Vec`.
pub fn new(body: Vec<u8>) -> HttpRequestBody {
HttpRequestBody {
body: body,
}
}
}
/// The response to an HTTP request.
///
/// Simply carries the response headers.
#[derive(Debug)]
pub struct HttpResponseHeaders {
pub headers: Vec<StaticHeader>,
}
/// A chunk of the response body.
#[derive(Debug)]
pub struct HttpResponseBody {
pub body: Vec<u8>,
}
/// The full response, including both all the headers (including pseudo-headers) and the full body.
#[derive(Debug)]
pub struct HttpResponse {
pub headers: Vec<StaticHeader>,
pub body: Vec<u8>,
}
|
use {
crate::{
demos::{Chunk, Demo},
types::{Hitable, HitableList, Ray, Sphere, Vec3},
Camera,
},
rand::Rng,
};
pub struct SimpleAntialiasing;
impl Demo for SimpleAntialiasing {
fn name(&self) -> &'static str {
"simple-antialiasing"
}
fn world(&self) -> Option<HitableList> {
Some(HitableList {
list: vec![
Box::new(Sphere::new(Vec3::new(0.0, 0.0, -1.0), 0.5)),
Box::new(Sphere::new(Vec3::new(0.0, -100.5, -1.0), 100.0)),
],
})
}
fn render_chunk(
&self,
chunk: &mut Chunk,
camera: Option<&Camera>,
world: Option<&HitableList>,
samples: u8,
) {
let &mut Chunk {
x,
y,
nx,
ny,
start_x,
start_y,
ref mut buffer,
} = chunk;
let camera = camera.unwrap();
let mut rng = rand::thread_rng();
let mut offset = 0;
for j in start_y..start_y + ny {
for i in start_x..start_x + nx {
let mut color = Vec3::new(0.0, 0.0, 0.0);
for _s in 0..samples {
let u = (i as f64 + rng.gen::<f64>()) / x as f64;
let v = (j as f64 + rng.gen::<f64>()) / y as f64;
let r = camera.get_ray(u, v);
color += calc_color(r, world.unwrap());
}
color /= samples as f64;
buffer[offset] = (255.99 * color.r()) as u8;
buffer[offset + 1] = (255.99 * color.g()) as u8;
buffer[offset + 2] = (255.99 * color.b()) as u8;
offset += 4;
}
}
}
}
fn calc_color(ray: Ray, world: &HitableList) -> Vec3 {
if let Some(hit_rec) = world.hit(&ray, 0.0, std::f64::MAX) {
// It's easier to visualise normals as unit vectors
// So, This trick of adding 1 to each dimension and then halving
// the resulting value shifts the normals from -1<->1 range to
// 0<->1 range
Vec3::new(
hit_rec.normal.x() + 1.0,
hit_rec.normal.y() + 1.0,
hit_rec.normal.z() + 1.0,
) * 0.5
} else {
let unit_direction = ray.direction().unit_vector();
let t = unit_direction.y() * 0.5 + 1.0;
Vec3::new(1.0, 1.0, 1.0) * (1.0 - t) + Vec3::new(0.5, 0.7, 1.0) * t
}
}
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::GString;
use glib_sys;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use webkit2_webextension_sys;
use DOMCharacterData;
use DOMEventTarget;
use DOMNode;
use DOMObject;
use DOMStyleSheet;
glib_wrapper! {
pub struct DOMProcessingInstruction(Object<webkit2_webextension_sys::WebKitDOMProcessingInstruction, webkit2_webextension_sys::WebKitDOMProcessingInstructionClass, DOMProcessingInstructionClass>) @extends DOMCharacterData, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
get_type => || webkit2_webextension_sys::webkit_dom_processing_instruction_get_type(),
}
}
pub const NONE_DOM_PROCESSING_INSTRUCTION: Option<&DOMProcessingInstruction> = None;
pub trait DOMProcessingInstructionExt: 'static {
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_sheet(&self) -> Option<DOMStyleSheet>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_target(&self) -> Option<GString>;
fn connect_property_sheet_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_target_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMProcessingInstruction>> DOMProcessingInstructionExt for O {
fn get_sheet(&self) -> Option<DOMStyleSheet> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_processing_instruction_get_sheet(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_target(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_processing_instruction_get_target(
self.as_ref().to_glib_none().0,
),
)
}
}
fn connect_property_sheet_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_sheet_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMProcessingInstruction,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMProcessingInstruction>,
{
let f: &F = &*(f as *const F);
f(&DOMProcessingInstruction::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::sheet\0".as_ptr() as *const _,
Some(transmute(notify_sheet_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_target_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_target_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMProcessingInstruction,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMProcessingInstruction>,
{
let f: &F = &*(f as *const F);
f(&DOMProcessingInstruction::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::target\0".as_ptr() as *const _,
Some(transmute(notify_target_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for DOMProcessingInstruction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMProcessingInstruction")
}
}
|
use crate::utl;
use colored::*;
use std::io::Write;
// note: just a quick direct translation of my C code from the early 90s ;)
/// Classification results
pub struct C12nResults {
model_class_names: Vec<String>,
result: Vec<Vec<i32>>,
confusion: Vec<Vec<i32>>,
// TODO eventually remove some to the above
y_true: Vec<String>,
y_pred: Vec<String>,
}
impl C12nResults {
pub fn new(model_class_names: Vec<String>) -> C12nResults {
let num_models = model_class_names.len();
let result = vec![vec![0i32; num_models + 1]; num_models + 1];
let confusion = vec![vec![0i32; num_models + 1]; num_models + 1];
let y_true = Vec::new();
let y_pred = Vec::new();
C12nResults {
model_class_names,
result,
confusion,
y_true,
y_pred,
}
}
pub fn add_case<F>(
&mut self,
class_id: usize,
seq_classname: &str,
probs: Vec<f64>,
show_ranked: bool,
f: F,
) where
F: FnOnce() -> String,
{
let num_models = self.model_class_names.len();
self.result[num_models][0] += 1_i32;
self.result[class_id][0] += 1_i32;
// sort given probabilities:
let mut probs: Vec<(usize, &f64)> = probs.iter().enumerate().collect();
probs.sort_by(|a, b| a.1.partial_cmp(b.1).unwrap());
let predicted_id = probs[num_models - 1].0;
let correct = class_id == predicted_id;
print!("{}", if correct { "*".green() } else { "_".red() });
std::io::stdout().flush().unwrap();
self.y_true.push(seq_classname.to_string());
let predicted_class_name = &self.model_class_names[predicted_id];
self.y_pred.push(predicted_class_name.to_string());
if show_ranked && !correct {
let header_line = f();
println!("{}", header_line);
for (index, r) in (0..num_models).rev().enumerate() {
let model_id = probs[r].0;
let model_class_name = &self.model_class_names[r];
let mark = if class_id == model_id { "*" } else { "" };
println!(
" [{:>2}] {:1} model: <{:>2}> {:e} : '{}' r={}",
index, mark, model_id, probs[model_id].1, model_class_name, r
);
// only show until corresponding model:
if class_id == model_id {
break;
}
}
println!();
}
self.confusion[class_id][probs[num_models - 1].0] += 1_i32;
// did best candidate correctly classify the instance?
if correct {
self.result[num_models][1] += 1_i32;
self.result[class_id][1] += 1_i32;
} else {
// update order of recognized candidate:
for i in 1..num_models {
if probs[num_models - 1 - i].0 == class_id {
self.result[num_models][i + 1] += 1_i32;
self.result[class_id][i + 1] += 1_i32;
break;
}
}
}
}
pub fn report_results(&mut self, class_names: Vec<&String>, out_base_name: String) {
let num_models = self.model_class_names.len();
// println!("result = {:?}\n", self.result);
// println!("confusion = {:?}\n", self.confusion);
if self.result[num_models][0] == 0 {
return;
}
let mut margin = 0;
for (i, class_name) in class_names.iter().enumerate().take(num_models) {
if self.result[i][0] > 0 {
let len = class_name.len();
if margin < len {
margin = len;
}
}
}
margin += 2;
println!("\n");
print!("{:margin$} ", "", margin = margin);
println!("Confusion matrix:");
print!("{:margin$} ", "", margin = margin);
print!(" ");
for j in 0..num_models {
if self.result[j][0] > 0 {
print!("{:>3} ", j);
}
}
println!(" tests errors");
for (i, class_name) in class_names.iter().enumerate().take(num_models) {
if self.result[i][0] == 0 {
continue;
}
println!();
print!("{:margin$} ", class_name, margin = margin);
print!("{:>3} ", i);
let mut num_errs = 0; // in row
for j in 0..num_models {
if self.result[j][0] > 0 {
print!("{:>3} ", self.confusion[i][j]);
if i != j {
num_errs += self.confusion[i][j];
}
}
}
print!("{:>8}{:>8}", self.result[i][0], num_errs);
}
println!("\n");
print!("{:margin$} ", "", margin = margin);
println!("class accuracy tests candidate order");
let mut num_classes = 0;
let mut summary = Summary {
accuracy: 0_f32,
avg_accuracy: 0_f32,
};
for (class_id, class_name) in class_names.iter().enumerate().take(num_models + 1) {
if self.result[class_id][0] == 0 {
continue;
}
let num_tests = self.result[class_id][0];
let correct_tests = self.result[class_id][1];
let acc = correct_tests as f32 / num_tests as f32;
if class_id < num_models {
num_classes += 1;
summary.avg_accuracy += acc;
print!("{:margin$} ", class_name, margin = margin);
print!(" {:3} ", class_id);
} else {
println!();
print!("{:margin$} ", "", margin = margin);
print!(" TOTAL ");
summary.accuracy = acc;
}
print!(" {:6.2}% {:4} ", 100_f32 * acc, num_tests);
for i in 1..=num_models {
print!("{:4} ", self.result[class_id][i]);
}
println!();
}
summary.accuracy *= 100_f32;
summary.avg_accuracy = summary.avg_accuracy * 100_f32 / num_classes as f32;
println!(" avg_accuracy {:6.2}%", summary.avg_accuracy);
//println!(" error_rate {:6.2}%", 100_f32 - summary.avg_accuracy);
println!();
let out_summary = format!("{}_classification.json", &out_base_name);
utl::save_json(&summary, &out_summary).unwrap();
println!("{} saved", out_summary);
let y_true = &self.y_true;
let y_pred = &self.y_pred;
let true_pred = TruePred {
y_true: y_true.to_vec(),
y_pred: y_pred.to_vec(),
};
let out_true_pred = format!("{}_y_true_pred.json", &out_base_name);
utl::save_json(&true_pred, &out_true_pred).unwrap();
println!("{} saved", out_true_pred);
}
}
#[derive(serde::Serialize)]
struct Summary {
accuracy: f32,
avg_accuracy: f32,
}
// TODO instead, generate a c12n CSV as the HMM C code does.
#[derive(serde::Serialize)]
struct TruePred {
y_true: Vec<String>,
y_pred: Vec<String>,
}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// pretty-expanded FIXME #23616
enum StdioContainer {
CreatePipe(bool)
}
struct Test<'a> {
args: &'a [String],
io: &'a [StdioContainer]
}
pub fn main() {
let test = Test {
args: &[],
io: &[StdioContainer::CreatePipe(true)]
};
}
|
use std::net::SocketAddr;
use serde::{Deserialize, Serialize};
use saoleile_derive::NetworkEvent;
use crate::event::NetworkEvent;
#[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)]
pub struct DisconnectEvent { }
#[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)]
pub struct DroppedNetworkEvent {
pub recipient: SocketAddr,
pub event: Box<dyn NetworkEvent>,
} |
fn main() {
let mut s = String::from("Hello");
change_str(&mut s);
println!("{}", s);
}
fn change_str(some_str: &mut String) {
some_str.push_str(", World!");
}
|
// MinIO Rust Library for Amazon S3 Compatible Cloud Storage
// Copyright 2022 MinIO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::s3::error::Error;
use crate::s3::utils::{to_query_string, Multimap};
use derivative::Derivative;
use hyper::http::Method;
use hyper::Uri;
use std::fmt;
#[derive(Derivative)]
#[derivative(Clone, Debug, Default)]
pub struct Url {
#[derivative(Default(value = "true"))]
pub https: bool,
pub host: String,
pub port: u16,
pub path: String,
pub query: Multimap,
}
impl Url {
pub fn host_header_value(&self) -> String {
if self.port > 0 {
return format!("{}:{}", self.host, self.port);
}
return self.host.clone();
}
}
impl fmt::Display for Url {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.host.is_empty() {
return Err(std::fmt::Error);
}
if self.https {
f.write_str("https://")?;
} else {
f.write_str("http://")?;
}
if self.port > 0 {
f.write_str(format!("{}:{}", self.host, self.port).as_str())?;
} else {
f.write_str(&self.host)?;
}
if !self.path.starts_with("/") {
f.write_str("/")?;
}
f.write_str(&self.path)?;
if !self.query.is_empty() {
f.write_str("?")?;
f.write_str(&to_query_string(&self.query))?;
}
Ok(())
}
}
fn extract_region(host: &str) -> String {
let tokens: Vec<&str> = host.split('.').collect();
let region = match tokens.get(1) {
Some(r) => match *r {
"dualstack" => match tokens.get(2) {
Some(t) => t,
_ => "",
},
"amazonaws" => "",
_ => r,
},
_ => "",
};
return region.to_string();
}
#[derive(Derivative)]
#[derivative(Clone, Debug, Default)]
pub struct BaseUrl {
#[derivative(Default(value = "true"))]
pub https: bool,
host: String,
port: u16,
pub region: String,
pub aws_host: bool,
accelerate_host: bool,
dualstack_host: bool,
virtual_style: bool,
}
impl BaseUrl {
pub fn build_url(
&self,
method: &Method,
region: &String,
query: &Multimap,
bucket_name: Option<&str>,
object_name: Option<&str>,
) -> Result<Url, Error> {
if !object_name.map_or(true, |v| v.is_empty()) {
if bucket_name.map_or(true, |v| v.is_empty()) {
return Err(Error::UrlBuildError(String::from(
"empty bucket name provided for object name",
)));
}
}
let mut url = Url::default();
url.https = self.https;
url.host = self.host.clone();
url.port = self.port;
url.query = query.clone();
if bucket_name.is_none() {
url.path.push_str("/");
if self.aws_host {
url.host = format!("s3.{}.{}", region, self.host);
}
return Ok(url);
}
let bucket = bucket_name.unwrap();
let enforce_path_style = true &&
// CreateBucket API requires path style in Amazon AWS S3.
(method == Method::PUT && object_name.is_none() && query.is_empty()) ||
// GetBucketLocation API requires path style in Amazon AWS S3.
query.contains_key("location") ||
// Use path style for bucket name containing '.' which causes
// SSL certificate validation error.
(bucket.contains('.') && self.https);
if self.aws_host {
let mut s3_domain = "s3.".to_string();
if self.accelerate_host {
if bucket.contains('.') {
return Err(Error::UrlBuildError(String::from(
"bucket name with '.' is not allowed for accelerate endpoint",
)));
}
if !enforce_path_style {
s3_domain = "s3-accelerate.".to_string();
}
}
if self.dualstack_host {
s3_domain.push_str("dualstack.");
}
if enforce_path_style || !self.accelerate_host {
s3_domain.push_str(region);
s3_domain.push_str(".");
}
url.host = s3_domain + &url.host;
}
if enforce_path_style || !self.virtual_style {
url.path.push_str("/");
url.path.push_str(bucket);
} else {
url.host = format!("{}.{}", bucket, url.host);
}
if object_name.is_some() {
if object_name.unwrap().chars().nth(0) != Some('/') {
url.path.push_str("/");
}
// FIXME: urlencode path
url.path.push_str(object_name.unwrap());
}
return Ok(url);
}
pub fn from_string(s: String) -> Result<BaseUrl, Error> {
let url = s.parse::<Uri>()?;
let https = match url.scheme() {
None => true,
Some(scheme) => match scheme.as_str() {
"http" => false,
"https" => true,
_ => {
return Err(Error::InvalidBaseUrl(String::from(
"scheme must be http or https",
)))
}
},
};
let mut host = match url.host() {
Some(h) => h,
_ => {
return Err(Error::InvalidBaseUrl(String::from(
"valid host must be provided",
)))
}
};
let ipv6host = "[".to_string() + host + "]";
if host.parse::<std::net::Ipv6Addr>().is_ok() {
host = &ipv6host;
}
let mut port = match url.port() {
Some(p) => p.as_u16(),
_ => 0u16,
};
if (https && port == 443) || (!https && port == 80) {
port = 0u16;
}
if url.path() != "/" && url.path() != "" {
return Err(Error::InvalidBaseUrl(String::from(
"path must be empty for base URL",
)));
}
if !url.query().is_none() {
return Err(Error::InvalidBaseUrl(String::from(
"query must be none for base URL",
)));
}
let mut accelerate_host = host.starts_with("s3-accelerate.");
let aws_host = (host.starts_with("s3.") || accelerate_host)
&& (host.ends_with(".amazonaws.com") || host.ends_with(".amazonaws.com.cn"));
let virtual_style = aws_host || host.ends_with("aliyuncs.com");
let mut region = String::new();
let mut dualstack_host = false;
if aws_host {
let mut aws_domain = "amazonaws.com";
region = extract_region(host);
let is_aws_china_host = host.ends_with(".cn");
if is_aws_china_host {
aws_domain = "amazonaws.com.cn";
if region.is_empty() {
return Err(Error::InvalidBaseUrl(String::from(
"region must be provided in Amazon S3 China endpoint",
)));
}
}
dualstack_host = host.contains(".dualstack.");
host = aws_domain;
} else {
accelerate_host = false;
}
return Ok(BaseUrl {
https: https,
host: host.to_string(),
port: port,
region: region,
aws_host: aws_host,
accelerate_host: accelerate_host,
dualstack_host: dualstack_host,
virtual_style: virtual_style,
});
}
}
|
mod apis;
mod models;
|
use super::v2;
pub(crate) fn invalid_referenceor<T>(message: String) -> openapiv3::ReferenceOr<T> {
debug_assert!(false, "{}", message);
openapiv3::ReferenceOr::ref_(&message)
}
impl<T> From<v2::Reference> for openapiv3::ReferenceOr<T> {
#[allow(clippy::only_used_in_recursion)]
fn from(v2: v2::Reference) -> Self {
Self::from(&v2)
}
}
impl<T> From<&v2::Reference> for openapiv3::ReferenceOr<T> {
fn from(v2: &v2::Reference) -> Self {
let reference = v2.reference.replace("definitions", "components/schemas");
openapiv3::ReferenceOr::ref_(&reference)
}
}
|
pub struct ApiKeyAuthor(String);
#[derive(Debug)]
pub enum ApiKeyError {
BadCount,
Missing,
Invalid,
}
|
mod question;
use anyhow::Error;
use serde::Deserialize;
// use std::error::Error;
use question::Question;
use wasm_bindgen::prelude::*;
use yew::prelude::*;
use yew::{
format::{Json, Nothing},
prelude::*,
services::fetch::{FetchService, FetchTask, Request, Response},
};
use yew::services::ConsoleService;
#[derive(Deserialize, Debug)]
struct Data {
value: Vec<Insd>,
}
#[derive(Deserialize, Debug)]
struct Insd {
filename: String,
value: String,
}
enum Msg {
Initialize,
FetchResourceComplete(Data),
FetchResourceFailed,
}
struct Model {
// `ComponentLink` is like a reference to a component.
// It can be used to send messages to the component
data: Data,
link: ComponentLink<Self>,
fetch_task: Option<FetchTask>,
}
impl Model {
fn view_data(&self) -> Html {
self.data
.value
.iter()
.enumerate()
.map(|(i, e)| {
html! {
<Question filename=e.filename.clone() value=e.value.replace("\n\n", "\n") />
// <div class="quest">
// <div class="questionno">
// <div class="no">{"Ques "}{e.filename.clone()}{". "}</div>
// </div>
// <div class="question">{e.value.clone()}</div>
// </div>
}
})
.collect::<Html>()
}
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
data: Data { value: Vec::new() },
link,
fetch_task: None,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Initialize => {
let get_request =
Request::get("https://divergent-anonymous.github.io/process/questionlist.json")
.body(Nothing)
.expect("could not build the request");
let callback =
self.link
.callback(|response: Response<Json<Result<Data, Error>>>| {
if let (meta, Json(Ok(body))) = response.into_parts() {
if meta.status.is_success() {
return Msg::FetchResourceComplete(body);
}
} else {
}
Msg::FetchResourceFailed
});
let task = FetchService::fetch(get_request, callback).expect("sdf");
self.fetch_task = Some(task);
true
}
Msg::FetchResourceComplete(e) => {
self.data = e;
true
}
Msg::FetchResourceFailed => true,
_ => true,
}
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
// Should only return "true" if new properties are different to
// previously received properties.
// This component has no properties so we will always return "false".
true
}
fn rendered(&mut self, first_render: bool) {
if first_render {
self.link.send_message(Msg::Initialize);
}
}
fn view(&self) -> Html {
html! {
<div>
<h1>{"Divergent"} </h1>
<ol>
<li>{"Page will only Update in Incognito Mode"}</li>
<li>{"Website have 20sec latency for updates"}</li>
</ol>
<h3>{"Add your answers in SpreedSheet"}</h3>
<a target="_blank" href="https://github.com/divergent-anonymous/divergent-anonymous.github.io/blob/main/process/all.txt">{"To Get Raw Text File (Updates Quickly with in 3 sec) Github Link for file"}</a>
<p></p>
{self.view_data()}
</div>
}
}
}
#[wasm_bindgen(start)]
pub fn run_app() {
App::<Model>::new().mount_to_body();
}
// unsafe {
// get_payload(wasm_bindgen::JsValue::from("asf"), wasm_bindgen::JsValue::from("asf"));
// // get_payload(js_sys::JsString::from("don"), js_sys::JsString::from("don"));
// }
|
use std::collections::HashMap;
use juniper::GraphQLObject;
use serde::Deserialize;
#[derive(Deserialize, Clone)]
pub struct Recipe {
pub name: String,
#[serde(default)]
pub notes: Option<String>,
pub tags: Vec<String>,
#[serde(default)]
pub image: Option<String>,
#[serde(default)]
pub links: Vec<String>,
pub steps: Vec<String>,
pub ingredients: Ingredients,
#[serde(default)]
pub nutrition: Option<Nutrition>,
}
/// A recipe that I've kept around
#[juniper::graphql_object]
impl Recipe {
/// The name of the dish
pub fn name(&self) -> &str {
&self.name
}
/// Tags to quickly sort recipes
pub fn tags(&self) -> &Vec<String> {
&self.tags
}
/// A link to an image of the finished dish
pub fn image(&self) -> &Option<String> {
&self.image
}
/// Links to the original recipe
pub fn links(&self) -> &Vec<String> {
&self.links
}
/// Steps to cook the dish
pub fn steps(&self) -> &Vec<String> {
&self.steps
}
/// The necessary ingredients
pub fn ingredients(&self) -> Vec<IngredientsForComponent> {
match &self.ingredients {
Ingredients::PlainList(ingredients) => vec![IngredientsForComponent {
component: self.name.clone(),
ingredients: ingredients.clone(),
}],
Ingredients::Components(components) => components
.iter()
.map(|(component, ingredients)| IngredientsForComponent {
component: component.clone(),
ingredients: ingredients.clone(),
})
.collect(),
}
}
/// The nutritional info for the recipe
pub fn nutrition(&self) -> &Option<Nutrition> {
&self.nutrition
}
}
#[derive(Deserialize, Clone)]
#[serde(untagged)]
pub enum Ingredients {
PlainList(Vec<Ingredient>),
Components(HashMap<String, Vec<Ingredient>>),
}
/// The ingredients for a component of a recipe
#[derive(Deserialize, GraphQLObject, Clone)]
pub struct IngredientsForComponent {
/// The name of the component
pub component: String,
/// The ingredients for the component
pub ingredients: Vec<Ingredient>,
}
/// An ingredient for a recipe
#[derive(Deserialize, Clone, GraphQLObject)]
pub struct Ingredient {
/// The name of the item
pub item: String,
/// How much of the item is called for
#[serde(default)]
pub quantity: Option<String>,
/// Additional notes about this ingredient
#[serde(default)]
pub notes: Option<String>,
/// Potential substitutes if you don't have this ingredient handy
#[serde(default)]
pub substitutes: Vec<String>,
/// Whether this ingredient is optional
#[serde(default)]
pub optional: bool,
}
/// The nutritional info for a recipe
#[derive(Deserialize, Clone, GraphQLObject)]
pub struct Nutrition {
/// The number of servings it makes
pub servings: Option<i32>,
/// The size of each serving
#[serde(rename = "serving-size")]
pub serving_size: Option<String>,
/// The calories (in grams) in each serving
pub calories: Option<f64>,
/// The fat (in grams) in each serving
pub fat: Option<f64>,
/// The carbohydrates (in grams) in each serving
pub carbs: Option<f64>,
/// The NET carbohydrates (in grams) in each serving
#[serde(rename = "net-carbs")]
pub net_carbs: Option<f64>,
/// The protein (in grams) in each serving
pub protein: Option<f64>,
/// The fiber (in grams) in each serving
pub fiber: Option<f64>,
}
|
//
// shape.rs
//
// Copyright (C) 2019 Malcolm Ramsay <malramsay64@gmail.com>
// Distributed under terms of the MIT license.
//
pub use super::Transform2;
pub mod components;
pub mod line_shape;
pub mod lj_shape;
pub mod molecular_shape2;
pub use components::*;
pub use line_shape::*;
pub use lj_shape::*;
pub use molecular_shape2::*;
|
//! Utilities for importing catalog and data from files
//! MORE COMING SOON: <https://github.com/influxdata/influxdb_iox/issues/7744>
use bytes::Bytes;
use data_types::{
partition_template::{
NamespacePartitionTemplateOverride, TablePartitionTemplateOverride, PARTITION_BY_DAY_PROTO,
},
ColumnSet, ColumnType, CompactionLevel, Namespace, NamespaceName, NamespaceNameError,
ParquetFileParams, Partition, Statistics, Table, TableId, Timestamp,
};
use generated_types::influxdata::iox::catalog::v1 as proto;
// ParquetFile as ProtoParquetFile, Partition as ProtoPartition,
use iox_catalog::interface::{CasFailure, Catalog, RepoCollection, SoftDeletedRows};
use object_store::ObjectStore;
use observability_deps::tracing::{debug, info, warn};
use parquet_file::{
metadata::{DecodedIoxParquetMetaData, IoxMetadata, IoxParquetMetaData},
ParquetFilePath,
};
use std::{
borrow::Cow,
io::Read,
path::{Path, PathBuf},
sync::Arc,
};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("Reading {path:?}: {e}")]
Reading { path: PathBuf, e: std::io::Error },
#[error("Not a directory: {0:?}")]
NotDirectory(PathBuf),
#[error("Error setting sort key: {0}")]
SetSortKey(iox_catalog::interface::Error),
#[error("Error decoding json in {path:?}: {e}")]
Json { path: PathBuf, e: serde_json::Error },
#[error("Parquet Metadata Not Found in {path:?}")]
ParquetMetadataNotFound { path: PathBuf },
#[error("Invalid Parquet Metadata: {0}")]
ParquetMetadata(#[from] parquet_file::metadata::Error),
#[error("Error creating default partition template override: {0}")]
PartitionOveride(#[from] data_types::partition_template::ValidationError),
#[error("Expected timestamp stats to be i64, but got: {stats:?}")]
BadStats { stats: Option<Statistics> },
#[error("Expected timestamp to have both min and max stats, had min={min:?}, max={max:?}")]
NoMinMax { min: Option<i64>, max: Option<i64> },
#[error("Mismatched sort key. Exported sort key is {exported}, existing is {existing}")]
MismatchedSortKey { exported: String, existing: String },
#[error("Unexpected parquet filename. Expected a name like <id>.<partition_id>.parquet, got {path:?}")]
UnexpectedFileName { path: PathBuf },
#[error("Invalid Namespace: {0}")]
NamespaceName(#[from] NamespaceNameError),
#[error(
"Unexpected error: cound not find sort key in catalog export or embedded parquet metadata"
)]
NoSortKey,
#[error("Unknown compaction level in encoded metadata: {0}")]
UnknownCompactionLevel(Box<dyn std::error::Error + std::marker::Send + Sync>),
#[error("Catalog error: {0}")]
Catalog(#[from] iox_catalog::interface::Error),
#[error("Object store error: {0}")]
ObjectStore(#[from] object_store::Error),
}
impl Error {
fn reading(path: impl Into<PathBuf>, e: std::io::Error) -> Self {
let path = path.into();
Self::Reading { path, e }
}
}
type Result<T, E = Error> = std::result::Result<T, E>;
/// Represents the contents of a directory exported using
/// [`RemoteExporter`]. This is a partial catalog snapshot.
///
/// [`RemoteExporter`]: crate::file::RemoteExporter
#[derive(Debug, Default)]
pub struct ExportedContents {
/// .parquet files
parquet_files: Vec<PathBuf>,
/// .parquet.json files (json that correspond to the parquet files)
parquet_json_files: Vec<PathBuf>,
/// table .json files
table_json_files: Vec<PathBuf>,
/// partition .json files
partition_json_files: Vec<PathBuf>,
/// Decoded partition metadata, found in the export
partition_metadata: Vec<proto::Partition>,
/// Decoded parquet metata found in the export
/// Key is object_store_id, value is decoded metadata
parquet_metadata: Vec<proto::ParquetFile>,
}
impl ExportedContents {
/// Read the contents of the directory in `dir_path`, categorizing
/// files in that directory.
pub fn try_new(dir_path: &Path) -> Result<Self> {
info!(?dir_path, "Reading exported catalog contents");
if !dir_path.is_dir() {
return Err(Error::NotDirectory(dir_path.into()));
};
let entries: Vec<_> = dir_path
.read_dir()
.map_err(|e| Error::reading(dir_path, e))?
.flatten()
.collect();
debug!(?entries, "Directory contents");
let mut new_self = Self::default();
for entry in entries {
let path = entry.path();
let extension = if let Some(extension) = path.extension() {
extension
} else {
warn!(?path, "IGNORING file with no extension");
continue;
};
if extension == "parquet" {
// names like "<UUID>.parquet"
new_self.parquet_files.push(path)
} else if extension == "json" {
let name = file_name(&path);
if name.starts_with("table.") {
new_self.table_json_files.push(path);
} else if name.starts_with("partition") {
// names like "partitition.<id>.json"
new_self.partition_json_files.push(path);
} else if name.ends_with(".parquet.json") {
// names like "<UUID>.parquet.json"
new_self.parquet_json_files.push(path);
} else {
warn!(?path, "IGNORING unknown JSON file");
}
} else {
warn!(?path, "IGNORING unknown file");
}
}
new_self.try_decode_files()?;
Ok(new_self)
}
/// tries to decode all the metadata files found in the export
fn try_decode_files(&mut self) -> Result<()> {
debug!("Decoding partition files");
for path in &self.partition_json_files {
debug!(?path, "Reading partition json file");
let json = std::fs::read_to_string(path).map_err(|e| Error::Reading {
path: path.clone(),
e,
})?;
let partition: proto::Partition =
serde_json::from_str(&json).map_err(|e| Error::Json {
path: path.clone(),
e,
})?;
self.partition_metadata.push(partition);
}
for path in &self.parquet_json_files {
debug!(?path, "Reading parquet json file");
let json = std::fs::read_to_string(path).map_err(|e| Error::Reading {
path: path.clone(),
e,
})?;
let parquet_file: proto::ParquetFile =
serde_json::from_str(&json).map_err(|e| Error::Json {
path: path.clone(),
e,
})?;
self.parquet_metadata.push(parquet_file);
}
Ok(())
}
/// Returns the name of the i'th entry in `self.parquet_files`, if
/// any
pub fn parquet_file_name(&self, i: usize) -> Option<Cow<'_, str>> {
self.parquet_files.get(i).map(|p| file_name(p))
}
pub fn parquet_files(&self) -> &[PathBuf] {
self.parquet_files.as_ref()
}
pub fn parquet_json_files(&self) -> &[PathBuf] {
self.parquet_json_files.as_ref()
}
pub fn table_json_files(&self) -> &[PathBuf] {
self.table_json_files.as_ref()
}
pub fn partition_json_files(&self) -> &[PathBuf] {
self.partition_json_files.as_ref()
}
/// Returns partition information retrieved from the exported
/// catalog, if any, with the given table id and partition key
pub fn partition_metadata(
&self,
table_id: i64,
partition_key: &str,
) -> Option<proto::Partition> {
self.partition_metadata
.iter()
.find(|p| p.table_id == table_id && p.key == partition_key)
.cloned()
}
/// Returns parquet file metadata, for the given object_store id, if any
pub fn parquet_metadata(&self, object_store_id: &str) -> Option<proto::ParquetFile> {
self.parquet_metadata
.iter()
.find(|p| p.object_store_id == object_store_id)
.cloned()
}
}
/// Returns the name of the file
fn file_name(p: &Path) -> Cow<'_, str> {
p.file_name()
.map(|p| p.to_string_lossy())
.unwrap_or_else(|| Cow::Borrowed(""))
}
/// Imports the contents of a [`ExportedContents`] into a catalog and
/// object_store instance
#[derive(Debug)]
pub struct RemoteImporter {
exported_contents: ExportedContents,
catalog: Arc<dyn Catalog>,
object_store: Arc<dyn ObjectStore>,
}
impl RemoteImporter {
pub fn new(
exported_contents: ExportedContents,
catalog: Arc<dyn Catalog>,
object_store: Arc<dyn ObjectStore>,
) -> Self {
Self {
exported_contents,
catalog,
object_store,
}
}
/// Performs the import, reporting status to observer and erroring
/// if a failure occurs
pub async fn import(&self) -> Result<()> {
let parquet_files = self.exported_contents.parquet_files();
let total_files = parquet_files.len();
info!(%total_files, "Begin importing files");
for (files_done, file) in parquet_files.iter().enumerate() {
self.import_parquet(file).await?;
// print a log message every 50 files
if files_done % 50 == 0 {
let pct = (files_done as f64 / total_files as f64).floor() * 100.0;
info!(%files_done, %total_files, %pct, "Import running");
}
}
info!(%total_files, "Completed importing files");
Ok(())
}
// tries to import the specified parquet file into the catalog
async fn import_parquet(&self, file_path: &Path) -> Result<()> {
info!(?file_path, "Beginning Import");
// step 1: figure out the location to write the parquet file in object store and do so
let mut in_file =
std::fs::File::open(file_path).map_err(|e| Error::reading(file_path, e))?;
let mut file_bytes = vec![];
in_file
.read_to_end(&mut file_bytes)
.map_err(|e| Error::reading(file_path, e))?;
let bytes = Bytes::from(file_bytes);
let file_size_bytes = bytes.len();
let Some(iox_parquet_metadata) = IoxParquetMetaData::from_file_bytes(bytes.clone())? else {
return Err(Error::ParquetMetadataNotFound {
path: PathBuf::from(file_path)
});
};
let decoded_iox_parquet_metadata = iox_parquet_metadata.decode()?;
let iox_metadata = decoded_iox_parquet_metadata.read_iox_metadata_new()?;
debug!(?iox_metadata, "read metadata");
// step 2: Add the appropriate entry to the catalog
let namespace_name = iox_metadata.namespace_name.as_ref();
let mut repos = self.catalog.repositories().await;
let namespace = repos
.namespaces()
.get_by_name(namespace_name, SoftDeletedRows::ExcludeDeleted)
.await?;
// create it if it doesn't exist
let namespace = match namespace {
Some(namespace) => {
debug!(%namespace_name, "Found existing namespace");
namespace
}
None => {
let namespace_name = NamespaceName::try_from(namespace_name)?;
let partition_template = None;
let retention_period_ns = None;
let service_protection_limits = None;
info!(%namespace_name, "Namespace found, creating new namespace");
repos
.namespaces()
.create(
&namespace_name,
partition_template,
retention_period_ns,
service_protection_limits,
)
.await?
}
};
let table = self
.table_for_parquet_file(repos.as_mut(), &namespace, &iox_metadata)
.await?;
let table_id = table.id;
debug!(%table_id, "Inserting catalog records into table");
let partition = self
.partition_for_parquet_file(repos.as_mut(), &table, &iox_metadata)
.await?;
// Note that for some reason, the object_store_id that is
// actually used in object_storage from the source system is
// different than what is stored in the metadata embedded in
// the parquet file itself. Thus use the object_store_id
// encoded into the parquet file name
let object_store_id =
object_store_id_from_parquet_filename(file_path).ok_or_else(|| {
Error::UnexpectedFileName {
path: file_path.into(),
}
})?;
debug!(partition_id=%partition.id, %object_store_id, "Inserting into partition");
let parquet_metadata = self.exported_contents.parquet_metadata(&object_store_id);
let parquet_params = self
.parquet_file_params(
repos.as_mut(),
&namespace,
&table,
&partition,
parquet_metadata,
&iox_metadata,
&decoded_iox_parquet_metadata,
file_size_bytes,
)
.await?;
let object_store_id = parquet_params.object_store_id;
let parquet_file = repos.parquet_files().create(parquet_params).await;
match parquet_file {
Ok(parquet_file) => {
debug!(parquet_file_id=?parquet_file.id, " Created parquet file entry {}", parquet_file.id);
}
Err(iox_catalog::interface::Error::FileExists { .. }) => {
warn!(%object_store_id, "parquet file already exists, skipping");
}
Err(e) => {
return Err(Error::Catalog(e));
}
};
// Now copy the parquet files into the object store
//let partition_id = TransitionPartitionId::Deprecated(partition.id);
let transition_partition_id = partition.transition_partition_id();
let parquet_path = ParquetFilePath::new(
namespace.id,
table_id,
&transition_partition_id,
object_store_id,
);
let object_store_path = parquet_path.object_store_path();
debug!(?object_store_path, "copying data to object store");
self.object_store.put(&object_store_path, bytes).await?;
info!(?file_path, %namespace_name, %object_store_path, %transition_partition_id, %table_id, "Successfully imported file");
Ok(())
}
/// Return the relevant Catlog [`Table`] for the specified parquet
/// file.
///
/// If the table does not yet exist, it is created, using any
/// available catalog metadata and falling back to what is in the
/// iox metadata if needed
async fn table_for_parquet_file(
&self,
repos: &mut dyn RepoCollection,
namespace: &Namespace,
iox_metadata: &IoxMetadata,
) -> Result<Table> {
let tables = repos.tables();
// Note the export format doesn't currently have any table level information
let table_name = iox_metadata.table_name.as_ref();
if let Some(table) = tables
.get_by_namespace_and_name(namespace.id, table_name)
.await?
{
return Ok(table);
}
// need to make a new table, create the default partitioning scheme...
let partition_template = PARTITION_BY_DAY_PROTO.as_ref().clone();
let namespace_template = NamespacePartitionTemplateOverride::try_from(partition_template)?;
let custom_table_template = None;
let partition_template =
TablePartitionTemplateOverride::try_new(custom_table_template, &namespace_template)?;
let table = tables
.create(table_name, partition_template, namespace.id)
.await?;
Ok(table)
}
/// Return the catalog [`Partition`] into which the specified parquet
/// file shoudl be inserted.
///
/// First attempts to use any available metadata from the
/// catalog export, and falls back to what is in the iox
/// metadata stored in the parquet file, if needed
async fn partition_for_parquet_file(
&self,
repos: &mut dyn RepoCollection,
table: &Table,
iox_metadata: &IoxMetadata,
) -> Result<Partition> {
let partition_key = iox_metadata.partition_key.clone();
let partition = repos
.partitions()
.create_or_get(partition_key.clone(), table.id)
.await?;
// Note we use the table_id embedded in the file's metadata
// from the source catalog to match the exported catlog (which
// is dfferent than the new table we just created in the
// target catalog);
let proto_partition = self
.exported_contents
.partition_metadata(iox_metadata.table_id.get(), partition_key.inner());
let new_sort_key: Vec<&str> = if let Some(proto_partition) = proto_partition.as_ref() {
// Use the sort key from the source catalog
debug!(array_sort_key=?proto_partition.array_sort_key, "Using sort key from catalog export");
proto_partition
.array_sort_key
.iter()
.map(|s| s.as_str())
.collect()
} else {
warn!("Could not find sort key in catalog metadata export, falling back to embedded metadata");
let sort_key = iox_metadata
.sort_key
.as_ref()
.ok_or_else(|| Error::NoSortKey)?;
sort_key.to_columns().collect()
};
if !partition.sort_key.is_empty() && partition.sort_key != new_sort_key {
let exported = new_sort_key.join(",");
let existing = partition.sort_key.join(",");
return Err(Error::MismatchedSortKey { exported, existing });
}
loop {
let res = repos
.partitions()
.cas_sort_key(
&partition.transition_partition_id(),
Some(partition.sort_key.clone()),
&new_sort_key,
)
.await;
match res {
Ok(partition) => return Ok(partition),
Err(CasFailure::ValueMismatch(_)) => {
debug!("Value mismatch when setting sort key, retrying...");
continue;
}
Err(CasFailure::QueryError(e)) => return Err(Error::SetSortKey(e)),
}
}
}
/// Return a [`ParquetFileParams`] (information needed to insert
/// the data into the target catalog).
///
/// First attempts to use any available metadata from the
/// catalog export, and falls back to what is in the iox
/// metadata stored in the parquet file, if needed
#[allow(clippy::too_many_arguments)]
async fn parquet_file_params(
&self,
repos: &mut dyn RepoCollection,
namespace: &Namespace,
table: &Table,
partition: &Partition,
// parquet metadata, if known
parquet_metadata: Option<proto::ParquetFile>,
iox_metadata: &IoxMetadata,
decoded_iox_parquet_metadata: &DecodedIoxParquetMetaData,
file_size_bytes: usize,
) -> Result<ParquetFileParams> {
let object_store_id = iox_metadata.object_store_id;
// need to make columns in the target catalog
let column_set = insert_columns(table.id, decoded_iox_parquet_metadata, repos).await?;
let params = if let Some(proto_parquet_file) = &parquet_metadata {
let compaction_level = proto_parquet_file
.compaction_level
.try_into()
.map_err(Error::UnknownCompactionLevel)?;
ParquetFileParams {
namespace_id: namespace.id,
table_id: table.id,
partition_id: partition.transition_partition_id(),
object_store_id,
min_time: Timestamp::new(proto_parquet_file.min_time),
max_time: Timestamp::new(proto_parquet_file.max_time),
file_size_bytes: proto_parquet_file.file_size_bytes,
row_count: proto_parquet_file.row_count,
compaction_level,
created_at: Timestamp::new(proto_parquet_file.created_at),
column_set,
max_l0_created_at: Timestamp::new(proto_parquet_file.max_l0_created_at),
}
} else {
warn!("Could not read parquet file metadata, reconstructing based on encoded metadata");
let (min_time, max_time) = get_min_max_times(decoded_iox_parquet_metadata)?;
let created_at = Timestamp::new(iox_metadata.creation_timestamp.timestamp_nanos());
ParquetFileParams {
namespace_id: namespace.id,
table_id: table.id,
partition_id: partition.transition_partition_id(),
object_store_id,
min_time,
max_time,
// use unwrap: if we can't fit the file size or row
// counts into usize, something is very wrong and we
// should stop immediately (and get an exact stack trace)
file_size_bytes: file_size_bytes.try_into().unwrap(),
row_count: decoded_iox_parquet_metadata.row_count().try_into().unwrap(),
//compaction_level: CompactionLevel::Final,
compaction_level: CompactionLevel::Initial,
created_at,
column_set,
max_l0_created_at: created_at,
}
};
debug!(?params, "Created ParquetFileParams");
Ok(params)
}
}
/// Returns a `ColumnSet` that represents all the columns specified in
/// `decoded_iox_parquet_metadata`.
///
/// Insert the appropriate column entries in the catalog they are not
/// already present.
async fn insert_columns(
table_id: TableId,
decoded_iox_parquet_metadata: &DecodedIoxParquetMetaData,
repos: &mut dyn RepoCollection,
) -> Result<ColumnSet> {
let schema = decoded_iox_parquet_metadata.read_schema()?;
let mut column_ids = vec![];
for (iox_column_type, field) in schema.iter() {
let column_name = field.name();
let column_type = ColumnType::from(iox_column_type);
let column = repos
.columns()
.create_or_get(column_name, table_id, column_type)
.await?;
column_ids.push(column.id);
}
Ok(ColumnSet::new(column_ids))
}
/// Reads out the min and max value for the decoded_iox_parquet_metadata column
fn get_min_max_times(
decoded_iox_parquet_metadata: &DecodedIoxParquetMetaData,
) -> Result<(Timestamp, Timestamp)> {
let schema = decoded_iox_parquet_metadata.read_schema()?;
let stats = decoded_iox_parquet_metadata.read_statistics(&schema)?;
let Some(summary) = stats
.iter()
.find(|s| s.name == schema::TIME_COLUMN_NAME) else {
return Err(Error::BadStats { stats: None });
};
let Statistics::I64(stats) = &summary.stats else {
return Err(Error::BadStats { stats: Some(summary.stats.clone()) });
};
let (Some(min), Some(max)) = (stats.min, stats.max) else {
return Err(Error::NoMinMax {
min: stats.min,
max: stats.max,
})
};
Ok((Timestamp::new(min), Timestamp::new(max)))
}
/// Given a filename of the store parquet metadata, returns the object_store_id
///
/// For example, `e65790df-3e42-0094-048f-0b69a7ee402c.13180488.parquet`,
/// returns `e65790df-3e42-0094-048f-0b69a7ee402c`
///
/// For some reason the object store id embedded in the parquet file's
/// [`IoxMetadata`] and the of the actual file in object storage are
/// different, so we need to use the object_store_id actually used in
/// the source system, which is embedded in the filename
fn object_store_id_from_parquet_filename(path: &Path) -> Option<String> {
let stem = path
// <uuid>.partition_id.parquet --> <uuid>.partition_id
.file_stem()?
.to_string_lossy();
// <uuid>.partition_id --> (<uuid>, partition_id)
let (object_store_id, _partition_id) = stem.split_once('.')?;
Some(object_store_id.to_string())
}
|
use std::collections::HashSet;
use juniper::FieldResult;
use super::context::Context;
use crate::error::Error;
use crate::recipe::Recipe;
use crate::review::Review;
pub struct Query;
#[juniper::graphql_object(context = Context)]
impl Query {
/// Find a recipe by name
pub fn recipe(name: String, context: &Context) -> FieldResult<&Recipe> {
context
.recipes
.iter()
.find(|recipe| recipe.name == name)
.ok_or_else(|| Error::NoRecipeNamed(name).into())
}
/// List all recipes with one of the given tags. If no tags are given, returns all recipes.
pub fn recipes(tags: Option<Vec<String>>, context: &Context) -> Vec<&Recipe> {
let tags = tags.unwrap_or_default();
context
.recipes
.iter()
.filter(|recipe| tags.is_empty() || tags.iter().any(|tag| recipe.tags.contains(tag)))
.collect()
}
/// List all tags found in any recipe
pub fn recipe_tags(context: &Context) -> Vec<&String> {
let all_tags: HashSet<&String> = context
.recipes
.iter()
.flat_map(|recipe| &recipe.tags)
.collect();
let mut tag_list: Vec<&String> = all_tags.into_iter().collect();
tag_list.sort();
tag_list
}
/// Find a review by movie title (and optionally the year)
pub fn review(title: String, year: Option<i32>, context: &Context) -> FieldResult<Review> {
let mut reviews = context
.reviews
.iter()
.filter(|review| {
review.title == title
&& year
.map(|y| review.year.map(|rt| rt == y).unwrap_or(false))
.unwrap_or(true)
})
.peekable();
match reviews.next() {
None => Err(Error::NoReviewTitled(title).into()),
Some(review) => {
if reviews.peek().is_none() {
Ok(review.clone())
} else {
let mut years = reviews
.flat_map(|r| r.year.clone())
.chain(review.year)
.collect::<Vec<i32>>();
years.sort();
Err(Error::MultipleMoviesTitled { title, years }.into())
}
}
}
}
/// List all movie reviews
pub fn reviews(context: &Context) -> &Vec<Review> {
&context.reviews
}
/// List all movies with no review yet
pub fn unreviewed_films(context: &Context) -> Vec<&Review> {
context
.reviews
.iter()
.filter(|review| review.rating.is_none() && review.review.is_none())
.collect()
}
}
|
pub struct Solution;
impl Solution {
pub fn is_self_crossing(x: Vec<i32>) -> bool {
if x.len() < 4 {
return false;
}
let mut i = 3;
let mut x0 = 0;
let mut x1 = 0;
let mut x2 = x[0] as i64;
let mut x3 = x[1] as i64;
let mut x4 = x[2] as i64;
let mut x5 = x[3] as i64;
loop {
if x2 >= x4 && x3 <= x5 {
return true;
}
if x0 + x4 >= x2 && x1 + x5 >= x3 && x2 >= x4 && x1 <= x3 {
return true;
}
i += 1;
if i == x.len() {
return false;
}
x0 = x1;
x1 = x2;
x2 = x3;
x3 = x4;
x4 = x5;
x5 = x[i] as i64;
}
}
}
#[test]
fn test0335() {
fn case(x: Vec<i32>, want: bool) {
let got = Solution::is_self_crossing(x);
assert_eq!(got, want);
}
case(vec![2, 1, 1, 2], true);
case(vec![1, 2, 3, 4], false);
case(vec![1, 1, 1, 1], true);
case(vec![1, 1, 2, 1, 1], true);
}
|
use join::Join;
use proconio::input;
fn main() {
input! {
n: usize,
};
let mut x = Vec::new();
if n % 4 > 0 {
x.push(n % 4);
}
x.extend(vec![4; n / 4]);
let m = x.iter().map(|d| d * 2).sum::<usize>();
println!("{}", m);
println!("{}", x.iter().join(""));
}
|
use crate::{
core::{
color::Color,
visitor::{
Visit,
Visitor,
VisitResult
}
},
scene::base::{
BaseBuilder,
Base,
AsBase
}
};
#[derive(Clone)]
pub struct SpotLight {
hotspot_cone_angle: f32,
falloff_angle_delta: f32,
distance: f32,
}
impl Default for SpotLight {
fn default() -> Self {
Self {
hotspot_cone_angle: 90.0f32.to_radians(),
falloff_angle_delta: 5.0f32.to_radians(),
distance: 10.0
}
}
}
impl SpotLight {
pub fn new(distance: f32, hotspot_cone_angle: f32, falloff_angle_delta: f32) -> Self {
Self {
hotspot_cone_angle: hotspot_cone_angle.abs(),
falloff_angle_delta: falloff_angle_delta.abs(),
distance
}
}
#[inline]
pub fn hotspot_cone_angle(&self) -> f32 {
self.hotspot_cone_angle
}
#[inline]
pub fn set_hotspot_cone_angle(&mut self, cone_angle: f32) -> &mut Self {
self.hotspot_cone_angle = cone_angle.abs();
self
}
#[inline]
pub fn set_falloff_angle_delta(&mut self, delta: f32) -> &mut Self {
self.falloff_angle_delta = delta;
self
}
#[inline]
pub fn falloff_angle_delta(&self) -> f32 {
self.falloff_angle_delta
}
#[inline]
pub fn full_cone_angle(&self) -> f32 {
self.hotspot_cone_angle + self.falloff_angle_delta
}
#[inline]
pub fn set_distance(&mut self, distance: f32) -> &mut Self {
self.distance = distance.abs();
self
}
#[inline]
pub fn distance(&self) -> f32 {
self.distance
}
}
impl Visit for SpotLight {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
self.hotspot_cone_angle.visit("HotspotConeAngle", visitor)?;
self.falloff_angle_delta.visit("FalloffAngleDelta", visitor)?;
self.distance.visit("Distance", visitor)?;
visitor.leave_region()
}
}
#[derive(Clone)]
pub struct PointLight {
radius: f32
}
impl PointLight {
pub fn new(radius: f32) -> Self {
Self {
radius
}
}
#[inline]
pub fn set_radius(&mut self, radius: f32) {
self.radius = radius.abs();
}
#[inline]
pub fn get_radius(&self) -> f32 {
self.radius
}
}
impl Visit for PointLight {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
self.radius.visit("Radius", visitor)?;
visitor.leave_region()
}
}
impl Default for PointLight {
fn default() -> Self {
Self {
radius: 10.0
}
}
}
#[derive(Clone)]
pub enum LightKind {
Spot(SpotLight),
Point(PointLight),
}
impl LightKind {
pub fn new(id: u32) -> Result<Self, String> {
match id {
0 => Ok(LightKind::Spot(Default::default())),
1 => Ok(LightKind::Point(Default::default())),
_ => Err(format!("Invalid light kind {}", id))
}
}
pub fn id(&self) -> u32 {
match self {
LightKind::Spot(_) => 0,
LightKind::Point(_) => 1,
}
}
}
impl Visit for LightKind {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
match self {
LightKind::Spot(spot_light) => spot_light.visit(name, visitor),
LightKind::Point(point_light) => point_light.visit(name, visitor),
}
}
}
#[derive(Clone)]
pub struct Light {
base: Base,
kind: LightKind,
color: Color,
cast_shadows: bool,
}
impl AsBase for Light {
fn base(&self) -> &Base {
&self.base
}
fn base_mut(&mut self) -> &mut Base {
&mut self.base
}
}
impl Default for Light {
fn default() -> Self {
Self {
base: Default::default(),
kind: LightKind::Point(Default::default()),
color: Color::WHITE,
cast_shadows: true,
}
}
}
impl Visit for Light {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
let mut kind_id = self.kind.id();
kind_id.visit("KindId", visitor)?;
if visitor.is_reading() {
self.kind = LightKind::new(kind_id)?;
}
self.kind.visit("Kind", visitor)?;
self.color.visit("Color", visitor)?;
self.base.visit("Base", visitor)?;
self.cast_shadows.visit("CastShadows", visitor)?;
visitor.leave_region()
}
}
impl Light {
pub fn new(kind: LightKind) -> Self {
Self {
kind,
.. Default::default()
}
}
#[inline]
pub fn set_color(&mut self, color: Color) {
self.color = color;
}
#[inline]
pub fn get_color(&self) -> Color {
self.color
}
#[inline]
pub fn get_kind(&self) -> &LightKind {
&self.kind
}
#[inline]
pub fn get_kind_mut(&mut self) -> &mut LightKind {
&mut self.kind
}
}
pub struct LightBuilder {
base_builder: BaseBuilder,
kind: LightKind,
color: Color,
cast_shadows: bool,
}
impl LightBuilder {
pub fn new(kind: LightKind, base_builder: BaseBuilder) -> Self {
Self {
base_builder,
kind,
color: Color::WHITE,
cast_shadows: true,
}
}
pub fn with_color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn cast_shadows(mut self, cast_shadows: bool) -> Self {
self.cast_shadows = cast_shadows;
self
}
pub fn build(self) -> Light {
Light {
base: self.base_builder.build(),
kind: self.kind,
color: self.color,
cast_shadows: self.cast_shadows
}
}
} |
use crate::{DocBase, VarType};
const DESCRIPTION: &'static str = r#"
Stochastic. It is calculated by a formula: `100 * (close - lowest(low, length)) / (highest(high, length) - lowest(low, length))`
"#;
const ARGUMENT: &'static str = r#"
**source (series)** Source series.
**high (series)** Series of high.
**low (series)** Series of low.
**length (integer)** Length (number of bars back).
"#;
pub fn gen_doc() -> Vec<DocBase> {
let fn_doc = DocBase {
var_type: VarType::Function,
name: "stoch",
signatures: vec![],
description: DESCRIPTION,
example: "",
returns: "Stochastic.",
arguments: ARGUMENT,
remarks: "",
links: "",
};
vec![fn_doc]
}
|
use super::Root;
pub struct Provider {
root: &Root
}
impl Provider {
pub fn new(root: &Root) -> Provider {
Provider {
root: root
}
}
}
|
#![deny(clippy::all)]
#![warn(clippy::pedantic)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::module_name_repetitions)]
#[macro_use]
extern crate assert_float_eq;
pub mod matrix;
mod number_traits;
pub mod quaternion;
pub mod vector;
|
use criterion::{black_box, criterion_group, criterion_main, Benchmark, BenchmarkId, Criterion};
use serde_json::Value;
use std::{collections::HashMap, fs, io::Read, path::Path};
use vector::{
transforms::{wasm::Wasm, Transform},
Event,
};
fn parse_event_artifact(path: impl AsRef<Path>) -> vector::Result<Event> {
let mut event = Event::new_empty_log();
let mut test_file = fs::File::open(path)?;
let mut buf = String::new();
test_file.read_to_string(&mut buf)?;
let test_json: HashMap<String, Value> = serde_json::from_str(&buf)?;
for (key, value) in test_json {
event.as_mut_log().insert(key, value.clone());
}
Ok(event)
}
pub fn protobuf(c: &mut Criterion) {
let input = parse_event_artifact("tests/data/wasm/protobuf/demo.json").unwrap();
let cloned_input = input.clone();
c.bench(
"wasm/protobuf",
Benchmark::new("wasm", move |b| {
let input = cloned_input.clone();
let mut transform = Wasm::new(
toml::from_str(
r#"
module = "target/wasm32-wasi/release/protobuf.wasm"
artifact_cache = "target/artifacts/"
"#,
)
.unwrap(),
)
.unwrap();
b.iter_with_setup(
|| input.clone(),
|input| {
let output = transform.transform(input);
black_box(output)
},
)
}),
);
}
pub fn drop(criterion: &mut Criterion) {
let transforms: Vec<(&str, Box<dyn Transform>)> = vec![
(
"lua",
Box::new(
vector::transforms::lua::v2::Lua::new(
&toml::from_str(
r#"
hooks.process = """
function (event, emit)
end
"""
"#,
)
.unwrap(),
)
.unwrap(),
),
),
(
"wasm",
Box::new(
Wasm::new(
toml::from_str(
r#"
module = "target/wasm32-wasi/release/drop.wasm"
artifact_cache = "target/artifacts/"
"#,
)
.unwrap(),
)
.unwrap(),
),
),
];
let parameters = vec![0, 2, 8, 16];
bench_group_transforms_over_parameterized_event_sizes(
criterion,
"wasm/drop",
transforms,
parameters,
);
}
pub fn add_fields(criterion: &mut Criterion) {
let transforms: Vec<(&str, Box<dyn Transform>)> = vec![
(
"lua",
Box::new(
vector::transforms::lua::v2::Lua::new(
&toml::from_str(
r#"
hooks.process = """
function (event, emit)
event.log.test_key = "test_value"
event.log.test_key2 = "test_value2"
emit(event)
end
"""
"#,
)
.unwrap(),
)
.unwrap(),
),
),
(
"wasm",
Box::new(
Wasm::new(
toml::from_str(
r#"
module = "target/wasm32-wasi/release/add_fields.wasm"
artifact_cache = "target/artifacts/"
"#,
)
.unwrap(),
)
.unwrap(),
),
),
(
"native",
Box::new({
let mut fields = indexmap::IndexMap::default();
fields.insert("test_key".into(), "test_value".into());
fields.insert("test_key2".into(), "test_value2".into());
vector::transforms::add_fields::AddFields::new(fields, false)
}),
),
];
let parameters = vec![0, 2, 8, 16];
bench_group_transforms_over_parameterized_event_sizes(
criterion,
"wasm/add_fields",
transforms,
parameters,
);
}
fn bench_group_transforms_over_parameterized_event_sizes(
criterion: &mut Criterion,
group: &str,
transforms: Vec<(&str, Box<dyn Transform>)>,
parameters: Vec<usize>,
) {
let mut group = criterion.benchmark_group(group);
for (name, mut transform) in transforms {
for ¶meter in ¶meters {
let mut input = Event::new_empty_log();
for key in 0..parameter {
input
.as_mut_log()
.insert(format!("key-{}", key), format!("value-{}", key));
}
let id = BenchmarkId::new(name.clone(), parameter);
group.bench_with_input(id, &input, |bencher, input| {
bencher.iter_with_setup(
|| input.clone(),
|input| {
let output = transform.transform(input);
black_box(output)
},
)
});
}
}
group.finish();
}
criterion_group!(wasm, protobuf, drop, add_fields);
criterion_main!(wasm);
|
use crate::lexer::*;
/// `'` *single_quoted_string_character** `'`
pub(crate) fn single_quoted_string(i: Input) -> StringResult {
let (i, _) = char('\'')(i)?;
let (i, contents) = many0(single_quoted_string_character)(i)?;
let (i, _) = char('\'')(i)?;
let mut string = String::new();
for s in contents {
string.push_str(&s);
}
Ok((i, string))
}
/// *single_quoted_string_non_escaped_character* | *single_quoted_escape_sequence*
pub(crate) fn single_quoted_string_character(i: Input) -> StringResult {
alt((
map(single_quoted_string_non_escaped_character, |char| {
char.to_string()
}),
single_quoted_escape_sequence,
))(i)
}
/// *single_escape_character_sequence* | *single_quoted_string_non_escaped_character_sequence*
pub(crate) fn single_quoted_escape_sequence(i: Input) -> StringResult {
alt((
single_escape_character_sequence,
single_quoted_string_non_escaped_character_sequence,
))(i)
}
/// `\` *single_quoted_string_meta_character*
pub(crate) fn single_escape_character_sequence(i: Input) -> StringResult {
let (i, _) = char('\\')(i)?;
let (i, char) = single_quoted_string_meta_character(i)?;
Ok((i, char.to_string()))
}
/// `\` *single_quoted_string_non_escaped_character*
pub(crate) fn single_quoted_string_non_escaped_character_sequence(i: Input) -> StringResult {
let (i, char1) = char('\\')(i)?;
let (i, char2) = single_quoted_string_non_escaped_character(i)?;
Ok((i, string_from_2_chars(char1, char2)))
}
/// `'` | `\`
pub(crate) fn single_quoted_string_meta_character(i: Input) -> CharResult {
one_of("'\\")(i)
}
/// *source_character* **but not** *single_quoted_string_meta_character*
pub(crate) fn single_quoted_string_non_escaped_character(i: Input) -> CharResult {
none_of("'\\")(i)
}
/// Constructs a string from two characters
fn string_from_2_chars(c1: char, c2: char) -> String {
let mut string = String::with_capacity(c1.len_utf8() + c2.len_utf8());
string.push(c1);
string.push(c2);
string
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_single_quoted_string_non_escaped_character_sequence() {
use_parser!(single_quoted_string_non_escaped_character_sequence);
// Parse errors
assert_err!("");
assert_err!("\\");
assert_err!("\\\\");
assert_err!("\\'");
assert_err!("foo");
// Success cases
assert_ok!("\\1", "\\1".to_owned());
assert_ok!("\\a", "\\a".to_owned());
assert_ok!("\\東", "\\東".to_owned()); // U+6771: 'CJK Unified Ideograph-6771' "East"
}
#[test]
fn test_single_escape_character_sequence() {
use_parser!(single_escape_character_sequence);
// Parse errors
assert_err!("");
assert_err!("\\");
assert_err!("\\1");
assert_err!("\\a");
assert_err!("foo");
// Success cases
assert_ok!("\\'", "'".to_owned());
assert_ok!("\\\\", "\\".to_owned());
}
#[test]
fn test_single_quoted_string() {
use_parser!(single_quoted_string);
fn t(i: &str) -> String {
i.to_owned()
}
// Parse errors
assert_err!("");
assert_err!("\\''");
assert_err!("'\\\\''");
assert_err!("foo");
assert_err!("'");
assert_err!("'''");
assert_err!("'foo");
// Success cases
assert_ok!("''");
assert_ok!("'\\''");
assert_ok!("'This is a normal string.'", t("This is a normal string."));
assert_ok!(
"'Here\\'s \\a \"handful\" of chars: \\\\ \n \0 東 é é.'",
t("Here's \\a \"handful\" of chars: \\ \n \0 東 é é.")
);
// Semantics
assert_ok!("'\\a\\'\\\\'", t("\\a'\\"));
// Positioning
assert_eq!(
single_quoted_string("'One\nTwo\nThree'".into()),
Ok((Input::new_with_pos("", 15, 3, 7), t("One\nTwo\nThree")))
);
assert_eq!(
single_quoted_string("''".into()),
Ok((Input::new_with_pos("", 2, 1, 3), t("")))
);
assert_eq!(
single_quoted_string("'\n'".into()),
Ok((Input::new_with_pos("", 3, 2, 2), t("\n")))
);
}
}
|
use clap::{App, Arg};
use env_logger;
use pickup::printer::Printer;
use pickup::reader::Reader;
use pickup::storage::FileStorage;
use pickup::{Pickup, PickupOpts};
use std::io;
fn main() -> io::Result<()> {
env_logger::init();
let stdio = io::stdin();
let stdin = stdio.lock();
let stdout = io::stdout();
let mut pickup = Pickup::new(Reader::new(stdin), Printer::new(stdout), FileStorage::new());
if !pickup.storage.config_dir_exists() {
println!(
"Configuration directory was not found. Creating one at {}",
pickup.storage.config_dir_path()?
);
pickup.storage.create_config_dir()?;
}
if !pickup.storage.items_file_exists() {
println!(
"Storage file not found. Creating one at {}",
pickup.storage.json_file_path()?
);
pickup.storage.create_items_file()?;
}
let matches = App::new("Pickup")
.version("0.1")
.author("Aaron Burdick")
.about("Helps you remember to pick things up")
.arg(
Arg::with_name("list")
.short("l")
.long("ls")
.help("List all the things you need to pickup"),
)
.arg(
Arg::with_name("show item")
.short("s")
.long("show")
.takes_value(true)
.help("Show an item from your list"),
)
.arg(
Arg::with_name("remove item")
.short("r")
.long("remove")
.takes_value(true)
.help("Remove an item from your list"),
)
.arg(
Arg::with_name("add item")
.short("a")
.long("add")
.takes_value(true)
.help("Add something you need to pickup"),
)
.get_matches();
let opts = PickupOpts {
list_items: matches.index_of("list").is_some(),
show_item: (
matches.index_of("show item").is_some(),
matches
.value_of("show item")
.map_or(0, |val| val.parse::<usize>().unwrap()),
),
remove_item: (
matches.index_of("show item").is_some(),
matches
.value_of("remove item")
.map_or(0, |val| val.parse::<usize>().unwrap()),
),
add_item: (
matches.index_of("add item").is_some(),
matches
.value_of("add item")
.map_or(String::new(), String::from),
),
};
pickup.run(opts)?;
Ok(())
}
|
use yew::prelude::*;
use yew_router::components::RouterAnchor;
use crate::app::AppRoute;
pub struct SsoHome {}
pub enum Msg {}
impl Component for SsoHome {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
SsoHome {}
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
type Anchor = RouterAnchor<AppRoute>;
html! {
<>
<div class="col py-3">
<div>
<div class="mx-auto pt-5 pb-5 px-4" style="max-width: 1048px;">
<div class="mb-5">
<div class="d-flex flex-row mb-3">
<div class="flex-fill fs-3 fw-bold">
{"Single Sign On"}
</div>
</div>
<div style=" display: flex;
text-align: center;
align-items: center;
flex-direction: column;
margin-top: 60px;
padding: 40px;
border-radius: 6px;
border: 1px solid #e3e4e6;">
<img width="150" height=""
src="https://assets-global.website-files.com/60058af53d79fbd8e14841ea/602e971e34a1e12c00b8c9ab_sso.svg"
/>
<h4
style="padding-top: 20px;"
>
{"You don't have any SSO integrations yet."}
</h4>
<div>
<p>{"SSO enables users to authenticate at Auth0 with one set of credentials to
access
any number of service provider applications."}</p>
</div>
<button
style=" color: #fff;
background-color: #635dff;
box-shadow: none;
border-radius: 4px;
padding: 8px 16px;
margin: 20px"
>
<Anchor
route=AppRoute::CreateSso
classes="text-decoration-none text-light px-2 link-primary pe-auto"
>
{"+ Create SSO Integration"}
</Anchor>
</button>
<a href="https://auth0.com/docs/sso/single-sign-on" target="_blank">{"Learn More"}</a>
</div>
</div>
</div>
</div>
</div>
</>
}
}
}
|
use crate::{id, proof, Result};
use chrono::{self, prelude::*};
use crev_common::{
self,
serde::{as_rfc3339_fixed, from_rfc3339_fixed},
};
use serde_yaml;
use std::{default::Default, fmt};
const BEGIN_BLOCK: &str = "-----BEGIN CREV PROJECT REVIEW-----";
const BEGIN_SIGNATURE: &str = "-----BEGIN CREV PROJECT REVIEW SIGNATURE-----";
const END_BLOCK: &str = "-----END CREV PROJECT REVIEW-----";
/// Body of a Project Review Proof
#[derive(Clone, Builder, Debug, Serialize, Deserialize)]
// TODO: validate setters(no newlines, etc)
// TODO: https://github.com/colin-kiegel/rust-derive-builder/issues/136
/// Unsigned proof of code review
pub struct Project {
#[builder(default = "crate::current_version()")]
version: i64,
#[builder(default = "crev_common::now()")]
#[serde(
serialize_with = "as_rfc3339_fixed",
deserialize_with = "from_rfc3339_fixed"
)]
date: chrono::DateTime<FixedOffset>,
pub from: crate::PubId,
#[serde(rename = "project")]
pub project: proof::ProjectInfo,
#[builder(default = "Default::default()")]
review: super::Score,
#[serde(skip_serializing_if = "String::is_empty", default = "Default::default")]
#[builder(default = "Default::default()")]
comment: String,
}
/// Like `Project` but serializes for interactive editing
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProjectDraft {
#[serde(skip_serializing, default = "crate::current_version")]
version: i64,
#[serde(
serialize_with = "as_rfc3339_fixed",
deserialize_with = "from_rfc3339_fixed"
)]
date: chrono::DateTime<FixedOffset>,
pub from: crate::PubId,
#[serde(rename = "project")]
pub project: proof::ProjectInfo,
review: super::Score,
#[serde(default = "Default::default")]
comment: String,
}
impl From<Project> for ProjectDraft {
fn from(project: Project) -> Self {
ProjectDraft {
version: project.version,
date: project.date,
from: project.from,
project: project.project,
review: project.review,
comment: project.comment,
}
}
}
impl From<ProjectDraft> for Project {
fn from(project: ProjectDraft) -> Self {
Project {
version: project.version,
date: project.date,
from: project.from,
project: project.project,
review: project.review,
comment: project.comment,
}
}
}
impl Project {
pub(crate) const BEGIN_BLOCK: &'static str = BEGIN_BLOCK;
pub(crate) const BEGIN_SIGNATURE: &'static str = BEGIN_SIGNATURE;
pub(crate) const END_BLOCK: &'static str = END_BLOCK;
}
impl proof::ContentCommon for Project {
fn date(&self) -> &chrono::DateTime<FixedOffset> {
&self.date
}
fn author(&self) -> &crate::PubId {
&self.from
}
}
impl super::Common for Project {
fn score(&self) -> &super::Score {
&self.review
}
}
impl Project {
pub fn parse(s: &str) -> Result<Self> {
Ok(serde_yaml::from_str(&s)?)
}
pub fn sign_by(self, id: &id::OwnId) -> Result<proof::Proof> {
proof::Content::from(self).sign_by(id)
}
}
impl ProjectDraft {
pub fn parse(s: &str) -> Result<Self> {
Ok(serde_yaml::from_str(&s)?)
}
}
impl fmt::Display for Project {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
crev_common::serde::write_as_headerless_yaml(self, f)
}
}
impl fmt::Display for ProjectDraft {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
crev_common::serde::write_as_headerless_yaml(self, f)
}
}
|
pub mod client_dao;
pub mod user_dao; |
#[macro_use] extern crate clap;
use std::{ io, ffi, process };
const STATUS_ERROR: i32 = 1;
const ERROR_NO_COMMAND: &'static str = "You must supply a command argument";
fn make_command<It: Iterator<Item = S>, S: AsRef<ffi::OsStr>>(mut args: It) -> process::Command {
let mut cmd = process::Command::new(args.next().expect(ERROR_NO_COMMAND));
args.fold(&mut cmd, |c, a| {
let os_arg: &ffi::OsStr = a.as_ref();
c.arg(os_arg)
}).stdin(process::Stdio::piped()).stdout(process::Stdio::inherit());
cmd
}
fn exit_status_result(status: &process::ExitStatus) -> Result<(), String> {
if status.success() {
Ok(())
} else {
let message = match status.code() {
Some(code) => format!("Child process exited with code: {}", code),
None => format!("Child process terminated by signal"),
};
Err(message)
}
}
fn main() {
use io::{ BufRead, Write };
let matches = clap::App::new(option_env!("CARGO_PKG_NAME").unwrap_or("eachline"))
.author(crate_authors!("\n"))
.version(option_env!("CARGO_PKG_VERSION").unwrap_or(""))
.about("stdin line shuffling utility")
.arg(clap::Arg::with_name("newlines")
.short("n")
.long("newlines")
.help("Print newlines after each child process's output")
.takes_value(false))
.arg(clap::Arg::with_name("verbose")
.short("v")
.long("verbose")
.help("Print verbose output")
.takes_value(false))
.arg(clap::Arg::with_name("command")
.multiple(true)
.required(true)
.last(true))
.get_matches();
let stdin = io::stdin();
let mut exit_statuses = stdin.lock().lines().map(|line| line.unwrap()).map(|line| {
let line = line.as_bytes();
let mut command = make_command(matches.values_of("command").expect(ERROR_NO_COMMAND));
let mut child = command.spawn().unwrap();
child.stdin.as_mut().unwrap().write_all(line).unwrap();
let status = exit_status_result(&child.wait().unwrap());
if matches.is_present("newlines") {
println!("");
}
if matches.is_present("verbose") {
if let Err(ref err) = status {
eprintln!("{}", err);
}
}
status
});
let fst = exit_statuses.next().unwrap_or(Ok(()));
let final_status = exit_statuses
.fold(fst, |a, b| a.and(b));
if final_status.is_err() {
process::exit(STATUS_ERROR);
}
}
|
use projecteuler::digits;
use projecteuler::helper;
fn main() {
helper::check_bench(|| {
solve();
});
assert_eq!(solve(), 8581146);
dbg!(solve());
}
fn solve() -> usize {
/*
maximum number below ten million:
9_999_999
square of 9: 81
7*9^2 = 576
*/
let mut count = 0;
let mut cache = Vec::with_capacity(577);
cache.push(false);
for i in 1..10_000_000 {
let i = if i <= 576 {
cache.push(ends_in_89(i));
i
} else {
next(i)
};
if cache[i] {
count += 1;
}
}
count
}
fn next(n: usize) -> usize {
digits::digits_iterator(n)
.map(|d| (d * d) as usize)
.sum::<usize>()
}
fn ends_in_89(mut n: usize) -> bool {
while n != 1 && n != 89 {
n = next(n);
}
n == 89
}
|
use super::gl;
use super::*;
use image::{DynamicImage, GenericImageView};
use std::ffi::c_void;
use std::path::Path;
use math::Mat4;
use generational_arena::Index;
#[derive(Clone, Copy)]
pub enum TextureWrapping {
ClampToEdge = gl::CLAMP_TO_EDGE as isize,
}
#[derive(Clone, Copy)]
pub enum TextureFiltering {
Smooth = gl::LINEAR as isize,
Pixelated = gl::NEAREST as isize,
}
pub enum TextureStorage {
Canvas2D(SkiaCanvas),
Image(DynamicImage),
Zeroed,
}
impl TextureStorage {
pub fn from_canvas(width: u32, height: u32) -> TextureStorage {
TextureStorage::Canvas2D(SkiaCanvas::new(500, 500))
}
pub fn from_image<P>(path: P) -> TextureStorage
where
P: AsRef<Path>,
{
TextureStorage::Image(image::open(path).unwrap())
}
}
pub struct Texture {
pub wrapping: TextureWrapping,
pub filtering: TextureFiltering,
pub storage: TextureStorage,
pub needs_update: bool,
pub handle: Option<GLTexture>,
}
impl Texture {
pub fn new(wrapping: TextureWrapping, filtering: TextureFiltering) -> Self {
Self {
wrapping,
filtering,
storage: TextureStorage::Zeroed,
needs_update: true,
handle: None,
}
}
pub fn new_initialized(
wrapping: TextureWrapping,
filtering: TextureFiltering,
storage: TextureStorage,
) -> Self {
Self {
wrapping,
filtering,
storage,
needs_update: true,
handle: None,
}
}
pub fn set_handle(&mut self, handle: GLTexture) {
self.handle = Some(handle);
}
}
pub struct RenderComponent {
pub material: GLShader,
pub textures: Vec<Index<Texture>>,
pub vao: GLVertexArray,
pub ibo: Option<GLBuffer>,
pub vbo: GLBuffer,
pub depth_write: bool,
pub draw_mode: u32,
pub is_indexed: bool,
pub vertex_count: usize,
}
impl RenderComponent {
pub fn new(
material: GLShader,
textures: Vec<Index<Texture>>,
vao: GLVertexArray,
vbo: GLBuffer,
ibo: Option<GLBuffer>,
depth_write: bool,
draw_mode: u32,
vertex_count: usize,
) -> Self {
let is_indexed = ibo.is_some();
let component = Self {
material,
textures,
vao,
ibo,
vbo,
depth_write,
draw_mode,
is_indexed,
vertex_count,
};
component
}
}
|
use std::fs;
use std::include_str;
use std::path::PathBuf;
use std::process::Command;
use crate::patcher::{get_patcher_name, PatcherCommand, PatcherConfiguration};
use futures::executor::block_on;
use tokio::sync::mpsc;
use web_view::{Content, Handle, WebView};
/// 'Opaque" struct that can be used to update the UI.
pub struct UIController {
web_view_handle: Handle<WebViewUserData>,
}
impl UIController {
pub fn new<'a>(web_view: &WebView<'a, WebViewUserData>) -> UIController {
UIController {
web_view_handle: web_view.handle(),
}
}
/// Allows another thread to indicate the current status of the patching process.
///
/// This updates the UI with useful information.
pub async fn dispatch_patching_status(&self, status: PatchingStatus) {
if let Err(e) = self.web_view_handle.dispatch(move |webview| {
let result = match status {
PatchingStatus::Ready => webview.eval("patchingStatusReady()"),
PatchingStatus::Error(msg) => {
webview.eval(&format!("patchingStatusError(\"{}\")", msg))
}
PatchingStatus::DownloadInProgress(nb_downloaded, nb_total, bytes_per_sec) => {
webview.eval(&format!(
"patchingStatusDownloading({}, {}, {})",
nb_downloaded, nb_total, bytes_per_sec
))
}
PatchingStatus::InstallationInProgress(nb_installed, nb_total) => webview.eval(
&format!("patchingStatusInstalling({}, {})", nb_installed, nb_total),
),
};
if let Err(e) = result {
log::warn!("Failed to dispatch patching status: {}.", e);
}
Ok(())
}) {
log::warn!("Failed to dispatch patching status: {}.", e);
}
}
}
/// Used to indicate the current status of the patching process.
pub enum PatchingStatus {
Ready,
Error(String), // Error message
DownloadInProgress(usize, usize, u64), // Downloaded files, Total number, Bytes per second
InstallationInProgress(usize, usize), // Installed patches, Total number
}
pub struct WebViewUserData {
patcher_config: PatcherConfiguration,
patching_thread_tx: mpsc::Sender<PatcherCommand>,
}
impl WebViewUserData {
pub fn new(
patcher_config: PatcherConfiguration,
patching_thread_tx: mpsc::Sender<PatcherCommand>,
) -> WebViewUserData {
WebViewUserData {
patcher_config,
patching_thread_tx,
}
}
}
impl Drop for WebViewUserData {
fn drop(&mut self) {
// Ask the patching thread to stop whenever WebViewUserData is dropped
let _res = self.patching_thread_tx.try_send(PatcherCommand::Cancel);
}
}
/// Creates a message box with the given title and message.
///
/// Panics in case of error.
pub fn msg_box<S1, S2>(title: S1, message: S2)
where
S1: AsRef<str>,
S2: AsRef<str>,
{
// Note(LinkZ): Empirical approximation of the required height for the window.
// TODO: Improve
let height = 63 + (message.as_ref().len() / 40) * 14;
let html_template = include_str!("../resources/msg_box.html");
let content = html_template.replace("MSG_BOX_MESSAGE", message.as_ref());
let webview = web_view::builder()
.title(title.as_ref())
.content(Content::Html(content))
.user_data(0)
.size(310, height as i32)
.resizable(false)
.invoke_handler(|_, _| Ok(()))
.build()
.unwrap();
webview.run().unwrap();
}
/// Creates a `WebView` object with the appropriate settings for our needs.
pub fn build_webview<'a>(
window_title: &'a str,
user_data: WebViewUserData,
) -> web_view::WVResult<WebView<'a, WebViewUserData>> {
web_view::builder()
.title(window_title)
.content(Content::Url(user_data.patcher_config.web.index_url.clone()))
.size(
user_data.patcher_config.window.width,
user_data.patcher_config.window.height,
)
.resizable(user_data.patcher_config.window.resizable)
.user_data(user_data)
.invoke_handler(|webview, arg| {
match arg {
"play" => handle_play(webview),
"setup" => handle_setup(webview),
"exit" => handle_exit(webview),
"start_update" => handle_start_update(webview),
"cancel_update" => handle_cancel_update(webview),
"reset_cache" => handle_reset_cache(webview),
_ => (),
}
Ok(())
})
.build()
}
/// Opens the configured game client with the configured arguments.
///
/// This function can create elevated processes on Windows with UAC activated.
fn handle_play(webview: &mut WebView<WebViewUserData>) {
let client_exe: &String = &webview.user_data().patcher_config.play.path;
let client_argument: &String = &webview.user_data().patcher_config.play.argument;
if cfg!(target_os = "windows") {
#[cfg(windows)]
match windows::spawn_elevated_win32_process(client_exe, client_argument) {
Ok(_) => log::trace!("Client started."),
Err(e) => {
log::warn!("Failed to start client: {}", e);
}
}
} else {
match Command::new(client_exe).arg(client_argument).spawn() {
Ok(child) => log::trace!("Client started: pid={}", child.id()),
Err(e) => {
log::warn!("Failed to start client: {}", e);
}
}
}
}
/// Opens the configured 'Setup' software with the configured arguments.
///
/// This function can create elevated processes on Windows with UAC activated.
fn handle_setup(webview: &mut WebView<WebViewUserData>) {
let setup_exe: &String = &webview.user_data().patcher_config.setup.path;
let setup_argument: &String = &webview.user_data().patcher_config.setup.argument;
if cfg!(target_os = "windows") {
#[cfg(windows)]
match windows::spawn_elevated_win32_process(setup_exe, setup_argument) {
Ok(_) => log::trace!("Setup software started."),
Err(e) => {
log::warn!("Failed to start setup software: {}", e);
}
}
} else {
match Command::new(setup_exe).arg(setup_argument).spawn() {
Ok(child) => log::trace!("Setup software started: pid={}", child.id()),
Err(e) => {
log::warn!("Failed to start setup software: {}", e);
}
}
}
}
/// Exits the patcher cleanly.
fn handle_exit(webview: &mut WebView<WebViewUserData>) {
webview.exit();
}
/// Starts the patching task/thread.
fn handle_start_update(webview: &mut WebView<WebViewUserData>) {
if block_on(
webview
.user_data_mut()
.patching_thread_tx
.send(PatcherCommand::Start),
)
.is_ok()
{
log::trace!("Sent start command to patching thread");
}
}
/// Cancels the patching task/thread.
fn handle_cancel_update(webview: &mut WebView<WebViewUserData>) {
if block_on(
webview
.user_data_mut()
.patching_thread_tx
.send(PatcherCommand::Cancel),
)
.is_ok()
{
log::trace!("Sent cancel command to patching thread");
}
}
/// Resets the patcher cache (which is used to keep track of already applied
/// patches).
fn handle_reset_cache(_webview: &mut WebView<WebViewUserData>) {
if let Ok(patcher_name) = get_patcher_name() {
let cache_file_path = PathBuf::from(patcher_name).with_extension("dat");
if let Err(e) = fs::remove_file(cache_file_path) {
log::warn!("Failed to remove the cache file: {}", e);
}
}
}
// Note: Taken from the rustup project
#[cfg(windows)]
mod windows {
use std::ffi::OsStr;
use std::io;
use std::os::windows::ffi::OsStrExt;
fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
fn inner(s: &OsStr) -> io::Result<Vec<u16>> {
let mut maybe_result: Vec<u16> = s.encode_wide().collect();
if maybe_result.iter().any(|&u| u == 0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"strings passed to WinAPI cannot contain NULs",
));
}
maybe_result.push(0);
Ok(maybe_result)
}
inner(s.as_ref())
}
/// This function is required to start processes that require elevation, from
/// a non-elevated process.
pub fn spawn_elevated_win32_process<S: AsRef<OsStr>>(
path: S,
parameter: S,
) -> io::Result<bool> {
use std::ptr;
use winapi::ctypes::c_int;
use winapi::shared::minwindef::HINSTANCE;
use winapi::shared::ntdef::LPCWSTR;
use winapi::shared::windef::HWND;
extern "system" {
pub fn ShellExecuteW(
hwnd: HWND,
lpOperation: LPCWSTR,
lpFile: LPCWSTR,
lpParameters: LPCWSTR,
lpDirectory: LPCWSTR,
nShowCmd: c_int,
) -> HINSTANCE;
}
const SW_SHOW: c_int = 5;
let path = to_u16s(path)?;
let parameter = to_u16s(parameter)?;
let operation = to_u16s("runas")?;
let result = unsafe {
ShellExecuteW(
ptr::null_mut(),
operation.as_ptr(),
path.as_ptr(),
parameter.as_ptr(),
ptr::null(),
SW_SHOW,
)
};
Ok(result as usize > 32)
}
}
|
use coi::{container, Inject};
pub trait Trait1: Inject {
fn a(&self) -> &'static str;
}
pub trait Trait2: Inject {
fn b(&self) -> &'static str;
}
#[derive(Inject)]
#[coi(provides dyn Trait1 as ImplTrait1Provider with Impl)]
#[coi(provides dyn Trait2 as ImplTrait2Provider with Impl)]
struct Impl;
impl Trait1 for Impl {
fn a(&self) -> &'static str {
"a"
}
}
impl Trait2 for Impl {
fn b(&self) -> &'static str {
"b"
}
}
#[test]
fn main() {
let container = container! {
trait1 => ImplTrait1Provider,
trait2 => ImplTrait2Provider,
};
let _trait1 = container
.resolve::<dyn Trait1>("trait1")
.expect("Trait1 should exist");
let _trait2 = container
.resolve::<dyn Trait2>("trait2")
.expect("Trait2 should exist");
}
|
use std::fmt;
use crate::block::Block;
use crate::block_exit::BlockExit;
use crate::cmd_options::CmdOptions;
use crate::command::Command;
use crate::counters::{CodelChooser, Counters, DirectionPointer};
// TODO: this file is too big, needs being split up
// TODO: we needs tests (also for other modules)
// TODO: needs better module/method level documentation
// TODO: parse gif files using https://github.com/image-rs/image-gif
const MAX_ALLOWED__POINTER_TOGGLES: u8 = 8;
const LIGHT_LEVELS: u8 = 3;
const HUE_LEVELS: u8 = 6;
#[derive(Debug)]
enum Codel {
Color {
x: usize,
y: usize,
hue: u8,
light: u8,
block_index: Option<usize>,
},
Black {
x: usize,
y: usize,
},
White {
x: usize,
y: usize,
},
}
impl fmt::Display for Codel {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Codel::Black { x, y } => write!(f, "Codel::Black<{}, {}>", x, y),
Codel::White { x, y } => write!(f, "Codel::White<{}, {}>", x, y),
Codel::Color {
x,
y,
hue,
light,
block_index,
} => write!(
f,
"Codel::Color<{}, {}> hue: {}, light: {}, block_index: {:?}",
x, y, hue, light, block_index
),
}
}
}
#[derive(Debug)]
pub struct Interpreter {
dp: DirectionPointer,
cc: CodelChooser,
alive: bool,
stack: Vec<i64>,
step_counter: u128,
max_steps: u128,
unlimited_steps: bool,
verbose_logging: bool,
canvas: Vec<Vec<Codel>>,
blocks: Vec<Block>,
width: usize,
height: usize,
current_position: (usize, usize),
toggled_pointers_without_move: u8,
last_toggled_pointer: Counters,
}
impl Interpreter {
pub fn from_rgb_rows(rgb_rows: Vec<Vec<(u8, u8, u8)>>, options: &CmdOptions) -> Interpreter {
let canvas = create_canvas(rgb_rows, options);
let width = canvas[0].len();
let height = canvas.len();
let mut interpreter = Interpreter {
dp: DirectionPointer::Right,
cc: CodelChooser::Left,
alive: true,
stack: Vec::with_capacity(64),
step_counter: 0,
max_steps: options.max_steps,
unlimited_steps: options.unlimited_steps,
verbose_logging: options.verbose,
canvas,
blocks: Vec::new(),
width,
height,
current_position: (0, 0),
toggled_pointers_without_move: 0,
last_toggled_pointer: Counters::DirectionPointer,
};
interpreter.detect_blocks();
interpreter.assign_codels_to_blocks();
interpreter.find_exits_for_blocks();
interpreter
}
pub fn is_alive(&self) -> bool {
self.alive
}
pub fn advance(&mut self) {
self.step_counter += 1;
if self.max_steps_reached() || self.program_should_end() {
self.exit();
return;
}
match self.find_next_codel() {
Some((new_position, traveled_through_white, reached_new_block)) => {
self.toggled_pointers_without_move = 0;
let old_position = self.current_position;
self.current_position = new_position;
if reached_new_block {
if !traveled_through_white {
let cmd = self.command_to_execute(old_position, new_position);
self.execute(cmd.unwrap(), old_position);
}
} else {
self.toogle_counters();
}
}
None => {
self.toogle_counters();
self.toggled_pointers_without_move += 1;
}
};
}
fn execute(&mut self, command: Command, old_position: (usize, usize)) {
if let Codel::Color { block_index, .. } = self.canvas[old_position.1][old_position.0] {
if let Some(block_index) = block_index {
let block_size = self.blocks[block_index].size();
command.execute(
&mut self.stack,
&mut self.dp,
&mut self.cc,
block_size,
self.verbose_logging,
);
}
}
}
fn command_to_execute(
&mut self,
old_position: (usize, usize),
new_position: (usize, usize),
) -> Option<Command> {
Command::from(self.light_and_hue_difference(old_position, new_position))
}
fn light_and_hue_difference(&self, coord1: (usize, usize), coord2: (usize, usize)) -> (u8, u8) {
if let Some(block1) = self.block_for_coord(coord1) {
if let Some(block2) = self.block_for_coord(coord2) {
let light_diff = (block2.light + LIGHT_LEVELS - block1.light) % LIGHT_LEVELS;
let hue_diff = (block2.hue + HUE_LEVELS - block1.hue) % HUE_LEVELS;
return (light_diff, hue_diff);
}
}
(0, 0)
}
fn block_for_coord(&self, coord: (usize, usize)) -> Option<&Block> {
let codel = self.codel_for(coord);
if let Codel::Color { block_index, .. } = codel {
if let Some(block_index) = block_index {
return Some(&self.blocks[*block_index]);
}
}
None
}
fn current_block(&self) -> Option<&Block> {
self.block_for_coord(self.current_position)
}
fn find_next_codel(&self) -> Option<((usize, usize), bool, bool)> {
let origin_block = self.current_block();
let mut coord = match origin_block {
Some(block) => block.exit_coordinates(&self.dp, &self.cc)?,
None => (self.current_position.0, self.current_position.1),
};
let mut traveled_through_white = false;
while let Some(next_codel) = self.find_next_codel_from(coord) {
match *next_codel {
Codel::Black { .. } => break,
Codel::White { x, y } => {
traveled_through_white = true;
coord = (x, y);
}
Codel::Color {
x, y, block_index, ..
} => {
let block_index = block_index?;
match origin_block {
Some(origin_block) => {
if origin_block != &self.blocks[block_index] {
return Some(((x, y), traveled_through_white, true));
}
}
None => {
// must travel through white when not coming from a color with a block (= color codel)
// this can happen e.g. when arriving ad black/edge while sliding through a white area
return Some(((x, y), true, true));
}
}
coord = (x, y);
}
}
}
// reached an end of our current travel in the given direction (black codel or picture edge)
match origin_block {
Some(_) => {
match self.block_for_coord(coord) {
Some(_) => {
// we ended in a block, but it is the same block as before (the case of a different block is handled
// with an early return above). This means we could not *actually* move out of the block and cannot report a new position
None
}
None => {
// we started from a colored codel (-> with block) and arrived at a colored codel, so we moved but ended
// in a position without executable command (since that case is handled with an early return above).
// pointers (dp,cc) need to be toggled and jouney needs to continue from the current coords
// must travel through white when arriving at a color with a block (= color codel)
Some((coord, true, false))
}
}
}
None => {
if self.current_position != coord {
// we started from a not-colored codel (-> no block) and arrived at a non-colored codel, so we moved but ended
// in a position without executable command (since that case is handled with an early return above).
// pointers (dp,cc) need to be toggled and jouney needs to continue from the current coords
// must travel through white when not coming from a color with a block (= color codel)
// this can happen e.g. when arriving ad black/edge while sliding through a white area
Some((coord, true, false))
} else {
// we did not move at all, so we cannod return a new position
None
}
}
}
}
fn find_next_codel_from(&self, start: (usize, usize)) -> Option<&Codel> {
let next_coords = match self.dp {
DirectionPointer::Up => coord_up(start, self.width, self.height),
DirectionPointer::Right => coord_right(start, self.width, self.height),
DirectionPointer::Down => coord_down(start, self.width, self.height),
DirectionPointer::Left => coord_left(start, self.width, self.height),
};
next_coords.map(|coord| self.codel_for(coord))
}
fn codel_for(&self, coord: (usize, usize)) -> &Codel {
&self.canvas[coord.1][coord.0]
}
fn max_steps_reached(&self) -> bool {
!self.unlimited_steps && self.step_counter >= self.max_steps
}
fn program_should_end(&self) -> bool {
self.toggled_pointers_without_move >= MAX_ALLOWED__POINTER_TOGGLES
}
fn toogle_counters(&mut self) {
match self.last_toggled_pointer {
Counters::DirectionPointer => {
self.last_toggled_pointer = Counters::CodelChooser;
self.cc = match self.cc {
CodelChooser::Right => CodelChooser::Left,
CodelChooser::Left => CodelChooser::Right,
};
}
Counters::CodelChooser => {
self.last_toggled_pointer = Counters::DirectionPointer;
self.dp = match self.dp {
DirectionPointer::Up => DirectionPointer::Right,
DirectionPointer::Right => DirectionPointer::Down,
DirectionPointer::Down => DirectionPointer::Left,
DirectionPointer::Left => DirectionPointer::Up,
};
}
}
}
fn exit(&mut self) {
self.alive = false;
}
fn assign_codels_to_blocks(&mut self) {
for row in self.canvas.iter_mut() {
for codel in row.iter_mut() {
if let Codel::Color {
block_index, x, y, ..
} = codel
{
*block_index = self
.blocks
.iter_mut()
.position(|b| b.codel_coordinates.contains(&(*x, *y)));
}
}
}
}
fn detect_blocks(&mut self) {
let mut visited: Vec<Vec<bool>> = vec![vec![false; self.width]; self.height];
for row in self.canvas.iter() {
for codel in row.iter() {
if let Codel::Color {
x, y, hue, light, ..
} = codel
{
if visited[*y][*x] {
continue;
}
let block = Block {
codel_coordinates: Vec::new(),
hue: *hue,
light: *light,
block_exit: None,
};
self.blocks.push(block);
let new_block_index = self.blocks.len() - 1;
let mut visit_list: Vec<(usize, usize)> = [(*x, *y)].to_vec();
while !visit_list.is_empty() {
let coord = visit_list.pop().unwrap();
if visited[coord.1][coord.0] {
continue;
}
visited[coord.1][coord.0] = true;
let block = &mut self.blocks[new_block_index];
block.codel_coordinates.push(coord);
// right neighbour
if let Some(other_coord) = coord_right(coord, self.width, self.height) {
let other_codel = &self.canvas[other_coord.1][other_coord.0];
if let Codel::Color {
x, y, hue, light, ..
} = other_codel
{
if !visited[*y][*x] && block.hue == *hue && block.light == *light {
visit_list.push(other_coord);
}
}
}
// left neighbour
if let Some(other_coord) = coord_left(coord, self.width, self.height) {
let other_codel = &self.canvas[other_coord.1][other_coord.0];
if let Codel::Color {
x, y, hue, light, ..
} = other_codel
{
if !visited[*y][*x] && block.hue == *hue && block.light == *light {
visit_list.push(other_coord);
}
}
}
// up neighbour
if let Some(other_coord) = coord_up(coord, self.width, self.height) {
let other_codel = &self.canvas[other_coord.1][other_coord.0];
if let Codel::Color {
x, y, hue, light, ..
} = other_codel
{
if !visited[*y][*x] && block.hue == *hue && block.light == *light {
visit_list.push(other_coord);
}
}
}
// down neighbour
if let Some(other_coord) = coord_down(coord, self.width, self.height) {
let other_codel = &self.canvas[other_coord.1][other_coord.0];
if let Codel::Color {
x, y, hue, light, ..
} = other_codel
{
if !visited[*y][*x] && block.hue == *hue && block.light == *light {
visit_list.push(other_coord);
}
}
}
}
}
}
}
}
fn find_exits_for_blocks(&mut self) {
for block in self.blocks.iter_mut() {
block.block_exit = Some(BlockExit::from_coords(&block.codel_coordinates));
}
}
}
fn coord_right(coord: (usize, usize), width: usize, _height: usize) -> Option<(usize, usize)> {
if coord.0 + 1 >= width {
None
} else {
Some {
0: (coord.0 + 1, coord.1),
}
}
}
fn coord_left(coord: (usize, usize), _width: usize, _height: usize) -> Option<(usize, usize)> {
if coord.0 == 0 {
None
} else {
Some {
0: (coord.0 - 1, coord.1),
}
}
}
fn coord_up(coord: (usize, usize), _width: usize, _height: usize) -> Option<(usize, usize)> {
if coord.1 == 0 {
None
} else {
Some {
0: (coord.0, coord.1 - 1),
}
}
}
fn coord_down(coord: (usize, usize), _width: usize, height: usize) -> Option<(usize, usize)> {
if coord.1 + 1 >= height {
None
} else {
Some {
0: (coord.0, coord.1 + 1),
}
}
}
fn create_canvas<'a>(rgb_rows: Vec<Vec<(u8, u8, u8)>>, options: &CmdOptions) -> Vec<Vec<Codel>> {
let mut canvas = Vec::with_capacity(rgb_rows.len());
for (y, rgb_row) in rgb_rows.into_iter().enumerate() {
let mut codels = Vec::with_capacity(rgb_row.len());
for (x, rgb) in rgb_row.into_iter().enumerate() {
codels.push(rgb_to_codel(rgb, x, y, options.unknown_white));
}
canvas.push(codels);
}
canvas
}
fn rgb_to_codel<'a>(rgb: (u8, u8, u8), x: usize, y: usize, unknown_white: bool) -> Codel {
match rgb {
(0x00, 0x00, 0x00) => Codel::Black { x: x, y: y },
(0xFF, 0xFF, 0xFF) => Codel::White { x: x, y: y },
// light red
(0xFF, 0xC0, 0xC0) => Codel::Color {
x: x,
y: y,
hue: 0,
light: 0,
block_index: None,
},
// red
(0xFF, 0x00, 0x00) => Codel::Color {
x: x,
y: y,
hue: 0,
light: 1,
block_index: None,
},
// dark red
(0xC0, 0x00, 0x00) => Codel::Color {
x: x,
y: y,
hue: 0,
light: 2,
block_index: None,
},
// light yellow
(0xFF, 0xFF, 0xC0) => Codel::Color {
x: x,
y: y,
hue: 1,
light: 0,
block_index: None,
},
// yellow
(0xFF, 0xFF, 0x00) => Codel::Color {
x: x,
y: y,
hue: 1,
light: 1,
block_index: None,
},
// dark yellow
(0xC0, 0xC0, 0x00) => Codel::Color {
x: x,
y: y,
hue: 1,
light: 2,
block_index: None,
},
// light green
(0xC0, 0xFF, 0xC0) => Codel::Color {
x: x,
y: y,
hue: 2,
light: 0,
block_index: None,
},
// green
(0x00, 0xFF, 0x00) => Codel::Color {
x: x,
y: y,
hue: 2,
light: 1,
block_index: None,
},
// dark green
(0x00, 0xC0, 0x00) => Codel::Color {
x: x,
y: y,
hue: 2,
light: 2,
block_index: None,
},
// light cyan
(0xC0, 0xFF, 0xFF) => Codel::Color {
x: x,
y: y,
hue: 3,
light: 0,
block_index: None,
},
// cyan
(0x00, 0xFF, 0xFF) => Codel::Color {
x: x,
y: y,
hue: 3,
light: 1,
block_index: None,
},
// dark cyan
(0x00, 0xC0, 0xC0) => Codel::Color {
x: x,
y: y,
hue: 3,
light: 2,
block_index: None,
},
// light blue
(0xC0, 0xC0, 0xFF) => Codel::Color {
x: x,
y: y,
hue: 4,
light: 0,
block_index: None,
},
// blue
(0x00, 0x00, 0xFF) => Codel::Color {
x: x,
y: y,
hue: 4,
light: 1,
block_index: None,
},
// dark blue
(0x00, 0x00, 0xC0) => Codel::Color {
x: x,
y: y,
hue: 4,
light: 2,
block_index: None,
},
// light magenta
(0xFF, 0xC0, 0xFF) => Codel::Color {
x: x,
y: y,
hue: 5,
light: 0,
block_index: None,
},
// magenta
(0xFF, 0x00, 0xFF) => Codel::Color {
x: x,
y: y,
hue: 5,
light: 1,
block_index: None,
},
// dark magenta
(0xC0, 0x00, 0xC0) => Codel::Color {
x: x,
y: y,
hue: 5,
light: 2,
block_index: None,
},
(r, g, b) => {
eprintln!("Parsed unknown codel color ({r}, {g}, {b}) / (#{r:02X}{g:02X}{b:02X}) at pos ({x},{y})", r=r, g=g, b=b, x=x, y=y);
if unknown_white {
Codel::White { x: x, y: y }
} else {
Codel::Black { x: x, y: y }
}
}
}
}
impl fmt::Display for Interpreter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Interpreter<dp: {}, cc: {}, pos: {:?} alive: {}, steps: {}, pointer_toggles_without_move: {}, stack: {:?}>",
self.dp, self.cc, self.current_position, self.alive, self.step_counter, self.toggled_pointers_without_move, self.stack
)
}
}
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkCommandBufferBeginInfo {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkCommandBufferUsageFlagBits,
pub pInheritanceInfo: *const VkCommandBufferInheritanceInfo,
}
impl VkCommandBufferBeginInfo {
pub fn new<T>(flags: T) -> Self
where
T: Into<VkCommandBufferUsageFlagBits>,
{
VkCommandBufferBeginInfo {
sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
pNext: ptr::null(),
flags: flags.into(),
pInheritanceInfo: ptr::null(),
}
}
pub fn set_inheritance_info<'a, 'b: 'a>(
&'a mut self,
inheritance_info: &'b VkCommandBufferInheritanceInfo,
) {
self.pInheritanceInfo = inheritance_info as *const VkCommandBufferInheritanceInfo;
}
}
|
use std::ops::{Deref, DerefMut};
use failure::Error;
use crate::client;
/// This marks that something is a driver, that is it manages an instance of
/// something used to remote control a browser.
pub trait Driver {
/// Shut down the driver.
fn close(&mut self) -> Result<(), Error>;
}
/// This is designed to serve as a placeholder to make it easy to have the
/// driver live as long as the client.
pub struct DriverHolder {
pub(crate) client: client::Client,
// This is only used so we can drop it _after_ we have dropped the client.
#[allow(dead_code)]
pub(crate) driver: Box<dyn Driver>,
}
impl DriverHolder {
/// This will shut down both the associated webdriver session, and driver.
pub fn close(self) -> Result<(), Error> {
let DriverHolder {
mut client,
mut driver,
} = self;
client.close()?;
driver.close()?;
Ok(())
}
}
impl Deref for DriverHolder {
type Target = client::Client;
fn deref(&self) -> &Self::Target {
&self.client
}
}
impl DerefMut for DriverHolder {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.client
}
}
|
use super::*;
impl From<Row> for Trace {
fn from(row: Row) -> Self {
Self {
id: row.get("id"),
name: row.get("name"),
created_at: row.get("created_at"),
updated_at: row.get("updated_at"),
}
}
}
#[async_trait]
impl Create<Trace> for Client {
async fn create(&self, row: &Trace) -> Result<(), Error> {
self.execute(
"INSERT INTO traces (id, name, created_at, updated_at) VALUES ($1, $2, $3, $4)",
&[&row.id, &row.name, &row.created_at, &row.updated_at],
)
.await?;
Ok(())
}
}
#[async_trait]
impl Get<Trace> for Client {
type Key = NameKey;
async fn get(&self, key: &NameKey) -> Result<Option<Trace>, Error> {
let res = self
.query_opt("SELECT * FROM traces WHERE name = $1", &[&key.name])
.await?
.map(|x| x.into());
Ok(res)
}
}
#[async_trait]
impl Delete<Trace> for Client {
type Key = IdKey;
async fn delete(&self, key: &IdKey) -> Result<(), Error> {
self.execute("DELETE FROM traces WHERE id = $1", &[&key.id])
.await?;
Ok(())
}
}
#[async_trait]
impl Contain<Trace> for Client {
type Key = NameKey;
async fn contain(&self, key: &NameKey) -> Result<Vec<Trace>, Error> {
let regex = format!("%{}%", &key.name);
let res: Vec<Trace> = self
.query("SELECT * FROM traces WHERE name LIKE $1", &[®ex])
.await?
.into_iter()
.map(|x| x.into())
.collect();
Ok(res)
}
}
|
use crate::libbb::appletlib::bb_show_usage;
use crate::libbb::bb_pwd::xuid2uname;
use libc::c_char;
use libc::c_int;
use libc::geteuid;
/*
* Mini whoami implementation for busybox
*
* Copyright (C) 2000 Edward Betts <edward@debian.org>.
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config WHOAMI
//config: bool "whoami (3.2 kb)"
//config: default y
//config: help
//config: whoami is used to print the username of the current
//config: user id (same as id -un).
//applet:IF_WHOAMI(APPLET_NOFORK(whoami, whoami, BB_DIR_USR_BIN, SUID_DROP, whoami))
//kbuild:lib-$(CONFIG_WHOAMI) += whoami.o
/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
//usage:#define whoami_trivial_usage
//usage: ""
//usage:#define whoami_full_usage "\n\n"
//usage: "Print the user name associated with the current effective user id"
pub unsafe fn whoami_main(mut _argc: c_int, mut argv: *mut *mut c_char) -> c_int {
if !(*argv.offset(1)).is_null() {
bb_show_usage();
}
/* Will complain and die if username not found */
let euid = geteuid();
let user_name = xuid2uname(euid);
println!("{}", *user_name);
0
}
|
extern crate kiss3d;
extern crate nalgebra as na;
use kiss3d::light::Light;
use kiss3d::window::Window;
use nphysics3d::force_generator::DefaultForceGeneratorSet;
use nphysics3d::joint::DefaultJointConstraintSet;
use nphysics3d::object::ColliderDesc;
use nphysics3d::object::{BodyStatus, RigidBodyDesc};
use nphysics3d::object::{DefaultBodySet, DefaultColliderSet};
use nphysics3d::world::{DefaultGeometricalWorld, DefaultMechanicalWorld};
use na::{Isometry3, Matrix3, Point3, UnitQuaternion, Vector3};
use nphysics3d::math::{Inertia, Velocity};
use nphysics3d::object::{BodyPartHandle, BodySet};
use ncollide3d::shape::{Cuboid, ShapeHandle};
fn main() {
let mut mechanical_world = DefaultMechanicalWorld::new(Vector3::new(0.0, -9.81, 0.0));
let mut geometrical_world = DefaultGeometricalWorld::new();
let mut bodies = DefaultBodySet::new();
let mut colliders = DefaultColliderSet::new();
let mut joint_constraints = DefaultJointConstraintSet::new();
let mut force_generators = DefaultForceGeneratorSet::new();
//create rigid body
let rb = RigidBodyDesc::new().mass(1.2).build();
let handle_rb = bodies.insert(rb);
//create collider
let shape = ShapeHandle::new(Cuboid::new(Vector3::new(1.0, 1.0, 1.0)));
let box_collider = ColliderDesc::new(shape).build(BodyPartHandle(handle_rb, 0));
let collider_handler = colliders.insert(box_collider);
//creare kiss window
let mut window = Window::new("Kiss3d: cube");
let mut c = window.add_cube(1.0, 1.0, 1.0);
c.set_color(1.0, 0.0, 0.0);
window.set_light(Light::StickToCamera);
//let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014);
//main loop
while window.render() {
mechanical_world.step(
&mut geometrical_world,
&mut bodies,
&mut colliders,
&mut joint_constraints,
&mut force_generators,
);
let mrb = bodies.rigid_body(handle_rb).expect("Rigid body not found.");
let pos = mrb.position();
c.set_local_transformation(*pos);
// c.append_translation();
}
}
|
pub mod register_form;
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::string::String;
use alloc::vec::Vec;
use alloc::sync::Arc;
use spin::Mutex;
use core::any::Any;
use socket::unix::transport::unix::BoundEndpoint;
use super::super::super::qlib::common::*;
use super::super::super::qlib::linux_def::*;
use super::super::super::qlib::auth::*;
use super::super::super::qlib::device::*;
use super::super::super::qlib::qmsg::*;
use super::super::super::kernel::time::*;
use super::super::super::Kernel::*;
use super::super::super::task::*;
use super::super::attr::*;
use super::super::mount::*;
use super::super::flags::*;
use super::super::file::*;
use super::super::inode::*;
use super::super::dirent::*;
use super::super::host::hostinodeop::*;
use super::tmpfs_dir::*;
pub fn NewTmpfsFileInode(_task: &Task, uattr: UnstableAttr, msrc: &Arc<Mutex<MountSource>>) -> Result<Inode> {
let mut fstat = LibcStat::default();
let tmpfd = HostSpace::NewTmpfsFile(TmpfsFileType::File, &mut fstat as * mut _ as u64) as i32;
if tmpfd < 0 {
return Err(Error::SysError(-tmpfd))
}
let inode = Inode::NewHostInode(msrc, tmpfd, &fstat, true)?;
let inodeops = inode.lock().InodeOp.clone();
let hostiops = match inodeops.as_any().downcast_ref::<HostInodeOp>() {
None => return Err(Error::SysError(SysErr::EBADF)),
Some(iops) => iops.clone(),
};
let ops = TmpfsFileInodeOp {
inodeops: hostiops,
uattr: Arc::new(Mutex::new(uattr)),
};
let deviceId = TMPFS_DEVICE.lock().DeviceID();
let inodeId = TMPFS_DEVICE.lock().NextIno();
let attr = StableAttr {
Type: InodeType::RegularFile,
DeviceId: deviceId,
InodeId: inodeId,
BlockSize: MemoryDef::PAGE_SIZE as i64,
DeviceFileMajor: 0,
DeviceFileMinor: 0,
};
return Ok(Inode::New(&Arc::new(ops), msrc, &attr));
}
pub struct TmpfsFileInodeOp {
pub inodeops : HostInodeOp,
pub uattr: Arc<Mutex<UnstableAttr>>,
}
impl InodeOperations for TmpfsFileInodeOp {
fn as_any(&self) -> &Any {
return self
}
fn IopsType(&self) -> IopsType {
return IopsType::TmpfsFileInodeOp;
}
fn InodeType(&self) -> InodeType {
return self.inodeops.InodeType();
}
fn InodeFileType(&self) -> InodeFileType{
return InodeFileType::TmpfsFile;
}
fn WouldBlock(&self) -> bool {
return self.inodeops.WouldBlock();
}
fn Lookup(&self, task: &Task, dir: &Inode, name: &str) -> Result<Dirent> {
return self.inodeops.Lookup(task, dir, name)
}
fn Create(&self, task: &Task, dir: &mut Inode, name: &str, flags: &FileFlags, perm: &FilePermissions) -> Result<File> {
return self.inodeops.Create(task, dir, name, flags, perm)
}
fn CreateDirectory(&self, task: &Task, dir: &mut Inode, name: &str, perm: &FilePermissions) -> Result<()> {
return self.inodeops.CreateDirectory(task, dir, name, perm)
}
fn CreateLink(&self, task: &Task, dir: &mut Inode, oldname: &str, newname: &str) -> Result<()> {
return self.inodeops.CreateLink(task, dir, oldname, newname)
}
fn CreateHardLink(&self, task: &Task, dir: &mut Inode, target: &Inode, name: &str) -> Result<()> {
return self.inodeops.CreateHardLink(task, dir, target, name)
}
fn CreateFifo(&self, task: &Task, dir: &mut Inode, name: &str, perm: &FilePermissions) -> Result<()> {
return self.inodeops.CreateFifo(task, dir, name, perm)
}
//fn RemoveDirent(&mut self, dir: &mut InodeStruStru, remove: &Arc<Mutex<Dirent>>) -> Result<()> ;
fn Remove(&self, task: &Task, dir: &mut Inode, name: &str) -> Result<()> {
return self.inodeops.Remove(task, dir, name)
}
fn RemoveDirectory(&self, task: &Task, dir: &mut Inode, name: &str) -> Result<()>{
return self.inodeops.RemoveDirectory(task, dir, name)
}
fn Rename(&self, task: &Task, _dir: &mut Inode, oldParent: &Inode, oldname: &str, newParent: &Inode, newname: &str, replacement: bool) -> Result<()> {
return TmpfsRename(task, oldParent, oldname, newParent, newname, replacement)
}
fn Bind(&self, task: &Task, dir: &Inode, name: &str, data: &BoundEndpoint, perms: &FilePermissions) -> Result<Dirent> {
return self.inodeops.Bind(task, dir, name, data, perms)
}
fn BoundEndpoint(&self, task: &Task, inode: &Inode, path: &str) -> Option<BoundEndpoint> {
return self.inodeops.BoundEndpoint(task, inode, path)
}
fn GetFile(&self, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> {
//let mut flags = flags;
//flags.Read = true;
//flags.Write = true;
return self.inodeops.GetFile(task, dir, dirent, flags)
}
fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> {
let (size, blocks) = self.inodeops.Size()?;
let mut ret = *self.uattr.lock();
ret.Usage = blocks * 512;
ret.Size = size;
return Ok(ret);
}
fn Getxattr(&self, dir: &Inode, name: &str) -> Result<String> {
return self.inodeops.Getxattr(dir, name)
}
fn Setxattr(&self, dir: &mut Inode, name: &str, value: &str) -> Result<()> {
return self.inodeops.Setxattr(dir, name, value)
}
fn Listxattr(&self, dir: &Inode) -> Result<Vec<String>> {
return self.inodeops.Listxattr(dir)
}
fn Check(&self, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {
return self.inodeops.Check(task, inode, reqPerms)
}
fn SetPermissions(&self, task: &Task, _dir: &mut Inode, f: FilePermissions) -> bool {
self.uattr.lock().SetPermissions(task, &f);
return true;
}
fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> {
self.uattr.lock().SetOwner(task, owner);
return Ok(())
}
fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> {
self.uattr.lock().SetTimestamps(task, ts);
return Ok(())
}
fn Truncate(&self, task: &Task, dir: &mut Inode, size: i64) -> Result<()> {
return self.inodeops.Truncate(task, dir, size)
}
fn Allocate(&self, task: &Task, dir: &mut Inode, offset: i64, length: i64) -> Result<()> {
return self.inodeops.Allocate(task, dir, offset, length)
}
fn ReadLink(&self, task: &Task,dir: &Inode) -> Result<String> {
return self.inodeops.ReadLink(task, dir)
}
fn GetLink(&self, task: &Task, dir: &Inode) -> Result<Dirent> {
return self.inodeops.GetLink(task, dir)
}
fn AddLink(&self, _task: &Task) {
self.uattr.lock().Links += 1;
}
fn DropLink(&self, _task: &Task) {
self.uattr.lock().Links -= 1;
}
fn IsVirtual(&self) -> bool {
return true;
}
fn Sync(&self) -> Result<()> {
return self.inodeops.Sync()
}
fn StatFS(&self, _task: &Task) -> Result<FsInfo> {
return Ok(TMPFS_FSINFO)
}
fn Mappable(&self) -> Result<HostInodeOp> {
return self.inodeops.Mappable()
}
} |
use std::default::Default;
use std::fmt;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
use glob::glob;
use serde::{Deserialize, Serialize};
use slog::Logger;
use crate::errors::PsqlpackErrorKind::*;
use crate::errors::{PsqlpackError, PsqlpackResult, PsqlpackResultExt};
use crate::model::Package;
use crate::sql::ast::*;
use crate::sql::lexer;
use crate::sql::parser::StatementListParser;
use crate::Semver;
#[cfg(feature = "symbols")]
macro_rules! dump_statement {
($log:ident, $statement:ident) => {
let log = $log.new(o!("symbols" => "ast"));
trace!(log, "{:?}", $statement);
};
}
#[cfg(not(feature = "symbols"))]
macro_rules! dump_statement {
($log:ident, $statement:ident) => {};
}
#[derive(Deserialize, Serialize)]
pub struct Project {
// Internal only tracking for the project path
#[serde(skip_serializing)]
project_file_path: Option<PathBuf>,
/// The version of this profile file format
pub version: Semver,
/// The default schema for the database. Typically `public`
#[serde(alias = "defaultSchema")]
pub default_schema: String,
/// An array of scripts to run before anything is deployed
#[serde(alias = "preDeployScripts")]
pub pre_deploy_scripts: Vec<String>,
/// An array of scripts to run after everything has been deployed
#[serde(alias = "postDeployScripts")]
pub post_deploy_scripts: Vec<String>,
/// An array of extensions to include within this project
#[serde(skip_serializing_if = "Option::is_none")]
pub extensions: Option<Vec<Dependency>>,
/// An array of globs representing files/folders to be included within your project. Defaults to `["**/*.sql"]`.
#[serde(
alias = "fileIncludeGlobs",
alias = "file_include_globs",
skip_serializing_if = "Option::is_none"
)]
pub include_globs: Option<Vec<String>>,
/// An array of globs representing files/folders to be excluded within your project.
#[serde(
alias = "fileExcludeGlobs",
alias = "file_exclude_globs",
skip_serializing_if = "Option::is_none"
)]
pub exclude_globs: Option<Vec<String>>,
/// An array of search paths to look in outside of the standard paths (./lib, ~/.psqlpack/lib).
#[serde(alias = "referenceSearchPaths", skip_serializing_if = "Option::is_none")]
pub reference_search_paths: Option<Vec<String>>,
}
#[derive(Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct Dependency {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<Semver>,
}
impl fmt::Display for Dependency {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(version) = self.version {
write!(f, "{}-{}", self.name, version)
} else {
write!(f, "{}", self.name)
}
}
}
impl Default for Project {
fn default() -> Self {
Project {
project_file_path: None,
version: "1.0".into(),
default_schema: "public".into(),
pre_deploy_scripts: Vec::new(),
post_deploy_scripts: Vec::new(),
extensions: None,
include_globs: None,
exclude_globs: None,
reference_search_paths: None,
}
}
}
impl Project {
pub fn from_project_file(log: &Logger, project_file_path: &Path) -> PsqlpackResult<Project> {
let log = log.new(o!("project" => "from_project_file"));
trace!(log, "Attempting to open project file"; "project_file_path" => project_file_path.to_str().unwrap());
File::open(project_file_path)
.chain_err(|| ProjectReadError(project_file_path.to_path_buf()))
.and_then(|file| {
trace!(log, "Parsing project file");
Self::from_reader(file)
})
.map(|mut project: Project| {
project.project_file_path = Some(project_file_path.to_path_buf());
if project.default_schema.is_empty() {
project.default_schema = "public".into();
}
project
})
}
fn from_reader<R>(reader: R) -> PsqlpackResult<Project>
where
R: Read,
{
let mut buffered_reader = BufReader::new(reader);
let mut contents = String::new();
if buffered_reader
.read_to_string(&mut contents)
.chain_err(|| ProjectParseError("Failed to read contents".into()))?
== 0
{
bail!(ProjectParseError("Data was empty".into()))
}
let trimmed = contents.trim_start();
if trimmed.starts_with('{') {
serde_json::from_str(&contents).chain_err(|| ProjectParseError("Failed to read JSON".into()))
} else {
toml::from_str(&contents).chain_err(|| ProjectParseError("Failed to read TOML".into()))
}
}
pub fn build_package(&self, log: &Logger) -> PsqlpackResult<Package> {
let log = log.new(o!("project" => "build_package"));
// Turn the pre/post into paths to quickly check
let parent = match self.project_file_path {
Some(ref path) => path.parent().unwrap().canonicalize().unwrap(),
None => bail!(GenerationError("Project path not set".to_owned())),
};
let make_path = |script: &str| {
parent
.join(Path::new(script))
.canonicalize()
.chain_err(|| InvalidScriptPath(script.to_owned()))
};
trace!(log, "Canonicalizing predeploy paths");
let mut predeploy_paths = Vec::new();
for script in &self.pre_deploy_scripts {
predeploy_paths.push(make_path(script)?);
}
trace!(log, "Done predeploy paths"; "count" => predeploy_paths.len());
trace!(log, "Canonicalizing postdeploy paths");
let mut postdeploy_paths = Vec::new();
for script in &self.post_deploy_scripts {
postdeploy_paths.push(make_path(script)?);
}
trace!(log, "Done postdeploy paths"; "count" => postdeploy_paths.len());
// Start the package
let mut package = Package::new();
let mut errors: Vec<PsqlpackError> = Vec::new();
// Add extensions into package
if let Some(ref extensions) = self.extensions {
for extension in extensions {
package.push_extension(Dependency {
name: extension.name.clone(),
version: extension.version,
});
}
}
// Enumerate the glob paths
for path in self.walk_files(&parent)? {
let log = log.new(o!("file" => path.to_str().unwrap().to_owned()));
let mut contents = String::new();
if let Err(err) = File::open(&path).and_then(|mut f| f.read_to_string(&mut contents)) {
error!(log, "Error reading file");
errors.push(IOError(format!("{}", path.display()), format!("{}", err)).into());
continue;
}
// Figure out if it's a pre/post deployment script
let real_path = path.to_path_buf().canonicalize().unwrap();
if let Some(pos) = predeploy_paths.iter().position(|x| real_path.eq(x)) {
trace!(log, "Found predeploy script");
package.push_script(ScriptDefinition {
name: path.file_name().unwrap().to_str().unwrap().to_owned(),
kind: ScriptKind::PreDeployment,
order: pos,
contents,
});
} else if let Some(pos) = postdeploy_paths.iter().position(|x| real_path.eq(x)) {
trace!(log, "Found postdeploy script");
package.push_script(ScriptDefinition {
name: path.file_name().unwrap().to_str().unwrap().to_owned(),
kind: ScriptKind::PostDeployment,
order: pos,
contents,
});
} else {
trace!(log, "Tokenizing file");
let tokens = match lexer::tokenize_stmt(&contents[..]) {
Ok(t) => t,
Err(e) => {
errors.push(
SyntaxError(
format!("{}", path.display()),
e.line.to_owned(),
e.line_number as usize,
e.start_pos as usize,
e.end_pos as usize,
)
.into(),
);
continue;
}
};
trace!(log, "Finished tokenizing"; "count" => tokens.len());
trace!(log, "Parsing file");
// TODO: In the future it'd be nice to allow the parser to generate
// shift/reduce rules when dump-symbols is defined
match StatementListParser::new().parse(tokens) {
Ok(statement_list) => {
trace!(log, "Finished parsing statements"; "count" => statement_list.len());
for statement in statement_list {
dump_statement!(log, statement);
match statement {
Statement::Error(kind) => {
errors.push(HandledParseError(kind).into());
}
Statement::Function(function_definition) => package.push_function(function_definition),
Statement::Index(index_definition) => package.push_index(index_definition),
Statement::Schema(schema_definition) => package.push_schema(schema_definition),
Statement::Table(table_definition) => package.push_table(table_definition),
Statement::Type(type_definition) => package.push_type(type_definition),
}
}
}
Err(err) => {
errors.push(ParseError(format!("{}", path.display()), vec![err]).into());
continue;
}
}
}
}
// Early exit if errors
if !errors.is_empty() {
bail!(MultipleErrors(errors));
}
// Update any missing defaults, then try to validate the project
trace!(log, "Setting defaults");
package.set_defaults(self);
trace!(log, "Load references");
let references = package.load_references(self, &log);
trace!(log, "Validating package");
package.validate(&references)?;
Ok(package)
}
// Walk the files according to the include and exclude globs. This could be made more efficient with an iterator
// in the future (may want to extend glob). One downside of the current implementation is that pre/post deploy
// scripts could be inadvertantly excluded
fn walk_files(&self, parent: &Path) -> PsqlpackResult<Vec<PathBuf>> {
let include_globs = match self.include_globs {
Some(ref globs) => globs.to_owned(),
None => vec!["**/*.sql".into()],
};
let mut exclude_paths = Vec::new();
if let Some(ref globs) = self.exclude_globs {
for exclude_glob in globs {
for entry in
glob(&format!("{}/{}", parent.to_str().unwrap(), exclude_glob)).map_err(GlobPatternError)?
{
let path = entry.unwrap().canonicalize().unwrap();
exclude_paths.push(path);
}
}
}
let mut paths = Vec::new();
for include_glob in include_globs {
for entry in glob(&format!("{}/{}", parent.to_str().unwrap(), include_glob)).map_err(GlobPatternError)? {
// Get the path entry
let path = entry.unwrap();
// If this has been explicitly excluded then continue
let real_path = path.to_path_buf().canonicalize().unwrap();
if exclude_paths.iter().any(|x| real_path.eq(x)) {
continue;
}
paths.push(path);
}
}
Ok(paths)
}
}
#[cfg(test)]
mod tests {
use crate::model::project::Project;
use crate::{Dependency, Semver};
use std::path::Path;
#[test]
fn it_can_iterate_default_include_exclude_globs_correctly() {
// This test relies on the `simple` samples directory
let parent = Path::new("../samples/simple");
let project = Project::default();
let result = project.walk_files(&parent);
// Check the expected files were returned
assert!(result.is_ok());
let result = result.unwrap();
assert_eq!(result.len(), 4);
let result: Vec<&str> = result.iter().map(|x| x.to_str().unwrap()).collect();
assert!(
result.contains(&"../samples/simple/public/tables/public.expense_status.sql"),
"expense_status.sql"
);
assert!(
result.contains(&"../samples/simple/public/tables/public.organisation.sql"),
"organisation.sql"
);
assert!(
result.contains(&"../samples/simple/public/tables/public.tax_table.sql"),
"tax_table.sql"
);
assert!(
result.contains(&"../samples/simple/public/tables/public.vendor.sql"),
"vendor.sql"
);
}
#[test]
fn it_can_iterate_custom_exclude_globs_correctly() {
// This test relies on the `simple` samples directory
let parent = Path::new("../samples/simple");
let project = Project {
project_file_path: None,
version: "1.0".into(),
default_schema: "public".into(),
pre_deploy_scripts: Vec::new(),
post_deploy_scripts: Vec::new(),
extensions: None,
include_globs: None,
exclude_globs: Some(vec!["**/*org*".into()]),
reference_search_paths: None,
};
let result = project.walk_files(&parent);
// Check the expected files were returned
assert!(result.is_ok());
let result = result.unwrap();
assert_eq!(result.len(), 3);
let result: Vec<&str> = result.iter().map(|x| x.to_str().unwrap()).collect();
assert!(!result.contains(&"../samples/simple/public/tables/public.organisation.sql"));
assert!(result.contains(&"../samples/simple/public/tables/public.expense_status.sql"));
assert!(result.contains(&"../samples/simple/public/tables/public.tax_table.sql"));
assert!(result.contains(&"../samples/simple/public/tables/public.vendor.sql"));
}
#[test]
fn it_can_iterate_custom_exclude_globs_correctly_2() {
// This test relies on the `simple` samples directory
let parent = Path::new("../samples/complex");
let project = Project {
project_file_path: None,
version: "1.0".into(),
default_schema: "public".into(),
pre_deploy_scripts: Vec::new(),
post_deploy_scripts: Vec::new(),
extensions: None,
include_globs: None,
exclude_globs: Some(vec!["**/geo/**/*.sql".into(), "**/geo.*".into()]),
reference_search_paths: None,
};
let result = project.walk_files(&parent);
// Check the expected files were returned
assert!(result.is_ok());
let result = result.unwrap();
let result: Vec<&str> = result.iter().map(|x| x.to_str().unwrap()).collect();
assert!(!result.contains(&"../samples/complex/geo/functions/fn_do_any_coordinates_fall_inside.sql"));
assert!(!result.contains(&"../samples/complex/geo/tables/states.sql"));
assert!(!result.contains(&"../samples/complex/scripts/seed/geo.states.sql"));
}
#[test]
fn it_can_iterate_custom_include_globs_correctly() {
// This test relies on the `simple` samples directory
let parent = Path::new("../samples/simple");
let project = Project {
project_file_path: None,
version: "1.0".into(),
default_schema: "public".into(),
pre_deploy_scripts: Vec::new(),
post_deploy_scripts: Vec::new(),
extensions: None,
include_globs: Some(vec!["**/*org*.sql".into()]),
exclude_globs: None,
reference_search_paths: None,
};
let result = project.walk_files(&parent);
// Check the expected files were returned
assert!(result.is_ok());
let result = result.unwrap();
assert_eq!(result.len(), 1);
let result: Vec<&str> = result.iter().map(|x| x.to_str().unwrap()).collect();
assert!(result.contains(&"../samples/simple/public/tables/public.organisation.sql"));
}
#[test]
fn it_can_add_read_a_project_in_json_format() {
const DATA: &str = r#"
{
"version": "1.0",
"defaultSchema": "public",
"preDeployScripts": [
"scripts/pre-deploy/drop-something.sql"
],
"postDeployScripts": [
"scripts/seed/seed1.sql",
"scripts/seed/seed2.sql"
],
"fileExcludeGlobs": [
"**/ex/**/*.sql",
"**/ex.*"
],
"extensions": [
{ "name": "postgis" },
{ "name": "postgis_topology" },
{ "name": "postgis_tiger_geocoder" }
]
}
"#;
let project = Project::from_reader(DATA.as_bytes());
let project = project.unwrap();
assert_eq!(project.version, Semver::new(1, 0, None));
assert_eq!(project.default_schema, "public");
assert_eq!(project.pre_deploy_scripts.len(), 1);
assert_eq!(project.pre_deploy_scripts[0], "scripts/pre-deploy/drop-something.sql");
assert_eq!(project.post_deploy_scripts.len(), 2);
assert_eq!(project.post_deploy_scripts[0], "scripts/seed/seed1.sql");
assert_eq!(project.post_deploy_scripts[1], "scripts/seed/seed2.sql");
assert!(project.exclude_globs.is_some());
let exclude_globs = project.exclude_globs.unwrap();
assert_eq!(exclude_globs.len(), 2);
assert_eq!(exclude_globs[0], "**/ex/**/*.sql");
assert_eq!(exclude_globs[1], "**/ex.*");
assert!(project.extensions.is_some());
let extensions = project.extensions.unwrap();
assert_eq!(extensions.len(), 3);
assert_eq!(
extensions[0],
Dependency {
name: "postgis".into(),
version: None,
}
);
assert_eq!(
extensions[1],
Dependency {
name: "postgis_topology".into(),
version: None,
}
);
assert_eq!(
extensions[2],
Dependency {
name: "postgis_tiger_geocoder".into(),
version: None,
}
);
}
#[test]
fn it_can_add_read_a_project_in_toml_format() {
const DATA: &str = r#"
version = "1.0"
default_schema = "public"
pre_deploy_scripts = [
"scripts/pre-deploy/drop-something.sql"
]
post_deploy_scripts = [
"scripts/seed/seed1.sql",
"scripts/seed/seed2.sql"
]
file_exclude_globs = [
"**/ex/**/*.sql",
"**/ex.*"
]
extensions = [
{ name = "postgis" },
{ name = "postgis_topology" },
{ name = "postgis_tiger_geocoder" }
]
"#;
let project = Project::from_reader(DATA.as_bytes());
let project = project.unwrap();
assert_eq!(project.version, Semver::new(1, 0, None));
assert_eq!(project.default_schema, "public");
assert_eq!(project.pre_deploy_scripts.len(), 1);
assert_eq!(project.pre_deploy_scripts[0], "scripts/pre-deploy/drop-something.sql");
assert_eq!(project.post_deploy_scripts.len(), 2);
assert_eq!(project.post_deploy_scripts[0], "scripts/seed/seed1.sql");
assert_eq!(project.post_deploy_scripts[1], "scripts/seed/seed2.sql");
assert!(project.exclude_globs.is_some());
let exclude_globs = project.exclude_globs.unwrap();
assert_eq!(exclude_globs.len(), 2);
assert_eq!(exclude_globs[0], "**/ex/**/*.sql");
assert_eq!(exclude_globs[1], "**/ex.*");
assert!(project.extensions.is_some());
let extensions = project.extensions.unwrap();
assert_eq!(extensions.len(), 3);
assert_eq!(
extensions[0],
Dependency {
name: "postgis".into(),
version: None,
}
);
assert_eq!(
extensions[1],
Dependency {
name: "postgis_topology".into(),
version: None,
}
);
assert_eq!(
extensions[2],
Dependency {
name: "postgis_tiger_geocoder".into(),
version: None,
}
);
}
}
|
use shared_library::dynamic_library::DynamicLibrary;
use utilities::prelude::*;
use crate::impl_vk_handle;
use crate::loader::*;
use crate::prelude::*;
use crate::Extensions;
use std::collections::HashSet;
use std::fmt;
use std::mem::MaybeUninit;
use std::ptr;
use std::sync::Arc;
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ffi::CStr;
use std::ffi::CString;
Extensions!(InstanceExtensions, {
(xlib_surface, "VK_KHR_xlib_surface"),
(wayland_surface, "VK_KHR_wayland_surface"),
(android_surface, "VK_KHR_android_surface"),
(macos_surface, "VK_KHR_macos_surface"),
(win32_surface, "VK_KHR_win32_surface"),
(surface, "VK_KHR_surface"),
(physical_device_properties2, "VK_KHR_get_physical_device_properties2"),
});
#[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
pub struct VulkanDebugInfo {
pub debugging: bool,
pub steam_layer: bool,
pub verbose: bool,
pub renderdoc: bool,
pub use_util: bool,
}
pub struct Instance {
_vulkan_library: Option<DynamicLibrary>,
_static_functions: StaticFunctions,
_entry_functions: EntryFunctions,
instance_functions: InstanceFunctions,
instance_wsi_functions: InstanceWSIFunctions,
physical_device_properties2_functions: PhysicalDeviceProperties2Functions,
debug_report_callback_functions: DebugReportCallbackFunctions,
debug_utils_messenger_functions: DebugUtilsMessengerFunctions,
instance: VkInstance,
instance_extensions: InstanceExtensions,
debug_report: Option<VkDebugReportCallbackEXT>,
debug_utils: Option<VkDebugUtilsMessengerEXT>,
}
struct Layer {
props: Vec<VkLayerProperties>,
}
impl Layer {
fn create(entry_functions: &EntryFunctions) -> VerboseResult<Layer> {
Ok(Layer {
props: Instance::enumerate_layer_properties(
entry_functions.vkEnumerateInstanceLayerProperties,
)?,
})
}
fn names(
&self,
debugging: bool,
steam_layer: bool,
verbose: bool,
renderdoc: bool,
) -> VerboseResult<Vec<VkString>> {
let mut names = Vec::new();
for i in 0..self.props.len() {
let name_string = self.props[i].layer_name()?;
let name = name_string.as_str();
if debugging
&& (name == "VK_LAYER_LUNARG_standard_validation"
|| name == "VK_LAYER_KHRONOS_validation")
{
names.push(name_string.clone());
}
if verbose && name == "VK_LAYER_LUNARG_api_dump" {
names.push(name_string.clone());
}
if renderdoc && name == "VK_LAYER_RENDERDOC_Capture" {
names.push(name_string.clone());
}
if steam_layer
&& (name == "VK_LAYER_VALVE_steam_overlay_64"
|| name == "VK_LAYER_VALVE_steam_overlay_32")
{
names.push(name_string.clone());
}
}
Ok(names)
}
}
impl Instance {
pub fn new(
app_info: VkApplicationInfo<'_>,
debug_info: VulkanDebugInfo,
extensions: InstanceExtensions,
) -> VerboseResult<Arc<Instance>> {
let (library, static_functions) = load_static()?;
let entry_functions = load_entry(&static_functions);
let layers = if debug_info.debugging {
let layer_object = Layer::create(&entry_functions)?;
layer_object.names(
true,
debug_info.steam_layer,
debug_info.verbose,
debug_info.renderdoc,
)?
} else if debug_info.renderdoc {
let layer_object = Layer::create(&entry_functions)?;
// render doc only
layer_object.names(false, false, false, true)?
} else {
Vec::new()
};
let mut checked_extensions = Vec::new();
let mut extension_list = extensions.as_list();
if debug_info.debugging || debug_info.renderdoc {
extension_list.push(VkString::new("VK_EXT_debug_report"));
}
if debug_info.use_util {
extension_list.push(VkString::new("VK_EXT_debug_utils"));
}
if !extension_list.is_empty() {
let extension_properties = Self::get_extension_properties(&entry_functions, &layers)?;
for extension in extension_list {
for ext_prop in &extension_properties {
if extension == *ext_prop {
checked_extensions.push(extension);
break;
}
}
}
}
// instance create info
let layer_names = VkNames::new(layers.as_slice());
let extension_names = VkNames::new(checked_extensions.as_slice());
let instance_ci = VkInstanceCreateInfo::new(
VK_INSTANCE_CREATE_NULL_BIT,
&app_info,
&layer_names,
&extension_names,
);
if debug_info.debugging {
println!("enabled layers ({}):", layer_names.len());
for layer_name in layer_names.iter() {
println!("\t- {:?}", layer_name);
}
println!("\nenabled instance extensions ({}):", extension_names.len());
for extension_name in extension_names.iter() {
println!("\t- {:?}", extension_name);
}
println!();
}
let enabled_extensions = InstanceExtensions::from_list(&checked_extensions);
if debug_info.debugging {
if let Err(missing_extensions) = extensions.check_availability(&enabled_extensions) {
for m in missing_extensions {
println!("{}", m);
}
}
}
let instance = unsafe {
let mut instance = MaybeUninit::uninit();
let result =
entry_functions.vkCreateInstance(&instance_ci, ptr::null(), instance.as_mut_ptr());
if result == VK_SUCCESS {
instance.assume_init()
} else {
create_error!(format!("failed creating VkInstance handle: {:?}", result))
}
};
let instance_functions = load_instance(&static_functions, instance);
let instance_wsi_functions = load_instance_wsi(&static_functions, instance);
let physical_device_properties2_functions =
load_physical_device_properties_2(&static_functions, instance);
let debug_report_callback_functions = load_debug_report_ext(&static_functions, instance);
let debug_utils_messenger_functions = load_debug_utils_ext(&static_functions, instance);
let mut instance = Instance {
_vulkan_library: Some(library),
_static_functions: static_functions,
_entry_functions: entry_functions,
instance_functions,
instance_wsi_functions,
physical_device_properties2_functions,
debug_report_callback_functions,
debug_utils_messenger_functions,
instance,
instance_extensions: enabled_extensions,
debug_utils: None,
debug_report: None,
};
if !layers.is_empty() {
let use_util = if debug_info.use_util {
// TODO: debug util doesnt output anything
match instance.create_debug_util() {
Ok(_) => true,
Err(msg) => {
println!("failed creating debug util: {}", msg);
false
}
}
} else {
false
};
// only create debug report when debug util isnt created
if !use_util {
if let Err(msg) = instance.create_debug_report() {
println!("failed creating debug report: {}", msg);
}
}
}
Ok(Arc::new(instance))
}
pub fn vk_instance(&self) -> VkInstance {
self.instance
}
pub fn enabled_extensions(&self) -> &InstanceExtensions {
&self.instance_extensions
}
}
impl_vk_handle!(Instance, VkInstance, instance);
// private
impl Instance {
fn create_debug_report(&mut self) -> VerboseResult<()> {
let debug_report_info = VkDebugReportCallbackCreateInfoEXT::new(
VK_DEBUG_REPORT_WARNING_BIT_EXT
| VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT
| VK_DEBUG_REPORT_ERROR_BIT_EXT,
Instance::debug_report_callback,
);
let debug_report = self.create_debug_report_callbacks(&debug_report_info)?;
self.debug_report = Some(debug_report);
Ok(())
}
fn create_debug_util(&mut self) -> VerboseResult<()> {
let debug_util_create_ci = VkDebugUtilsMessengerCreateInfoEXT::new(
VK_DEBUG_UTILS_MESSENGER_CREATE_NULL_BIT,
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT
| VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT
| VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT
| VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
Self::debug_util_callback,
);
let debug_util_messenger = self.create_debug_utils_messenger(&debug_util_create_ci)?;
self.debug_utils = Some(debug_util_messenger);
Ok(())
}
fn get_extension_properties(
entry_functions: &EntryFunctions,
layers: &[VkString],
) -> VerboseResult<Vec<VkString>> {
let mut properties = HashSet::new();
let default_properties = Self::enumerate_extension_properties(
entry_functions.vkEnumerateInstanceExtensionProperties,
None,
)?;
for property in default_properties {
let prop_string = VkString::new(&property.extension_name()?);
properties.insert(prop_string);
}
for layer in layers {
let tmp_properties = Self::enumerate_extension_properties(
entry_functions.vkEnumerateInstanceExtensionProperties,
Some(layer),
)?;
for property in tmp_properties {
let prop_string = VkString::new(&property.extension_name()?);
properties.insert(prop_string);
}
}
Ok(properties.iter().cloned().collect())
}
}
// debug
impl Instance {
extern "system" fn debug_report_callback(
flags: VkDebugReportFlagsEXT,
object_type: VkDebugReportObjectTypeEXT,
_src_object: u64,
_location: usize,
_msg_code: i32,
_layer_prefix: *const c_char,
msg: *const c_char,
_user_data: *mut c_void,
) -> VkBool32 {
let mut output: String = String::new();
output += match flags {
VK_DEBUG_REPORT_INFORMATION_BIT_EXT => "INFO",
VK_DEBUG_REPORT_WARNING_BIT_EXT => "WARNING",
VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT => "PERFORMANCE",
VK_DEBUG_REPORT_ERROR_BIT_EXT => "ERROR",
VK_DEBUG_REPORT_DEBUG_BIT_EXT => "DEBUG",
};
output += ": OBJ( ";
output += match object_type {
VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT => "UNKNOWN",
VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT => "INSTANCE",
VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT => "PHYSICAL DEVICE",
VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT => "DEVICE",
VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT => "QUEUE",
VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT => "SEMAPHORE",
VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT => "COMMAND BUFFER",
VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT => "FENCE",
VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT => "DEVICE MEMORY",
VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT => "BUFFER",
VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT => "IMAGE",
VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT => "EVENT",
VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT => "QUERY POOL",
VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT => "BUFFER VIEW",
VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT => "IMAGE VIEW",
VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT => "SHADER MODULE",
VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT => "PIPELINE CACHE",
VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT => "PIPELINE LAYOUT",
VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT => "RENDER PASS",
VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT => "PIPELINE",
VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT => "DESCRIPTOR SET LAYOUT",
VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT => "SAMPLER",
VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT => "DESCRIPTOR POOL",
VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT => "DESCRIPTOR SET",
VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT => "FRAME BUFFER",
VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT => "COMMAND POOL",
VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT => "SURFACE KHR",
VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT => "SWAPCHAIN KHR",
VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT => "DEBUG REPORT",
VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT => "DISPLAY KHR",
VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT => "DISPLAY MODE KHR",
VK_DEBUG_REPORT_OBJECT_TYPE_OBJECT_TABLE_NVX_EXT => "OBJECT TABLE NVX",
VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT => {
"INDIRECT COMMANDS LAYOUT NVX"
}
VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT => "VALIDATION CACHE ",
VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT => "SAMPLER YCBCR CONVERSION ",
VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_EXT => {
"DESCRIPTOR UPDATE TEMPLATE "
}
VK_DEBUG_REPORT_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV_EXT => {
"ACCELERATION STRUCTURE NV"
}
};
let tmp1 = unsafe { CString::from_raw(msg as *mut c_char) };
let tmp2 = match tmp1.into_string() {
Ok(string) => string,
Err(err) => {
println!("{}", err);
return VK_FALSE;
}
};
output += " ):\n\t";
output += tmp2.as_ref();
println!("{}", output);
VK_TRUE
}
extern "system" fn debug_util_callback(
message_severity: VkDebugUtilsMessageSeverityFlagsEXT,
message_type: VkDebugUtilsMessageTypeFlagsEXT,
messenger_data: *const VkDebugUtilsMessengerCallbackDataEXT,
_user_data: *mut c_void,
) -> VkBool32 {
let mut output = String::new();
output += match message_severity {
VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT => "VERBOSE",
VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT => "INFO",
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT => "WARNING",
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT => "ERROR",
};
output += ": TYPE( ";
output += match message_type {
VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT => "GENERAL",
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT => "VALIDATION",
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT => "PERFORMANCE",
};
output += " )";
let data = unsafe { &*messenger_data };
let objects = data.objects();
for object in objects {
output += "OBJ( ";
output += match object.objectType {
VK_OBJECT_TYPE_UNKNOWN => "UNKNOWN",
VK_OBJECT_TYPE_INSTANCE => "INSTANCE",
VK_OBJECT_TYPE_PHYSICAL_DEVICE => "PHYSICAL DEVICE",
VK_OBJECT_TYPE_DEVICE => "DEVICE",
VK_OBJECT_TYPE_QUEUE => "QUEUE",
VK_OBJECT_TYPE_SEMAPHORE => "SEMAPHORE",
VK_OBJECT_TYPE_COMMAND_BUFFER => "COMMAND BUFFER",
VK_OBJECT_TYPE_FENCE => "FENCE",
VK_OBJECT_TYPE_DEVICE_MEMORY => "DEVICE MEMORY",
VK_OBJECT_TYPE_BUFFER => "BUFFER",
VK_OBJECT_TYPE_IMAGE => "IMAGE",
VK_OBJECT_TYPE_EVENT => "EVENT",
VK_OBJECT_TYPE_QUERY_POOL => "QUERY POOL",
VK_OBJECT_TYPE_BUFFER_VIEW => "BUFFER VIEW",
VK_OBJECT_TYPE_IMAGE_VIEW => "IMAGE VIEW",
VK_OBJECT_TYPE_SHADER_MODULE => "SHADER MODULE",
VK_OBJECT_TYPE_PIPELINE_CACHE => "PIPELINE CACHE",
VK_OBJECT_TYPE_PIPELINE_LAYOUT => "PIPELINE LAYOUT",
VK_OBJECT_TYPE_RENDER_PASS => "RENDER PASS",
VK_OBJECT_TYPE_PIPELINE => "PIPELINE",
VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT => "DESCRIPTOR SET LAYOUT",
VK_OBJECT_TYPE_SAMPLER => "SAMPLER",
VK_OBJECT_TYPE_DESCRIPTOR_POOL => "DESCRIPTOR POOL",
VK_OBJECT_TYPE_DESCRIPTOR_SET => "DESCRIPTOR SET",
VK_OBJECT_TYPE_FRAMEBUFFER => "FRAME BUFFER",
VK_OBJECT_TYPE_COMMAND_POOL => "COMMAND POOL",
VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION => "SAMPLER YCBCR CONVERSION",
VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE => "DESCRIPTOR UPDATE TEMPLATE",
VK_OBJECT_TYPE_SURFACE_KHR => "SURFACE KHR",
VK_OBJECT_TYPE_SWAPCHAIN_KHR => "SWAPCHAIN KHR",
VK_OBJECT_TYPE_DISPLAY_KHR => "DISPLAY KHR",
VK_OBJECT_TYPE_DISPLAY_MODE_KHR => "DISPLAY MODE KHR",
VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT => "DEBUG REPORT CALLBACK EXT",
VK_OBJECT_TYPE_OBJECT_TABLE_NVX => "OBJECT TABLE NVX",
VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX => "INDIRECT COMMANDS LAYOUT NVX",
VK_OBJECT_TYPE_VALIDATION_CACHE_EXT => "VALIDATION CACHE EXT",
VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT => "DEBUG UTILS MESSENGER EXT",
};
output += " ) ";
}
output += ": ";
if let Ok(message) = data.message() {
output += &message;
}
VK_TRUE
}
}
impl fmt::Debug for Instance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Instance (VkInstance: {:#?})", self.instance)
}
}
impl Drop for Instance {
fn drop(&mut self) {
if let Some(debug_report) = &self.debug_report {
self.destroy_debug_report_callbacks(*debug_report);
}
if let Some(debug_utils) = &self.debug_utils {
self.destroy_debug_utils_messenger(*debug_utils);
}
self.destroy_instance();
}
}
// private wrapper
impl Instance {
fn enumerate_layer_properties(
enumerate_instance_layer_properties: PFN_vkEnumerateInstanceLayerProperties,
) -> VerboseResult<Vec<VkLayerProperties>> {
let mut property_count: u32 = 0;
// get the amount of properties
let result = enumerate_instance_layer_properties(&mut property_count, ptr::null_mut());
if result != VK_SUCCESS {
create_error!(format!("failed enumerating instance layers: {:?}", result));
}
let mut properties = Vec::with_capacity(property_count as usize);
unsafe { properties.set_len(property_count as usize) };
// get the properties
let result =
enumerate_instance_layer_properties(&mut property_count, properties.as_mut_ptr());
if result == VK_SUCCESS {
Ok(properties)
} else {
create_error!(format!("failed enumerating instance layers: {:?}", result));
}
}
fn enumerate_extension_properties(
enumerate_instance_extension_properties: PFN_vkEnumerateInstanceExtensionProperties,
layer_name: Option<&VkString>,
) -> VerboseResult<Vec<VkExtensionProperties>> {
let mut count = 0;
let name = match layer_name {
Some(name) => name.as_ptr(),
None => ptr::null(),
};
let mut result = enumerate_instance_extension_properties(name, &mut count, ptr::null_mut());
if result != VK_SUCCESS {
create_error!(format!(
"failed enumerating instance extensions: {:?}",
result
));
}
let mut properties = Vec::with_capacity(count as usize);
unsafe { properties.set_len(count as usize) };
result = enumerate_instance_extension_properties(name, &mut count, properties.as_mut_ptr());
if result == VK_SUCCESS {
Ok(properties)
} else {
create_error!(format!(
"failed enumerating instance extensions: {:?}",
result
));
}
}
fn destroy_instance(&self) {
unsafe {
self.instance_functions
.vkDestroyInstance(self.instance, ptr::null());
}
}
}
// public, wrapped vulkan calls
impl Instance {
pub fn create_debug_report_callbacks(
&self,
debug_report_callback_create_info: &VkDebugReportCallbackCreateInfoEXT,
) -> VerboseResult<VkDebugReportCallbackEXT> {
unsafe {
let mut debug_report_callback = MaybeUninit::uninit();
let result = self
.debug_report_callback_functions
.vkCreateDebugReportCallbackEXT(
self.instance,
debug_report_callback_create_info,
ptr::null(),
debug_report_callback.as_mut_ptr(),
);
if result == VK_SUCCESS {
Ok(debug_report_callback.assume_init())
} else {
create_error!(format!(
"failed creating VkDebugReportCallbackEXT: {:?}",
result
));
}
}
}
pub fn destroy_debug_report_callbacks(&self, debug_report_callback: VkDebugReportCallbackEXT) {
unsafe {
self.debug_report_callback_functions
.vkDestroyDebugReportCallbackEXT(self.instance, debug_report_callback, ptr::null())
}
}
pub fn create_debug_utils_messenger(
&self,
debug_utils_messenger_create_info: &VkDebugUtilsMessengerCreateInfoEXT,
) -> VerboseResult<VkDebugUtilsMessengerEXT> {
unsafe {
let mut debug_utils_messenger = MaybeUninit::uninit();
let result = self
.debug_utils_messenger_functions
.vkCreateDebugUtilsMessengerEXT(
self.instance,
debug_utils_messenger_create_info,
ptr::null(),
debug_utils_messenger.as_mut_ptr(),
);
if result == VK_SUCCESS {
Ok(debug_utils_messenger.assume_init())
} else {
create_error!(format!(
"failed creating VkDebugUtilsMessengerEXT: {:?}",
result
));
}
}
}
pub fn destroy_debug_utils_messenger(&self, debug_utils_messenger: VkDebugUtilsMessengerEXT) {
unsafe {
self.debug_utils_messenger_functions
.vkDestroyDebugUtilsMessengerEXT(self.instance, debug_utils_messenger, ptr::null())
}
}
pub fn get_device_proc_addr(&self, device: VkDevice, name: VkString) -> PFN_vkVoidFunction {
unsafe {
self.instance_functions
.vkGetDeviceProcAddr(device, name.as_ptr())
}
}
pub fn get_device_proc_addr_raw(&self, device: VkDevice, name: &CStr) -> PFN_vkVoidFunction {
unsafe {
self.instance_functions
.vkGetDeviceProcAddr(device, name.as_ptr())
}
}
pub fn enumerate_physical_devices(&self) -> VerboseResult<Vec<VkPhysicalDevice>> {
let mut count = 0;
let result = unsafe {
self.instance_functions.vkEnumeratePhysicalDevices(
self.instance,
&mut count,
ptr::null_mut(),
)
};
if result != VK_SUCCESS {
create_error!(format!("failed enumerating physical devices {:?}", result));
}
let mut physical_devices = Vec::with_capacity(count as usize);
unsafe { physical_devices.set_len(count as usize) };
let result = unsafe {
self.instance_functions.vkEnumeratePhysicalDevices(
self.instance,
&mut count,
physical_devices.as_mut_ptr(),
)
};
if result == VK_SUCCESS {
Ok(physical_devices)
} else {
create_error!(format!("failed enumerating physical devices {:?}", result));
}
}
pub fn physical_device_properties(
&self,
physical_device: VkPhysicalDevice,
) -> VkPhysicalDeviceProperties {
unsafe {
let mut physical_device_properties = MaybeUninit::uninit();
self.instance_functions.vkGetPhysicalDeviceProperties(
physical_device,
physical_device_properties.as_mut_ptr(),
);
physical_device_properties.assume_init()
}
}
pub fn physical_device_features(
&self,
physical_device: VkPhysicalDevice,
) -> VkPhysicalDeviceFeatures {
unsafe {
let mut physical_device_features = MaybeUninit::uninit();
self.instance_functions.vkGetPhysicalDeviceFeatures(
physical_device,
physical_device_features.as_mut_ptr(),
);
physical_device_features.assume_init()
}
}
pub fn physical_device_format_properties(
&self,
physical_device: VkPhysicalDevice,
format: VkFormat,
) -> VkFormatProperties {
unsafe {
let mut physical_device_format_properties = MaybeUninit::uninit();
self.instance_functions.vkGetPhysicalDeviceFormatProperties(
physical_device,
format,
physical_device_format_properties.as_mut_ptr(),
);
physical_device_format_properties.assume_init()
}
}
pub fn physical_device_queue_family_properties(
&self,
physical_device: VkPhysicalDevice,
) -> Vec<VkQueueFamilyProperties> {
let mut count = 0;
unsafe {
self.instance_functions
.vkGetPhysicalDeviceQueueFamilyProperties(
physical_device,
&mut count,
ptr::null_mut(),
);
}
let mut queue_family_properties = Vec::with_capacity(count as usize);
unsafe { queue_family_properties.set_len(count as usize) };
unsafe {
self.instance_functions
.vkGetPhysicalDeviceQueueFamilyProperties(
physical_device,
&mut count,
queue_family_properties.as_mut_ptr(),
);
}
queue_family_properties
}
pub fn physical_device_memory_properties(
&self,
physical_device: VkPhysicalDevice,
) -> VkPhysicalDeviceMemoryProperties {
unsafe {
let mut physical_device_memory_properties = MaybeUninit::uninit();
self.instance_functions.vkGetPhysicalDeviceMemoryProperties(
physical_device,
physical_device_memory_properties.as_mut_ptr(),
);
physical_device_memory_properties.assume_init()
}
}
pub fn physical_device_sparse_image_format_properties<T>(
&self,
physical_device: VkPhysicalDevice,
format: VkFormat,
ty: VkImageType,
samples: VkSampleCountFlags,
usage: impl Into<VkImageUsageFlagBits>,
tiling: VkImageTiling,
) -> Vec<VkSparseImageFormatProperties> {
let mut count = 0;
let usage = usage.into();
unsafe {
self.instance_functions
.vkGetPhysicalDeviceSparseImageFormatProperties(
physical_device,
format,
ty,
samples,
usage,
tiling,
&mut count,
ptr::null_mut(),
);
}
let mut sparse_image_formats = Vec::with_capacity(count as usize);
unsafe { sparse_image_formats.set_len(count as usize) };
unsafe {
self.instance_functions
.vkGetPhysicalDeviceSparseImageFormatProperties(
physical_device,
format,
ty,
samples,
usage,
tiling,
&mut count,
sparse_image_formats.as_mut_ptr(),
);
}
sparse_image_formats
}
pub fn physical_device_image_format_properties(
&self,
physical_device: VkPhysicalDevice,
format: VkFormat,
image_type: VkImageType,
tiling: VkImageTiling,
usage: impl Into<VkImageUsageFlagBits>,
flags: impl Into<VkImageCreateFlagBits>,
) -> VerboseResult<VkImageFormatProperties> {
unsafe {
let mut image_format_properties = MaybeUninit::uninit();
let result = self
.instance_functions
.vkGetPhysicalDeviceImageFormatProperties(
physical_device,
format,
image_type,
tiling,
usage.into(),
flags.into(),
image_format_properties.as_mut_ptr(),
);
if result == VK_SUCCESS {
Ok(image_format_properties.assume_init())
} else {
create_error!(format!(
"failed getting physical device image format properties {:?}",
result
))
}
}
}
pub fn create_device<'a>(
&self,
physical_device: VkPhysicalDevice,
device_create_info: &'a VkDeviceCreateInfo<'a>,
) -> VerboseResult<VkDevice> {
unsafe {
let mut device = MaybeUninit::uninit();
let result = self.instance_functions.vkCreateDevice(
physical_device,
device_create_info,
ptr::null(),
device.as_mut_ptr(),
);
if result == VK_SUCCESS {
Ok(device.assume_init())
} else {
create_error!(format!("failed creating VkDevice {:?}", result))
}
}
}
pub fn physical_device_surface_support(
&self,
physical_device: VkPhysicalDevice,
queue_family_index: u32,
surface: VkSurfaceKHR,
) -> VerboseResult<bool> {
unsafe {
let mut supported = MaybeUninit::uninit();
let result = self
.instance_wsi_functions
.vkGetPhysicalDeviceSurfaceSupportKHR(
physical_device,
queue_family_index,
surface,
supported.as_mut_ptr(),
);
if result == VK_SUCCESS {
Ok(supported.assume_init() == VK_TRUE)
} else {
create_error!(format!("failed getting surface support {:?}", result))
}
}
}
pub fn physical_device_surface_capabilities(
&self,
physical_device: VkPhysicalDevice,
surface: VkSurfaceKHR,
) -> VerboseResult<VkSurfaceCapabilitiesKHR> {
unsafe {
let mut surface_capabilities = MaybeUninit::uninit();
let result = self
.instance_wsi_functions
.vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
physical_device,
surface,
surface_capabilities.as_mut_ptr(),
);
if result == VK_SUCCESS {
Ok(surface_capabilities.assume_init())
} else {
create_error!(format!("failed getting surface capabilities {:?}", result))
}
}
}
pub fn physical_device_surface_formats(
&self,
physical_device: VkPhysicalDevice,
surface: VkSurfaceKHR,
) -> VerboseResult<Vec<VkSurfaceFormatKHR>> {
let mut count = 0;
let result = unsafe {
self.instance_wsi_functions
.vkGetPhysicalDeviceSurfaceFormatsKHR(
physical_device,
surface,
&mut count,
ptr::null_mut(),
)
};
if result != VK_SUCCESS {
create_error!(format!("failed getting surface formats {:?}", result))
}
let mut surface_formats = Vec::with_capacity(count as usize);
unsafe { surface_formats.set_len(count as usize) };
let result = unsafe {
self.instance_wsi_functions
.vkGetPhysicalDeviceSurfaceFormatsKHR(
physical_device,
surface,
&mut count,
surface_formats.as_mut_ptr(),
)
};
if result == VK_SUCCESS {
Ok(surface_formats)
} else {
create_error!(format!("failed getting surface formats {:?}", result))
}
}
pub fn physical_device_present_modes(
&self,
physical_device: VkPhysicalDevice,
surface: VkSurfaceKHR,
) -> VerboseResult<Vec<VkPresentModeKHR>> {
let mut count = 0;
let result = unsafe {
self.instance_wsi_functions
.vkGetPhysicalDeviceSurfacePresentModesKHR(
physical_device,
surface,
&mut count,
ptr::null_mut(),
)
};
if result != VK_SUCCESS {
create_error!(format!("failed getting present modes {:?}", result))
}
let mut surface_present_modes = Vec::with_capacity(count as usize);
unsafe { surface_present_modes.set_len(count as usize) };
let result = unsafe {
self.instance_wsi_functions
.vkGetPhysicalDeviceSurfacePresentModesKHR(
physical_device,
surface,
&mut count,
surface_present_modes.as_mut_ptr(),
)
};
if result == VK_SUCCESS {
Ok(surface_present_modes)
} else {
create_error!(format!("failed getting present modes {:?}", result))
}
}
pub fn enumerate_device_extensions(
&self,
physical_device: VkPhysicalDevice,
) -> VerboseResult<Vec<VkExtensionProperties>> {
let mut count = 0;
let result = unsafe {
self.instance_functions
.vkEnumerateDeviceExtensionProperties(
physical_device,
ptr::null(),
&mut count,
ptr::null_mut(),
)
};
if result != VK_SUCCESS {
create_error!(format!("failed enumerating device extensions {:?}", result))
}
let mut extension_properties = Vec::with_capacity(count as usize);
unsafe { extension_properties.set_len(count as usize) };
let result = unsafe {
self.instance_functions
.vkEnumerateDeviceExtensionProperties(
physical_device,
ptr::null(),
&mut count,
extension_properties.as_mut_ptr(),
)
};
if result == VK_SUCCESS {
Ok(extension_properties)
} else {
create_error!(format!("failed enumerating device extensions {:?}", result))
}
}
pub fn physical_device_properties2(
&self,
physical_device: VkPhysicalDevice,
device_properties: &mut VkPhysicalDeviceProperties2KHR,
) {
unsafe {
self.physical_device_properties2_functions
.vkGetPhysicalDeviceProperties2KHR(physical_device, device_properties);
}
}
pub fn physical_device_features2(
&self,
physical_device: VkPhysicalDevice,
device_features: &mut VkPhysicalDeviceFeatures2KHR,
) {
unsafe {
self.physical_device_properties2_functions
.vkGetPhysicalDeviceFeatures2KHR(physical_device, device_features);
}
}
pub fn physical_device_format_properties2(
&self,
physical_device: VkPhysicalDevice,
) -> VkFormatProperties2KHR<'_> {
unsafe {
let mut handle = MaybeUninit::uninit();
self.physical_device_properties2_functions
.vkGetPhysicalDeviceFormatProperties2KHR(physical_device, handle.as_mut_ptr());
handle.assume_init()
}
}
pub fn physical_device_image_format_properties2(
&self,
physical_device: VkPhysicalDevice,
image_format_info: &VkPhysicalDeviceImageFormatInfo2KHR,
) -> VkImageFormatProperties2KHR<'_> {
unsafe {
let mut handle = MaybeUninit::uninit();
self.physical_device_properties2_functions
.vkGetPhysicalDeviceImageFormatProperties2KHR(
physical_device,
image_format_info,
handle.as_mut_ptr(),
);
handle.assume_init()
}
}
pub fn physical_device_queue_family_properties2(
&self,
physical_device: VkPhysicalDevice,
) -> Vec<VkQueueFamilyProperties2KHR> {
let mut count = 0;
unsafe {
self.physical_device_properties2_functions
.vkGetPhysicalDeviceQueueFamilyProperties2KHR(
physical_device,
&mut count,
ptr::null_mut(),
)
};
let mut family_queue_properties = Vec::with_capacity(count as usize);
unsafe { family_queue_properties.set_len(count as usize) };
unsafe {
self.physical_device_properties2_functions
.vkGetPhysicalDeviceQueueFamilyProperties2KHR(
physical_device,
&mut count,
family_queue_properties.as_mut_ptr(),
)
};
family_queue_properties
}
pub fn physical_device_memory_properties2(
&self,
physical_device: VkPhysicalDevice,
) -> VkPhysicalDeviceMemoryProperties2KHR {
unsafe {
let mut handle = MaybeUninit::uninit();
self.physical_device_properties2_functions
.vkGetPhysicalDeviceMemoryProperties2KHR(physical_device, handle.as_mut_ptr());
handle.assume_init()
}
}
pub fn physical_device_memory_budget(
&self,
physical_device: VkPhysicalDevice,
) -> (VkPhysicalDeviceMemoryBudgetPropertiesEXT, u32) {
unsafe {
let mut properties = VkPhysicalDeviceMemoryProperties2KHR::default();
let memory_budget = VkPhysicalDeviceMemoryBudgetPropertiesEXT::default();
properties.chain(&memory_budget);
self.physical_device_properties2_functions
.vkGetPhysicalDeviceMemoryProperties2KHR(physical_device, &mut properties);
(memory_budget, properties.memoryProperties.memoryHeapCount)
}
}
pub fn physical_device_sparse_image_format_properties2(
&self,
physical_device: VkPhysicalDevice,
format_info: &VkPhysicalDeviceSparseImageFormatInfo2KHR,
) -> Vec<VkSparseImageFormatProperties2KHR> {
let mut count = 0;
unsafe {
self.physical_device_properties2_functions
.vkGetPhysicalDeviceSparseImageFormatProperties2KHR(
physical_device,
format_info,
&mut count,
ptr::null_mut(),
)
};
let mut sparse_image_formats = Vec::with_capacity(count as usize);
unsafe { sparse_image_formats.set_len(count as usize) };
unsafe {
self.physical_device_properties2_functions
.vkGetPhysicalDeviceSparseImageFormatProperties2KHR(
physical_device,
format_info,
&mut count,
sparse_image_formats.as_mut_ptr(),
)
};
sparse_image_formats
}
pub fn destroy_surface(&self, surface: VkSurfaceKHR) {
unsafe {
self.instance_wsi_functions
.vkDestroySurfaceKHR(self.instance, surface, ptr::null())
};
}
}
|
#[macro_use]
extern crate webframework;
use webframework::{Database, Form, Former, Renderer, Tag, Content, Server, path::*, Store, Serialize, Error};
use std::sync::Arc;
#[derive(Default, Form, Store, Serialize, Clone)]
struct Bullet {
#[id] #[form(type="text", min=1, max=512)] id: u64,
#[form(name="Description", type="text", min=1, max=512)] description: String,
}
fn main() {
let database = Arc::new(Database::new());
let renderer = Renderer::new(database.clone());
let mut server = Server::new("127.0.0.1:8000");
server.threads(8);
let bullet = Bullet {
id: 0,
description: String::from("This is a test.")
};
//bullet.create(&database);
server.route(path!(/), renderer.content(move |arguments| html!(
"<!DOCTYPE html>";
html {
head {
title { "Hello Rust Web Framework!"; }
}
body {
h1 { "Hello Rust Web Framework!"; }
p {
format!("{:?}", arguments);
}
Former::update(Bullet::read(0, &database.clone()).unwrap(), |bullet| {});
}
}
)));
server.start();
} |
macro_rules! ok_or_panic {
{ $e:expr } => {
match $e {
Ok(x) => x,
Err(err) => panic!("{} failed with {}", stringify!($e), err),
}
};
}
pub mod paths;
pub mod sandbox;
|
use crate::score::ex_score::ExScore;
use serde::Serialize;
#[derive(Clone, Debug, Serialize, Default)]
pub struct Judge {
pub early_pgreat: i32,
pub late_pgreat: i32,
pub early_great: i32,
pub late_great: i32,
pub early_good: i32,
pub late_good: i32,
pub early_bad: i32,
pub late_bad: i32,
pub early_poor: i32,
pub late_poor: i32,
pub early_miss: i32,
pub late_miss: i32,
}
impl Judge {
pub fn ex_score(&self) -> ExScore {
ExScore::from_score(
self.early_pgreat * 2 + self.late_pgreat * 2 + self.early_great + self.late_great,
)
}
}
impl std::ops::Sub<Judge> for Judge {
type Output = Judge;
fn sub(self, rhs: Judge) -> Judge {
Judge {
early_pgreat: self.early_pgreat - rhs.early_pgreat,
late_pgreat: self.late_pgreat - rhs.late_pgreat,
early_great: self.early_great - rhs.early_great,
late_great: self.late_great - rhs.late_great,
early_good: self.early_good - rhs.early_good,
late_good: self.late_good - rhs.late_good,
early_bad: self.early_bad - rhs.early_bad,
late_bad: self.late_bad - rhs.late_bad,
early_poor: self.early_poor - rhs.early_poor,
late_poor: self.late_poor - rhs.late_poor,
early_miss: self.early_miss - rhs.early_miss,
late_miss: self.late_miss - rhs.late_miss,
}
}
}
#[cfg(test)]
mod tests {
use crate::score::ex_score::ExScore;
use crate::Judge;
#[test]
fn ex_score() {
let judge = Judge {
early_pgreat: 1,
late_pgreat: 3,
early_great: 10,
late_great: 30,
early_good: 100,
late_good: 300,
early_bad: 1000,
late_bad: 3000,
early_poor: 10000,
late_poor: 30000,
early_miss: 100000,
late_miss: 300000,
};
assert_eq!(judge.ex_score(), ExScore::from_score(48))
}
}
|
table! {
grounds (id) {
id -> Int8,
types -> Varchar,
vertexes -> Json,
angles -> Json,
vectors -> Json,
}
}
allow_tables_to_appear_in_same_query!(
grounds
); |
use json_utils::json::JsNumber;
pub trait IntoJsNumber {
fn into_js_number(self) -> JsNumber;
}
impl IntoJsNumber for JsNumber {
fn into_js_number(self) -> JsNumber {
self
}
}
impl IntoJsNumber for usize {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
impl IntoJsNumber for u8 {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
impl IntoJsNumber for u16 {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
impl IntoJsNumber for u32 {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
impl IntoJsNumber for u64 {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
impl IntoJsNumber for i8 {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
impl IntoJsNumber for i16 {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
impl IntoJsNumber for i32 {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
impl IntoJsNumber for i64 {
fn into_js_number(self) -> JsNumber {
self.into()
}
}
|
extern crate cmake;
fn main() {
let dst = cmake::build("");
println!("cargo:rustc-link-search=native={}", dst.display());
println!("cargo:rustc-link-lib=static=axal");
// TODO: Generate this from the cmake file
println!("cargo:rustc-link-lib=dylib=GL");
println!("cargo:rustc-link-lib=dylib=Qt5Core");
println!("cargo:rustc-link-lib=dylib=Qt5Widgets");
println!("cargo:rustc-link-lib=dylib=Qt5Gui");
println!("cargo:rustc-link-lib=dylib=stdc++");
}
|
extern crate color;
extern crate nalgebra;
extern crate rand;
extern crate arc_swap;
extern crate dyn_clone;
mod geom;
mod image;
mod ppm;
mod raycasting;
mod renderer;
mod types;
mod material;
use arc_swap::ArcSwap;
use crate::geom::hittable::Hittable;
use crate::geom::sphere::Sphere;
use crate::types::{Vector3f, Vector2i};
use crate::renderer::camera::Camera;
use crate::material::material::{Lambertian, Metal, Dielectric};
extern crate piston_window;
extern crate image as piston_image;
use graphics::rectangle::rectangle_by_corners;
use piston_window::*;
// use image::Image as PistonImage;
use piston_image::ImageBuffer;
use piston_image::buffer::ConvertBuffer;
use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};
type RgbImageU8Vec = ImageBuffer::<piston_image::Rgb<u8>, std::vec::Vec<u8>>;
type RgbaImageU8Vec = ImageBuffer::<piston_image::Rgba<u8>, std::vec::Vec<u8>>;
type MainTextureContext = piston_window::TextureContext<
gfx_device_gl::Factory,
gfx_device_gl::Resources,
gfx_device_gl::CommandBuffer>;
fn renderer_image_to_piston_imagebuffer(src: image::image::Image) -> RgbImageU8Vec{
let dest = RgbImageU8Vec::from_raw(
src.size.width() as u32, src.size.height() as u32, src.data).unwrap();
dest
}
fn rgb2rgba(src: RgbImageU8Vec) -> RgbaImageU8Vec {
let dest = src.convert();
dest
}
use std::collections::HashSet;
type ArcMutex<T> = std::sync::Arc<std::sync::Mutex<T>>;
fn make_arc_mutex<T>(value: T) -> ArcMutex<T>{
std::sync::Arc::new(std::sync::Mutex::new(value))
}
struct UserInput {
pressed_keys: HashSet<Key>,
exit_requested: bool
}
impl UserInput {
pub fn new() -> UserInput {
UserInput {
pressed_keys: HashSet::new(),
exit_requested: false
}
}
}
fn start_render_thread(user_input_rx: Receiver<UserInput>,
renderer_framebuffer_tx: Sender<RgbaImageU8Vec>,
game_conf: GameConf,
game_state: ArcSwap<GameState>) -> std::thread::JoinHandle<()> {
let game: Game = Game::new();
let renderer_thread = thread::spawn( move || {
let mut running = true;
while running {
if let Ok(user_input) = user_input_rx.try_recv() {
if user_input.exit_requested {
running = false;
break;
}
}
println!("{:?}", game_state.load().camera.origin);
let rendered_image = game.render(game_state.load().as_ref());
println!("rendered!");
let image_buffer = renderer_image_to_piston_imagebuffer(rendered_image);
let image_buffer_rgba = rgb2rgba(image_buffer);
renderer_framebuffer_tx.send(image_buffer_rgba);
}
println!("exit from render thread");
});
renderer_thread
}
struct GameConf{
camera_size: Vector2i
}
fn generate_user_input(e: &Event) -> UserInput {
let mut user_input = UserInput::new();
if let Some(Button::Keyboard(key)) = e.press_args() {
user_input.pressed_keys.insert(key);
}
if user_input.pressed_keys.contains(&Key::Escape) {
println!("exiting from main thread");
user_input.exit_requested = true;
}
user_input
}
fn draw_window(window: &mut PistonWindow, e: &Event,
renderer_framebuffer_rx: &Receiver<RgbaImageU8Vec>,
texture_context: &mut MainTextureContext) {
window.draw_2d(e, |c, g, _device| {
match renderer_framebuffer_rx.try_recv() {
Ok(image) => {
println!("received rendered image");
clear([1.0; 4], g);
let img = Image::new().rect(rectangle_by_corners(0.0, 0.0,
image.width().into(),
image.height().into()));
let texture_settings = TextureSettings::new();
let texture = Texture::from_image(texture_context, &image, &texture_settings ).unwrap();
img.draw(&texture, &c.draw_state, c.transform.scale(5.0, 5.0), g);
},
Err(e) => {
}
}
});
}
fn make_wasd_vector(user_input: &UserInput) -> Vector3f {
let mut wasd_vector = Vector3f::new(0.0, 0.0, 0.0);
if user_input.pressed_keys.contains(&Key::W) {
wasd_vector.z += 1.0;
} else if user_input.pressed_keys.contains(&Key::S) {
wasd_vector.z -= 1.0;
}
if(user_input.pressed_keys.contains(&Key::A)) {
wasd_vector.x += 1.0;
} else if (user_input.pressed_keys.contains(&Key::D)) {
wasd_vector.x -= 1.0;
}
wasd_vector
}
fn update_camera(user_input: &UserInput, camera: Camera) -> Camera {
let mut new_camera = camera;
let mut wasd_vector = make_wasd_vector(user_input);
new_camera.fps_move(wasd_vector);
new_camera
}
fn update_game_state(user_input: &UserInput, previous_game_state: &GameState) -> GameState {
let mut new_game_state = dyn_clone::clone(previous_game_state);
new_game_state.camera = update_camera(user_input, new_game_state.camera);
new_game_state
}
fn main_thread(mut window: PistonWindow,
user_input_tx: Sender<UserInput>,
renderer_framebuffer_rx: Receiver<RgbaImageU8Vec>,
game_state: ArcSwap<GameState>) {
let mut running = true;
let mut texture_context = TextureContext {
factory: window.factory.clone(),
encoder: window.factory.create_command_buffer().into()
};
while let Some(e) = window.next() {
if !running {
break
}
let user_input = generate_user_input(&e);
let previous_game_state = game_state.load();
let new_game_state = update_game_state(&user_input, previous_game_state.as_ref());
game_state.store(std::sync::Arc::new(new_game_state));
if user_input.exit_requested {
println!("exiting from main thread");
running = false;
user_input_tx.send(user_input);
}
draw_window(&mut window, &e, &renderer_framebuffer_rx, &mut texture_context);
}
}
fn get_camera_size() -> Vector2i {
let camera_width : u32 = 200;
let camera_height: u32 = 120;
let camera_size = Vector2i::new(camera_width as i32, camera_height as i32);
camera_size
}
fn make_initial_game_state(camera_size: Vector2i) -> GameState {
GameState {
camera: Camera::new(camera_size.x, camera_size.y),
hittables: make_default_hittables()
}
}
fn main() {
let camera_size = get_camera_size();
let window: PistonWindow =
WindowSettings::new("renderer",
[camera_size.x as u32, camera_size.y as u32])
.exit_on_esc(true).build().unwrap();
let game_conf = GameConf { camera_size };
let (renderer_framebuffer_tx, renderer_framebuffer_rx) = channel();
let (user_input_tx, user_input_rx) = channel::<UserInput>();
let initial_game_state = make_initial_game_state(camera_size);
// let game_state = make_arc_mutex(initial_game_state);
let game_state = ArcSwap::new(std::sync::Arc::new(initial_game_state));
let renderer_thread = start_render_thread(
user_input_rx, renderer_framebuffer_tx,
game_conf, game_state.clone(),
);
main_thread(window, user_input_tx,
renderer_framebuffer_rx,
game_state);
renderer_thread.join().unwrap();
}
struct Game {
renderer: renderer::renderer::Renderer
}
#[derive(Clone)]
struct GameState {
hittables: Vec<Box<dyn Hittable>>,
camera: Camera
}
impl GameState {
pub fn new(camera: Camera) -> GameState {
GameState {
hittables: Vec::new(),
camera: camera
}
}
}
pub fn make_default_hittables() -> Vec<Box<dyn Hittable>> {
let material_ground = Lambertian::new(Vector3f::new(0.8, 0.8, 0.0));
let material_center = Lambertian::new(Vector3f::new(0.7, 0.3, 0.3));
// let material_left = Metal::new(Vector3f::new(0.8, 0.8, 0.8), 0.3);
// let material_center = Dielectric::new(1.5f32);
let material_left = Dielectric::new(1.5f32);
let material_right = Metal::new(Vector3f::new(0.8, 0.6, 0.2), 0.05);
let sphere_ground = Sphere {
origin: Vector3f::new(0f32, -100.5f32, -1.0f32),
radius: 100f32,
material: Some(Box::new(material_ground))
};
let sphere_center = Sphere {
origin: Vector3f::new(0f32, 0f32, -1f32),
radius: 0.5f32,
material: Some(Box::new(material_center))
};
let sphere_left = Sphere {
origin: Vector3f::new(-1f32, 0f32, -1f32),
radius: 0.5f32,
material: Some(Box::new(material_left))
};
let sphere_right = Sphere {
origin: Vector3f::new(1f32, 0f32, -1f32),
radius: 0.5f32,
material: Some(Box::new(material_right))
};
let hittables: Vec<Box<dyn Hittable>> = vec![
Box::new(sphere_ground),
Box::new(sphere_left),
Box::new(sphere_right),
Box::new(sphere_center),
];
hittables
}
impl Game {
pub fn new() -> Game {
let renderer = renderer::renderer::Renderer::new();
Game {
renderer
}
}
pub fn render(&self, game_state: &GameState) -> image::image::Image {
let hittables = &game_state.hittables;
let camera = &game_state.camera;
let image = self.renderer.run(camera, hittables);
ppm::save_image_to_ppm(
image.data.as_slice(),
image.size.width(),
image.size.height(),
"output.ppm",
);
image
}
}
|
use crate::{parser::ParserSettings, Runner, SMResult, AST};
impl Default for Runner {
fn default() -> Self {
Self { parser: ParserSettings { file: String::from("anonymous"), refine: true }, ctx: Default::default() }
}
}
impl Runner {
pub(crate) fn parse(&mut self, s: &str) -> SMResult<()> {
self.ctx.index += 1;
self.ctx.inputs.insert(self.ctx.index, String::from(s));
Ok(())
}
pub(crate) fn forward(&mut self) -> SMResult<()> {
let input = self.ctx.inputs.get(&self.ctx.index).unwrap();
let ast = self.parser.parse(input)?;
let output = ast.forward(&mut self.ctx)?;
self.ctx.outputs.insert(self.ctx.index, output);
Ok(())
}
pub fn evaluate(&mut self, input: &str) -> SMResult<String> {
self.parse(input)?;
self.forward()?;
let s = format!("{}", self.ctx.outputs.get(&self.ctx.index).unwrap());
Ok(s)
}
pub fn last(&self) -> SMResult<AST> {
let o = self.ctx.outputs.get(&self.ctx.index).unwrap();
Ok(o.clone())
}
}
|
#[doc = "Reader of register ITLINE7"]
pub type R = crate::R<u32, super::ITLINE7>;
#[doc = "Reader of field `EXTI4`"]
pub type EXTI4_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI5`"]
pub type EXTI5_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI6`"]
pub type EXTI6_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI7`"]
pub type EXTI7_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI8`"]
pub type EXTI8_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI9`"]
pub type EXTI9_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI10`"]
pub type EXTI10_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI11`"]
pub type EXTI11_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI12`"]
pub type EXTI12_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI13`"]
pub type EXTI13_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI14`"]
pub type EXTI14_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI15`"]
pub type EXTI15_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - EXTI4"]
#[inline(always)]
pub fn exti4(&self) -> EXTI4_R {
EXTI4_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - EXTI5"]
#[inline(always)]
pub fn exti5(&self) -> EXTI5_R {
EXTI5_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - EXTI6"]
#[inline(always)]
pub fn exti6(&self) -> EXTI6_R {
EXTI6_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - EXTI7"]
#[inline(always)]
pub fn exti7(&self) -> EXTI7_R {
EXTI7_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - EXTI8"]
#[inline(always)]
pub fn exti8(&self) -> EXTI8_R {
EXTI8_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - EXTI9"]
#[inline(always)]
pub fn exti9(&self) -> EXTI9_R {
EXTI9_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - EXTI10"]
#[inline(always)]
pub fn exti10(&self) -> EXTI10_R {
EXTI10_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - EXTI11"]
#[inline(always)]
pub fn exti11(&self) -> EXTI11_R {
EXTI11_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - EXTI12"]
#[inline(always)]
pub fn exti12(&self) -> EXTI12_R {
EXTI12_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - EXTI13"]
#[inline(always)]
pub fn exti13(&self) -> EXTI13_R {
EXTI13_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - EXTI14"]
#[inline(always)]
pub fn exti14(&self) -> EXTI14_R {
EXTI14_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - EXTI15"]
#[inline(always)]
pub fn exti15(&self) -> EXTI15_R {
EXTI15_R::new(((self.bits >> 11) & 0x01) != 0)
}
}
|
//! Clones a git repository and publishes it to crates.io.
use xshell::{cmd, Shell};
fn main() -> anyhow::Result<()> {
let sh = Shell::new()?;
let user = "matklad";
let repo = "xshell";
cmd!(sh, "git clone https://github.com/{user}/{repo}.git").run()?;
sh.change_dir(repo);
let test_args = ["-Zunstable-options", "--report-time"];
cmd!(sh, "cargo test -- {test_args...}").run()?;
let manifest = sh.read_file("Cargo.toml")?;
let version = manifest
.split_once("version = \"")
.and_then(|it| it.1.split_once('\"'))
.map(|it| it.0)
.ok_or_else(|| anyhow::format_err!("can't find version field in the manifest"))?;
cmd!(sh, "git tag {version}").run()?;
let dry_run = if sh.var("CI").is_ok() { None } else { Some("--dry-run") };
cmd!(sh, "cargo publish {dry_run...}").run()?;
Ok(())
}
|
use bitboard::base::BB;
use iterable::Iterable;
use iterable::ElemIterator;
use iterable::ElemSquareIterator;
use iterable::ElemRowColIterator;
impl Iterable<uint> for BB {
fn at(&self, idx:uint) -> uint {
((*self) & (0x1u64 << idx) != 0) as uint
}
fn at_sq(&self, row:uint, col:uint) -> uint {
let idx = (row << 3) | col;
self.at(idx)
}
fn each(&self) -> ElemIterator<uint> {
ElemIterator::new(self)
}
fn each_with_square(&self) -> ElemSquareIterator<uint> {
ElemSquareIterator::new(self)
}
fn each_with_row_col(&self) -> ElemRowColIterator<uint> {
ElemRowColIterator::new(self)
}
}
#[cfg(test)]
mod tests {
use iterable::*;
use bitboard::*;
#[test]
fn each_with_square() {
let bb = 0b1111u64 as BB;
for (sq, elem) in bb.each_with_square() {
if sq >= 4 {
assert_eq!(elem, 0)
} else {
assert_eq!(elem, 1)
}
}
}
}
|
mod disk;
mod errors;
pub use self::errors::Result;
use std::path::{Path, PathBuf};
pub struct Resource {
pub path: PathBuf,
}
pub trait ResourceReader {}
pub trait ResourceWriter {}
pub trait ResourceManager {
type R: ResourceReader;
type W: ResourceWriter;
fn get_resource(&self, path: &Path) -> Result<Resource>;
fn reader() -> Self::R;
fn writer() -> Self::W;
}
|
//!
//! The Semaphone CI pipeline demo library.
//!
use futures::{future, prelude::*};
use hyper::{Body, Request, Response, Server};
///
/// The blocking method which runs the HTTP server.
///
pub fn run(port: u16) {
let addr = ([0, 0, 0, 0], port).into();
println!("Starting the HTTP server at {}", addr);
let server = Server::bind(&addr)
.serve(|| hyper::service::service_fn(hello))
.map_err(|error| eprintln!("The HTTP server error: {}", error));
hyper::rt::run(server);
}
///
/// The HTTP request handler which returns hello-world responses.
///
fn hello(_request: Request<Body>) -> impl Future<Item = Response<Body>, Error = hyper::Error> {
let mut response = Response::new(Body::empty());
*response.body_mut() = Body::from("Hello, World!");
future::ok(response)
}
#[cfg(test)]
mod tests {
///
/// The default unit test.
///
#[test]
fn default() {
assert_eq!(2 + 2, 4);
}
}
|
mod vehicle;
use rapier3d::na::ArrayStorage;
use rapier3d::na::Const;
use rapier3d::prelude::*;
use vehicle::Vehicle;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct World {
gravity: rapier3d::na::base::Matrix<f32, Const<3>, Const<1>, ArrayStorage<f32, 3, 1>>,
integration_parameters: IntegrationParameters,
physics_pipeline: PhysicsPipeline,
island_manager: IslandManager,
broad_phase: BroadPhase,
narrow_phase: NarrowPhase,
joints: JointSet,
bodies: RigidBodySet,
colliders: ColliderSet,
ccd_solver: CCDSolver,
physics_hooks: (),
event_handler: (),
vehicle_handle: Option<Box<dyn Vehicle>>,
vehicle_type: Option<vehicle::VehicleType>,
}
#[wasm_bindgen]
impl World {
pub fn new() -> World {
let rigid_body_set = RigidBodySet::new();
let mut collider_set = ColliderSet::new();
/* Create the ground. */
let mut collider = ColliderBuilder::cuboid(100.0, 0.1, 100.0).build();
collider.set_translation(vector![0.0, -2.5, 0.0]);
collider_set.insert(collider);
World {
gravity: vector![0.0, -9.81, 0.0],
integration_parameters: IntegrationParameters::default(),
physics_pipeline: PhysicsPipeline::new(),
island_manager: IslandManager::new(),
broad_phase: BroadPhase::new(),
narrow_phase: NarrowPhase::new(),
joints: JointSet::new(),
bodies: rigid_body_set,
colliders: collider_set,
ccd_solver: CCDSolver::new(),
physics_hooks: (),
event_handler: (),
vehicle_handle: None,
vehicle_type: None,
}
}
pub fn build_ground(&mut self, y: f32) {
let collider = ColliderBuilder::cuboid(50.0, 1.0, 50.0)
.translation(vector![0.0, y - 1.0, 0.0])
.build();
self.colliders.insert(collider);
}
pub fn build_vehicle(&mut self, vehicle_name: &str) -> Box<[f32]> {
let mut vehicle = match vehicle_name {
"Drone" => vehicle::create_vehicle(vehicle::VehicleType::Drone, false, &[0.0]),
_ => vehicle::create_vehicle(vehicle::VehicleType::Drone, false, &[0.0]),
};
vehicle.build(&mut self.bodies, &mut self.colliders);
self.vehicle_handle = Some(vehicle);
return Box::new(
self.vehicle_handle
.as_ref()
.unwrap()
.transform(&self.bodies),
);
}
pub fn update_controls(&mut self, data: &[f32]) {
self.vehicle_handle.as_mut().unwrap().controls(data);
}
pub fn step(&mut self) -> Box<[f32]> {
self.vehicle_handle
.as_mut()
.unwrap()
.execute_forces(&mut self.bodies);
self.physics_pipeline.step(
&self.gravity,
&self.integration_parameters,
&mut self.island_manager,
&mut self.broad_phase,
&mut self.narrow_phase,
&mut self.bodies,
&mut self.colliders,
&mut self.joints,
&mut self.ccd_solver,
&self.physics_hooks,
&self.event_handler,
);
let mut out = [0.0; 13];
let transform = self
.vehicle_handle
.as_ref()
.unwrap()
.transform(&self.bodies);
let sensor_data = self.vehicle_handle.as_mut().unwrap().sensor_data(
&self.bodies,
&self.integration_parameters,
&self.gravity,
);
out[..7].copy_from_slice(&transform);
out[7..].copy_from_slice(&sensor_data);
return Box::new(out);
}
}
pub trait RawIsometry {
fn raw_isometry(&self) -> [f32; 7];
}
impl RawIsometry for RigidBody {
fn raw_isometry(&self) -> [f32; 7] {
let translation = self.translation();
let quaternion = self.rotation();
[
translation.x,
translation.y,
translation.z,
quaternion.i,
quaternion.j,
quaternion.k,
quaternion.w,
]
}
}
|
pub mod allocator;
pub mod lock;
pub mod kauth;
pub mod fs;
pub mod process;
pub mod random;
pub use self::lock::read_write::RwLock;
pub use self::lock::group::LockGroup;
pub use self::lock::attributes::LockGroupAttribute;
pub use self::lock::attributes::LockAttribute;
pub use self::kauth::KAuthResult;
pub use self::kauth::KAuth;
pub use self::kauth::scope::Scope;
pub use self::kauth::scope::ScopeCallback;
pub use self::kauth::scope::ScopeListener;
pub use self::kauth::vnode::KAuthVNodeAction;
pub use self::kauth::vnode::KAuthVNodeDirectoryAction;
pub use self::fs::vnode::VNode;
pub use self::fs::vnode::VType;
pub use self::process::Process;
|
use std::ffi::OsStr;
use menmos_client::{Query, Type};
use crate::MenmosFS;
use super::{Error, Result};
impl MenmosFS {
async fn rm_rf(&self, blob_id: &str) -> anyhow::Result<()> {
let mut working_stack = vec![(String::from(blob_id), Type::Directory)];
while !working_stack.is_empty() {
// Get a new root.
let (target_id, blob_type) = working_stack.pop().unwrap();
if blob_type == Type::Directory {
// List the root's children.
let results = self
.client
.query(Query::default().and_parent(&target_id).with_size(5000))
.await?;
for hit in results.hits.into_iter() {
working_stack.push((hit.id, hit.meta.blob_type));
}
}
// Delete the root.
// TODO: Batch delete would be a nice addition.
self.client.delete(target_id).await?;
}
Ok(())
}
pub async fn rmdir_impl(&self, parent: u64, name: &OsStr) -> Result<()> {
log::info!("rmdir i{}/{:?}", parent, name);
let str_name = name.to_string_lossy().to_string();
let blob_id = self
.name_to_blobid
.get(&(parent, str_name))
.await
.ok_or(Error::NotFound)?;
self.rm_rf(&blob_id).await.map_err(|e| {
log::error!("client error: {}", e);
Error::IOError
})?;
Ok(())
}
}
|
use serde::*;
use serde_xml_rs::*;
use std::fs::File;
use std::io::Read;
//use std::path::PathBuf;
//use serde::de::value::UsizeDeserializer;
//use std::num::ParseIntError;
//--------------- serverconfig
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Property {
pub name: String,
pub value: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct ServerSettings {
pub property: Vec<Property>,
}
/*
------------------ serveradmin.xml
*/
#[allow(non_snake_case)]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct User {
#[allow(non_snake_case)]
pub steamID: String,
pub permission_level: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Admin {
pub user: Vec<User>,
//pub admin: Vec<User>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AdminTools {
pub admins: Vec<Admin>,
//pub permissions: Vec<permission>,
//pub blacklist: Vec<blacklisted>,
}
pub fn pobierz_port() -> u16 {
//set_logger();
let mut port = 8080u16;
let settingsy = pobierz_ustawienia().property;
//let settingsy = wczytaj_ustawienia_xml("serverconfig.xml").property;
for p in settingsy {
if p.name.to_ascii_lowercase() == "telnetport" {
port = p.value.parse::<u16>().unwrap() + 2;
}
}
log::info!("Setting Port to: {}", &port);
port
}
pub fn pobierz_nazwe() -> Box<String> {
//set_logger();
let mut nazwa = String::from("Server 7dtd");
let settingsy = pobierz_ustawienia().property;
//let settingsy = wczytaj_ustawienia_xml("serverconfig.xml").property;
for p in settingsy {
if p.name.to_ascii_lowercase() == "servername" {
nazwa = p.value;
}
}
log::info!("Setting Web Name to: {}", &nazwa);
Box::new(nazwa)
}
pub fn pobierz_ustawienia() -> Box<ServerSettings> {
let settingsy = wczytaj_ustawienia_xml("serverconfig.xml");
Box::new(settingsy)
}
fn znajdz_sciezke_serveradmins() -> String {
let mut sciezka = String::new();
//TODO zle pobiera sciezke z pliku xml!
let settingsy = pobierz_ustawienia().property;
for p in settingsy {
if p.name.to_ascii_lowercase() == "savegamefolder" {
sciezka.push_str(p.value.as_str()); //jesli istnieje to podmien sciezke na wpisana przez uzytkownika
}
}
if sciezka.is_empty() {
match dirs::home_dir() {
None => {}
Some(patch) => {
sciezka.push_str(&patch.to_str().unwrap());
sciezka.push_str("/.local/share/7DaysToDie/Saves");
}
}
}
sciezka.push_str("/serveradmin.xml"); //dodaj plik do wczytania na koncu sciezki
sciezka
}
/*fn znajdz_sciezke_serveradmins() -> Box<String> {
let mut sciezka = String::new();
match dirs::home_dir() {
None => {
log::warn!("Error...");
}
Some(patch) => {
sciezka.push_str(&patch.to_str().unwrap());
sciezka.push_str("/.local/share/7DaysToDie/Saves");
}
} //zapisano domyslna sciezke: [pobrany_katalog_domowy]/.local/share/7DaysToDie/Saves
//na wszelki wypadek sprawdz czy istnieje wlasciwosc "SaveGameFolder"
/*let settingsy = pobierz_ustawienia().property;
for p in settingsy {
if p.name.to_ascii_lowercase() == "savegamefolder" {
sciezka.clear();
sciezka.push_str(p.value.as_str()); //jesli istnieje to podmien sciezke na wpisana przez uzytkownika
}
}*/
sciezka.push_str("/serveradmin.xml"); //dodaj plik do wczytania na koncu sciezki
log::info!("serveradmins.xml path: {}", &sciezka);
Box::new(sciezka)
}*/
fn wczytaj_serveradmins_xml() -> Option<AdminTools> {
let sciezka = znajdz_sciezke_serveradmins();
//let sciezka = "/home/marcin/.local/share/7DaysToDie/Saves/serveradmin.xml".to_string();
let mut bufor = String::new();
let plik_ustawien = File::open(sciezka);
//log::info!("path: {}",&sciezka);
match plik_ustawien
{
Ok(mut file) => {
let result = file.read_to_string(&mut bufor);
match result {
Ok(_) => {}
Err(_) => {}
}
}
Err(_) => {
log::warn!("Błąd wczytania pliku serveradmin.xml");
panic!("Can't read from serveradmin.xml file");
}
};
//Wywalić BOM z początku stringa
let bomless = bufor.trim_start_matches("\u{FEFF}");
let serialize_ustawienia: Result<AdminTools, Error> = serde_xml_rs::from_str(bomless);
match serialize_ustawienia {
Ok(wynik) => {
Some(wynik)
}
Err(_) => {
log::warn!("Error parsing in serveradmin.xml file");
None
}
}
}
pub fn admins_list() -> Option<Vec<String>> {
let serveradmins = wczytaj_serveradmins_xml();
let mut wyjscie: Vec<String> = Vec::new();
match serveradmins {
None => {
None
}
Some(plik) => {
let settingsy = plik.admins;
for adminek in settingsy {
let userek = adminek.user;
for admin_nr in userek {
let level = admin_nr.permission_level.parse::<i32>();
match level {
Ok(liczba) => {
if liczba == 0 {
wyjscie.push(admin_nr.steamID);
}
}
Err(_) => {}
}
}
}
Some(wyjscie)
}
}
}
fn wczytaj_ustawienia_xml(sciezka: &str) -> ServerSettings {
let mut bufor = String::new();
let plik_ustawien = File::open(sciezka);
//log::info!("ścieżka: {}",sciezka);
match plik_ustawien
{
Ok(mut file) => {
let result = file.read_to_string(&mut bufor);
match result {
Ok(_) => {}
Err(_) => {}
}
}
Err(_) => {
log::warn!("Błąd wczytania pliku ustawień");
panic!("Can't read from settings file");
}
};
let serialize_ustawienia = serde_xml_rs::from_str(bufor.as_str()).unwrap();
serialize_ustawienia
}
//ustawienie logowania
/*fn set_logger() {
let result = simple_logging::log_to_file("Mods/SevenWebser/output.log", LevelFilter::Info);
match result {
Ok(_) => {}
Err(_) => {}
}
}*/
|
use super::{utils::heap_object_impls, HeapObjectTrait};
use crate::{
heap::{object_heap::HeapObject, Heap, Int, List, Tag, Text},
utils::{impl_debug_display_via_debugdisplay, impl_eq_hash_ord_via_get, DebugDisplay},
};
use derive_more::Deref;
use itertools::Itertools;
use rustc_hash::FxHashMap;
use std::{
fmt::{self, Formatter},
ops::Range,
ptr::{self, NonNull},
slice, str,
};
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone, Copy, Deref)]
pub struct HeapText(HeapObject);
impl HeapText {
const BYTE_LEN_SHIFT: usize = 4;
pub fn new_unchecked(object: HeapObject) -> Self {
Self(object)
}
pub fn create(heap: &mut Heap, is_reference_counted: bool, value: &str) -> Self {
let byte_len = value.len();
assert_eq!(
(byte_len << Self::BYTE_LEN_SHIFT) >> Self::BYTE_LEN_SHIFT,
byte_len,
"Text is too long.",
);
let text = Self(heap.allocate(
HeapObject::KIND_TEXT,
is_reference_counted,
(byte_len as u64) << Self::BYTE_LEN_SHIFT,
byte_len,
));
unsafe { ptr::copy_nonoverlapping(value.as_ptr(), text.text_pointer().as_ptr(), byte_len) };
text
}
pub fn byte_len(self) -> usize {
(self.header_word() >> Self::BYTE_LEN_SHIFT) as usize
}
fn text_pointer(self) -> NonNull<u8> {
self.content_word_pointer(0).cast()
}
pub fn get<'a>(self) -> &'a str {
let pointer = self.text_pointer().as_ptr();
unsafe { str::from_utf8_unchecked(slice::from_raw_parts(pointer, self.byte_len())) }
}
pub fn is_empty(self) -> Tag {
Tag::create_bool(self.get().is_empty())
}
pub fn length(self, heap: &mut Heap) -> Int {
Int::create(heap, true, self.get().graphemes(true).count())
}
pub fn characters(self, heap: &mut Heap) -> List {
let characters = self
.get()
.graphemes(true)
.map(|it| Text::create(heap, true, it).into())
.collect_vec();
List::create(heap, true, &characters)
}
pub fn contains(self, pattern: Text) -> Tag {
Tag::create_bool(self.get().contains(pattern.get()))
}
pub fn starts_with(self, prefix: Text) -> Tag {
Tag::create_bool(self.get().starts_with(prefix.get()))
}
pub fn ends_with(self, suffix: Text) -> Tag {
Tag::create_bool(self.get().ends_with(suffix.get()))
}
pub fn get_range(self, heap: &mut Heap, range: Range<Int>) -> Text {
// TODO: Support indices larger than usize.
let start_inclusive = range
.start
.try_get()
.expect("Tried to get a range from a text with an index that's too large for usize.");
let end_exclusive = range
.end
.try_get::<usize>()
.expect("Tried to get a range from a text with an index that's too large for usize.");
let text: String = self
.get()
.graphemes(true)
.skip(start_inclusive)
.take(end_exclusive - start_inclusive)
.collect();
Text::create(heap, true, &text)
}
pub fn concatenate(self, heap: &mut Heap, other: Text) -> Text {
Text::create(heap, true, &format!("{}{}", self.get(), other.get()))
}
pub fn trim_start(self, heap: &mut Heap) -> Text {
Text::create(heap, true, self.get().trim_start())
}
pub fn trim_end(self, heap: &mut Heap) -> Text {
Text::create(heap, true, self.get().trim_end())
}
}
impl DebugDisplay for HeapText {
fn fmt(&self, f: &mut Formatter, _is_debug: bool) -> fmt::Result {
write!(f, "\"{}\"", self.get())
}
}
impl_debug_display_via_debugdisplay!(HeapText);
impl_eq_hash_ord_via_get!(HeapText);
heap_object_impls!(HeapText);
impl HeapObjectTrait for HeapText {
fn content_size(self) -> usize {
self.byte_len()
}
fn clone_content_to_heap_with_mapping(
self,
_heap: &mut Heap,
clone: HeapObject,
_address_map: &mut FxHashMap<HeapObject, HeapObject>,
) {
let clone = Self(clone);
unsafe {
ptr::copy_nonoverlapping(
self.text_pointer().as_ptr(),
clone.text_pointer().as_ptr(),
self.byte_len(),
)
};
}
fn drop_children(self, _heap: &mut Heap) {}
fn deallocate_external_stuff(self) {}
}
|
#![allow(unused)]
use runestick::{ContextError, Item, Mut, Object, Ref, Shared, Tuple, Value};
use runestick_macros::{Any, FromValue, ToValue};
#[derive(Any)]
#[rune(name = "Bar")]
struct Foo {}
#[derive(Any)]
struct Bar {}
#[test]
fn test_rename() {
let mut module = runestick::Module::new();
module.ty::<Foo>().unwrap();
module.ty::<Bar>().unwrap();
let mut context = runestick::Context::new();
let e = context.install(&module).unwrap_err();
match e {
ContextError::ConflictingType { item, .. } => {
assert_eq!(item, Item::with_item(&["Bar"]));
}
actual => {
panic!("expected conflicting type but got: {:?}", actual);
}
}
}
|
//! Locale implementation for MacOS X
use std::borrow::ToOwned;
use std::env::var;
use std::fs::{metadata, File};
use std::io::{BufRead, Error, Result, BufReader};
use std::path::{Path, PathBuf};
use super::{LocaleFactory, Numeric, Time};
/// The directory inside which locale files are found.
///
/// For example, the set of Korean files will be in
/// `/usr/share/locale/ko`.
static LOCALE_DIR: &'static str = "/usr/share/locale";
#[derive(Debug, Clone)]
enum LocaleType {
Numeric, Time,
}
fn find_user_locale_path(file_name: &str) -> Option<PathBuf> {
let locale_dir = Path::new(LOCALE_DIR);
if let Ok(specific_path) = var(file_name) {
let path = locale_dir.join(Path::new(&specific_path)).join(Path::new(file_name));
if path.exists() {
return Some(path);
}
}
if let Ok(all_path) = var("LC_ALL") {
let path = locale_dir.join(Path::new(&all_path)).join(Path::new(file_name));
if path.exists() {
return Some(path);
}
}
if let Ok(lang) = var("LANG") {
let path = locale_dir.join(Path::new(&lang)).join(Path::new(file_name));
if path.exists() {
return Some(path);
}
}
None
}
fn find_locale_path(locale_type: LocaleType, locale_name: &str) -> Option<PathBuf> {
let file_name = match locale_type {
LocaleType::Numeric => "LC_NUMERIC",
LocaleType::Time => "LC_TIME",
};
if locale_name == "" {
return find_user_locale_path(&file_name);
} else {
let locale_dir = Path::new(LOCALE_DIR);
let path = locale_dir.join(locale_name).join(file_name);
if path.exists() {
return Some(path);
}
}
None
}
fn load_numeric(locale: &str) -> Result<Numeric> {
let path = find_locale_path(LocaleType::Numeric, locale);
if let Some(path) = path {
let file = BufReader::new(try!(File::open(&path)));
let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
Ok(Numeric {
decimal_sep: lines[0].trim().to_string(),
thousands_sep: lines[1].trim().to_string(),
})
}
else {
return Err(Error::last_os_error());
}
}
fn load_time(locale: &str) -> Result<Time> {
let path = find_locale_path(LocaleType::Time, locale);
if let Some(path) = path {
let file = BufReader::new(try!(File::open(&path)));
let mut iter = file.lines().map(|x| x.unwrap().trim().to_string());
let month_names = iter.by_ref().take(12).collect();
let long_month_names = iter.by_ref().take(12).collect();
let day_names = iter.by_ref().take(7).collect();
let long_day_names = iter.by_ref().take(7).collect();
Ok(Time {
month_names: month_names,
long_month_names: long_month_names,
day_names: day_names,
long_day_names: long_day_names,
})
}
else {
return Err(Error::last_os_error());
}
}
pub struct MacOSLocaleFactory {
locale: String,
}
impl MacOSLocaleFactory {
// TODO: Should really check whether the locale exists.
pub fn new(locale: &str) -> Result<Self> {
Ok(MacOSLocaleFactory {
locale: locale.to_owned()
})
}
}
impl LocaleFactory for MacOSLocaleFactory {
fn get_numeric(&mut self) -> Option<Box<Numeric>> {
if let Ok(numeric) = load_numeric(&self.locale) {
Some(Box::new(numeric))
} else {
None
}
}
fn get_time(&mut self) -> Option<Box<Time>> {
if let Ok(time) = load_time(&self.locale) {
Some(Box::new(time))
} else {
None
}
}
}
// ---- PathExt replacement ----
pub trait PathExt {
fn exists(&self) -> bool;
}
impl PathExt for Path {
fn exists(&self) -> bool { metadata(self).is_ok() }
}
|
//! Classes for describing instruction formats.
|
#[doc = "Reader of register MDIOS_DINR12"]
pub type R = crate::R<u32, super::MDIOS_DINR12>;
#[doc = "Reader of field `DIN12`"]
pub type DIN12_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Input data received from MDIO Master during write frames"]
#[inline(always)]
pub fn din12(&self) -> DIN12_R {
DIN12_R::new((self.bits & 0xffff) as u16)
}
}
|
mod config;
mod world;
mod renderer;
mod init;
mod media;
mod dom;
mod mainloop;
mod controller;
mod physics;
mod squares;
use init::init;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen(start)]
pub async fn run() -> Result<(), JsValue> {
init().await
}
|
use std::rc::Rc;
use yew::prelude::*;
use yew_functional::{function_component, use_state};
#[function_component(Counter)]
pub fn state() -> Html {
let (counter, set_counter) = use_state(|| 0);
let onclick = {
let counter = Rc::clone(&counter);
Callback::from(move |_| set_counter(*counter + 1))
};
html! {
<div>
<button onclick=onclick>{ "Increment value" }</button>
<p>
<b>{ "Current value: " }</b>
{ counter }
</p>
</div>
}
}
|
#![allow(dead_code)]
use crate::vec3::Vec3;
#[derive(Copy, Clone)]
pub struct Ray {
a: Vec3,
b: Vec3,
}
impl Ray {
pub fn new(v1: Vec3, v2: Vec3) -> Self {
Self {
a: v1,
b: v2,
}
}
pub fn origin(&self) -> Vec3 {
self.a
}
pub fn direction(&self) -> Vec3 {
self.b
}
pub fn point_at_parameter(&self, t: f64) -> Vec3 {
self.a + self.b * t
}
}
|
use std::{ env, process };
use std::path::Path;
use std::fmt::Write;
extern crate gethostname;
use gethostname::gethostname;
extern crate git2;
use git2::{ Error, ErrorCode, Repository, StatusOptions };
fn get_branch_name(repo: &Repository) -> Result<String, Error> {
let head = match repo.head() {
Ok(head) => Some(head),
Err(ref e) if e.code() == ErrorCode::UnbornBranch || e.code() == ErrorCode::NotFound => {
None
}
Err(e) => return Err(e),
};
let head = head.as_ref().and_then(|h| h.shorthand());
return Ok(head.unwrap_or("(empty branch)").to_string());
}
fn index_changed(repo: &Repository) -> bool {
let mut opts = StatusOptions::new();
opts.include_untracked(true);
// TODO: might want to recurse_untracked_dirs
let statuses = repo.statuses(Some(&mut opts)).unwrap();
for entry in statuses.iter() {
let is_index_changed = match entry.status() {
s if s.contains(git2::Status::INDEX_NEW) => true,
s if s.contains(git2::Status::INDEX_MODIFIED) => true,
s if s.contains(git2::Status::INDEX_DELETED) => true,
s if s.contains(git2::Status::INDEX_RENAMED) => true,
s if s.contains(git2::Status::INDEX_TYPECHANGE) => true,
s if s.contains(git2::Status::WT_NEW) => true,
s if s.contains(git2::Status::WT_MODIFIED) => true,
s if s.contains(git2::Status::WT_DELETED) => true,
s if s.contains(git2::Status::WT_RENAMED) => true,
s if s.contains(git2::Status::WT_TYPECHANGE) => true,
_ => false,
};
if is_index_changed {
return true;
}
}
return false;
}
fn main () {
// colorization is optional and read through these env vars (recommended to populate via tput)
// it would be far too expensive to parse terminfo databases
let style_user = env::var("PROMPT_STYLE_USER").unwrap_or_default();
let style_hostname = env::var("PROMPT_STYLE_HOSTNAME").unwrap_or_default();
let style_wd = env::var("PROMPT_STYLE_WD").unwrap_or_default();
let style_branch = env::var("PROMPT_STYLE_BRANCH").unwrap_or_default();
let style_reset = env::var("PROMPT_STYLE_RESET").unwrap_or_default();
let user = env::var("USER").unwrap_or_default();
// TODO: if it matches HOME, then print it as ~
let pwd = env::current_dir().unwrap();
let wd = pwd.as_path().file_name().unwrap().to_str().unwrap();
let _hostname = gethostname(); // im bad at rust why do i have to separate this
let hostname = _hostname.to_str().unwrap();
let mut prompt = String::new();
write!(
&mut prompt, "{}{}{}@{}{}{} {}{}{}",
style_user, user, style_reset,
style_hostname, hostname, style_reset,
style_wd, wd, style_reset,
).unwrap();
// XXX: need to canonicalize otherwise .parent will return Some("")
// see https://github.com/rust-lang/rust/issues/36861
let _gitroot = Path::new(".").canonicalize().unwrap();
let mut gitroot = _gitroot.as_path();
loop {
if gitroot.join(".git").is_dir() {
break;
}
gitroot = match gitroot.parent() {
Some(p) => p,
None => {
println!("{} $ ", prompt.to_string());
process::exit(0);
}
};
}
let repo = match Repository::open(gitroot) {
Ok(repo) => repo,
Err(_e) => {
println!("{} $ ", prompt.to_string());
process::exit(0);
}
};
if index_changed(&repo) {
prompt.push_str(" *");
}
let mut branch_name = get_branch_name(&repo).unwrap();
// XXX: this isn't 100% correct, but it'll do. I don't want to additionally inspect symbolic ref.
if branch_name == "HEAD" {
branch_name = "(detached HEAD)".to_string()
}
write!(&mut prompt, " {}{}{}", style_branch, branch_name, style_reset).unwrap();
println!("{} $ ", prompt.to_string());
}
|
use cgmath::{EuclideanSpace, InnerSpace};
use futures::executor::block_on;
use imgui::*;
use imgui_wgpu::Renderer;
use imgui_winit_support;
use imguizmo::{Gizmo, Mode, Operation, Rect};
use std::time::Instant;
use winit::{
dpi::LogicalSize,
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::Window,
};
fn main() {
env_logger::init();
// Set up window and GPU
let event_loop = EventLoop::new();
let mut hidpi_factor = 1.0;
let (window, mut size, surface) = {
let version = env!("CARGO_PKG_VERSION");
let window = Window::new(&event_loop).unwrap();
window.set_inner_size(LogicalSize {
width: 1280.0,
height: 720.0,
});
window.set_title(&format!("ImGuizmo {}", version));
let size = window.inner_size();
let surface = wgpu::Surface::create(&window);
(window, size, surface)
};
let adapter = block_on(wgpu::Adapter::request(
&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
},
wgpu::BackendBit::PRIMARY,
))
.unwrap();
let (mut device, mut queue) = block_on(adapter.request_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
limits: wgpu::Limits::default(),
}));
let mut sc_desc = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8Unorm,
width: size.width as u32,
height: size.height as u32,
present_mode: wgpu::PresentMode::Mailbox,
};
let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
let mut imgui = imgui::Context::create();
let mut platform = imgui_winit_support::WinitPlatform::init(&mut imgui);
platform.attach_window(
imgui.io_mut(),
&window,
imgui_winit_support::HiDpiMode::Default,
);
imgui.set_ini_filename(None);
let font_size = (13.0 * hidpi_factor) as f32;
imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32;
imgui.fonts().add_font(&[FontSource::DefaultFontData {
config: Some(imgui::FontConfig {
oversample_h: 1,
pixel_snap_h: true,
size_pixels: font_size,
..Default::default()
}),
}]);
let clear_color = wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
};
let mut renderer = Renderer::new(
&mut imgui,
&device,
&mut queue,
sc_desc.format,
Some(clear_color),
);
let mut last_frame = Instant::now();
let mut last_cursor = None;
let mut cube_model: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let grid_model: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let eye = cgmath::Point3::new(8.0, 8.0, 8.0);
let center = cgmath::Point3::origin();
let up = cgmath::Vector3::unit_y();
let mut view: [[f32; 4]; 4] = cgmath::Matrix4::<f32>::look_at(eye, center, up).into();
let camera_distance = (eye - center).magnitude();
let mut draw_cube = true;
let mut draw_grid = true;
let mut is_orthographic = false;
let mut operation = Operation::Rotate;
let mut mode = Mode::Local;
let mut grid_size = 10.0;
let mut use_snap = false;
let mut snap = [1.0, 1.0, 1.0];
let mut bounds = [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]];
let mut bounds_snap = [0.1, 0.1, 0.1];
let mut bound_sizing = false;
let mut bound_sizing_snap = false;
event_loop.run(move |event, _, control_flow| {
*control_flow = if cfg!(feature = "metal-auto-capture") {
ControlFlow::Exit
} else {
ControlFlow::Poll
};
match event {
Event::WindowEvent {
event: WindowEvent::ScaleFactorChanged { scale_factor, .. },
..
} => {
hidpi_factor = scale_factor;
}
Event::WindowEvent {
event: WindowEvent::Resized(_),
..
} => {
size = window.inner_size();
sc_desc = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8Unorm,
width: size.width as u32,
height: size.height as u32,
present_mode: wgpu::PresentMode::Mailbox,
};
swap_chain = device.create_swap_chain(&surface, &sc_desc);
}
Event::WindowEvent {
event:
WindowEvent::KeyboardInput {
input:
KeyboardInput {
virtual_keycode: Some(VirtualKeyCode::Escape),
state: ElementState::Pressed,
..
},
..
},
..
}
| Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => {
*control_flow = ControlFlow::Exit;
}
Event::MainEventsCleared => window.request_redraw(),
Event::RedrawEventsCleared => {
last_frame = imgui.io_mut().update_delta_time(last_frame);
let frame = match swap_chain.get_next_texture() {
Ok(frame) => frame,
Err(e) => {
eprintln!("dropped frame: {:?}", e);
return;
}
};
platform
.prepare_frame(imgui.io_mut(), &window)
.expect("Failed to prepare frame");
let ui = imgui.frame();
{
let [width, height] = ui.io().display_size;
let aspect_ratio = width / height;
let projection: [[f32; 4]; 4] = if !is_orthographic {
cgmath::perspective(cgmath::Deg(65.0), aspect_ratio, 0.01, 1000.0).into()
} else {
let view_width = 10.0;
let view_height = view_width * height / width;
cgmath::ortho(
-view_width,
view_width,
-view_height,
view_height,
-1000.0,
1000.0,
)
.into()
};
let gizmo = Gizmo::begin_frame(&ui);
if let Some(window) = imgui::Window::new(im_str!("Gizmo Options")).begin(&ui) {
ui.checkbox(im_str!("Cube"), &mut draw_cube);
ui.checkbox(im_str!("Grid"), &mut draw_grid);
ui.checkbox(im_str!("Orthographic"), &mut is_orthographic);
ui.drag_float(im_str!("Grid size"), &mut grid_size).build();
ui.new_line();
ui.radio_button(im_str!("Local"), &mut mode, Mode::Local);
ui.radio_button(im_str!("World"), &mut mode, Mode::World);
ui.new_line();
ui.radio_button(im_str!("Rotate"), &mut operation, Operation::Rotate);
ui.radio_button(im_str!("Translate"), &mut operation, Operation::Translate);
ui.radio_button(im_str!("Scale"), &mut operation, Operation::Scale);
ui.new_line();
ui.checkbox(im_str!("Use snap"), &mut use_snap);
ui.checkbox(im_str!("Bound sizing"), &mut bound_sizing);
ui.checkbox(im_str!("Bound sizing snap"), &mut bound_sizing_snap);
window.end(&ui);
}
let rect = Rect::from_display(&ui);
gizmo.set_rect(rect.x, rect.y, rect.width, rect.height);
gizmo.set_orthographic(is_orthographic);
if draw_cube {
gizmo.draw_cube(&view, &projection, &cube_model);
}
if draw_grid {
gizmo.draw_grid(&view, &projection, &grid_model, grid_size);
}
gizmo.manipulate(
&view,
&projection,
operation,
mode,
&mut cube_model,
None,
if use_snap { Some(&mut snap) } else { None },
if bound_sizing {
Some(&mut bounds)
} else {
None
},
if bound_sizing_snap {
Some(&mut bounds_snap)
} else {
None
},
);
let size = [128.0, 128.0];
let position = [width - size[0], 0.0];
let background_color = 0;
gizmo.view_manipulate(
&mut view,
camera_distance,
position,
size,
background_color,
);
}
let mut encoder: wgpu::CommandEncoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
if last_cursor != Some(ui.mouse_cursor()) {
last_cursor = Some(ui.mouse_cursor());
platform.prepare_render(&ui, &window);
}
renderer
.render(ui.render(), &mut device, &mut encoder, &frame.view)
.expect("Rendering failed");
queue.submit(&[encoder.finish()]);
}
_ => (),
}
platform.handle_event(imgui.io_mut(), &window, &event);
});
}
|
pub fn round_float(n: f64, d_points: usize) -> String {
let rounder = (10 ^ d_points) as f64;
let answer = (n * rounder).round() / rounder;
return format!("{:.*}", d_points, answer);
}
#[allow(dead_code)]
fn build_str() -> String {
let mut s = String::new();
s.push_str("Hello, world!");
return s;
}
|
use ndarray::prelude::*;
use pyo3::prelude::*;
#[pyclass]
#[pyo3(name = "DistanceMatrix")]
pub struct PyDistanceMatrix {
distance_matrix: Array2<f32>,
}
impl PyDistanceMatrix {
pub fn new_with_distance_matrix(distance_matrix: Array2<f32>) -> PyDistanceMatrix {
PyDistanceMatrix { distance_matrix }
}
pub fn distance_matrix(&self) -> &Array2<f32> {
&self.distance_matrix
}
}
#[pymethods]
impl PyDistanceMatrix {
#[new]
pub fn new(n: usize) -> PyDistanceMatrix {
let distance_matrix = Array::from_elem((n, n), 0.);
PyDistanceMatrix::new_with_distance_matrix(distance_matrix)
}
pub fn get(&self, u: usize, v: usize) -> f32 {
self.distance_matrix[[u, v]]
}
pub fn set(&mut self, u: usize, v: usize, d: f32) {
self.distance_matrix[[u, v]] = d
}
}
pub fn register(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_class::<PyDistanceMatrix>()?;
Ok(())
}
|
use read_input::prelude::*;
fn main() {
let x: f64 = input().msg("Please enter a number \n").get();
println!("Your first number is {}", x);
let y: f64 = input().msg("Please enter a number \n").get();
println!("Your second number is {}", y);
let op: char = input().msg("Please enter an operation \n").get();
match op {
'+' => println!("The result is: {}", x+y),
'-' => println!("The result is: {}", x-y),
'*' => println!("The result is: {}", x*y),
'/' => println!("The result is: {}", x/y),
_ => println!("Now that was not very nice of you."),
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn BrowseForGPO(lpbrowseinfo: *mut GPOBROWSEINFO) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn CommandLineFromMsiDescriptor(descriptor: super::super::Foundation::PWSTR, commandline: super::super::Foundation::PWSTR, commandlinelength: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateGPOLink(lpgpo: super::super::Foundation::PWSTR, lpcontainer: super::super::Foundation::PWSTR, fhighpriority: super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteAllGPOLinks(lpcontainer: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteGPOLink(lpgpo: super::super::Foundation::PWSTR, lpcontainer: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn EnterCriticalPolicySection(bmachine: super::super::Foundation::BOOL) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn ExportRSoPData(lpnamespace: super::super::Foundation::PWSTR, lpfilename: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn FreeGPOListA(pgpolist: *const GROUP_POLICY_OBJECTA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FreeGPOListW(pgpolist: *const GROUP_POLICY_OBJECTW) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GenerateGPNotification(bmachine: super::super::Foundation::BOOL, lpwszmgmtproduct: super::super::Foundation::PWSTR, dwmgmtproductoptions: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetAppliedGPOListA(dwflags: u32, pmachinename: super::super::Foundation::PSTR, psiduser: super::super::Foundation::PSID, pguidextension: *const ::windows_sys::core::GUID, ppgpolist: *mut *mut GROUP_POLICY_OBJECTA) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetAppliedGPOListW(dwflags: u32, pmachinename: super::super::Foundation::PWSTR, psiduser: super::super::Foundation::PSID, pguidextension: *const ::windows_sys::core::GUID, ppgpolist: *mut *mut GROUP_POLICY_OBJECTW) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetGPOListA(htoken: super::super::Foundation::HANDLE, lpname: super::super::Foundation::PSTR, lphostname: super::super::Foundation::PSTR, lpcomputername: super::super::Foundation::PSTR, dwflags: u32, pgpolist: *mut *mut GROUP_POLICY_OBJECTA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetGPOListW(htoken: super::super::Foundation::HANDLE, lpname: super::super::Foundation::PWSTR, lphostname: super::super::Foundation::PWSTR, lpcomputername: super::super::Foundation::PWSTR, dwflags: u32, pgpolist: *mut *mut GROUP_POLICY_OBJECTW) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetLocalManagedApplicationData(productcode: super::super::Foundation::PWSTR, displayname: *mut super::super::Foundation::PWSTR, supporturl: *mut super::super::Foundation::PWSTR);
#[cfg(feature = "Win32_Foundation")]
pub fn GetLocalManagedApplications(buserapps: super::super::Foundation::BOOL, pdwapps: *mut u32, prglocalapps: *mut *mut LOCALMANAGEDAPPLICATION) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Shell"))]
pub fn GetManagedApplicationCategories(dwreserved: u32, pappcategory: *mut super::super::UI::Shell::APPCATEGORYINFOLIST) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetManagedApplications(pcategory: *const ::windows_sys::core::GUID, dwqueryflags: u32, dwinfolevel: u32, pdwapps: *mut u32, prgmanagedapps: *mut *mut MANAGEDAPPLICATION) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn ImportRSoPData(lpnamespace: super::super::Foundation::PWSTR, lpfilename: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn InstallApplication(pinstallinfo: *const INSTALLDATA) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn LeaveCriticalPolicySection(hsection: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
pub fn ProcessGroupPolicyCompleted(extensionid: *const ::windows_sys::core::GUID, pasynchandle: usize, dwstatus: u32) -> u32;
pub fn ProcessGroupPolicyCompletedEx(extensionid: *const ::windows_sys::core::GUID, pasynchandle: usize, dwstatus: u32, rsopstatus: ::windows_sys::core::HRESULT) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn RefreshPolicy(bmachine: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn RefreshPolicyEx(bmachine: super::super::Foundation::BOOL, dwoptions: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn RegisterGPNotification(hevent: super::super::Foundation::HANDLE, bmachine: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub fn RsopAccessCheckByType(
psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR,
pprincipalselfsid: super::super::Foundation::PSID,
prsoptoken: *const ::core::ffi::c_void,
dwdesiredaccessmask: u32,
pobjecttypelist: *const super::super::Security::OBJECT_TYPE_LIST,
objecttypelistlength: u32,
pgenericmapping: *const super::super::Security::GENERIC_MAPPING,
pprivilegeset: *const super::super::Security::PRIVILEGE_SET,
pdwprivilegesetlength: *const u32,
pdwgrantedaccessmask: *mut u32,
pbaccessstatus: *mut i32,
) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn RsopFileAccessCheck(pszfilename: super::super::Foundation::PWSTR, prsoptoken: *const ::core::ffi::c_void, dwdesiredaccessmask: u32, pdwgrantedaccessmask: *mut u32, pbaccessstatus: *mut i32) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_System_Wmi")]
pub fn RsopResetPolicySettingStatus(dwflags: u32, pservices: super::Wmi::IWbemServices, psettinginstance: super::Wmi::IWbemClassObject) -> ::windows_sys::core::HRESULT;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Wmi"))]
pub fn RsopSetPolicySettingStatus(dwflags: u32, pservices: super::Wmi::IWbemServices, psettinginstance: super::Wmi::IWbemClassObject, ninfo: u32, pstatus: *const POLICYSETTINGSTATUSINFO) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn UninstallApplication(productcode: super::super::Foundation::PWSTR, dwstatus: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UnregisterGPNotification(hevent: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
}
pub type APPSTATE = i32;
pub const ABSENT: APPSTATE = 0i32;
pub const ASSIGNED: APPSTATE = 1i32;
pub const PUBLISHED: APPSTATE = 2i32;
pub const CLSID_GPESnapIn: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2411771700, data2: 41185, data3: 4561, data4: [167, 211, 0, 0, 248, 117, 113, 227] };
pub const CLSID_GroupPolicyObject: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3931121442, data2: 41533, data3: 4561, data4: [167, 211, 0, 0, 248, 117, 113, 227] };
pub const CLSID_RSOPSnapIn: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1841528907,
data2: 29202,
data3: 17805,
data4: [173, 176, 154, 7, 226, 174, 31, 162],
};
pub type CriticalPolicySectionHandle = isize;
pub const FLAG_ASSUME_COMP_WQLFILTER_TRUE: u32 = 33554432u32;
pub const FLAG_ASSUME_SLOW_LINK: u32 = 536870912u32;
pub const FLAG_ASSUME_USER_WQLFILTER_TRUE: u32 = 67108864u32;
pub const FLAG_FORCE_CREATENAMESPACE: u32 = 4u32;
pub const FLAG_LOOPBACK_MERGE: u32 = 268435456u32;
pub const FLAG_LOOPBACK_REPLACE: u32 = 134217728u32;
pub const FLAG_NO_COMPUTER: u32 = 2u32;
pub const FLAG_NO_CSE_INVOKE: u32 = 1073741824u32;
pub const FLAG_NO_GPO_FILTER: u32 = 2147483648u32;
pub const FLAG_NO_USER: u32 = 1u32;
pub const FLAG_PLANNING_MODE: u32 = 16777216u32;
pub const GPC_BLOCK_POLICY: u32 = 1u32;
pub const GPM: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 4117317384,
data2: 35070,
data3: 19253,
data4: [186, 191, 229, 97, 98, 213, 251, 200],
};
pub const GPMAsyncCancel: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 925341353, data2: 30444, data3: 18333, data4: [173, 108, 85, 99, 24, 237, 95, 157] };
pub const GPMBackup: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3977925816,
data2: 24314,
data3: 18474,
data4: [147, 192, 138, 216, 111, 13, 104, 195],
};
pub const GPMBackupCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3952018267,
data2: 28891,
data3: 19103,
data4: [150, 118, 55, 194, 89, 148, 233, 220],
};
pub const GPMBackupDir: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4242843037, data2: 3873, data3: 19194, data4: [184, 89, 230, 208, 198, 44, 209, 12] };
pub const GPMBackupDirEx: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3904936074,
data2: 52995,
data3: 19547,
data4: [139, 226, 42, 169, 173, 50, 170, 218],
};
pub type GPMBackupType = i32;
pub const typeGPO: GPMBackupType = 0i32;
pub const typeStarterGPO: GPMBackupType = 1i32;
pub const GPMCSECollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3482499112,
data2: 11588,
data3: 19297,
data4: [177, 10, 179, 39, 175, 212, 45, 168],
};
pub const GPMClientSideExtension: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3248678670,
data2: 26012,
data3: 19226,
data4: [148, 11, 248, 139, 10, 249, 200, 164],
};
pub const GPMConstants: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 945154176, data2: 52638, data3: 19724, data4: [158, 175, 21, 121, 40, 58, 24, 136] };
pub type GPMDestinationOption = i32;
pub const opDestinationSameAsSource: GPMDestinationOption = 0i32;
pub const opDestinationNone: GPMDestinationOption = 1i32;
pub const opDestinationByRelativeName: GPMDestinationOption = 2i32;
pub const opDestinationSet: GPMDestinationOption = 3i32;
pub const GPMDomain: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1896415678,
data2: 4176,
data3: 19633,
data4: [131, 138, 197, 207, 242, 89, 225, 131],
};
pub type GPMEntryType = i32;
pub const typeUser: GPMEntryType = 0i32;
pub const typeComputer: GPMEntryType = 1i32;
pub const typeLocalGroup: GPMEntryType = 2i32;
pub const typeGlobalGroup: GPMEntryType = 3i32;
pub const typeUniversalGroup: GPMEntryType = 4i32;
pub const typeUNCPath: GPMEntryType = 5i32;
pub const typeUnknown: GPMEntryType = 6i32;
pub const GPMGPO: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3536726420,
data2: 22965,
data3: 16484,
data4: [181, 129, 77, 104, 72, 106, 22, 196],
};
pub const GPMGPOCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2047177509, data2: 33581, data3: 19939, data4: [164, 31, 199, 128, 67, 106, 78, 9] };
pub const GPMGPOLink: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3252656256,
data2: 21251,
data3: 17094,
data4: [138, 60, 4, 136, 225, 191, 115, 100],
};
pub const GPMGPOLinksCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 4142749722,
data2: 18853,
data3: 18402,
data4: [183, 113, 253, 141, 192, 43, 98, 89],
};
pub const GPMMapEntry: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2358727251, data2: 21553, data3: 17521, data4: [179, 93, 6, 38, 201, 40, 37, 138] };
pub const GPMMapEntryCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 217537883,
data2: 41889,
data3: 19541,
data4: [180, 254, 158, 20, 156, 65, 246, 109],
};
pub const GPMMigrationTable: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1437548611, data2: 10758, data3: 20338, data4: [171, 239, 99, 27, 68, 7, 156, 118] };
pub const GPMPermission: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1483842570, data2: 59840, data3: 18156, data4: [145, 62, 148, 78, 249, 34, 90, 148] };
pub type GPMPermissionType = i32;
pub const permGPOApply: GPMPermissionType = 65536i32;
pub const permGPORead: GPMPermissionType = 65792i32;
pub const permGPOEdit: GPMPermissionType = 65793i32;
pub const permGPOEditSecurityAndDelete: GPMPermissionType = 65794i32;
pub const permGPOCustom: GPMPermissionType = 65795i32;
pub const permWMIFilterEdit: GPMPermissionType = 131072i32;
pub const permWMIFilterFullControl: GPMPermissionType = 131073i32;
pub const permWMIFilterCustom: GPMPermissionType = 131074i32;
pub const permSOMLink: GPMPermissionType = 1835008i32;
pub const permSOMLogging: GPMPermissionType = 1573120i32;
pub const permSOMPlanning: GPMPermissionType = 1573376i32;
pub const permSOMWMICreate: GPMPermissionType = 1049344i32;
pub const permSOMWMIFullControl: GPMPermissionType = 1049345i32;
pub const permSOMGPOCreate: GPMPermissionType = 1049600i32;
pub const permStarterGPORead: GPMPermissionType = 197888i32;
pub const permStarterGPOEdit: GPMPermissionType = 197889i32;
pub const permStarterGPOFullControl: GPMPermissionType = 197890i32;
pub const permStarterGPOCustom: GPMPermissionType = 197891i32;
pub const permSOMStarterGPOCreate: GPMPermissionType = 1049856i32;
pub const GPMRSOP: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1218120879,
data2: 40642,
data3: 20151,
data4: [145, 245, 182, 247, 29, 67, 218, 140],
};
pub type GPMRSOPMode = i32;
pub const rsopUnknown: GPMRSOPMode = 0i32;
pub const rsopPlanning: GPMRSOPMode = 1i32;
pub const rsopLogging: GPMRSOPMode = 2i32;
pub type GPMReportType = i32;
pub const repXML: GPMReportType = 0i32;
pub const repHTML: GPMReportType = 1i32;
pub const repInfraXML: GPMReportType = 2i32;
pub const repInfraRefreshXML: GPMReportType = 3i32;
pub const repClientHealthXML: GPMReportType = 4i32;
pub const repClientHealthRefreshXML: GPMReportType = 5i32;
pub type GPMReportingOptions = i32;
pub const opReportLegacy: GPMReportingOptions = 0i32;
pub const opReportComments: GPMReportingOptions = 1i32;
pub const GPMResult: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2450528960,
data2: 37511,
data3: 16902,
data4: [163, 178, 75, 219, 115, 210, 37, 246],
};
pub const GPMSOM: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 853098412,
data2: 17678,
data3: 17615,
data4: [130, 156, 139, 34, 255, 107, 218, 225],
};
pub const GPMSOMCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 616689991, data2: 14112, data3: 20315, data4: [169, 195, 6, 180, 228, 249, 49, 210] };
pub type GPMSOMType = i32;
pub const somSite: GPMSOMType = 0i32;
pub const somDomain: GPMSOMType = 1i32;
pub const somOU: GPMSOMType = 2i32;
pub const GPMSearchCriteria: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 397068838, data2: 23776, data3: 17658, data4: [140, 192, 82, 89, 230, 72, 53, 102] };
pub type GPMSearchOperation = i32;
pub const opEquals: GPMSearchOperation = 0i32;
pub const opContains: GPMSearchOperation = 1i32;
pub const opNotContains: GPMSearchOperation = 2i32;
pub const opNotEquals: GPMSearchOperation = 3i32;
pub type GPMSearchProperty = i32;
pub const gpoPermissions: GPMSearchProperty = 0i32;
pub const gpoEffectivePermissions: GPMSearchProperty = 1i32;
pub const gpoDisplayName: GPMSearchProperty = 2i32;
pub const gpoWMIFilter: GPMSearchProperty = 3i32;
pub const gpoID: GPMSearchProperty = 4i32;
pub const gpoComputerExtensions: GPMSearchProperty = 5i32;
pub const gpoUserExtensions: GPMSearchProperty = 6i32;
pub const somLinks: GPMSearchProperty = 7i32;
pub const gpoDomain: GPMSearchProperty = 8i32;
pub const backupMostRecent: GPMSearchProperty = 9i32;
pub const starterGPOPermissions: GPMSearchProperty = 10i32;
pub const starterGPOEffectivePermissions: GPMSearchProperty = 11i32;
pub const starterGPODisplayName: GPMSearchProperty = 12i32;
pub const starterGPOID: GPMSearchProperty = 13i32;
pub const starterGPODomain: GPMSearchProperty = 14i32;
pub const GPMSecurityInfo: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1417305743,
data2: 37218,
data3: 17686,
data4: [164, 223, 157, 219, 150, 134, 216, 70],
};
pub const GPMSitesContainer: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 580869186,
data2: 34092,
data3: 19248,
data4: [148, 95, 197, 34, 190, 155, 211, 134],
};
pub const GPMStarterGPOBackup: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 949895178, data2: 55535, data3: 17755, data4: [168, 97, 95, 156, 163, 74, 106, 2] };
pub const GPMStarterGPOBackupCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3881739677, data2: 6891, data3: 19637, data4: [167, 138, 40, 29, 170, 88, 36, 6] };
pub const GPMStarterGPOCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2197334667,
data2: 18874,
data3: 17330,
data4: [149, 110, 51, 151, 249, 185, 76, 58],
};
pub type GPMStarterGPOType = i32;
pub const typeSystem: GPMStarterGPOType = 0i32;
pub const typeCustom: GPMStarterGPOType = 1i32;
pub const GPMStatusMessage: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1266142356, data2: 53845, data3: 16539, data4: [188, 98, 55, 8, 129, 113, 90, 25] };
pub const GPMStatusMsgCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 673506494, data2: 19404, data3: 19628, data4: [158, 96, 14, 62, 215, 241, 36, 150] };
pub const GPMTemplate: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3975271508,
data2: 29146,
data3: 20015,
data4: [168, 192, 129, 133, 70, 89, 17, 217],
};
pub const GPMTrustee: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3309989901, data2: 6582, data3: 16913, data4: [188, 176, 232, 226, 71, 94, 71, 30] };
pub const GPMWMIFilter: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1650935256,
data2: 3562,
data3: 16482,
data4: [191, 96, 207, 197, 177, 202, 18, 134],
};
pub const GPMWMIFilterCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1960602920,
data2: 59424,
data3: 18390,
data4: [160, 184, 240, 141, 147, 215, 250, 51],
};
pub const GPM_DONOTUSE_W2KDC: u32 = 2u32;
pub const GPM_DONOT_VALIDATEDC: u32 = 1u32;
pub const GPM_MIGRATIONTABLE_ONLY: u32 = 1u32;
pub const GPM_PROCESS_SECURITY: u32 = 2u32;
pub const GPM_USE_ANYDC: u32 = 1u32;
pub const GPM_USE_PDC: u32 = 0u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct GPOBROWSEINFO {
pub dwSize: u32,
pub dwFlags: u32,
pub hwndOwner: super::super::Foundation::HWND,
pub lpTitle: super::super::Foundation::PWSTR,
pub lpInitialOU: super::super::Foundation::PWSTR,
pub lpDSPath: super::super::Foundation::PWSTR,
pub dwDSPathSize: u32,
pub lpName: super::super::Foundation::PWSTR,
pub dwNameSize: u32,
pub gpoType: GROUP_POLICY_OBJECT_TYPE,
pub gpoHint: GROUP_POLICY_HINT_TYPE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GPOBROWSEINFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GPOBROWSEINFO {
fn clone(&self) -> Self {
*self
}
}
pub const GPO_BROWSE_DISABLENEW: u32 = 1u32;
pub const GPO_BROWSE_INITTOALL: u32 = 16u32;
pub const GPO_BROWSE_NOCOMPUTERS: u32 = 2u32;
pub const GPO_BROWSE_NODSGPOS: u32 = 4u32;
pub const GPO_BROWSE_NOUSERGPOS: u32 = 32u32;
pub const GPO_BROWSE_OPENBUTTON: u32 = 8u32;
pub const GPO_BROWSE_SENDAPPLYONEDIT: u32 = 64u32;
pub const GPO_FLAG_DISABLE: u32 = 1u32;
pub const GPO_FLAG_FORCE: u32 = 2u32;
pub const GPO_INFO_FLAG_ASYNC_FOREGROUND: u32 = 4096u32;
pub const GPO_INFO_FLAG_BACKGROUND: u32 = 16u32;
pub const GPO_INFO_FLAG_FORCED_REFRESH: u32 = 1024u32;
pub const GPO_INFO_FLAG_LINKTRANSITION: u32 = 256u32;
pub const GPO_INFO_FLAG_LOGRSOP_TRANSITION: u32 = 512u32;
pub const GPO_INFO_FLAG_MACHINE: u32 = 1u32;
pub const GPO_INFO_FLAG_NOCHANGES: u32 = 128u32;
pub const GPO_INFO_FLAG_SAFEMODE_BOOT: u32 = 2048u32;
pub const GPO_INFO_FLAG_SLOWLINK: u32 = 32u32;
pub const GPO_INFO_FLAG_VERBOSE: u32 = 64u32;
pub type GPO_LINK = i32;
pub const GPLinkUnknown: GPO_LINK = 0i32;
pub const GPLinkMachine: GPO_LINK = 1i32;
pub const GPLinkSite: GPO_LINK = 2i32;
pub const GPLinkDomain: GPO_LINK = 3i32;
pub const GPLinkOrganizationalUnit: GPO_LINK = 4i32;
pub const GPO_LIST_FLAG_MACHINE: u32 = 1u32;
pub const GPO_LIST_FLAG_NO_SECURITYFILTERS: u32 = 8u32;
pub const GPO_LIST_FLAG_NO_WMIFILTERS: u32 = 4u32;
pub const GPO_LIST_FLAG_SITEONLY: u32 = 2u32;
pub const GPO_OPEN_LOAD_REGISTRY: u32 = 1u32;
pub const GPO_OPEN_READ_ONLY: u32 = 2u32;
pub const GPO_OPTION_DISABLE_MACHINE: u32 = 2u32;
pub const GPO_OPTION_DISABLE_USER: u32 = 1u32;
pub const GPO_SECTION_MACHINE: u32 = 2u32;
pub const GPO_SECTION_ROOT: u32 = 0u32;
pub const GPO_SECTION_USER: u32 = 1u32;
pub type GROUP_POLICY_HINT_TYPE = i32;
pub const GPHintUnknown: GROUP_POLICY_HINT_TYPE = 0i32;
pub const GPHintMachine: GROUP_POLICY_HINT_TYPE = 1i32;
pub const GPHintSite: GROUP_POLICY_HINT_TYPE = 2i32;
pub const GPHintDomain: GROUP_POLICY_HINT_TYPE = 3i32;
pub const GPHintOrganizationalUnit: GROUP_POLICY_HINT_TYPE = 4i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct GROUP_POLICY_OBJECTA {
pub dwOptions: u32,
pub dwVersion: u32,
pub lpDSPath: super::super::Foundation::PSTR,
pub lpFileSysPath: super::super::Foundation::PSTR,
pub lpDisplayName: super::super::Foundation::PSTR,
pub szGPOName: [super::super::Foundation::CHAR; 50],
pub GPOLink: GPO_LINK,
pub lParam: super::super::Foundation::LPARAM,
pub pNext: *mut GROUP_POLICY_OBJECTA,
pub pPrev: *mut GROUP_POLICY_OBJECTA,
pub lpExtensions: super::super::Foundation::PSTR,
pub lParam2: super::super::Foundation::LPARAM,
pub lpLink: super::super::Foundation::PSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GROUP_POLICY_OBJECTA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GROUP_POLICY_OBJECTA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct GROUP_POLICY_OBJECTW {
pub dwOptions: u32,
pub dwVersion: u32,
pub lpDSPath: super::super::Foundation::PWSTR,
pub lpFileSysPath: super::super::Foundation::PWSTR,
pub lpDisplayName: super::super::Foundation::PWSTR,
pub szGPOName: [u16; 50],
pub GPOLink: GPO_LINK,
pub lParam: super::super::Foundation::LPARAM,
pub pNext: *mut GROUP_POLICY_OBJECTW,
pub pPrev: *mut GROUP_POLICY_OBJECTW,
pub lpExtensions: super::super::Foundation::PWSTR,
pub lParam2: super::super::Foundation::LPARAM,
pub lpLink: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GROUP_POLICY_OBJECTW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GROUP_POLICY_OBJECTW {
fn clone(&self) -> Self {
*self
}
}
pub type GROUP_POLICY_OBJECT_TYPE = i32;
pub const GPOTypeLocal: GROUP_POLICY_OBJECT_TYPE = 0i32;
pub const GPOTypeRemote: GROUP_POLICY_OBJECT_TYPE = 1i32;
pub const GPOTypeDS: GROUP_POLICY_OBJECT_TYPE = 2i32;
pub const GPOTypeLocalUser: GROUP_POLICY_OBJECT_TYPE = 3i32;
pub const GPOTypeLocalGroup: GROUP_POLICY_OBJECT_TYPE = 4i32;
pub type IGPEInformation = *mut ::core::ffi::c_void;
pub type IGPM = *mut ::core::ffi::c_void;
pub type IGPM2 = *mut ::core::ffi::c_void;
pub type IGPMAsyncCancel = *mut ::core::ffi::c_void;
pub type IGPMAsyncProgress = *mut ::core::ffi::c_void;
pub type IGPMBackup = *mut ::core::ffi::c_void;
pub type IGPMBackupCollection = *mut ::core::ffi::c_void;
pub type IGPMBackupDir = *mut ::core::ffi::c_void;
pub type IGPMBackupDirEx = *mut ::core::ffi::c_void;
pub type IGPMCSECollection = *mut ::core::ffi::c_void;
pub type IGPMClientSideExtension = *mut ::core::ffi::c_void;
pub type IGPMConstants = *mut ::core::ffi::c_void;
pub type IGPMConstants2 = *mut ::core::ffi::c_void;
pub type IGPMDomain = *mut ::core::ffi::c_void;
pub type IGPMDomain2 = *mut ::core::ffi::c_void;
pub type IGPMDomain3 = *mut ::core::ffi::c_void;
pub type IGPMGPO = *mut ::core::ffi::c_void;
pub type IGPMGPO2 = *mut ::core::ffi::c_void;
pub type IGPMGPO3 = *mut ::core::ffi::c_void;
pub type IGPMGPOCollection = *mut ::core::ffi::c_void;
pub type IGPMGPOLink = *mut ::core::ffi::c_void;
pub type IGPMGPOLinksCollection = *mut ::core::ffi::c_void;
pub type IGPMMapEntry = *mut ::core::ffi::c_void;
pub type IGPMMapEntryCollection = *mut ::core::ffi::c_void;
pub type IGPMMigrationTable = *mut ::core::ffi::c_void;
pub type IGPMPermission = *mut ::core::ffi::c_void;
pub type IGPMRSOP = *mut ::core::ffi::c_void;
pub type IGPMResult = *mut ::core::ffi::c_void;
pub type IGPMSOM = *mut ::core::ffi::c_void;
pub type IGPMSOMCollection = *mut ::core::ffi::c_void;
pub type IGPMSearchCriteria = *mut ::core::ffi::c_void;
pub type IGPMSecurityInfo = *mut ::core::ffi::c_void;
pub type IGPMSitesContainer = *mut ::core::ffi::c_void;
pub type IGPMStarterGPO = *mut ::core::ffi::c_void;
pub type IGPMStarterGPOBackup = *mut ::core::ffi::c_void;
pub type IGPMStarterGPOBackupCollection = *mut ::core::ffi::c_void;
pub type IGPMStarterGPOCollection = *mut ::core::ffi::c_void;
pub type IGPMStatusMessage = *mut ::core::ffi::c_void;
pub type IGPMStatusMsgCollection = *mut ::core::ffi::c_void;
pub type IGPMTrustee = *mut ::core::ffi::c_void;
pub type IGPMWMIFilter = *mut ::core::ffi::c_void;
pub type IGPMWMIFilterCollection = *mut ::core::ffi::c_void;
pub type IGroupPolicyObject = *mut ::core::ffi::c_void;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INSTALLDATA {
pub Type: INSTALLSPECTYPE,
pub Spec: INSTALLSPEC,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INSTALLDATA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INSTALLDATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union INSTALLSPEC {
pub AppName: INSTALLSPEC_0,
pub FileExt: super::super::Foundation::PWSTR,
pub ProgId: super::super::Foundation::PWSTR,
pub COMClass: INSTALLSPEC_1,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INSTALLSPEC {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INSTALLSPEC {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INSTALLSPEC_0 {
pub Name: super::super::Foundation::PWSTR,
pub GPOId: ::windows_sys::core::GUID,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INSTALLSPEC_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INSTALLSPEC_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INSTALLSPEC_1 {
pub Clsid: ::windows_sys::core::GUID,
pub ClsCtx: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INSTALLSPEC_1 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INSTALLSPEC_1 {
fn clone(&self) -> Self {
*self
}
}
pub type INSTALLSPECTYPE = i32;
pub const APPNAME: INSTALLSPECTYPE = 1i32;
pub const FILEEXT: INSTALLSPECTYPE = 2i32;
pub const PROGID: INSTALLSPECTYPE = 3i32;
pub const COMCLASS: INSTALLSPECTYPE = 4i32;
pub type IRSOPInformation = *mut ::core::ffi::c_void;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct LOCALMANAGEDAPPLICATION {
pub pszDeploymentName: super::super::Foundation::PWSTR,
pub pszPolicyName: super::super::Foundation::PWSTR,
pub pszProductId: super::super::Foundation::PWSTR,
pub dwState: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for LOCALMANAGEDAPPLICATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for LOCALMANAGEDAPPLICATION {
fn clone(&self) -> Self {
*self
}
}
pub const LOCALSTATE_ASSIGNED: u32 = 1u32;
pub const LOCALSTATE_ORPHANED: u32 = 32u32;
pub const LOCALSTATE_POLICYREMOVE_ORPHAN: u32 = 8u32;
pub const LOCALSTATE_POLICYREMOVE_UNINSTALL: u32 = 16u32;
pub const LOCALSTATE_PUBLISHED: u32 = 2u32;
pub const LOCALSTATE_UNINSTALLED: u32 = 64u32;
pub const LOCALSTATE_UNINSTALL_UNMANAGED: u32 = 4u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MANAGEDAPPLICATION {
pub pszPackageName: super::super::Foundation::PWSTR,
pub pszPublisher: super::super::Foundation::PWSTR,
pub dwVersionHi: u32,
pub dwVersionLo: u32,
pub dwRevision: u32,
pub GpoId: ::windows_sys::core::GUID,
pub pszPolicyName: super::super::Foundation::PWSTR,
pub ProductId: ::windows_sys::core::GUID,
pub Language: u16,
pub pszOwner: super::super::Foundation::PWSTR,
pub pszCompany: super::super::Foundation::PWSTR,
pub pszComments: super::super::Foundation::PWSTR,
pub pszContact: super::super::Foundation::PWSTR,
pub pszSupportUrl: super::super::Foundation::PWSTR,
pub dwPathType: u32,
pub bInstalled: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MANAGEDAPPLICATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MANAGEDAPPLICATION {
fn clone(&self) -> Self {
*self
}
}
pub const MANAGED_APPS_FROMCATEGORY: u32 = 2u32;
pub const MANAGED_APPS_INFOLEVEL_DEFAULT: u32 = 65536u32;
pub const MANAGED_APPS_USERAPPLICATIONS: u32 = 1u32;
pub const MANAGED_APPTYPE_SETUPEXE: u32 = 2u32;
pub const MANAGED_APPTYPE_UNSUPPORTED: u32 = 3u32;
pub const MANAGED_APPTYPE_WINDOWSINSTALLER: u32 = 1u32;
pub const NODEID_Machine: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2411771703, data2: 41185, data3: 4561, data4: [167, 211, 0, 0, 248, 117, 113, 227] };
pub const NODEID_MachineSWSettings: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2411771706, data2: 41185, data3: 4561, data4: [167, 211, 0, 0, 248, 117, 113, 227] };
pub const NODEID_RSOPMachine: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3175881262,
data2: 2938,
data3: 19042,
data4: [166, 176, 192, 87, 117, 57, 201, 126],
};
pub const NODEID_RSOPMachineSWSettings: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1786128190, data2: 60302, data3: 17883, data4: [148, 197, 37, 102, 58, 95, 44, 26] };
pub const NODEID_RSOPUser: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2877765199,
data2: 3308,
data3: 19672,
data4: [155, 248, 137, 143, 52, 98, 143, 184],
};
pub const NODEID_RSOPUserSWSettings: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3844889827,
data2: 64807,
data3: 17410,
data4: [132, 222, 217, 165, 242, 133, 137, 16],
};
pub const NODEID_User: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2411771704, data2: 41185, data3: 4561, data4: [167, 211, 0, 0, 248, 117, 113, 227] };
pub const NODEID_UserSWSettings: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2411771708, data2: 41185, data3: 4561, data4: [167, 211, 0, 0, 248, 117, 113, 227] };
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Wmi"))]
pub type PFNGENERATEGROUPPOLICY = ::core::option::Option<unsafe extern "system" fn(dwflags: u32, pbabort: *mut super::super::Foundation::BOOL, pwszsite: super::super::Foundation::PWSTR, pcomputertarget: *const RSOP_TARGET, pusertarget: *const RSOP_TARGET) -> u32>;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
pub type PFNPROCESSGROUPPOLICY = ::core::option::Option<unsafe extern "system" fn(dwflags: u32, htoken: super::super::Foundation::HANDLE, hkeyroot: super::Registry::HKEY, pdeletedgpolist: *const GROUP_POLICY_OBJECTA, pchangedgpolist: *const GROUP_POLICY_OBJECTA, phandle: usize, pbabort: *mut super::super::Foundation::BOOL, pstatuscallback: PFNSTATUSMESSAGECALLBACK) -> u32>;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry", feature = "Win32_System_Wmi"))]
pub type PFNPROCESSGROUPPOLICYEX = ::core::option::Option<unsafe extern "system" fn(dwflags: u32, htoken: super::super::Foundation::HANDLE, hkeyroot: super::Registry::HKEY, pdeletedgpolist: *const GROUP_POLICY_OBJECTA, pchangedgpolist: *const GROUP_POLICY_OBJECTA, phandle: usize, pbabort: *mut super::super::Foundation::BOOL, pstatuscallback: PFNSTATUSMESSAGECALLBACK, pwbemservices: super::Wmi::IWbemServices, prsopstatus: *mut ::windows_sys::core::HRESULT) -> u32>;
#[cfg(feature = "Win32_Foundation")]
pub type PFNSTATUSMESSAGECALLBACK = ::core::option::Option<unsafe extern "system" fn(bverbose: super::super::Foundation::BOOL, lpmessage: super::super::Foundation::PWSTR) -> u32>;
pub const PI_APPLYPOLICY: u32 = 2u32;
pub const PI_NOUI: u32 = 1u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct POLICYSETTINGSTATUSINFO {
pub szKey: super::super::Foundation::PWSTR,
pub szEventSource: super::super::Foundation::PWSTR,
pub szEventLogName: super::super::Foundation::PWSTR,
pub dwEventID: u32,
pub dwErrorCode: u32,
pub status: SETTINGSTATUS,
pub timeLogged: super::super::Foundation::SYSTEMTIME,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for POLICYSETTINGSTATUSINFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for POLICYSETTINGSTATUSINFO {
fn clone(&self) -> Self {
*self
}
}
pub const PT_MANDATORY: u32 = 4u32;
pub const PT_ROAMING: u32 = 2u32;
pub const PT_ROAMING_PREEXISTING: u32 = 8u32;
pub const PT_TEMPORARY: u32 = 1u32;
pub const RP_FORCE: u32 = 1u32;
pub const RP_SYNC: u32 = 2u32;
pub const RSOP_COMPUTER_ACCESS_DENIED: u32 = 2u32;
pub const RSOP_INFO_FLAG_DIAGNOSTIC_MODE: u32 = 1u32;
pub const RSOP_NO_COMPUTER: u32 = 65536u32;
pub const RSOP_NO_USER: u32 = 131072u32;
pub const RSOP_PLANNING_ASSUME_COMP_WQLFILTER_TRUE: u32 = 16u32;
pub const RSOP_PLANNING_ASSUME_LOOPBACK_MERGE: u32 = 2u32;
pub const RSOP_PLANNING_ASSUME_LOOPBACK_REPLACE: u32 = 4u32;
pub const RSOP_PLANNING_ASSUME_SLOW_LINK: u32 = 1u32;
pub const RSOP_PLANNING_ASSUME_USER_WQLFILTER_TRUE: u32 = 8u32;
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Wmi"))]
pub struct RSOP_TARGET {
pub pwszAccountName: super::super::Foundation::PWSTR,
pub pwszNewSOM: super::super::Foundation::PWSTR,
pub psaSecurityGroups: *mut super::Com::SAFEARRAY,
pub pRsopToken: *mut ::core::ffi::c_void,
pub pGPOList: *mut GROUP_POLICY_OBJECTA,
pub pWbemServices: super::Wmi::IWbemServices,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Wmi"))]
impl ::core::marker::Copy for RSOP_TARGET {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Wmi"))]
impl ::core::clone::Clone for RSOP_TARGET {
fn clone(&self) -> Self {
*self
}
}
pub const RSOP_TEMPNAMESPACE_EXISTS: u32 = 4u32;
pub const RSOP_USER_ACCESS_DENIED: u32 = 1u32;
pub type SETTINGSTATUS = i32;
pub const RSOPUnspecified: SETTINGSTATUS = 0i32;
pub const RSOPApplied: SETTINGSTATUS = 1i32;
pub const RSOPIgnored: SETTINGSTATUS = 2i32;
pub const RSOPFailed: SETTINGSTATUS = 3i32;
pub const RSOPSubsettingFailed: SETTINGSTATUS = 4i32;
|
pub struct Solution;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Tree,
pub right: Tree,
}
use std::cell::RefCell;
use std::rc::Rc;
type Tree = Option<Rc<RefCell<TreeNode>>>;
impl Solution {
pub fn recover_tree(root: &mut Tree) {
let tl = left_mistake(root).unwrap();
let tr = right_mistake(root).unwrap();
let tmp = tl.borrow().val;
tl.borrow_mut().val = tr.borrow().val;
tr.borrow_mut().val = tmp;
}
}
fn left_mistake(root: &Tree) -> Tree {
if root.is_none() {
return None;
}
let node = root.as_ref().unwrap().borrow();
let res = left_mistake(&node.left);
if res.is_some() {
return res;
}
let prev = rightmost(&node.left);
if prev.is_some() && prev.as_ref().unwrap().borrow().val > node.val {
return prev;
}
let next = leftmost(&node.right);
if next.is_some() && node.val > next.as_ref().unwrap().borrow().val {
return root.clone();
}
left_mistake(&node.right)
}
fn right_mistake(root: &Tree) -> Tree {
if root.is_none() {
return None;
}
let node = root.as_ref().unwrap().borrow();
let res = right_mistake(&node.right);
if res.is_some() {
return res;
}
let next = leftmost(&node.right);
if next.is_some() && node.val > next.as_ref().unwrap().borrow().val {
return next;
}
let prev = rightmost(&node.left);
if prev.is_some() && prev.as_ref().unwrap().borrow().val > node.val {
return root.clone();
}
right_mistake(&node.left)
}
fn leftmost(root: &Tree) -> Tree {
if root.is_none() {
None
} else if root.as_ref().unwrap().borrow().left.is_some() {
leftmost(&root.as_ref().unwrap().borrow().left)
} else {
root.clone()
}
}
fn rightmost(root: &Tree) -> Tree {
if root.is_none() {
None
} else if root.as_ref().unwrap().borrow().right.is_some() {
rightmost(&root.as_ref().unwrap().borrow().right)
} else {
root.clone()
}
}
#[test]
fn test0099() {
fn tree(left: Tree, val: i32, right: Tree) -> Tree {
Some(Rc::new(RefCell::new(TreeNode { val, left, right })))
}
let mut t = tree(tree(None, 3, tree(None, 2, None)), 1, None);
Solution::recover_tree(&mut t);
assert_eq!(t, tree(tree(None, 1, tree(None, 2, None)), 3, None));
let mut t = tree(tree(None, 1, None), 3, tree(tree(None, 2, None), 4, None));
Solution::recover_tree(&mut t);
assert_eq!(
t,
tree(tree(None, 1, None), 2, tree(tree(None, 3, None), 4, None))
);
}
|
use super::*;
#[test]
fn reverse() {
assert_eq!(Op::Reverse().perform(10, 9), 0);
}
#[test]
fn cut_positive() {
assert_eq!(Op::Cut(3).perform(10, 0), 7);
assert_eq!(Op::Cut(3).perform(10, 2), 9);
assert_eq!(Op::Cut(3).perform(10, 3), 0);
assert_eq!(Op::Cut(3).perform(10, 9), 6);
}
#[test]
fn cut_negative() {
assert_eq!(Op::Cut(-4).perform(10, 0), 4);
assert_eq!(Op::Cut(-4).perform(10, 5), 9);
assert_eq!(Op::Cut(-4).perform(10, 6), 0);
assert_eq!(Op::Cut(-4).perform(10, 9), 3);
}
#[test]
fn deal() {
assert_eq!(Op::Deal(3).perform(10, 0), 0);
assert_eq!(Op::Deal(3).perform(10, 1), 3);
assert_eq!(Op::Deal(3).perform(10, 2), 6);
assert_eq!(Op::Deal(3).perform(10, 3), 9);
assert_eq!(Op::Deal(3).perform(10, 4), 2);
assert_eq!(Op::Deal(3).perform(10, 9), 7);
}
fn deal_symmetry(ds: i64, n: i64) {
let op = Op::Deal(n);
let rev = op.invert(ds);
for i in 0..ds {
let si = op.perform(ds, i);
let usi = rev.perform(ds, i);
assert_eq!(rev.perform(ds, si), i);
assert_eq!(op.perform(ds, usi), i);
}
}
#[test]
fn undeal() {
deal_symmetry(7, 3)
}
#[test]
fn example_one() {
#[cfg_attr(rustfmt, rustfmt_skip)]
let ops = vec![
Op::Deal(7),
Op::Reverse(),
Op::Reverse(),
];
assert_eq!(slam_shuffle(&ops, 10, 0), 0);
assert_eq!(slam_shuffle(&ops, 10, 3), 1);
assert_eq!(slam_shuffle(&ops, 10, 6), 2);
assert_eq!(slam_shuffle(&ops, 10, 9), 3);
assert_eq!(slam_shuffle(&ops, 10, 2), 4);
assert_eq!(slam_shuffle(&ops, 10, 5), 5);
assert_eq!(slam_shuffle(&ops, 10, 8), 6);
assert_eq!(slam_shuffle(&ops, 10, 1), 7);
assert_eq!(slam_shuffle(&ops, 10, 4), 8);
assert_eq!(slam_shuffle(&ops, 10, 7), 9);
}
#[test]
fn test_inverse() {
assert_eq!(inverse(3, 7), 5);
assert_eq!(inverse(4, 7), 2);
}
#[test]
fn table() {
let ops = vec![
Op::Reverse(),
Op::Cut(-2),
Op::Deal(7),
Op::Cut(8),
Op::Cut(-4),
Op::Deal(7),
Op::Cut(3),
Op::Deal(9),
Op::Deal(3),
Op::Cut(-1),
];
let deck_size = 19;
for op in ops.iter() {
match op {
Op::Reverse() => {}
Op::Cut(_) => {}
Op::Deal(n) => {
if gcd(*n, deck_size) != 1 {
panic!("deck size {} is not compatible with Deal({})", deck_size, n)
}
}
}
}
let mut result = Vec::new();
for idx in 0..deck_size {
result.push(idx);
}
for itr in 0..=deck_size {
let mut next = Vec::new();
next.resize(deck_size as usize, 0);
for idx in 0..deck_size {
next[slam_shuffle(&ops, deck_size, idx) as usize] = result[idx as usize];
}
println!("{:2} {:?}", itr, result);
result = next;
}
}
|
#[macro_use]
extern crate nom;
extern crate num;
use std::ops::{Add, Mul, Div, Sub};
use num::pow;
use num::traits::PrimInt;
use num::integer::Integer;
use num::rational::{Ratio, BigRational};
use num::bigint::{BigInt, Sign, ToBigInt, BigUint, ParseBigIntError};
use nom::InputLength;
use nom::{error_to_list, IResult, digit, eof, eol, space};
use nom::IResult::*;
// Parser definition
use std::str;
use std::str::FromStr;
struct Commodity {
symbol: String,
// should the symbol appear on the left or the right
side: bool,
// should thousands be comma-separated
comma: bool,
}
// https://hackage.haskell.org/package/hledger-0.3/docs/Ledger-Parse.html
struct Amount {
commodity: Commodity,
quantity: i64
}
struct UDigits {
value: BigUint,
num_digits: usize
}
// struct Digits {
// value: BigInt,
// num_digits: usize
// }
fn to_digits(input: &[u8]) -> Result<UDigits, ParseBigIntError> {
let input_len = input.input_len();
let input: &str = str::from_utf8(&input).unwrap();
match BigUint::from_str(input) {
Err(why) => Err(why),
Ok(resolved_int) => {
let res = UDigits {
value: resolved_int,
num_digits: input_len
};
Ok(res)
}
}
}
// goal:
// parse: XXXX.YYYY COMMODITY
named!(biguint_digit<UDigits>,
map_res!(
digit,
to_digits
)
);
named!(bigint_plus<Sign>,
chain!(
char!('+'),
|| {
Sign::Plus
}
)
);
named!(bigint_neg<Sign>,
chain!(
char!('-'),
|| {
Sign::Minus
}
)
);
named!(bigint_sign<Sign>,
alt!(
bigint_plus |
bigint_neg
)
);
named!(integer_value<BigRational>,
chain!(
space? ~
sign: bigint_sign? ~
raw_digits: biguint_digit ~
space? ,
|| {
// TODO: remove/cleanup
// match sign {
// Some(sign) => {
// Digits {
// value: BigInt::from_biguint(sign, raw_digits.value.clone()),
// num_digits: raw_digits.num_digits
// }
// },
// None => {
// Digits {
// value: BigInt::from_biguint(Sign::Plus, raw_digits.value.clone()),
// num_digits: raw_digits.num_digits
// }
// }
// }
let sign = match sign {
Some(sign) => sign,
None => Sign::Plus
};
let integer = BigInt::from_biguint(sign, raw_digits.value.clone());
return BigRational::from_integer(integer);
}
)
);
named!(floating_value<BigRational>,
chain!(
space? ~
sign: bigint_sign? ~
int_part: biguint_digit ~
char!('.') ~
frac_part: biguint_digit ~
space?,
|| {
let sign = match sign {
Some(sign) => sign,
None => Sign::Plus
};
// TODO: needs refactor
// integer_component(X) + frac_component(X) / 10 ^ digit_len(frac_component(X))
let scale = BigRational::from_integer(10.to_bigint().unwrap());
let scale = num::pow(scale, frac_part.num_digits);
let scale = scale.recip();
// numerator of proper fraction
let __proper_numerator = BigInt::from_biguint(sign, frac_part.value.clone());
let proper_numerator = BigRational::from_integer(__proper_numerator);
// proper fraction
let proper_frac = proper_numerator.mul(scale);
let __int_part = BigInt::from_biguint(sign, int_part.value.clone());
let mixed_frac = proper_frac.add(BigRational::from_integer(__int_part));
return mixed_frac;
}
)
);
named!(int_or_float<BigRational>,
alt!(
complete!(floating_value) |
complete!(integer_value)
)
);
named!(parens<BigRational>, delimited!(
char!('('),
expr_val,
char!(')')
)
);
named!(factor_val<BigRational>,
alt!(
int_or_float
| parens
)
);
named!(term_val <BigRational>,
chain!(
space? ~
mut acc: factor_val ~
many0!(
alt!(
tap!(mul: preceded!(tag!("*"), factor_val) => acc = acc.mul(mul.clone())) |
tap!(div: preceded!(tag!("/"), factor_val) => acc = acc.div(div.clone()))
)
) ~
space? ,
|| { return acc }
)
);
named!(expr_val <BigRational>,
chain!(
space? ~
mut acc: term_val ~
many0!(
alt!(
tap!(add: preceded!(tag!("+"), term_val) => acc = acc.add(add.clone())) |
tap!(sub: preceded!(tag!("-"), term_val) => acc = acc.sub(sub.clone()))
)
) ~
space? ,
|| { return acc }
)
);
named!(commodity_quantity<BigRational>,
alt!(
parens | expr_val
)
);
fn main() {
// match bigint_digit(b"14") {
// Done(_, out) => {
// println!("{}", out.value);
// },
// Error(why) => {
// println!("{:?}", why);
// },
// Incomplete(why) => {
// println!("incomplete input");
// }
// }
match commodity_quantity(b"2") {
Done(_, out) => {
println!("{}", out);
},
Error(why) => {
println!("{:?}", why);
},
Incomplete(why) => {
println!("incomplete input");
}
}
// println!("{}", bigint_digit(b"14"));
}
|
fn main() {
println!("🔓 Challenge 15");
println!("Code in 'cipher/src/padding.rs'");
}
|
fn main(){ println!("Hello fellow reader!"); }
|
#[doc = "Reader of register FDCAN_ILS"]
pub type R = crate::R<u32, super::FDCAN_ILS>;
#[doc = "Writer for register FDCAN_ILS"]
pub type W = crate::W<u32, super::FDCAN_ILS>;
#[doc = "Register FDCAN_ILS `reset()`'s with value 0"]
impl crate::ResetValue for super::FDCAN_ILS {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `RxFIFO0`"]
pub type RXFIFO0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RxFIFO0`"]
pub struct RXFIFO0_W<'a> {
w: &'a mut W,
}
impl<'a> RXFIFO0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
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) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `RxFIFO1`"]
pub type RXFIFO1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RxFIFO1`"]
pub struct RXFIFO1_W<'a> {
w: &'a mut W,
}
impl<'a> RXFIFO1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
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 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `SMSG`"]
pub type SMSG_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SMSG`"]
pub struct SMSG_W<'a> {
w: &'a mut W,
}
impl<'a> SMSG_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
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 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `TFERR`"]
pub type TFERR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TFERR`"]
pub struct TFERR_W<'a> {
w: &'a mut W,
}
impl<'a> TFERR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
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 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `MISC`"]
pub type MISC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MISC`"]
pub struct MISC_W<'a> {
w: &'a mut W,
}
impl<'a> MISC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
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 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `BERR`"]
pub type BERR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BERR`"]
pub struct BERR_W<'a> {
w: &'a mut W,
}
impl<'a> BERR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `PERR`"]
pub type PERR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PERR`"]
pub struct PERR_W<'a> {
w: &'a mut W,
}
impl<'a> PERR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
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 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
impl R {
#[doc = "Bit 0 - RxFIFO0"]
#[inline(always)]
pub fn rx_fifo0(&self) -> RXFIFO0_R {
RXFIFO0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - RxFIFO1"]
#[inline(always)]
pub fn rx_fifo1(&self) -> RXFIFO1_R {
RXFIFO1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - SMSG"]
#[inline(always)]
pub fn smsg(&self) -> SMSG_R {
SMSG_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - TFERR"]
#[inline(always)]
pub fn tferr(&self) -> TFERR_R {
TFERR_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - MISC"]
#[inline(always)]
pub fn misc(&self) -> MISC_R {
MISC_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - BERR"]
#[inline(always)]
pub fn berr(&self) -> BERR_R {
BERR_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - PERR"]
#[inline(always)]
pub fn perr(&self) -> PERR_R {
PERR_R::new(((self.bits >> 6) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - RxFIFO0"]
#[inline(always)]
pub fn rx_fifo0(&mut self) -> RXFIFO0_W {
RXFIFO0_W { w: self }
}
#[doc = "Bit 1 - RxFIFO1"]
#[inline(always)]
pub fn rx_fifo1(&mut self) -> RXFIFO1_W {
RXFIFO1_W { w: self }
}
#[doc = "Bit 2 - SMSG"]
#[inline(always)]
pub fn smsg(&mut self) -> SMSG_W {
SMSG_W { w: self }
}
#[doc = "Bit 3 - TFERR"]
#[inline(always)]
pub fn tferr(&mut self) -> TFERR_W {
TFERR_W { w: self }
}
#[doc = "Bit 4 - MISC"]
#[inline(always)]
pub fn misc(&mut self) -> MISC_W {
MISC_W { w: self }
}
#[doc = "Bit 5 - BERR"]
#[inline(always)]
pub fn berr(&mut self) -> BERR_W {
BERR_W { w: self }
}
#[doc = "Bit 6 - PERR"]
#[inline(always)]
pub fn perr(&mut self) -> PERR_W {
PERR_W { w: self }
}
}
|
use std::collections::BTreeMap;
use std::string::ToString;
use std::default::Default;
use rustc_serialize::json::{Json,ToJson};
use parse::*;
use parse::Presence::*;
use record;
use record::{Record, PartialRecord};
make_record_type!(ContactGroup, PartialContactGroup, "ContactGroup",
name: String => "name",
contact_ids: Vec<String> => "contactIds"
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.