<commit_before>#[macro_use]
extern crate serenity;
extern crate rand;
extern crate typemap;
extern crate stalch;
extern crate seximal;

use std::io;
use stalch::{run_with_state, InOuter, State, Result as StalchResult};

use std::env;
use std::result::Result as StdResult;
use typemap::Key;

use rand::Rng;
use rand::thread_rng;

use serenity::prelude::*;
use serenity::model::*;
use serenity::Result;
use serenity::utils;

use serenity::framework::StandardFramework;

const PREFIX: &str = "f>";
const WESTMANN: UserId = UserId(229154015626264577);
const MEMES: ChannelId = ChannelId(306454829738491904);

command!(info(_ctx, msg, _args) {
    msg.channel_id.send_message(|cm| {
        cm.embed(|e| {
            e.title("lfalchbot")
             .colour(utils::Colour::blue())
             .description("(c) LFalch.com 2017")
             .footer(|f| f.text(serenity::constants::USER_AGENT))
        })
    }).unwrap();
});

command!(setgame(ctx, _msg, args) {
    ctx.set_game(Game::playing(&args.join(" ")));
});

command!(rpn(_ctx, msg, args) {
    match calculate(&*args) {
        Ok(r) => msg.reply(&format!("Result: {}", r)),
        Err(e) => msg.reply(&format!("Error: {:?}", e))
    }.unwrap();
});

command!(stalch(_ctx, msg, args) {
    match stalch_run(args.join(" ") + "\n") {
        Ok((r, s)) => {
            if r.is_empty() {
                msg.reply(&format!("Stack:\n```\n{}\n```", s))
            } else {
                msg.reply(&format!("Output:\n```\n{}\n```", r))
            }
        }
        Err(e) => msg.reply(&format!("Error: {:?}", e))
    }.unwrap();
});

command!(seximal(_ctx, msg, args) {
    let s = args.join("");
    match seximal::to_seximal_words(&s) {
        Ok(ref s) => msg.reply(s),
        Err(_) => msg.reply("Malformed number")
    }.unwrap();
});

const CSGO_MSGS: [&str; 6] = [
    "Vi varmer op med en comp!",
    "Jeg er på!",
    "Jeg er mere til Call of Duty ..",
    "Сука блядь!",
    "-skyder en bot for at få dens Bizon-",
    "Mongoskrald!"
];

const BEARTOOTH: [&str; 3] = [
    "I’m not useless! I’m just the king of excuses!",
    "One life and one decision! Make sure it ends with you still living!",
    "Lorteskat på T-shirts."
];

const RESPONSES: [&str; 4] = [
    "Undskyld, kan ikke snakke lige nu :(",
    "Hey, kan jeg ringe igen senere?",
    "Hva' så, din noob!? :P",
    "Ad, hvem er du?"
];

const REDALERT: [&str; 4] = [
    "Your base is under a salt!",
    "Det gamle lortespil?",
    "Jeg er mere til CSGO.",
    "\"Mine depleted\" ..."
];

struct BotUser;

impl Key for BotUser {
    type Value = String;
}

struct Handler;

fn main() {
    let token = env::var("DISCORD_TOKEN")
        .expect("Expected a token in the environment");
    let mut client = Client::new(&token, Handler);

    client.with_framework(StandardFramework::new()
        .configure(|c| c.prefix(PREFIX))
        .command("ping", |c| c.exec_str("Pong!"))
        .on("info", info)
        .on("setgame", setgame)
        .on("rpn", rpn)
        .on("stalch", stalch)
        .on("seximal", seximal)
    );

    {
        let mut data = client.data.lock();
        data.insert::<BotUser>(String::default());
    }

    if let Err(why) = client.start() {
        println!("Client error: {:?}", why);
    }
}

macro_rules! joke {
    ($s:expr; $($trigger:expr),+; $bl:block) => (
        if $($s.contains($trigger))||* $bl
    );
    ($s:expr, $channel_id:expr; $($trigger:expr),+;; $joke:expr) => (
        joke!($s; $($trigger),*; {
            $channel_id.say($joke).unwrap();
        })
    );
    ($s:expr, $channel_id:expr; $($trigger:expr),+; $jokes:expr) => (
        joke!($s; $($trigger),*; {
            send_random($channel_id, &$jokes).unwrap();
        })
    );
}

impl EventHandler for Handler {
    fn on_ready(&self, ctx: Context, ready: Ready) {
        println!("{} is connected!", ready.user.name);
        println!("Guilds:");
        for name in ready.guilds.iter().map(|g| g.id().get().unwrap().name) {
            println!("    {}", name);
        }
        {
            let mut data = ctx.data.lock();
            *data.get_mut::<BotUser>().unwrap() = ready.user.tag();
        }
    }

    fn on_message(&self, ctx: Context, msg: Message) {
        if msg.author.bot {
            return
        }
        if msg.channel_id == MEMES && msg.author.id == WESTMANN && msg.embeds.iter().any(|a| a.image.is_some()) {
            msg.channel_id.say("Den er gammel!");
        }
        let s: String = msg.content.chars()
        .filter(|c| c.is_alphanumeric())
        .flat_map(|c|c.to_lowercase())
        .collect();

        joke!(s, msg.channel_id; "css", "source";; "Hvor er mine skins!?");
        joke!(s, msg.channel_id; "csgo", "counterstrike", "globaloffensive"; CSGO_MSGS);
        joke!(s, msg.channel_id; "mc", "minecraft";; "MINECRAFT!");
        joke!(s, msg.channel_id; "beartooth"; BEARTOOTH);
        joke!(s, msg.channel_id; "rep";; "Rep mig!");
        joke!(s, msg.channel_id; "ftl";; "Zoltan shield OP");
        joke!(s, msg.channel_id; "bindingofisaac";; "Mom OP");
        joke!(s, msg.channel_id; "meme";; "krydrede migmig'er");
        joke!(s, msg.channel_id; "gunsoficarus";; "Spillere online: 85");
        joke!(s, msg.channel_id; "doom";; "Rip and tear!");
        joke!(s, msg.channel_id; "dyinglight";; "Det dér Left 4 Dead-spil?");
        joke!(s, msg.channel_id; "report";; "ReviewBrah");
        joke!(s; "english"; {
            msg.channel_id.send_message(|cm| {
                cm.embed(|e| {
                    e.image("http://dev.lfalch.com/english.jpg")
                })
            }).unwrap();
        });
        joke!(s, msg.channel_id; "warthunder", "wt", "thunder", "tankspil";; "Jeg hader World of Tanks!");
        joke!(s, msg.channel_id; "ra3", "redalert"; REDALERT);
        joke!(s, msg.channel_id; "rusland", "russia", "росси", "russisk",
        "russian", "русск", "russer";; "Communism is the ultimate goal of socialism.");

        let user = {
            ctx.data.lock().get::<BotUser>().unwrap().clone()
        };
        if msg.mentions.iter().map(|u| u.tag()).any(|u| u == user) {
            send_random(msg.channel_id, &RESPONSES).unwrap();
        }
    }
}

fn send_random(chl: ChannelId, list: &[&str]) -> Result<Message> {
    let i = thread_rng().gen_range(0, list.len());
    chl.say(list[i])
}

#[derive(Debug, Copy, Clone)]
pub enum RpnError<'a> {
    StackTooSmall,
    UnknownOperator(&'a str)
}

use RpnError::*;

pub fn calculate<'a, T: IntoIterator<Item=&'a String>>(operations: T) -> StdResult<f64, RpnError<'a>> {
    let mut stack = Vec::new();

    for operation in operations {
        if let Some(d) = operation.parse::<f64>().ok() {
            stack.push(d)
        }else{
            calc(operation, &mut stack)?
        }
    }

    stack.pop().ok_or(StackTooSmall)
}

fn calc<'a>(op: &'a str, stack: &mut Vec<f64>) -> StdResult<(), RpnError<'a>>{
    let res = match (stack.pop(), stack.pop()){
        (Some(op1), Some(op2)) => match op{
            "+"|"add" => op2 + op1,
            "-"|"sub" => op2 - op1,
            "/"|"div" => op2 / op1,
            "*"|"mul" => op2 * op1,
            "^"|"pow" => op2.powf(op1),
            "log" => op2.log(op1),
            "hypot" => op2.hypot(op1),
            "%"|"rem" => op2 % op1,
            "|"|"or" => (op2 as i64 | op1 as i64) as f64,
            "&"|"and" => (op2 as i64 & op1 as i64) as f64,
            "xor" => (op2  as i64 ^ op1 as i64) as f64,
            _ => return Err(UnknownOperator(op))
        },
        _ => return Err(StackTooSmall)
    };
    Ok(stack.push(res))
}

fn stalch_run<'a>(s: String) -> StalchResult<(String, String)> {
    let mut state = State::new();
    let mut io = InOuter::new(Vec::new(), io::repeat(b'\n'));

    run_with_state(s.as_bytes(), &mut state, &mut io)?;

    let (output, _) = io.extract();

    let s = String::from_utf8(output).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

    Ok((s, format!("{:?}", state.stack())))
}
<commit_msg>Do some debugging<commit_after>#[macro_use]
extern crate serenity;
extern crate rand;
extern crate typemap;
extern crate stalch;
extern crate seximal;

use std::io;
use stalch::{run_with_state, InOuter, State, Result as StalchResult};

use std::env;
use std::result::Result as StdResult;
use typemap::Key;

use rand::Rng;
use rand::thread_rng;

use serenity::prelude::*;
use serenity::model::*;
use serenity::Result;
use serenity::utils;

use serenity::framework::StandardFramework;

const PREFIX: &str = "f>";
const WESTMANN: UserId = UserId(229154015626264577);
const MEMES: ChannelId = ChannelId(306454829738491904);

command!(info(_ctx, msg, _args) {
    msg.channel_id.send_message(|cm| {
        cm.embed(|e| {
            e.title("lfalchbot")
             .colour(utils::Colour::blue())
             .description("(c) LFalch.com 2017")
             .footer(|f| f.text(serenity::constants::USER_AGENT))
        })
    }).unwrap();
});

command!(setgame(ctx, _msg, args) {
    ctx.set_game(Game::playing(&args.join(" ")));
});

command!(rpn(_ctx, msg, args) {
    match calculate(&*args) {
        Ok(r) => msg.reply(&format!("Result: {}", r)),
        Err(e) => msg.reply(&format!("Error: {:?}", e))
    }.unwrap();
});

command!(stalch(_ctx, msg, args) {
    match stalch_run(args.join(" ") + "\n") {
        Ok((r, s)) => {
            if r.is_empty() {
                msg.reply(&format!("Stack:\n```\n{}\n```", s))
            } else {
                msg.reply(&format!("Output:\n```\n{}\n```", r))
            }
        }
        Err(e) => msg.reply(&format!("Error: {:?}", e))
    }.unwrap();
});

command!(seximal(_ctx, msg, args) {
    let s = args.join("");
    match seximal::to_seximal_words(&s) {
        Ok(ref s) => msg.reply(s),
        Err(_) => msg.reply("Malformed number")
    }.unwrap();
});

const CSGO_MSGS: [&str; 6] = [
    "Vi varmer op med en comp!",
    "Jeg er på!",
    "Jeg er mere til Call of Duty ..",
    "Сука блядь!",
    "-skyder en bot for at få dens Bizon-",
    "Mongoskrald!"
];

const BEARTOOTH: [&str; 3] = [
    "I’m not useless! I’m just the king of excuses!",
    "One life and one decision! Make sure it ends with you still living!",
    "Lorteskat på T-shirts."
];

const RESPONSES: [&str; 4] = [
    "Undskyld, kan ikke snakke lige nu :(",
    "Hey, kan jeg ringe igen senere?",
    "Hva' så, din noob!? :P",
    "Ad, hvem er du?"
];

const REDALERT: [&str; 4] = [
    "Your base is under a salt!",
    "Det gamle lortespil?",
    "Jeg er mere til CSGO.",
    "\"Mine depleted\" ..."
];

struct BotUser;

impl Key for BotUser {
    type Value = String;
}

struct Handler;

fn main() {
    println!("{} in {}", WESTMANN, MEMES);

    let token = env::var("DISCORD_TOKEN")
        .expect("Expected a token in the environment");
    let mut client = Client::new(&token, Handler);

    client.with_framework(StandardFramework::new()
        .configure(|c| c.prefix(PREFIX))
        .command("ping", |c| c.exec_str("Pong!"))
        .on("info", info)
        .on("setgame", setgame)
        .on("rpn", rpn)
        .on("stalch", stalch)
        .on("seximal", seximal)
    );

    {
        let mut data = client.data.lock();
        data.insert::<BotUser>(String::default());
    }

    if let Err(why) = client.start() {
        println!("Client error: {:?}", why);
    }
}

macro_rules! joke {
    ($s:expr; $($trigger:expr),+; $bl:block) => (
        if $($s.contains($trigger))||* $bl
    );
    ($s:expr, $channel_id:expr; $($trigger:expr),+;; $joke:expr) => (
        joke!($s; $($trigger),*; {
            $channel_id.say($joke).unwrap();
        })
    );
    ($s:expr, $channel_id:expr; $($trigger:expr),+; $jokes:expr) => (
        joke!($s; $($trigger),*; {
            send_random($channel_id, &$jokes).unwrap();
        })
    );
}

impl EventHandler for Handler {
    fn on_ready(&self, ctx: Context, ready: Ready) {
        println!("{} is connected!", ready.user.name);
        println!("Guilds:");
        for name in ready.guilds.iter().map(|g| g.id().get().unwrap().name) {
            println!("    {}", name);
        }
        {
            let mut data = ctx.data.lock();
            *data.get_mut::<BotUser>().unwrap() = ready.user.tag();
        }
    }

    fn on_message(&self, ctx: Context, msg: Message) {
        if msg.author.bot {
            return
        }
        eprintln!("{} in {}: image: {}", msg.channel_id.0, msg.author.id.0, msg.embeds.iter().any(|a| a.image.is_some()));
        if msg.channel_id == MEMES && msg.author.id == WESTMANN && msg.embeds.iter().any(|a| a.image.is_some()) {
            msg.channel_id.say("Den er gammel!");
        }
        let s: String = msg.content.chars()
        .filter(|c| c.is_alphanumeric())
        .flat_map(|c|c.to_lowercase())
        .collect();

        joke!(s, msg.channel_id; "css", "source";; "Hvor er mine skins!?");
        joke!(s, msg.channel_id; "csgo", "counterstrike", "globaloffensive"; CSGO_MSGS);
        joke!(s, msg.channel_id; "mc", "minecraft";; "MINECRAFT!");
        joke!(s, msg.channel_id; "beartooth"; BEARTOOTH);
        joke!(s, msg.channel_id; "rep";; "Rep mig!");
        joke!(s, msg.channel_id; "ftl";; "Zoltan shield OP");
        joke!(s, msg.channel_id; "bindingofisaac";; "Mom OP");
        joke!(s, msg.channel_id; "meme";; "krydrede migmig'er");
        joke!(s, msg.channel_id; "gunsoficarus";; "Spillere online: 85");
        joke!(s, msg.channel_id; "doom";; "Rip and tear!");
        joke!(s, msg.channel_id; "dyinglight";; "Det dér Left 4 Dead-spil?");
        joke!(s, msg.channel_id; "report";; "ReviewBrah");
        joke!(s; "english"; {
            msg.channel_id.send_message(|cm| {
                cm.embed(|e| {
                    e.image("http://dev.lfalch.com/english.jpg")
                })
            }).unwrap();
        });
        joke!(s, msg.channel_id; "warthunder", "wt", "thunder", "tankspil";; "Jeg hader World of Tanks!");
        joke!(s, msg.channel_id; "ra3", "redalert"; REDALERT);
        joke!(s, msg.channel_id; "rusland", "russia", "росси", "russisk",
        "russian", "русск", "russer";; "Communism is the ultimate goal of socialism.");

        let user = {
            ctx.data.lock().get::<BotUser>().unwrap().clone()
        };
        if msg.mentions.iter().map(|u| u.tag()).any(|u| u == user) {
            send_random(msg.channel_id, &RESPONSES).unwrap();
        }
    }
}

fn send_random(chl: ChannelId, list: &[&str]) -> Result<Message> {
    let i = thread_rng().gen_range(0, list.len());
    chl.say(list[i])
}

#[derive(Debug, Copy, Clone)]
pub enum RpnError<'a> {
    StackTooSmall,
    UnknownOperator(&'a str)
}

use RpnError::*;

pub fn calculate<'a, T: IntoIterator<Item=&'a String>>(operations: T) -> StdResult<f64, RpnError<'a>> {
    let mut stack = Vec::new();

    for operation in operations {
        if let Some(d) = operation.parse::<f64>().ok() {
            stack.push(d)
        }else{
            calc(operation, &mut stack)?
        }
    }

    stack.pop().ok_or(StackTooSmall)
}

fn calc<'a>(op: &'a str, stack: &mut Vec<f64>) -> StdResult<(), RpnError<'a>>{
    let res = match (stack.pop(), stack.pop()){
        (Some(op1), Some(op2)) => match op{
            "+"|"add" => op2 + op1,
            "-"|"sub" => op2 - op1,
            "/"|"div" => op2 / op1,
            "*"|"mul" => op2 * op1,
            "^"|"pow" => op2.powf(op1),
            "log" => op2.log(op1),
            "hypot" => op2.hypot(op1),
            "%"|"rem" => op2 % op1,
            "|"|"or" => (op2 as i64 | op1 as i64) as f64,
            "&"|"and" => (op2 as i64 & op1 as i64) as f64,
            "xor" => (op2  as i64 ^ op1 as i64) as f64,
            _ => return Err(UnknownOperator(op))
        },
        _ => return Err(StackTooSmall)
    };
    Ok(stack.push(res))
}

fn stalch_run<'a>(s: String) -> StalchResult<(String, String)> {
    let mut state = State::new();
    let mut io = InOuter::new(Vec::new(), io::repeat(b'\n'));

    run_with_state(s.as_bytes(), &mut state, &mut io)?;

    let (output, _) = io.extract();

    let s = String::from_utf8(output).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

    Ok((s, format!("{:?}", state.stack())))
}
<|endoftext|>


<commit_before>use std::io::prelude::*;
use std::io::Error;
use std::fs::File;
use parser::parse;
use std::time::Instant;
use docopt::Docopt;
use std::process;

pub mod lexicon;
pub mod tokenizer;
pub mod parser;
pub mod grammar;
pub mod transformer;
extern crate docopt;
extern crate rustc_serialize;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const USAGE: &'static str = "
honeybadger

Usage:
  badger [options]
  badger --version

Options:
  -h --help              Show this screen.
  --version              Show version.
  -f FILE, --file=FILE   Specifies the input file
";

fn read_file(path: &str) -> Result<String, Error> {
    let mut f = try!(File::open(path));
    let mut s = String::new();
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(err) => Err(err)
    }
}

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_file: String,
    flag_version: bool
}

fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.decode())
        .unwrap_or_else(|e| e.exit());

    if args.flag_version {
        println!("v{}", VERSION);
        process::exit(0);
    }

    let file = match read_file(&args.flag_file) {
        Ok(file) => file,
        Err(err) => {
            println!("ERR Couldn't read file: {:?}", err);
            process::exit(1)
        }
    };

    let ast = parser::parse(file);

    let transformed_ast = transformer::traverse(ast);
    println!("{:?}", transformed_ast);
}
<commit_msg>Write output code into new file<commit_after>use std::io::prelude::*;
use std::io::Error;
use std::fs::File;
use parser::parse;
use std::time::Instant;
use docopt::Docopt;
use std::process;

pub mod lexicon;
pub mod tokenizer;
pub mod parser;
pub mod grammar;
pub mod transformer;
pub mod codegen;
extern crate docopt;
extern crate rustc_serialize;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const USAGE: &'static str = "
honeybadger

Usage:
  badger [options]
  badger --version

Options:
  -h --help              Show this screen.
  --version              Show version.
  -f FILE, --file=FILE   Specifies the input file
";

fn read_file(path: &str) -> Result<String, Error> {
    let mut f = try!(File::open(path));
    let mut s = String::new();
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(err) => Err(err)
    }
}

fn write_file(filename: &str, program: String) -> Result<(), Error> {
    let mut f = try!(File::create(filename));
    match f.write_all(&program.into_bytes()[..]) {
        Ok(_) => Ok(()),
        Err(err) => Err(err)
    }
}

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_file: String,
    flag_version: bool
}

fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.decode())
        .unwrap_or_else(|e| e.exit());

    if args.flag_version {
        println!("v{}", VERSION);
        process::exit(0);
    }

    let file = match read_file(&args.flag_file) {
        Ok(file) => file,
        Err(err) => {
            println!("ERR Couldn't read file: {:?}", err);
            process::exit(1)
        }
    };

    let ast = parser::parse(file);

    let transformed_ast = transformer::traverse(ast);
    let program = match codegen::generate_code(transformed_ast) {
        Ok(program) => program,
        Err(errs) => {
            for err in errs {
                println!("ERR {}", err);
            }
            process::exit(1);
        }
    };

    match write_file("out.js", program) {
        Ok(()) => {},
        Err(err) => {
            println!("ERR Writing out.js {}", err);
            process::exit(1);
        }
    }
}
<|endoftext|>


<commit_before>extern crate docopt;
extern crate image;
extern crate serde_json;
extern crate vegas_lattice;

use std::error::Error;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;

use docopt::{ArgvMap, Docopt};
use vegas_lattice::{Axis, Lattice, Mask};

const USAGE: &'static str = "
Vegas lattice.

Usage:
    vegas-lattice check [<input>]
    vegas-lattice compress [<input>]
    vegas-lattice drop [-x -y -z] [<input>]
    vegas-lattice expand [--x=<x> --y=<y> --z=<z>] [<input>]
    vegas-lattice mask [--ppu=<ppu>] <mask> [<input>]
    vegas-lattice into xyz [<input>]
    vegas-lattice (-h | --help)
    vegas-lattice --version

Options:
    --ppu=<ppu>     Pixels per unit [default: 10].
    -h --help       Show this message.
    --version       Show version and exit.
";

fn read(input: &str) -> Result<Lattice, Box<Error>> {
    let mut data = String::new();
    if !input.is_empty() {
        let mut file = File::open(input)?;
        file.read_to_string(&mut data)?;
    } else {
        io::stdin().read_to_string(&mut data)?;
    };
    let lattice: Lattice = data.parse()?;
    Ok(lattice)
}

fn write_compressed(lattice: Lattice) {
    println!("{}", serde_json::to_string(&lattice).unwrap());
}

fn write(lattice: Lattice) {
    println!("{}", serde_json::to_string_pretty(&lattice).unwrap());
}

fn check_error(res: Result<(), Box<Error>>) {
    match res {
        Err(e) => {
            eprintln!("Error: {}", e.description());
            match e.cause() {
                Some(cause) => eprintln!("Cause: {}", cause),
                _ => ()
            };
            std::process::exit(1);
        },
        _ => {},
    }
}

// Commands over here

fn check(args: ArgvMap) -> Result<(), Box<Error>> {
    let lattice = read(args.get_str("<input>"))?;
    write(lattice);
    Ok(())
}

fn compress(args: ArgvMap) -> Result<(), Box<Error>> {
    let lattice = read(args.get_str("<input>"))?;
    write_compressed(lattice);
    Ok(())
}

fn drop(args: ArgvMap) -> Result<(), Box<Error>> {
    let mut lattice = read(args.get_str("<input>"))?;
    for (key, axis) in Axis::map(Some("-".to_string())) {
        if args.get_bool(&key) {
            lattice = lattice.drop(axis);
        }
    }
    write(lattice);
    Ok(())
}

fn expand(args: ArgvMap) -> Result<(), Box<Error>> {
    let map = Axis::map(Some("--".to_string()));
    let mut lattice = read(args.get_str("<input>"))?;
    for (flag, axis) in map.into_iter() {
        let string_value = args.get_str(&flag);
        if !string_value.is_empty() {
            let size: usize = string_value.parse()?;
            lattice = lattice.expand_along(axis, size);
        }
    }
    write(lattice);
    Ok(())
}

fn mask(args: ArgvMap) -> Result<(), Box<Error>> {
    let path = args.get_str("<mask>");
    let ppu: f64 = args.get_str("--ppu").parse()?;
    let mask = Mask::new(&Path::new(path), ppu)?;
    let mut lattice = read(args.get_str("<input>"))?;
    lattice = lattice.apply_mask(mask);
    write(lattice);
    Ok(())
}

fn into(args: ArgvMap) -> Result<(), Box<Error>> {
    if args.get_bool("xyz") {
        let lattice = read(args.get_str("<input>"))?;
        for site in lattice.sites().iter() {
            let (x, y, z) = site.position;
            println!("{} {} {} {}", x, y, z, site.kind)
        }
    }
    Ok(())
}

fn main() {
    let args = Docopt::new(USAGE)
        .and_then(|doc| doc.version(Some("0.0.1".to_string())).parse())
        .unwrap_or_else(|e| e.exit());

    if args.get_bool("check") {
        check_error(check(args));
    } else if args.get_bool("compress") {
        check_error(compress(args));
    } else if args.get_bool("drop") {
        check_error(drop(args));
    } else if args.get_bool("expand") {
        check_error(expand(args));
    } else if args.get_bool("mask") {
        check_error(mask(args));
    } else if args.get_bool("into") {
        check_error(into(args));
    } else {
        println!("{:?}", args);
    }
}<commit_msg>Revert "Chean up docopt"<commit_after>extern crate docopt;
extern crate image;
extern crate serde_json;
extern crate vegas_lattice;

use std::error::Error;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;

use docopt::{ArgvMap, Docopt};
use vegas_lattice::{Axis, Lattice, Mask};

const USAGE: &'static str = "
Vegas lattice.

Usage:
    vegas-lattice check [<input>]
    vegas-lattice compress [<input>]
    vegas-lattice drop [-x -y -z] [<input>]
    vegas-lattice expand [--x=<x> --y=<y> --z=<z>] [<input>]
    vegas-lattice mask [--ppu=<ppu>] <mask> [<input>]
    vegas-lattice into xyz [<input>]
    vegas-lattice (-h | --help)
    vegas-lattice --version

Options:
    -p=<ppu> --ppu=<ppu>        Pixels per unit [default: 10].
    -h --help       Show this message.
    --version       Show version and exit.
";

fn read(input: &str) -> Result<Lattice, Box<Error>> {
    let mut data = String::new();
    if !input.is_empty() {
        let mut file = File::open(input)?;
        file.read_to_string(&mut data)?;
    } else {
        io::stdin().read_to_string(&mut data)?;
    };
    let lattice: Lattice = data.parse()?;
    Ok(lattice)
}

fn write_compressed(lattice: Lattice) {
    println!("{}", serde_json::to_string(&lattice).unwrap());
}

fn write(lattice: Lattice) {
    println!("{}", serde_json::to_string_pretty(&lattice).unwrap());
}

fn check_error(res: Result<(), Box<Error>>) {
    match res {
        Err(e) => {
            eprintln!("Error: {}", e.description());
            match e.cause() {
                Some(cause) => eprintln!("Cause: {}", cause),
                _ => ()
            };
            std::process::exit(1);
        },
        _ => {},
    }
}

// Commands over here

fn check(args: ArgvMap) -> Result<(), Box<Error>> {
    let lattice = read(args.get_str("<input>"))?;
    write(lattice);
    Ok(())
}

fn compress(args: ArgvMap) -> Result<(), Box<Error>> {
    let lattice = read(args.get_str("<input>"))?;
    write_compressed(lattice);
    Ok(())
}

fn drop(args: ArgvMap) -> Result<(), Box<Error>> {
    let mut lattice = read(args.get_str("<input>"))?;
    for (key, axis) in Axis::map(Some("-".to_string())) {
        if args.get_bool(&key) {
            lattice = lattice.drop(axis);
        }
    }
    write(lattice);
    Ok(())
}

fn expand(args: ArgvMap) -> Result<(), Box<Error>> {
    let map = Axis::map(Some("--".to_string()));
    let mut lattice = read(args.get_str("<input>"))?;
    for (flag, axis) in map.into_iter() {
        let string_value = args.get_str(&flag);
        if !string_value.is_empty() {
            let size: usize = string_value.parse()?;
            lattice = lattice.expand_along(axis, size);
        }
    }
    write(lattice);
    Ok(())
}

fn mask(args: ArgvMap) -> Result<(), Box<Error>> {
    let path = args.get_str("<mask>");
    let ppu: f64 = args.get_str("--ppu").parse()?;
    let mask = Mask::new(&Path::new(path), ppu)?;
    let mut lattice = read(args.get_str("<input>"))?;
    lattice = lattice.apply_mask(mask);
    write(lattice);
    Ok(())
}

fn into(args: ArgvMap) -> Result<(), Box<Error>> {
    if args.get_bool("xyz") {
        let lattice = read(args.get_str("<input>"))?;
        for site in lattice.sites().iter() {
            let (x, y, z) = site.position;
            println!("{} {} {} {}", x, y, z, site.kind)
        }
    }
    Ok(())
}

fn main() {
    let args = Docopt::new(USAGE)
        .and_then(|doc| doc.version(Some("0.0.1".to_string())).parse())
        .unwrap_or_else(|e| e.exit());

    if args.get_bool("check") {
        check_error(check(args));
    } else if args.get_bool("compress") {
        check_error(compress(args));
    } else if args.get_bool("drop") {
        check_error(drop(args));
    } else if args.get_bool("expand") {
        check_error(expand(args));
    } else if args.get_bool("mask") {
        check_error(mask(args));
    } else if args.get_bool("into") {
        check_error(into(args));
    } else {
        println!("{:?}", args);
    }
}<|endoftext|>


<commit_before>use std::old_io;
use std::rand;

fn main() {
    let random = (rand::random::<u32>() % 10) + 1;
    println!("{}", random);
    println!("Hello, it's a guessing game!");
    println!("I'll draw a number between 1-10 and you need to guess which one.");
    println!("Only one shot!");

    let input = old_io::stdin().read_line().ok().expect("You need to pass nummber");

    // It seems, that we need to remove newline before parsing (bug?)
    let parsed_input: Result<u32, _> = input.trim_right_matches("\n").parse();

    let num = match parsed_input {
        Ok(num) => num,
        Err(_) => {
            println!("Please input number!");
            return;
        }
    };

    if random == num {
        println!("You won!");
    } else {
        println!("Looser!");
    }
}
<commit_msg>From book: use trim function<commit_after>use std::old_io;
use std::rand;

fn main() {
    let random = (rand::random::<u32>() % 10) + 1;
    println!("{}", random);
    println!("Hello, it's a guessing game!");
    println!("I'll draw a number between 1-10 and you need to guess which one.");
    println!("Only one shot!");

    let input = old_io::stdin().read_line().ok().expect("You need to pass nummber");

    // It seems, that we need to remove newline before parsing (bug?)
    let parsed_input: Result<u32, _> = input.trim().parse();

    let num = match parsed_input {
        Ok(num) => num,
        Err(_) => {
            println!("Please input number!");
            return;
        }
    };

    if random == num {
        println!("You won!");
    } else {
        println!("Looser!");
    }
}
<|endoftext|>


<commit_before>#![feature(path_ext)]
extern crate mysql;
extern crate ini;
extern crate toml;
#[macro_use]
extern crate lazy_static;

use mysql::conn::MyOpts;
use std::default::Default;
use mysql::conn::pool;
use mysql::value::from_value;

use ini::Ini;
use toml::Table;
use toml::Encoder;

use std::io::Write;

use std::env::current_dir;
use std::path::PathBuf;
use std::path::Path;
use std::fs::PathExt;
use std::fs::File;

use std::collections::HashMap;

static VERSION : &'static str = "0.1"; // String not valid

lazy_static! {
	static ref CONFIG: HashMap< &'static str, String> = {
		let mut m = HashMap::new();
		m.insert("user", "root".to_string());
		m.insert("password", "".to_string());
		m.insert("db", "testdb".to_string());
		m.insert("ip", "127.0.0.1".to_string());
		m //return
	};

}

fn main() {
    println!("Starting yayd-backend v{}",&VERSION);

    init_config();

    let options = mysql_options();
    let pool = pool::MyPool::new(options).unwrap();

	let toml = r#"
    [test]
    foo = "bar"
	"#;

	let value = toml::Parser::new(toml).parse().unwrap();
	println!("{:?}", value);
}

/// create PathBuf by getting the current working dir
/// set_file_name doesn't return smth -> needs to be run on mut path
fn init_config(){
    let mut path = current_dir().unwrap();
    path.set_file_name("config.cfg");
    // let  = path.as_path();
    println!("{:?}",path );
    //let conftbl: TomlTable = TomlTable(nul);
    if path.as_path().is_file() {
    	println!("Config file found.");
    }else{
    	println!("Config file not found.");
    	let mut file = File::create(path.to_str().unwrap()).unwrap();
    	create_config(&mut file);
    }
}

fn create_config(file: &mut File) {
	let toml = r#"[db]
	user = "root"
	password = ""
	db = "testdb"
	port = 3306
	ip = "127.0.0.1"
	"#;
	let value = toml::Parser::new(toml).parse().unwrap();
	println!("{:?}", value);
	match file.write_all(toml.as_bytes()) {
		Ok(_) => {},
		Err(err) => panic!("Error writing the config: {}",err),
	};
}

/// Set options for the connection
fn mysql_options() -> MyOpts {
    MyOpts {
    	tcp_addr: Some(CONFIG.get("ip").unwrap().clone()),
    	tcp_port: 3306,
    	//tcp_port: "3306"
    	user: Some(CONFIG.get("user").unwrap().clone()),
    	pass: Some(CONFIG.get("password").unwrap().clone()),
    	db_name: Some(CONFIG.get("db").unwrap().clone()),
    	..Default::default() // set other to default
    }
}<commit_msg>some changes, nothing finished<commit_after>#![feature(path_ext)]
extern crate mysql;
extern crate ini;
extern crate toml;
#[macro_use]
extern crate lazy_static;

use mysql::conn::MyOpts;
use std::default::Default;
use mysql::conn::pool;
use mysql::value::from_value;

use toml::Table;
use toml::Encoder;

use std::io::Write;

use std::env::current_dir;
use std::path::PathBuf;
use std::path::Path;
use std::fs::PathExt;
use std::fs::File;

use std::collections::HashMap;

static VERSION : &'static str = "0.1"; // String not valid

lazy_static! {
	// static ref CONFIG: Table = {
	// 	println!("Starting yayd-backend v{}",&VERSION);

	// 	init_config() //return
	// };

}

fn main() {
    init_config();
	// println!("\nValue: {:?}", CONFIG.get("db").unwrap());

    // let options = mysql_options();
    // let pool = pool::MyPool::new(options).unwrap();

}

/// create PathBuf by getting the current working dir
/// set_file_name doesn't return smth -> needs to be run on mut path
fn init_config() -> Result<Table,ConfigError> {
    let mut path = current_dir().unwrap();
    path.set_file_name("config.cfg");
    // let  = path.as_path();
    println!("{:?}",path );
    //let conftbl: TomlTable = TomlTable(nul);
    let mut config : Option<Table> = None;
    if path.as_path().is_file() {
    	println!("Config file found.");
    	let mut file = try!(File::open(path.to_str().unwrap()).map_err(|e| ConfigError::OpenError));
    	let config = read_config(&mut file);
    }else{
    	println!("Config file not found.");
    	let mut file = try!(File::create(path.to_str().unwrap()));
    	//config = Some();
    	let config = try!(create_config(&mut file));
    }
    config
}

//makes it printable..
use std::{io,error};
#[derive(Debug)]
enum ConfigError { ParseError,OpenError(io::Error),ReadError(io::Error),WriteError(io::Error),CreateError(io::Error),ErrTypeUnkown }

impl From<ConfigError> for ConfigError {
    fn from(err: ConfigError) -> ConfigError {
        ConfigError(err)
    }
}

///wrap io::Error, for example usage
impl From<io::Error> for ConfigError {
    fn from(err: io::Error) -> ConfigError {
        ConfigError::ErrTypeUnkown
    }
}

fn read_config<T>(file: &mut File) -> Result<Table,ConfigError> {
	let mut f = File::open("foo.txt").map_err(|e| {ConfigError::OpenError(e)});
	let mut toml = String::new();
	f.read_to_string(&mut toml).map_err(|e| {ConfigError::ReadError(e)});
	toml::Parser::new(toml).parse().map_err(|e| {ConfigError::ParseError(e)});
}

fn create_config<T>(file: &mut File) -> Result<Table,ConfigError> {
	//TODO: replace with import_string
	let toml = r#"[db]
user = "root"
password = ""
db = "testdb"
port = 3306
ip = "127.0.0.1"
	"#;
	let mut parser = toml::Parser::new(toml);
	let config: Table = parser.parse().unwrap();
	println!("{:?}", config);
	file.write_all(toml.as_bytes()).map_err(|e| {ConfigError::WriteError(e)});
	config
}

// Set options for the connection
// fn mysql_options() -> MyOpts {
//     MyOpts {
//     	tcp_addr: Some(CONFIG.get("ip").unwrap().clone()),
//     	tcp_port: 3306,
//     	//tcp_port: "3306"
//     	user: Some(CONFIG.get("user").unwrap().clone()),
//     	pass: Some(CONFIG.get("password").unwrap().clone()),
//     	db_name: Some(CONFIG.get("db").unwrap().clone()),
//     	..Default::default() // set other to default
//     }
// }<|endoftext|>


<commit_before>extern crate turtle;

use std::fmt;
use std::fs::File;
use turtle::{Canvas, Turtle};

#[derive(Debug, Eq, PartialEq, Clone)]
struct Character(char);

#[derive(Eq, PartialEq, Clone)]
struct Symbol {
    character: Character,
}

impl fmt::Debug for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.character.0)
    }
}

#[derive(Clone)]
struct SymbolString(Vec<Symbol>);

impl fmt::Debug for SymbolString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let v = &self.0;
        try!(write!(f, "\""));
        if !v.is_empty() {
            try!(write!(f, "{:?}", v[0]));
            for e in &v[1..] {
                try!(write!(f, " {:?}", e));
            }
        }
        write!(f, "\"")
    }
}

impl SymbolString {
    fn from_str(s: &str) -> SymbolString {
        SymbolString(s.chars().filter(|&c| !c.is_whitespace()).map(|c| Symbol{character: Character(c)}).collect())
    }
}

#[derive(Debug)]
struct Rule {
    lhs: Symbol,
    rhs: SymbolString,
}

impl Rule {
    fn produce(&self, sym: &Symbol) -> Option<SymbolString> {
        if self.lhs.eq(sym) {
            Some(self.rhs.clone())
        } else {
            None
        }
    }
}

#[derive(Debug)]
struct System {
    rules: Vec<Rule>,
}

impl System {
    fn develop(&self, axiom: SymbolString, iterations: usize) -> (SymbolString, usize) {
        let mut current = axiom;

        for iter in 0..iterations {
            let (next, progress) = self.develop1(&current);
            if !progress {
                return (current, iter);
            }
            current = next;
        }
        return (current, iterations);
    }

    fn develop1(&self, axiom: &SymbolString) -> (SymbolString, bool) {
        let mut expanded = Vec::new();
        let mut any_rule_applied = false;

        for symbol in axiom.0.iter() {
            let mut found = false;
            for rule in self.rules.iter() {
                if let Some(rhs) = rule.produce(&symbol) {
                    expanded.extend(rhs.0);
                    any_rule_applied = true;
                    found = true;
                    break;
                }
            }
            if !found {
                expanded.push(symbol.clone());
            }
        }

        (SymbolString(expanded), any_rule_applied)
    }
}
fn sym(c: char) -> Symbol {
    Symbol { character: Character(c) }
}

fn draw(symstr: &SymbolString, init_direction: f32, angle: f32, distance: f32, filename: &str) {
    let mut t = Canvas::new();
    t.right(init_direction);
    for sym in symstr.0.iter() {
        match sym.character.0 {
            'F' => t.forward(distance),
            '+' => t.right(angle),
            '-' => t.left(angle),
            '[' => t.push(),
            ']' => t.pop(),
            _   => {}
        }
    }
    t.save_svg(&mut File::create(filename).unwrap()).unwrap();
}

fn koch_curve(maxiter: usize) {
    let axiom = SymbolString::from_str("F++F++F");

    let system = System { rules: vec![
        Rule {
            lhs: sym('F'),
            rhs: SymbolString::from_str("F-F++F-F")
        }
        ] };
    println!("{:?}", system);

    let (after, iters) = system.develop(axiom, maxiter);

    draw(&after, -90.0, 60.0, 10.0, &format!("koch_{:02}.svg", iters));
}

fn dragon_curve(maxiter: usize) {
    let axiom = SymbolString::from_str("FX");

    let system = System { rules: vec![
        Rule {
            lhs: sym('X'),
            rhs: SymbolString::from_str("X+YF+")
        },
        Rule {
            lhs: sym('Y'),
            rhs: SymbolString::from_str("-FX-Y")
        }
        ] };
    println!("{:?}", system);

    let (after, iters) = system.develop(axiom, maxiter);

    draw(&after, 0.0, 90.0, 10.0, &format!("dragon_{:02}.svg", iters));
}

fn sierpinski_triangle(maxiter: usize) {
    let axiom = SymbolString::from_str("A");

    let system = System { rules: vec![
        Rule {
            lhs: sym('A'),
            rhs: SymbolString::from_str("+B-A-B+")
        },
        Rule {
            lhs: sym('B'),
            rhs: SymbolString::from_str("-A+B+A-")
        }
        ] };
    println!("{:?}", system);

    let (after, iters) = system.develop(axiom, maxiter);

    // replace A and B with F
    let system = System { rules: vec![
        Rule {
            lhs: sym('A'),
            rhs: SymbolString::from_str("F")
        },
        Rule {
            lhs: sym('B'),
            rhs: SymbolString::from_str("F")
        }
        ] };
    let (after, _iters) = system.develop1(&after);

    draw(&after, -90.0, 60.0, 10.0, &format!("sierpinski_{:02}.svg", iters));
}

fn fractal_plant(maxiter: usize) {
    let axiom = SymbolString::from_str("X");

    let system = System { rules: vec![
        Rule {
            lhs: sym('X'),
            rhs: SymbolString::from_str("F-[[X]+X]+F[+FX]-X")
        },
        Rule {
            lhs: sym('F'),
            rhs: SymbolString::from_str("FF")
        }
        ] };
    println!("{:?}", system);

    let (after, iters) = system.develop(axiom, maxiter);

    draw(&after, 0.0, 25.0, 10.0, &format!("plant_{:02}.svg", iters));
}

fn main() {
    for i in 0..7 {
        koch_curve(i);
    }
    for i in 0..16 {
        dragon_curve(i);
    }
    for i in 0..10 {
        sierpinski_triangle(i);
    }
    for i in 4..8 {
        fractal_plant(i);
    }
}
<commit_msg>Start implement parameterized L-systems<commit_after>extern crate turtle;

use std::fmt;
use std::fs::File;
use turtle::{Canvas, Turtle};

#[derive(Debug, Eq, PartialEq, Clone)]
struct Character(char);

#[derive(Eq, PartialEq, Clone)]
struct Symbol {
    character: Character,
}

struct Parameters;

impl Symbol {
    fn matches(&self, other: &Symbol) -> Option<Parameters> {
        if self.character == other.character {
            Some(Parameters)
        }
        else {
            None
        }
    }
}

impl fmt::Debug for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.character.0)
    }
}

#[derive(Clone)]
struct SymbolString(Vec<Symbol>);

impl fmt::Debug for SymbolString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let v = &self.0;
        try!(write!(f, "\""));
        if !v.is_empty() {
            try!(write!(f, "{:?}", v[0]));
            for e in &v[1..] {
                try!(write!(f, " {:?}", e));
            }
        }
        write!(f, "\"")
    }
}

impl SymbolString {
    fn from_str(s: &str) -> SymbolString {
        SymbolString(s.chars().filter(|&c| !c.is_whitespace()).map(|c| Symbol{character: Character(c)}).collect())
    }

    // XXX: Evaluate Parameters
    fn evaluate(&self, _parameters: Parameters) -> SymbolString {
        self.clone()
    }
}

#[derive(Debug)]
struct Rule {
    lhs: Symbol,
    rhs: SymbolString,
}

impl Rule {
    fn produce(&self, sym: &Symbol) -> Option<SymbolString> {
        self.lhs.matches(sym).map(|parameters| self.rhs.evaluate(parameters))
    }
}

#[derive(Debug)]
struct System {
    rules: Vec<Rule>,
}

impl System {
    fn develop(&self, axiom: SymbolString, iterations: usize) -> (SymbolString, usize) {
        let mut current = axiom;

        for iter in 0..iterations {
            let (next, progress) = self.develop1(&current);
            if !progress {
                return (current, iter);
            }
            current = next;
        }
        return (current, iterations);
    }

    fn develop1(&self, axiom: &SymbolString) -> (SymbolString, bool) {
        let mut expanded = Vec::new();
        let mut any_rule_applied = false;

        for symbol in axiom.0.iter() {
            let mut found = false;
            for rule in self.rules.iter() {
                if let Some(rhs) = rule.produce(&symbol) {
                    expanded.extend(rhs.0);
                    any_rule_applied = true;
                    found = true;
                    break;
                }
            }
            if !found {
                expanded.push(symbol.clone());
            }
        }

        (SymbolString(expanded), any_rule_applied)
    }
}
fn sym(c: char) -> Symbol {
    Symbol { character: Character(c) }
}

fn draw(symstr: &SymbolString, init_direction: f32, angle: f32, distance: f32, filename: &str) {
    let mut t = Canvas::new();
    t.right(init_direction);
    for sym in symstr.0.iter() {
        match sym.character.0 {
            'F' => t.forward(distance),
            '+' => t.right(angle),
            '-' => t.left(angle),
            '[' => t.push(),
            ']' => t.pop(),
            _   => {}
        }
    }
    t.save_svg(&mut File::create(filename).unwrap()).unwrap();
}

fn koch_curve(maxiter: usize) {
    let axiom = SymbolString::from_str("F++F++F");

    let system = System { rules: vec![
        Rule {
            lhs: sym('F'),
            rhs: SymbolString::from_str("F-F++F-F")
        }
        ] };
    println!("{:?}", system);

    let (after, iters) = system.develop(axiom, maxiter);

    draw(&after, -90.0, 60.0, 10.0, &format!("koch_{:02}.svg", iters));
}

fn dragon_curve(maxiter: usize) {
    let axiom = SymbolString::from_str("FX");

    let system = System { rules: vec![
        Rule {
            lhs: sym('X'),
            rhs: SymbolString::from_str("X+YF+")
        },
        Rule {
            lhs: sym('Y'),
            rhs: SymbolString::from_str("-FX-Y")
        }
        ] };
    println!("{:?}", system);

    let (after, iters) = system.develop(axiom, maxiter);

    draw(&after, 0.0, 90.0, 10.0, &format!("dragon_{:02}.svg", iters));
}

fn sierpinski_triangle(maxiter: usize) {
    let axiom = SymbolString::from_str("A");

    let system = System { rules: vec![
        Rule {
            lhs: sym('A'),
            rhs: SymbolString::from_str("+B-A-B+")
        },
        Rule {
            lhs: sym('B'),
            rhs: SymbolString::from_str("-A+B+A-")
        }
        ] };
    println!("{:?}", system);

    let (after, iters) = system.develop(axiom, maxiter);

    // replace A and B with F
    let system = System { rules: vec![
        Rule {
            lhs: sym('A'),
            rhs: SymbolString::from_str("F")
        },
        Rule {
            lhs: sym('B'),
            rhs: SymbolString::from_str("F")
        }
        ] };
    let (after, _iters) = system.develop1(&after);

    draw(&after, -90.0, 60.0, 10.0, &format!("sierpinski_{:02}.svg", iters));
}

fn fractal_plant(maxiter: usize) {
    let axiom = SymbolString::from_str("X");

    let system = System { rules: vec![
        Rule {
            lhs: sym('X'),
            rhs: SymbolString::from_str("F-[[X]+X]+F[+FX]-X")
        },
        Rule {
            lhs: sym('F'),
            rhs: SymbolString::from_str("FF")
        }
        ] };
    println!("{:?}", system);

    let (after, iters) = system.develop(axiom, maxiter);

    draw(&after, 0.0, 25.0, 10.0, &format!("plant_{:02}.svg", iters));
}

fn main() {
    for i in 0..7 {
        koch_curve(i);
    }
    for i in 0..16 {
        dragon_curve(i);
    }
    for i in 0..10 {
        sierpinski_triangle(i);
    }
    for i in 4..8 {
        fractal_plant(i);
    }
}
<|endoftext|>


<commit_before>#![feature(globs)]
extern crate libc;

use xlib::{XOpenDisplay, XDisplayName, XQueryExtension, XInitExtension, XSynchronize, XKeysymToString, XKeycodeToKeysym};
use libc::{c_int};
use std::ptr;
use xtst::{XRecordCreateContext, XRecordAllClients, XRecordAllocRange, XRecordRange, XRecordQueryVersion, XRecordEnableContext, XRecordEnableContextAsync,XRecordInterceptData, XRecordProcessReplies, XRecordFreeData};
use std::mem;
use std::c_str::CString;
use std::c_vec;
use std::time::Duration;
use std::io::Timer;
mod xtst;
mod xlib;
mod xlibint;
mod xutil;

struct XRecordDatum {
  xtype: ::libc::c_uchar,
  event: ::xlib::XEvent,
  req:   ::xlibint::xResourceReq,
  reply: ::xlibint::xGenericReply,
  error: ::xlibint::xError,
  setup: ::xlibint::xConnSetupPrefix,
}

static mut display_control: Display<'static> = Display {display: 0 as *mut xlib::Display};
static mut display_data: Display<'static> = Display {display: 0 as *mut xlib::Display};
static mut event_count:u32 = 0;
fn main() {
	unsafe {
		let mut a:  i8 = 0;
		display_control = Display::new();
		display_data = Display::new();

		XSynchronize(display_control.display, 1);

		let display_name = unsafe {XDisplayName(&a)};
		let ext_name = "RECORD";
		// Check presence of Record extension
		let arg2:*mut c_int = &mut 1;
		let arg3:*mut c_int = &mut 1;
		let arg4:*mut c_int = &mut 1;
		let has_record = XQueryExtension(display_control.display, ext_name.to_c_str().as_ptr() as *const i8,arg2,arg3,arg4);
		let extension = XInitExtension(display_control.display, ext_name.to_c_str().as_ptr() as *const i8);
		if extension.is_null() {
			panic!("XInitExtension() failed!");
		}

		// Get version
		let mut versionMajor: c_int = 0;
		let mut versionMinor: c_int = 0;
		XRecordQueryVersion(display_control.display, &mut versionMajor, &mut versionMinor);
		println!("RECORD extension version {}.{}", versionMajor, versionMinor);

		// Prepare record range
		let mut recordRange: XRecordRange = *XRecordAllocRange();
		let mut recordRangePtr: *mut *mut XRecordRange = std::mem::transmute(&mut &mut recordRange);
		recordRange.device_events.first = 2; // KeyPress
		recordRange.device_events.last = 6; // MotionNotify

		// Create context
		let context = XRecordCreateContext(
			display_control.display,
			0,
			&mut XRecordAllClients,
			1,
			recordRangePtr,
			1
		);
		if context == 0 {
			panic!("Fail create Record context\n");
		}

		// Run
		let res = XRecordEnableContextAsync(display_data.display, context, Some(recordCallback), &mut 0);
		if res == 0 {
			panic!("Cound not enable the Record context!\n");
		}
		xtst::XRecordFreeContext(display_data.display, context);

		// without this timer process consume 100% CPU
		let mut timer = Timer::new().unwrap();
		let periodic = timer.periodic(Duration::milliseconds(1000));
		loop {
			periodic.recv();
			XRecordProcessReplies(display_data.display);
		}
	}
}

extern "C" fn recordCallback(pointer:*mut i8, raw_data: *mut XRecordInterceptData) {

	unsafe {
		event_count += 1;
		let data = &*raw_data;

		if data.category != xtst::XRecordFromServer {
			return;
		}

		println!("Event count: {}", event_count);
		println!("Time {}", data.server_time);
		println!("Datalen {}", data.data_len);

		let mut xdatum_ptr: *mut XRecordDatum = data.data as *mut XRecordDatum;
		let mut xdatum = &*xdatum_ptr;

		let mut event = xdatum.event;
		println!("Type {}", xdatum.xtype);

		// Catch key event
		if xdatum.xtype == xtst::KeyPress || xdatum.xtype == xtst::KeyRelease {
			// extract key code
			let raw_bytes: &mut [u8,..4] = std::mem::transmute(data.data);
			let c_char  = XKeysymToString(XKeycodeToKeysym(display_control.display, raw_bytes[1], 0));
			let c_string = CString::new(std::mem::transmute(c_char), false);
			let char: &str = c_string.as_str().unwrap();
			println!("Keycode: {}, Character {}", raw_bytes[1], char);
		}

		let mut current_window = display_control.get_input_focus();
		let mut parent_window: Option<Window> = None;
		let mut wm_name_str: Option<String> = None;

		let mut i = 0u;
		while i < 10 {
			if current_window.id == 0 {
				break;
			}

			wm_name_str = current_window.get_wm_name();
			if wm_name_str.is_none() || wm_name_str.clone().unwrap() == "FocusProxy".to_string() {
				let tree = current_window.get_tree();
					parent_window = match tree {
						Some(WindowTree{parent: parent, children: _}) => {
							Some(parent)
						},
						_ => None
					}
			} else {
				break;
			}

			current_window = match parent_window {
				Some(win) => win,
				_ => current_window
			};

			i += 1;
		}
		match wm_name_str {
			Some(ref name) => {
				println!("WM_NAME: {}", *name);
			},
			None => {
				println!("WM_NAME: none");
			}
		}

		XRecordFreeData(raw_data);
	}
	println!("\n");
}

// ============================================================================
// Simple naive wrappers around X stuff
// ============================================================================
struct Display<'a> {
    display: *mut xlib::Display,
}

impl<'a> Display<'a> {
	fn new() -> Display<'a> {
		Display {display: unsafe {
			let mut a:  i8 = 0;
			let dpy = XOpenDisplay(&a);
			if dpy.is_null() {
				panic!("XOpenDisplay() failed!");
			}
			dpy
		}}
	}
	fn get_input_focus(&self) -> Window{
		let current_window: *mut xlib::Window = &mut 0;
		let revert_to_return: *mut i32 = &mut 0;
		unsafe{xlib::XGetInputFocus(self.display, current_window, revert_to_return)};
		Window {id: unsafe{*current_window as uint}, display: self.display}
	}
}

struct Window<'a> {
    id: uint, // XID
    display: *mut xlib::Display
}

impl<'a> Window<'a> {
	fn get_wm_name(&self) -> Option<String> {
		// let mut a:String = String::new();
		// let wmname = unsafe {
			// let mut window_name: *mut i8 = 0 as *mut i8;
			// let res = xlib::XFetchName(self.display, self.id, &mut window_name);
			// if res != 0 {
			// 	let c_wm_name = CString::new(std::mem::transmute(window_name), false);
			// 	// xlib::XFree(&mut window_name);
			// 	Some(String::from_str(c_wm_name.as_str().unwrap()))
			// } else {
			// 	// Try get _NET_WM_NAME
			// 	None
			// }
			let wmname_c = self.get_property("_NET_WM_NAME", "UTF8_STRING");
			match wmname_c {
				Some(bytes) => match String::from_utf8(bytes){
					Ok(value) => Some(value),
					Err(err) => {println!("Error: {}", err); None}
				},
				None => None
			}
		// };
		// wmname
	}
	fn get_property(&self, property_name: &str, property_type: &str) -> Option<Vec<u8>>{
		unsafe {
			let xa_property_type: xlibint::Atom = xlib::XInternAtom(self.display, property_type.to_c_str().as_ptr(), 0);
			let xa_property_name: xlibint::Atom = xlib::XInternAtom(self.display, property_name.to_c_str().as_ptr(), 0);
			let mut actual_type_return  : xlibint::Atom     = 0;
			let mut actual_format_return: libc::c_int       = 0;
			let mut nitems_return       : libc::c_ulong     = 0;
			let mut bytes_after_return  : libc::c_ulong     = 0;
			let mut tmp                 : libc::c_uchar     = 0u8;
			let mut prop_return         : *mut libc::c_uchar = mem::transmute(&mut tmp);
			let res = xlib::XGetWindowProperty(
				self.display,
				self.id as u32,
				xa_property_name,
				0,
				4096 / 4,
				0,
				xa_property_type,
				&mut actual_type_return,
				&mut actual_format_return,
				&mut nitems_return,
				&mut bytes_after_return,
				&mut prop_return
				);
			if (xa_property_type != actual_type_return) {
				println!("Invalid type of {} property", property_name);
				return None;
			}
			let tmp_size = ((actual_format_return as uint) / 8) * (nitems_return as uint);

			let data = c_vec::CVec::new(prop_return, tmp_size as uint);
			let mut copy_data = Vec::with_capacity(tmp_size as uint);
			for b in data.as_slice().iter() {
				copy_data.push(*b);
			}

			xlib::XFree(prop_return as *mut libc::types::common::c95::c_void);

			Some(copy_data)
		}
	}

	fn get_tree (&self) -> Option<WindowTree> {
		unsafe {
			let mut root: xlib::Window = 0;
			let mut parent: xlib::Window = 0;
			let mut children: *mut xlib::Window = mem::transmute(&mut 0u);
			let mut nchildren: u32 = 0;

			let res = xlib::XQueryTree(
				self.display,
				self.id as u32,
				&mut root,
				&mut parent,
				&mut children,
				&mut nchildren);

			match res {
				0 => None,
				_ => {
					let childs = match nchildren {
						0 => None,
						_ => {
							// let c = std::c_vec::CVec::new(children, nchildren);
							let mut b: Vec<Window> = Vec::new();
							for i in range(0, nchildren as int){
								b.push(Window{
									id: mem::transmute(*children.offset(i)),
									display: self.display
								});
							}
							Some(b)
						}
					};

					Some(WindowTree {
						parent: Window{
							id: parent as uint,
							display: self.display,
						},
						children: childs
					})
				}
			}
		}
	}
}

struct WindowTree<'a> {
    parent: Window<'a>,
    children: Option<Vec<Window<'a>>>,
}<commit_msg>transmute integer<commit_after>#![feature(globs)]
extern crate libc;

use xlib::{XOpenDisplay, XDisplayName, XQueryExtension, XInitExtension, XSynchronize, XKeysymToString, XKeycodeToKeysym};
use libc::{c_int};
use std::ptr;
use xtst::{XRecordCreateContext, XRecordAllClients, XRecordAllocRange, XRecordRange, XRecordQueryVersion, XRecordEnableContext, XRecordEnableContextAsync,XRecordInterceptData, XRecordProcessReplies, XRecordFreeData};
use std::mem;
use std::c_str::CString;
use std::c_vec;
use std::time::Duration;
use std::io::Timer;
mod xtst;
mod xlib;
mod xlibint;
mod xutil;

struct XRecordDatum {
  xtype: ::libc::c_uchar,
  event: ::xlib::XEvent,
  req:   ::xlibint::xResourceReq,
  reply: ::xlibint::xGenericReply,
  error: ::xlibint::xError,
  setup: ::xlibint::xConnSetupPrefix,
}

static mut display_control: Display<'static> = Display {display: 0 as *mut xlib::Display};
static mut display_data: Display<'static> = Display {display: 0 as *mut xlib::Display};
static mut event_count:u32 = 0;
fn main() {
	unsafe {
		let mut a:  i8 = 0;
		display_control = Display::new();
		display_data = Display::new();

		XSynchronize(display_control.display, 1);

		let display_name = unsafe {XDisplayName(&a)};
		let ext_name = "RECORD";
		// Check presence of Record extension
		let arg2:*mut c_int = &mut 1;
		let arg3:*mut c_int = &mut 1;
		let arg4:*mut c_int = &mut 1;
		let has_record = XQueryExtension(display_control.display, ext_name.to_c_str().as_ptr() as *const i8,arg2,arg3,arg4);
		let extension = XInitExtension(display_control.display, ext_name.to_c_str().as_ptr() as *const i8);
		if extension.is_null() {
			panic!("XInitExtension() failed!");
		}

		// Get version
		let mut versionMajor: c_int = 0;
		let mut versionMinor: c_int = 0;
		XRecordQueryVersion(display_control.display, &mut versionMajor, &mut versionMinor);
		println!("RECORD extension version {}.{}", versionMajor, versionMinor);

		// Prepare record range
		let mut recordRange: XRecordRange = *XRecordAllocRange();
		let mut recordRangePtr: *mut *mut XRecordRange = std::mem::transmute(&mut &mut recordRange);
		recordRange.device_events.first = 2; // KeyPress
		recordRange.device_events.last = 6; // MotionNotify

		// Create context
		let context = XRecordCreateContext(
			display_control.display,
			0,
			&mut XRecordAllClients,
			1,
			recordRangePtr,
			1
		);
		if context == 0 {
			panic!("Fail create Record context\n");
		}

		// Run
		let res = XRecordEnableContextAsync(display_data.display, context, Some(recordCallback), &mut 0);
		if res == 0 {
			panic!("Cound not enable the Record context!\n");
		}
		xtst::XRecordFreeContext(display_data.display, context);

		// without this timer process consume 100% CPU
		let mut timer = Timer::new().unwrap();
		let periodic = timer.periodic(Duration::milliseconds(1000));
		loop {
			periodic.recv();
			XRecordProcessReplies(display_data.display);
		}
	}
}

extern "C" fn recordCallback(pointer:*mut i8, raw_data: *mut XRecordInterceptData) {

	unsafe {
		event_count += 1;
		let data = &*raw_data;

		if data.category != xtst::XRecordFromServer {
			return;
		}

		println!("Event count: {}", event_count);
		println!("Time {}", data.server_time);
		println!("Datalen {}", data.data_len);

		let mut xdatum_ptr: *mut XRecordDatum = data.data as *mut XRecordDatum;
		let mut xdatum = &*xdatum_ptr;

		let mut event = xdatum.event;
		println!("Type {}", xdatum.xtype);

		// Catch key event
		if xdatum.xtype == xtst::KeyPress || xdatum.xtype == xtst::KeyRelease {
			// extract key code
			let raw_bytes: &mut [u8,..4] = std::mem::transmute(data.data);
			let c_char  = XKeysymToString(XKeycodeToKeysym(display_control.display, raw_bytes[1], 0));
			let c_string = CString::new(std::mem::transmute(c_char), false);
			let char: &str = c_string.as_str().unwrap();
			println!("Keycode: {}, Character {}", raw_bytes[1], char);
		}

		let mut current_window = display_control.get_input_focus();
		let mut parent_window: Option<Window> = None;
		let mut wm_name_str: Option<String> = None;

		let mut i = 0u;
		while i < 10 {
			if current_window.id == 0 {
				break;
			}

			wm_name_str = current_window.get_wm_name();
			if wm_name_str.is_none() || wm_name_str.clone().unwrap() == "FocusProxy".to_string() {
				let tree = current_window.get_tree();
					parent_window = match tree {
						Some(WindowTree{parent: parent, children: _}) => {
							Some(parent)
						},
						_ => None
					}
			} else {
				break;
			}

			current_window = match parent_window {
				Some(win) => win,
				_ => current_window
			};

			i += 1;
		}
		match wm_name_str {
			Some(ref name) => {
				println!("WM_NAME: {}", *name);
			},
			None => {
				println!("WM_NAME: none");
			}
		}

		XRecordFreeData(raw_data);
	}
	println!("\n");
}

// ============================================================================
// Simple naive wrappers around X stuff
// ============================================================================
struct Display<'a> {
    display: *mut xlib::Display,
}

impl<'a> Display<'a> {
	fn new() -> Display<'a> {
		Display {display: unsafe {
			let mut a:  i8 = 0;
			let dpy = XOpenDisplay(&a);
			if dpy.is_null() {
				panic!("XOpenDisplay() failed!");
			}
			dpy
		}}
	}
	fn get_input_focus(&self) -> Window{
		let current_window: *mut xlib::Window = &mut 0;
		let revert_to_return: *mut i32 = &mut 0;
		unsafe{xlib::XGetInputFocus(self.display, current_window, revert_to_return)};
		Window {id: unsafe{*current_window as uint}, display: self.display}
	}
}

struct Window<'a> {
    id: uint, // XID
    display: *mut xlib::Display
}

impl<'a> Window<'a> {
	fn get_wm_name(&self) -> Option<String> {
		// let mut a:String = String::new();
		// let wmname = unsafe {
			// let mut window_name: *mut i8 = 0 as *mut i8;
			// let res = xlib::XFetchName(self.display, self.id, &mut window_name);
			// if res != 0 {
			// 	let c_wm_name = CString::new(std::mem::transmute(window_name), false);
			// 	// xlib::XFree(&mut window_name);
			// 	Some(String::from_str(c_wm_name.as_str().unwrap()))
			// } else {
			// 	// Try get _NET_WM_NAME
			// 	None
			// }
			let wmname_c = self.get_property("_NET_WM_NAME", "UTF8_STRING");
			match wmname_c {
				Some(bytes) => match String::from_utf8(bytes){
					Ok(value) => Some(value),
					Err(err) => {println!("Error: {}", err); None}
				},
				None => None
			}
		// };
		// wmname
	}
	fn get_property(&self, property_name: &str, property_type: &str) -> Option<Vec<u8>>{
		unsafe {
			let xa_property_type: xlibint::Atom = xlib::XInternAtom(self.display, property_type.to_c_str().as_ptr(), 0);
			let xa_property_name: xlibint::Atom = xlib::XInternAtom(self.display, property_name.to_c_str().as_ptr(), 0);
			let mut actual_type_return  : xlibint::Atom     = 0;
			let mut actual_format_return: libc::c_int       = 0;
			let mut nitems_return       : libc::c_ulong     = 0;
			let mut bytes_after_return  : libc::c_ulong     = 0;
			let mut tmp                 : libc::c_uchar     = 0u8;
			let mut prop_return         : *mut libc::c_uchar = mem::transmute(&mut tmp);
			let res = xlib::XGetWindowProperty(
				self.display,
				mem::transmute(self.id),
				xa_property_name,
				0,
				4096 / 4,
				0,
				xa_property_type,
				&mut actual_type_return,
				&mut actual_format_return,
				&mut nitems_return,
				&mut bytes_after_return,
				&mut prop_return
				);
			if (xa_property_type != actual_type_return) {
				println!("Invalid type of {} property", property_name);
				return None;
			}
			let tmp_size = ((actual_format_return as uint) / 8) * (nitems_return as uint);

			let data = c_vec::CVec::new(prop_return, tmp_size as uint);
			let mut copy_data = Vec::with_capacity(tmp_size as uint);
			for b in data.as_slice().iter() {
				copy_data.push(*b);
			}

			xlib::XFree(prop_return as *mut libc::types::common::c95::c_void);

			Some(copy_data)
		}
	}

	fn get_tree (&self) -> Option<WindowTree> {
		unsafe {
			let mut root: xlib::Window = 0;
			let mut parent: xlib::Window = 0;
			let mut children: *mut xlib::Window = mem::transmute(&mut 0u);
			let mut nchildren: u32 = 0;

			let res = xlib::XQueryTree(
				self.display,
				mem::transmute(self.id),
				&mut root,
				&mut parent,
				&mut children,
				&mut nchildren);

			match res {
				0 => None,
				_ => {
					let childs = match nchildren {
						0 => None,
						_ => {
							// let c = std::c_vec::CVec::new(children, nchildren);
							let mut b: Vec<Window> = Vec::new();
							for i in range(0, nchildren as int){
								b.push(Window{
									id: mem::transmute(*children.offset(i)),
									display: self.display
								});
							}
							Some(b)
						}
					};

					Some(WindowTree {
						parent: Window{
							id: parent as uint,
							display: self.display,
						},
						children: childs
					})
				}
			}
		}
	}
}

struct WindowTree<'a> {
    parent: Window<'a>,
    children: Option<Vec<Window<'a>>>,
}<|endoftext|>


<commit_before>extern crate csv;

use std::io::{File};
//use std::num::{sqrt};
use std::os;

static CACHE_SIZE: uint = 16384;

fn main() {
    // Extract input file
    let args: Vec<String> = os::args();
    if args.len() != 2 {
      fail!("No input file provided. Please pass one as argument!");
    }

    // Open CSV file with statistics
    let file = File::open(&Path::new(args[1].as_slice()));
    let mut rdr = csv::Decoder::from_reader(file);
    rdr.separator(';');
    rdr.has_headers(true);
    rdr.enforce_same_length(false);
    // Ignore comment lines generated by benchmark suite
    for i in range(0u,3) {
      let ignored = rdr.iter().next();
      // println!("{} length", ignored.unwrap().len());
    }

    // Vectors for storage of data items
    let mut data : Vec<Vec<int>> = Vec::with_capacity(3);
    data.push(Vec::with_capacity(CACHE_SIZE)); // event latency
    data.push(Vec::with_capacity(CACHE_SIZE)); // dispatch latency + event latency
    data.push(Vec::with_capacity(CACHE_SIZE)); // execution time

    for (event_latency, dispatch_latency, exec_time) in rdr.decode_iter::<(int, int, int)>() {
        // println!("{}, {}, {}", event_latency, dispatch_latency, exec_time);
        data.get_mut(0).push(event_latency);
        data.get_mut(1).push(dispatch_latency);
        data.get_mut(2).push(exec_time);
    }

    // Sort vectors
    data.get_mut(0).sort_by(|a, b| compare_ints(a, b)); // |a, b| a.cmp(b)
    data.get_mut(1).sort_by(|a, b| compare_ints(a, b));
    data.get_mut(2).sort_by(|a, b| compare_ints(a, b));

    // for item in data[0].iter() {
    //     println!("{}", item);
    // }
    for dataset_id in range(0u, 3) {
        let dataset = &data[dataset_id];
        println!("Dataset {} with {} entries:", dataset_id, dataset.len());
        // Statistics about current dataset
        let (quantile_min, quantile_max) = get_quantiles(dataset);
        println!("First & Last & 5% & 95% & avg & stdDev")
        println!("{} & {} & {} & {} & {} & {}",
                 get_first(dataset), get_last(dataset),
                 quantile_min, quantile_max,
                 get_avg(dataset), get_variance(dataset).sqrt());

        println!("-----------------------------")
    }
}

fn get_first(input : &Vec<int>) -> int {
    input[0]
}

fn get_last(input : &Vec<int>) -> int {
    input[input.len() - 1]
}

fn get_avg(input : &Vec<int>) -> f32 {
    let mut sum = 0f32;

    for item in input.iter() {
        sum += *item as f32;
    }
    // Result
    return sum / (input.len() as f32);
}

fn get_variance(input : &Vec<int>) -> f32 {
    let avg: f32 = get_avg(input);
    let mut variance = 0f32;

    for item in input.iter() {
        let diff = (*item as f32) - avg;
        variance += diff * diff;
    }

    variance /= (input.len() - 1) as f32;
    // Result
    variance
}

/// Calculate 5% and 95% quantiles
fn get_quantiles(input : &Vec<int>) -> (int, int) {
    let low_index = ((input.len()-1) * 5u) / 100u;
    let high_index = ((input.len()-1) * 95u) / 100u;
    // Result
    (input[low_index], input[high_index])
}

fn compare_ints(left : &int, right : &int) -> Ordering {
    if left < right {
      Less
    } else if left > right {
      Greater
    } else {
      Equal
    }
}
<commit_msg>Added MD (average deviation about mean) calculations<commit_after>extern crate csv;

use std::io::{File};
use std::num::{abs};
use std::os;

static CACHE_SIZE: uint = 16384;

fn main() {
    // Extract input file
    let args: Vec<String> = os::args();
    if args.len() != 2 {
      fail!("No input file provided. Please pass one as argument!");
    }

    // Open CSV file with statistics
    let file = File::open(&Path::new(args[1].as_slice()));
    let mut rdr = csv::Decoder::from_reader(file);
    rdr.separator(';');
    rdr.has_headers(true);
    rdr.enforce_same_length(false);
    // Ignore comment lines generated by benchmark suite
    for i in range(0u,3) {
      let ignored = rdr.iter().next();
      // println!("{} length", ignored.unwrap().len());
    }

    // Vectors for storage of data items
    let mut data : Vec<Vec<int>> = Vec::with_capacity(3);
    data.push(Vec::with_capacity(CACHE_SIZE)); // event latency
    data.push(Vec::with_capacity(CACHE_SIZE)); // dispatch latency + event latency
    data.push(Vec::with_capacity(CACHE_SIZE)); // execution time

    for (event_latency, dispatch_latency, exec_time) in rdr.decode_iter::<(int, int, int)>() {
        // println!("{}, {}, {}", event_latency, dispatch_latency, exec_time);
        data.get_mut(0).push(event_latency);
        data.get_mut(1).push(dispatch_latency);
        data.get_mut(2).push(exec_time);
    }

    // Sort vectors
    data.get_mut(0).sort_by(|a, b| compare_ints(a, b)); // |a, b| a.cmp(b)
    data.get_mut(1).sort_by(|a, b| compare_ints(a, b));
    data.get_mut(2).sort_by(|a, b| compare_ints(a, b));

    // for item in data[0].iter() {
    //     println!("{}", item);
    // }
    for dataset_id in range(0u, 3) {
        let dataset = &data[dataset_id];
        println!("Dataset {} with {} entries:", dataset_id, dataset.len());
        // Statistics about current dataset
        let (quantile_min, quantile_max) = get_quantiles(dataset);
        println!("First & Last & 5% & 95% & average & stdDev & avgMedianDev")
        println!("{} & {} & {} & {} & {} & {} & {}",
                 get_first(dataset), get_last(dataset),
                 quantile_min, quantile_max,
                 get_avg(dataset), get_variance(dataset).sqrt(),
                 get_average_abs_deviation(dataset));

        println!("-----------------------------")
    }
}

fn get_first(input: &Vec<int>) -> int {
    input[0]
}

fn get_last(input: &Vec<int>) -> int {
    input[input.len() - 1]
}

fn get_avg(input: &Vec<int>) -> f32 {
    let mut sum = 0f32;

    for item in input.iter() {
        sum += *item as f32;
    }
    // Result
    return sum / (input.len() as f32);
}

fn get_median(input: &Vec<int>) -> int {
    let midway = input.len() / 2;
    // Result
    input[midway]
}

fn get_variance(input: &Vec<int>) -> f32 {
    let avg: f32 = get_avg(input);
    let mut variance = 0f32;

    for item in input.iter() {
        let diff = (*item as f32) - avg;
        variance += diff * diff;
    }

    variance /= (input.len() - 1) as f32;
    // Result
    variance
}

/// Average absolute deviation about median
///
/// Implement http://en.wikipedia.org/wiki/Median_absolute_deviation instead
fn get_average_abs_deviation(input: &Vec<int>) -> f32 {
    let median = get_median(input);

    let mut sum = 0i;
    for item in input.iter() {
        let diff = abs(item - median);
        sum += diff;
    }
    let res = (sum as f32) / (input.len() as f32);
    // Result
    res
}

/// Calculate 5% and 95% quantiles
fn get_quantiles(input : &Vec<int>) -> (int, int) {
    let low_index = ((input.len()-1) * 5u) / 100u;
    let high_index = ((input.len()-1) * 95u) / 100u;
    // Result
    (input[low_index], input[high_index])
}

fn compare_ints(left : &int, right : &int) -> Ordering {
    if left < right {
      Less
    } else if left > right {
      Greater
    } else {
      Equal
    }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate glium;

use glium::DisplayBuild;
use glium::Surface;

#[derive(Copy, Clone)]
struct Vertex {
    position: [f64; 2],
}

fn main() {
    let display = glium::glutin::WindowBuilder::new()
        .with_dimensions(500, 500)
        .with_title(format!("Elma Menu bounce balls deluxe")).build_glium().unwrap();

    implement_vertex!(Vertex, position);

    let circle_detail = 30_u8;
    let circle_radius = 0.2_f64;
    let circle_center = [0_f64, 0_f64];
    let mut circle_vertices = vec![];
    let twice_pi = std::f64::consts::PI * 2.;

    circle_vertices.push(Vertex { position: [circle_center[0], circle_center[1]] });
    for n in 0..circle_detail + 1 {
        circle_vertices.push(Vertex { position: [circle_center[0] + (circle_radius * (n as f64 * twice_pi / circle_detail as f64).cos()),
                             circle_center[1] + (circle_radius * (n as f64 * twice_pi / circle_detail as f64).sin())] });
	}

    let vertex_shader_src = r#"
        #version 140
        in vec2 position;

        void main() {
            gl_Position = vec4(position, 0.0, 1.0);
        }
    "#;

    let fragment_shader_src = r#"
        #version 140
        out vec4 color;

        void main() {
            color = vec4(0.49, 0.66, 0.46, 1);
        }
    "#;

    let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None).unwrap();
    let vertex_buffer = glium::VertexBuffer::new(&display, &circle_vertices).unwrap();
    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan);

    loop {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 0.0, 1.0);

        target.draw(&vertex_buffer, &indices, &program, &glium::uniforms::EmptyUniforms,
                        &Default::default()).unwrap();
        target.finish().unwrap();

        for event in display.poll_events() {
            match event {
                glium::glutin::Event::Closed => return,
                _ => ()
            }
        }
    }
}
<commit_msg>fix: separate out circle creation into own function<commit_after>#[macro_use]
extern crate glium;

use glium::DisplayBuild;
use glium::Surface;

#[derive(Copy, Clone)]
struct Vertex {
    position: [f64; 2],
}

const PI2: f64 = std::f64::consts::PI * 2.;

fn make_circle(center: [f64; 2], radius: f64, triangle_count: u8) -> Vec<Vertex> {
    let mut circle_vertices = vec![];

    circle_vertices.push(Vertex { position: [center[0], center[1]] });
    for n in 0..triangle_count + 1 {
        circle_vertices.push(Vertex { position: [center[0] + (radius * (n as f64 * PI2 / triangle_count as f64).cos()),
                                                 center[1] + (radius * (n as f64 * PI2 / triangle_count as f64).sin())] });
        }

    circle_vertices
}

fn main() {
    let display = glium::glutin::WindowBuilder::new()
        .with_dimensions(500, 500)
        .with_title(format!("Elma Menu bounce balls deluxe")).build_glium().unwrap();

    implement_vertex!(Vertex, position);

    let circle_one = make_circle([0.0, 0.0], 0.5, 50);

    let vertex_shader_src = r#"
        #version 140
        in vec2 position;

        void main() {
            gl_Position = vec4(position, 0.0, 1.0);
        }
    "#;

    let fragment_shader_src = r#"
        #version 140
        out vec4 color;

        void main() {
            color = vec4(0.49, 0.66, 0.46, 1);
        }
    "#;

    let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None).unwrap();
    let vertex_buffer = glium::VertexBuffer::new(&display, &circle_one).unwrap();
    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan);

    loop {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 0.0, 1.0);

        target.draw(&vertex_buffer, &indices, &program, &glium::uniforms::EmptyUniforms,
                        &Default::default()).unwrap();
        target.finish().unwrap();

        for event in display.poll_events() {
            match event {
                glium::glutin::Event::Closed => return,
                _ => ()
            }
        }
    }
}
<|endoftext|>


<commit_before>extern crate image;

use std::fs::File;
use std::path::Path;

use image::GenericImage;
// use image::imageops;

fn main() {
    // read in image
    let path = &Path::new("/Users/james/Documents/rust/ascii/img/pic.jpg");
    let mut img = image::open(path).unwrap();
    // img.grayscale();
    let size = img.dimensions();

    println!("Size: {:?}", size);

    let ref mut out = File::create(&Path::new("/Users/james/Documents/rust/ascii/out/test.png")).unwrap();

    // convert to greyscale
    let _ = img.grayscale().save(out, image::PNG).unwrap();

    // split into zones
    let zone_size = 10;

    // step_by doesn't exist yet :(
    // for x in (0..size.0).step_by(zone_size) {
    for y in 0..size.1 {
        if y % zone_size == 0 {
            println!("row {:?}", y / 10);

            for x in 0..size.0 {
                if x % zone_size == 0 {
                    // println!("{:?}:{:?}", x, y);

                    let sub_img = img.crop(x, y, x + zone_size, y + zone_size);
                    // let ref mut out = File::create(&Path::new("/Users/james/Documents/rust/ascii/out/test.png")).unwrap();
                    // let _ = sub_img.save(out, image::PNG);

                    // get intensity of sub img
                }
            }
        }
    }

    // get intensity
}
<commit_msg>All maths and stuff<commit_after>extern crate image;

use std::fs::File;
use std::path::Path;

use image::GenericImage;

fn main() {
    // read in image
    let path = &Path::new("/Users/james/Documents/rust/ascii/img/pic.jpg");
    let mut img = image::open(path).unwrap();
    let (width, height) = img.dimensions();

    println!("Size: {:?}, {:?}", width, height);

    let ref mut out = File::create(&Path::new("/Users/james/Documents/rust/ascii/out/test.png")).unwrap();

    // convert to greyscale
    let _ = img.grayscale().save(out, image::PNG).unwrap();

    // split into zones
    let zone_size = 10;
    let char_map = [".", ",", ":", ";", "o", "x", "%", "#", "@"];
    let map_length = char_map.len();
    let mut output = "".to_string();
    output = output + "test\r\n";

    // step_by doesn't exist yet :(
    // for x in (0..size.0).step_by(zone_size) {
    for y in 0..(height) {
        if y % zone_size == 0 {
            println!("row {:?}", y / 10);

            for x in 0..(width) {
                if x % zone_size == 0 {
                    // println!("{:?}:{:?}", x, y);

                    let sub_img = img.crop(x, y, x + zone_size, y + zone_size);
                    // let ref mut out = File::create(&Path::new("/Users/james/Documents/rust/ascii/out/test.png")).unwrap();
                    // let _ = sub_img.save(out, image::PNG);

                    // get intensity of sub img
                    // for pixel in sub_img
                    let mut r: f32 = 0.0;
                    let mut g: f32 = 0.0;
                    let mut b: f32 = 0.0;
                    let mut count = 0;
                    for (x, y, pixel) in sub_img.pixels() {
                        // println!("{:?}", pixel.data);
                        r = r + pixel.data[0] as f32;
                        g = g + pixel.data[1] as f32;
                        b = b + pixel.data[2] as f32;

                        count = count + 1;
                    }
                    // println!("{:?}, {:?}, {:?} / {:?}", r, g, b, count);
                    println!("{:?}", (((r * 0.3) + (b * 0.3) + (g * 0.3)) / count as f32).floor());
                    // add up all r, g, b vals
                    // divide by number of pixels in sub_img = average
                    // char_map[ (255 - average) * map_length/256 ]
                }
            }
        }
    }

    // get intensity
}
<|endoftext|>


<commit_before>extern crate chrono;
extern crate getopts;
extern crate izzet;
extern crate regex;
extern crate time;

use chrono::Local;
use getopts::{Matches, Options};
use izzet::error::{Error, Result};
use izzet::{gen, post};
use izzet::config::Config;
use regex::Regex;
use std::env;
use std::fs::{DirBuilder, OpenOptions};
use std::path::PathBuf;
use std::io::Write;

const PROG_NAME: &str = env!("CARGO_PKG_NAME");

// XXX this is ugly enough to deserve being rewritten
fn get_open_option(force: bool) -> OpenOptions {
    if force {
        OpenOptions::new().write(true).create(true).truncate(true).clone()
    }
    else {
        OpenOptions::new().write(true).create_new(true).clone()
    }
}

fn init_empty_site(m: &Matches) -> Result<()> {
    let dir = m.free.get(1)
        .and_then(|s| Some(PathBuf::from(s)))
        .unwrap_or(env::current_dir()?);

    let opt = get_open_option(m.opt_present("force"));

    for filename in &[izzet::CONFIG_FILE,
                      izzet::NOJEKYLL_FILE] {
        opt.open(dir.join(filename))
           .map_err(|e| format!("failed to create `{}`: {}", filename, e))?;
    }

    for dirname in &[izzet::FILES_DIR,
                     izzet::SRC_DIR,
                     izzet::TEMPLATES_DIR] {
        DirBuilder::new()
            .recursive(m.opt_present("force"))
            .create(dir.join(dirname))
            .map_err(|e| format!("failed to create `{}`: {}", dirname, e))?;
    }

    for &(filename, html) in &[(izzet::INDEX_FILE, izzet::INDEX_HTML),
                               (izzet::POST_FILE, izzet::INDEX_HTML),
                               (izzet::ARCHIVE_FILE, izzet::ARCHIVE_HTML)] {
        let mut file = opt.open(dir.join(izzet::TEMPLATES_DIR).join(filename))
                          .map_err(|e| format!("failed to create `{}': {}", filename, e))?;
        file.write(html)?;
    }

    Ok(())
}

// XXX let's not put the timestamp in the markdown file title
// XXX we can simply create a Post with default value (empty)
//     and serialize it to the file
fn create_post(m: &Matches) -> Result<()> {
    let link = m.free.get(1).expect("failed to get the link of post");
    if !Regex::new(r"^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$")?.is_match(link) {
        return Err(Error::from_string(format!("invalid link name `{}'", link)));
    }

    let filename = format!("{}.md", link);
    let opt = get_open_option(m.opt_present("force"));
    let mut file = opt.open(&filename)
                      .map_err(|e| format!("failed to create `{}': {}",
                                           filename, e))?;

    file.write(format!("title = ''\n\
                        link = '{}'\n\
                        timestamp = '{:?}'\n\
                        {}\n",
                       link,
                       Local::now(),
                       post::METADATA_DELIM_LINE)
               .as_bytes())?;

    Ok(())
}

fn is_initialized() -> bool {
    PathBuf::from(izzet::CONFIG_FILE).exists()
}

fn generate_site(_: &Matches) -> Result<()> {
    if !is_initialized() {
        return Err(Error::from_string("current directory is not initialized".to_string()));
    }

    let config = Config::from_path(&PathBuf::from(izzet::CONFIG_FILE))?;
    gen::generate(config)?;

    Ok(())
}

fn usage(opts: &Options) {
    println!("{}", opts.usage(&format!("Usage: {} <options> <args>", PROG_NAME)));
}

fn main() {
    let mut opts = Options::new();

    // one of these flags should be specified
    opts.optflag("n", "new", "Initialize an empty site at the given location.");
    opts.optflag("p", "post", "Create a post with the given permalink.");
    opts.optflag("g", "gen", "Generate site, can be used along with -i and -o \
                              to specify the input and output location.");
    opts.optflag("f", "force", "Overwrite existing files when creating posts, \
                                generating site output files, etc.");

    opts.optopt("c", "config", "Run with the given configuration file. By default \
                                configuration file will be looked for under the \
                                current directory.", "CONFIG");
    opts.optopt("i", "input", "Input site directory. Read input files from current \
                              directory by default.", "INPUT");
    opts.optopt("o", "output", "Output site directory. Write to current directory \
                               by default.", "OUTPUT");

    opts.optflag("h", "help", "Show this help message.");
    opts.optflag("V", "version", "Display version information.");

    let matches = match opts.parse(env::args()) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("{}\nTry `{1} -h` or `{1} --help` to see the help.", e, PROG_NAME);
            return;
        },
    };

    if matches.opt_present("h") {
        usage(&opts);
        return;
    }

    if matches.opt_present("V") {
        println!("{} {}", PROG_NAME, env!("CARGO_PKG_VERSION"));
        return;
    }

    if !matches.opt_present("n")
        && !matches.opt_present("p")
        && !matches.opt_present("g") {
        println!("{}: nothing to do", PROG_NAME);
        return;
    }

    let ret = if matches.opt_present("n") {
        init_empty_site(&matches)
    }
    else if matches.opt_present("p") {
        create_post(&matches)
    }
    else if matches.opt_present("g") {
        generate_site(&matches)
    }
    else {
        Ok(())
    };

    if let Err(e) = ret {
        println!("{}", e)
    }
}
<commit_msg>Minor updates on site initialization<commit_after>extern crate chrono;
extern crate getopts;
extern crate izzet;
extern crate regex;
extern crate time;

use chrono::Local;
use getopts::{Matches, Options};
use izzet::error::{Error, Result};
use izzet::{gen, post};
use izzet::config::Config;
use regex::Regex;
use std::env;
use std::fs::{DirBuilder, OpenOptions};
use std::path::PathBuf;
use std::io::Write;

const PROG_NAME: &str = env!("CARGO_PKG_NAME");

fn get_open_option(m: &Matches) -> OpenOptions {
    let mut opener = OpenOptions::new();
    opener.write(true);
    match m.opt_present("force") {
        true => { opener.create(true).truncate(true); }
        false => { opener.create_new(true); }
    }

    opener
}

fn init_site(m: &Matches) -> Result<()> {
    let dir = m.free.get(1)
        .and_then(|s| Some(PathBuf::from(s)))
        .unwrap_or(env::current_dir()?);

    let opener = get_open_option(m);

    for filename in &[izzet::CONFIG_FILE,
                      izzet::NOJEKYLL_FILE] {
        opener.open(dir.join(filename))
              .map_err(|e| format!("failed to create `{}`: {}", filename, e))?;
    }

    for dirname in &[izzet::FILES_DIR,
                     izzet::SRC_DIR,
                     izzet::TEMPLATES_DIR] {
        DirBuilder::new()
            .recursive(m.opt_present("force"))
            .create(dir.join(dirname))
            .map_err(|e| format!("failed to create `{}`: {}", dirname, e))?;
    }

    for &(filename, html) in &[(izzet::INDEX_FILE, izzet::INDEX_HTML),
                               (izzet::POST_FILE, izzet::INDEX_HTML),
                               (izzet::ARCHIVE_FILE, izzet::ARCHIVE_HTML)] {
        let mut file = opener.open(dir.join(izzet::TEMPLATES_DIR)
                                      .join(filename))
                             .map_err(|e| format!("failed to create `{}': {}", filename, e))?;
        file.write(html)?;
    }

    Ok(())
}

// XXX let's not put the timestamp in the markdown file title
// XXX we can simply create a Post with default value (empty)
//     and serialize it to the file
fn create_post(m: &Matches) -> Result<()> {
    let link = m.free.get(1).expect("failed to get the link of post");
    if !Regex::new(r"^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$")?.is_match(link) {
        return Err(Error::from_string(format!("invalid link name `{}'", link)));
    }

    let filename = format!("{}.md", link);
    let opt = get_open_option(m);
    let mut file = opt.open(&filename)
                      .map_err(|e| format!("failed to create `{}': {}",
                                           filename, e))?;

    file.write(format!("title = ''\n\
                        link = '{}'\n\
                        timestamp = '{:?}'\n\
                        {}\n",
                       link,
                       Local::now(),
                       post::METADATA_DELIM_LINE)
               .as_bytes())?;

    Ok(())
}

fn is_initialized() -> bool {
    PathBuf::from(izzet::CONFIG_FILE).exists()
}

fn generate_site(_: &Matches) -> Result<()> {
    if !is_initialized() {
        return Err(Error::from_string("current directory is not initialized".to_string()));
    }

    let config = Config::from_path(&PathBuf::from(izzet::CONFIG_FILE))?;
    gen::generate(config)?;

    Ok(())
}

fn usage(opts: &Options) {
    println!("{}", opts.usage(&format!("Usage: {} <options> <args>", PROG_NAME)));
}

fn main() {
    let mut opts = Options::new();

    // one of these flags should be specified
    opts.optflag("n", "new", "Initialize an empty site at the given location.");
    opts.optflag("p", "post", "Create a post with the given permalink.");
    opts.optflag("g", "gen", "Generate site, can be used along with -i and -o \
                              to specify the input and output location.");
    opts.optflag("f", "force", "Overwrite existing files when creating posts, \
                                generating site output files, etc.");

    opts.optopt("c", "config", "Run with the given configuration file. By default \
                                configuration file will be looked for under the \
                                current directory.", "CONFIG");
    opts.optopt("i", "input", "Input site directory. Read input files from current \
                              directory by default.", "INPUT");
    opts.optopt("o", "output", "Output site directory. Write to current directory \
                               by default.", "OUTPUT");

    opts.optflag("h", "help", "Show this help message.");
    opts.optflag("V", "version", "Display version information.");

    let matches = match opts.parse(env::args()) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("{}\nTry `{1} -h` or `{1} --help` to see the help.", e, PROG_NAME);
            return;
        },
    };

    if matches.opt_present("h") {
        usage(&opts);
        return;
    }

    if matches.opt_present("V") {
        println!("{} {}", PROG_NAME, env!("CARGO_PKG_VERSION"));
        return;
    }

    if !matches.opt_present("n")
        && !matches.opt_present("p")
        && !matches.opt_present("g") {
        println!("{}: nothing to do", PROG_NAME);
        return;
    }

    let ret = if matches.opt_present("n") {
        init_site(&matches)
    }
    else if matches.opt_present("p") {
        create_post(&matches)
    }
    else if matches.opt_present("g") {
        generate_site(&matches)
    }
    else {
        Ok(())
    };

    if let Err(e) = ret {
        println!("{}", e)
    }
}
<|endoftext|>