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

extern crate graphics;
extern crate piston;
extern crate opengl_graphics;
extern crate sdl2_game_window;

use std::os;

use graphics::*;
use opengl_graphics::Gl;
use piston::*;
use sdl2_game_window::GameWindowSDL2;

use lightsout::{StructLevel, Level};

mod lightsout;

fn cmd_main() {
	let sx:Option<uint> = from_str(os::args()[1].as_slice());
	let sx:uint = match sx {
		Some(x) => x,
		None => 4
	};
	let sy:Option<uint> = from_str(os::args()[2].as_slice());
	let sy:uint = match sy {
		Some(y) => y,
		None => 4
	};
	let mut l:StructLevel = Level::new(sx, sy);
	println!("{}", l);
	println!("solved: {}", l.is_solved());

	let sol = lightsout::solve(&mut l);

	println!("{}", sol);
}

struct Env {
	mousex: f64,
	mousey: f64,
	window_width: f64,
	window_height: f64,
}

#[inline(always)]
fn pt_in_rect(px:f64, py:f64, rx: f64, ry:f64, w:f64, h:f64) -> bool {
	px >= rx && px <= rx + w && py >= ry && py <= ry + h
}

fn clear_board(sx: uint, sy: uint, c: &Context, gl: &mut Gl) {
	let margin = 10.0;
	let w = 60.0;
	let h = 50.0;
	c.rect(0.0, 0.0, margin + (margin + w) * (sx as f64) + 1.0, margin + (margin + h) * (sy as f64) + 1.0)
		.rgb(0.0, 0.0, 0.0).draw(gl);
}

fn render_level(level: &Level, env: &Env, c: &Context, gl: &mut Gl) {
	let (sx, sy) = level.size();
	let margin = 10.0;
	let w = 60.0;
	let h = 50.0;
	for y in range(0, sy) {
		for x in range(0, sx) {
			let cx = margin + (margin + w) * (x as f64);
			let cy = margin + (margin + h) * (y as f64);
			if pt_in_rect(env.mousex, env.mousey, cx, cy, w, h) {
				c.rect(cx-1.0, cy-1.0, w+2.0, h+2.0).rgb(1.0, 1.0, 0.0).draw(gl);
			}
			let c = c.rect(cx, cy, w, h);
			if level.get(x, y).unwrap() == 0 {
				c.rgb(0.4, 0.4, 0.4)
			} else {
				c.rgb(0.8, 0.8, 0.8)
			}.draw(gl);
		}
	}
}

fn mouse_to_level(level: &Level, mx: f64, my: f64) -> Option<(uint, uint)> {
	let (sx, sy) = level.size();
	let margin = 10.0;
	let w = 60.0;
	let h = 50.0;
	if !pt_in_rect(mx, my,
		       margin, margin,
		       margin + (w + margin) * sx as f64, margin + (h + margin) * sy as f64) {
		return None
	}

	let lx = (mx - margin) / (margin + w);
	let ly = (my - margin) / (margin + h);
	println!("lx={} ly={}", lx, ly);
	let ulx = lx as uint;
	let uly = ly as uint;
	let sx = margin + (margin + w) * (ulx as f64);
	let sy = margin + (margin + h) * (uly as f64);
	if pt_in_rect(mx, my, sx, sy, w, h) {
		Some((ulx, uly))
	} else {
		None
	}
}

fn make_ai_move(level: &mut StructLevel) {
	let sol = lightsout::solve(level);
	println!("solution: {}", sol);
	match sol {
		Some(moves) => {
			if moves.len() > 0 {
				let move = moves[0];
				let (mx, my) = move;
				level.make_move(mx, my);
			}
		},
		None => {}
	};
}

fn main() {
	let mut window = GameWindowSDL2::new(
		GameWindowSettings {
			title: "Rust Lights Out".to_string(),
			size: [800u32, 600u32],
			fullscreen: false,
			exit_on_esc: true,
		}
	);
	println!("window: {:?}", window);

	let game_iter_settings = GameIteratorSettings {
		updates_per_second: 120,
		max_frames_per_second: 60,
	};

	let ref mut gl = Gl::new();
	let mut level:StructLevel = Level::new(5, 5);

	let mut env = Env {
		mousex: 0f64,
		mousey: 0f64,
		window_width: window.get_settings().size[0] as f64,
		window_height: window.get_settings().size[1] as f64,
	};

	level.make_move(2, 2);

	for event in GameIterator::new(&mut window, &game_iter_settings) {
		match event {
			Render(args) => {
				gl.viewport(0, 0, args.width as i32, args.height as i32);
				let c = Context::abs(args.width as f64, args.height as f64);
				c.rgb(1.0, 0.0, 0.0)
					.rect(0.0, 0.0, 100.0, 100.0)
					.draw(gl);
				clear_board(9, 9, &c, gl);
				render_level(&level, &env, &c, gl);
			},
			MouseMove(args) => {
				env.mousex = args.x;
				env.mousey = args.y;
			},
			MousePress(args) => {
				println!("{:?} {:?}", args, env);
				match mouse_to_level(&level, env.mousex, env.mousey) {
					Some((x, y)) => { level.make_move(x, y); },
					_ => {}
				}
			},
			KeyPress(args) => {
				println!("{:?} {:?}", args, env);
				match args.key {
					keyboard::Space => make_ai_move(&mut level),
					keyboard::Left
					| keyboard::Right
					| keyboard::Up
					| keyboard::Down => {
						let change_level_size = |dx: uint, dy: uint| {
							let (sx, sy) = level.size();
							if sx + dx > 1 && sy + dy > 1
									&& sx + dx < 10 && sy + dy < 10 {
								level = Level::new(sx + dx, sy + dy);
								println!("new level: {}", level);
							}
						};
						match args.key {
							keyboard::Up => change_level_size(0, -1),
							keyboard::Right => change_level_size(1, 0),
							keyboard::Down => change_level_size(0, 1),
							keyboard::Left => change_level_size(-1, 0),
							_ => {},
						};
					},
					keyboard::D1 => match mouse_to_level(&level, env.mousex, env.mousey) {
						Some((x, y)) => { level.set(x, y, 0); },
						_ => {},
					},
					keyboard::D2 => match mouse_to_level(&level, env.mousex, env.mousey) {
						Some((x, y)) => { level.set(x, y, 1); },
						_ => {},
					},
					_ => {}
				}
			},
			_ => {}
		}
	}
}
<commit_msg>cleanup of level resizing<commit_after>#![feature(globs)]
extern crate debug;

extern crate graphics;
extern crate piston;
extern crate opengl_graphics;
extern crate sdl2_game_window;

use std::os;

use graphics::*;
use opengl_graphics::Gl;
use piston::*;
use sdl2_game_window::GameWindowSDL2;

use lightsout::{StructLevel, Level};

mod lightsout;

fn cmd_main() {
	let sx:Option<uint> = from_str(os::args()[1].as_slice());
	let sx:uint = match sx {
		Some(x) => x,
		None => 4
	};
	let sy:Option<uint> = from_str(os::args()[2].as_slice());
	let sy:uint = match sy {
		Some(y) => y,
		None => 4
	};
	let mut l:StructLevel = Level::new(sx, sy);
	println!("{}", l);
	println!("solved: {}", l.is_solved());

	let sol = lightsout::solve(&mut l);

	println!("{}", sol);
}

struct Env {
	mousex: f64,
	mousey: f64,
	window_width: f64,
	window_height: f64,
}

#[inline(always)]
fn pt_in_rect(px:f64, py:f64, rx: f64, ry:f64, w:f64, h:f64) -> bool {
	px >= rx && px <= rx + w && py >= ry && py <= ry + h
}

fn clear_board(sx: uint, sy: uint, c: &Context, gl: &mut Gl) {
	let margin = 10.0;
	let w = 60.0;
	let h = 50.0;
	c.rect(0.0, 0.0, margin + (margin + w) * (sx as f64) + 1.0, margin + (margin + h) * (sy as f64) + 1.0)
		.rgb(0.0, 0.0, 0.0).draw(gl);
}

fn render_level(level: &Level, env: &Env, c: &Context, gl: &mut Gl) {
	let (sx, sy) = level.size();
	let margin = 10.0;
	let w = 60.0;
	let h = 50.0;
	for y in range(0, sy) {
		for x in range(0, sx) {
			let cx = margin + (margin + w) * (x as f64);
			let cy = margin + (margin + h) * (y as f64);
			if pt_in_rect(env.mousex, env.mousey, cx, cy, w, h) {
				c.rect(cx-1.0, cy-1.0, w+2.0, h+2.0).rgb(1.0, 1.0, 0.0).draw(gl);
			}
			let c = c.rect(cx, cy, w, h);
			if level.get(x, y).unwrap() == 0 {
				c.rgb(0.4, 0.4, 0.4)
			} else {
				c.rgb(0.8, 0.8, 0.8)
			}.draw(gl);
		}
	}
}

fn mouse_to_level(level: &Level, mx: f64, my: f64) -> Option<(uint, uint)> {
	let (sx, sy) = level.size();
	let margin = 10.0;
	let w = 60.0;
	let h = 50.0;
	if !pt_in_rect(mx, my,
		       margin, margin,
		       margin + (w + margin) * sx as f64, margin + (h + margin) * sy as f64) {
		return None
	}

	let lx = (mx - margin) / (margin + w);
	let ly = (my - margin) / (margin + h);
	println!("lx={} ly={}", lx, ly);
	let ulx = lx as uint;
	let uly = ly as uint;
	let sx = margin + (margin + w) * (ulx as f64);
	let sy = margin + (margin + h) * (uly as f64);
	if pt_in_rect(mx, my, sx, sy, w, h) {
		Some((ulx, uly))
	} else {
		None
	}
}

fn make_ai_move(level: &mut StructLevel) {
	let sol = lightsout::solve(level);
	println!("solution: {}", sol);
	match sol {
		Some(moves) => {
			if moves.len() > 0 {
				let move = moves[0];
				let (mx, my) = move;
				level.make_move(mx, my);
			}
		},
		None => {}
	};
}

fn change_level_size<T: Level>(level: T, dx: int, dy: int) -> T {
	let (sx, sy) = level.size();
	let sx = sx as int;
	let sy = sy as int;
	if sx + dx > 1 && sy + dy > 1
			&& sx + dx < 10 && sy + dy < 10 {
		let r:T = Level::new((sx + dx) as uint, (sy + dy) as uint);
		r
	} else {
		level
	}
}

fn main() {
	let mut window = GameWindowSDL2::new(
		GameWindowSettings {
			title: "Rust Lights Out".to_string(),
			size: [800u32, 600u32],
			fullscreen: false,
			exit_on_esc: true,
		}
	);
	println!("window: {:?}", window);

	let game_iter_settings = GameIteratorSettings {
		updates_per_second: 120,
		max_frames_per_second: 60,
	};

	let ref mut gl = Gl::new();
	let mut level:StructLevel = Level::new(5, 5);

	let mut env = Env {
		mousex: 0f64,
		mousey: 0f64,
		window_width: window.get_settings().size[0] as f64,
		window_height: window.get_settings().size[1] as f64,
	};

	level.make_move(2, 2);

	for event in GameIterator::new(&mut window, &game_iter_settings) {
		match event {
			Render(args) => {
				gl.viewport(0, 0, args.width as i32, args.height as i32);
				let c = Context::abs(args.width as f64, args.height as f64);
				clear_board(9, 9, &c, gl);
				render_level(&level, &env, &c, gl);
			},
			MouseMove(args) => {
				env.mousex = args.x;
				env.mousey = args.y;
			},
			MousePress(args) => {
				println!("{:?} {:?}", args, env);
				match mouse_to_level(&level, env.mousex, env.mousey) {
					Some((x, y)) => { level.make_move(x, y); },
					_ => {}
				}
			},
			KeyPress(args) => {
				println!("{:?} {:?}", args, env);
				match args.key {
					keyboard::Space => make_ai_move(&mut level),
					keyboard::Up => level = change_level_size(level, 0, -1),
					keyboard::Right => level = change_level_size(level, 1, 0),
					keyboard::Down => level = change_level_size(level, 0, 1),
					keyboard::Left => level = change_level_size(level, -1, 0),
					keyboard::D1 => match mouse_to_level(&level, env.mousex, env.mousey) {
						Some((x, y)) => { level.set(x, y, 0); },
						_ => {},
					},
					keyboard::D2 => match mouse_to_level(&level, env.mousex, env.mousey) {
						Some((x, y)) => { level.set(x, y, 1); },
						_ => {},
					},
					_ => {}
				}
			},
			_ => {}
		}
	}
}
<|endoftext|>


<commit_before>extern crate markdown;

use std::path::Path;

fn main() {
    let path = Path::new("test.md");
    let display = path.display();

    println!("{}", markdown::file_to_html(&path).unwrap());
}

<commit_msg>Test file from stdin<commit_after>extern crate markdown;

use std::path::Path;
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    println!("{:?}", args);
    let path = Path::new(&args[1]);
    let display = path.display();

    println!("{}", markdown::file_to_html(&path).unwrap());
}

<|endoftext|>


<commit_before>//#![feature(convert)]

#[macro_use]
extern crate nickel;
extern crate rustc_serialize;
extern crate hyper;
extern crate nickel_postgres;
extern crate postgres;
extern crate r2d2_postgres;
extern crate r2d2;
extern crate time;

use nickel::{Nickel, HttpRouter, QueryString};
use nickel::extensions::Redirect;
use nickel::status::StatusCode;
use rustc_serialize::json;
use hyper::Client;
use hyper::header::Connection;
use hyper::status::StatusClass;
use hyper::client::response::Response;
use std::io::Read;
use std::env;
use r2d2::{NopErrorHandler, PooledConnection};
use r2d2_postgres::{TlsMode, PostgresConnectionManager};
use nickel_postgres::{PostgresMiddleware, PostgresRequestExtensions};
use time::now;

#[derive(RustcDecodable, Debug)]
struct Data {
    data: User,
}

#[derive(RustcDecodable, Debug)]
struct User {
    id: i32,
    email: String,
    created_at: String,
    updated_at: String,
    first_name: String,
    last_name: String,
    major: String,
    shirt_size: String,
    dietary_restrictions: String,
    special_needs: Option<String>,
    date_of_birth: String,
    gender: String,
    phone_number: String,
    school: School,
}

#[derive(RustcDecodable, Debug)]
struct School {
    id: i32,
    name: String,
}

#[derive(RustcDecodable, Debug)]
struct TokenResp {
    access_token: String,
    token_type: String,
    scope: String,
    created_at: u64,
}

#[derive(RustcEncodable, Debug)]
struct Payload {
    channel: String,
    username: String,
    text: String,
    icon_emoji: String,
}

#[derive(Debug)]
enum ApiError {
    ClientError,
    ServerError,
}

#[derive(Debug)]
enum RequestError {
    Hyper(hyper::error::Error),
    Io(std::io::Error),
    JsonEnc(rustc_serialize::json::EncoderError),
    JsonDec(rustc_serialize::json::DecoderError),
    Api(ApiError),
}

// `env_err!(var, message)` gets `var` from the environment, and panics with
// `message` if that fails
// `env_err!(var)` gets `var` from the environment and panics with `"Failed to
// get env var $var"` if that fails
macro_rules! env_err {
    ( $var:expr, $error:expr ) => {
        env::var($var).expect($error)
    };
    ( $var:expr ) => {
        env_err!($var, &format!("Failed to get env var {}", $var))
    }
}

// Error handling code.  Expands to impl-ing From for enum_t from from_t to to_t
// See https://doc.rust-lang.org/book/error-handling.html for a full description
macro_rules! impl_from {
    ( $from_t:path, $to_t:path, $enum_t:path ) => {
        impl From<$from_t> for $enum_t {
            fn from(err: $from_t) -> $enum_t {
                $to_t(err)
            }
        }
    }
}

// All the impls for RequestError
impl_from!(hyper::error::Error, RequestError::Hyper, RequestError);
impl_from!(std::io::Error, RequestError::Io, RequestError);
impl_from!(rustc_serialize::json::DecoderError,
           RequestError::JsonDec,
           RequestError);
impl_from!(rustc_serialize::json::EncoderError,
           RequestError::JsonEnc,
           RequestError);
impl_from!(ApiError, RequestError::Api, RequestError);

// Checks for 4xx or 5xx errors and returns the appropriate ApiError
fn check_http_error(res: &Response) -> Result<(), ApiError> {
    match res.status.class() {
        StatusClass::ClientError => Err(ApiError::ClientError),
        StatusClass::ServerError => Err(ApiError::ServerError),
        _ => Ok(()),
    }
}

// Do the OAUTH stuff for my.mlh.io
// TODO: Something better about the long api urls
fn do_request(code: &str) -> Result<Data, RequestError> {
    let id = env_err!("ID");
    let secret = env_err!("SECRET");
    let redirect = env_err!("REDIRECT");

    let url = format!("https://my.mlh.io/oauth/token?client_id={}&\
                      client_secret={}&code={}&redirect_uri={}&\
                      grant_type=authorization_code",
                      id,
                      secret,
                      code,
                      redirect);

    let client = Client::new();
    let mut res = try!(client.post(&url)
        .header(Connection::close())
        .send());

    try!(check_http_error(&res));

    let mut body = String::new();
    try!(res.read_to_string(&mut body));

    let token: TokenResp = try!(json::decode(&body));
    let url2 = format!("https://my.mlh.io/api/v2/user?access_token={}",
                       token.access_token);

    res = try!(client.get(&url2)
        .header(Connection::close())
        .send());

    try!(check_http_error(&res));

    body = String::new();
    try!(res.read_to_string(&mut body));

    let person_data: Data = try!(json::decode(&body));

    Ok(person_data)
}

// Send a message to slack when a new user signs up
fn slack_send(user: User) -> Result<(), RequestError> {
    let url = env_err!("SLACKURL");
    let client = Client::new();
    let payload = Payload {
        channel: "#signups".to_string(),
        username: "Signup bot".to_string(),
        icon_emoji: ":hackcwru:".to_string(),
        text: format!("{}, a {} major from {}, has signed up!",
                      user.first_name,
                      user.major,
                      user.school.name),
    };
    let payload_str = try!(json::encode(&payload));
    let res = try!(client.post(&url)
        .body(&payload_str)
        .send());

    try!(check_http_error(&res));

    Ok(())
}

// Create the table if it doesn't exist.  Runs on each startup
fn create_table(conn: PooledConnection<PostgresConnectionManager>) {
    let _r =
        conn.execute("CREATE TABLE IF NOT EXISTS person (
                id SERIAL PRIMARY KEY,
                email VARCHAR NOT NULL,
                created_at VARCHAR NOT NULL,
                updated_at VARCHAR NOT NULL,
                first_name VARCHAR NOT NULL,
                last_name VARCHAR NOT NULL,
                graduation VARCHAR,
                major VARCHAR NOT NULL,
                shirt_size VARCHAR NOT NULL,
                dietary_restrictions VARCHAR NOT NULL,
                special_needs VARCHAR,
                date_of_birth VARCHAR NOT NULL,
                gender VARCHAR NOT NULL,
                phone_number VARCHAR NOT NULL,
                school_id integer,
                school_name VARCHAR
                )",
            &[]
        );
    let _r = conn.execute("CREATE TABLE IF NOT EXISTS email (email VARCHAR \
                          PRIMARY KEY)",
                          &[]);
    let _r = conn.execute("ALTER TABLE person ADD COLUMN year integer \
                          NOT NULL DEFAULT 2016",
                          &[]);
    let _r = conn.execute("ALTER TABLE person ALTER COLUMN graduation \
                          DROP NOT NULL",
                          &[]);
    let _r = conn.execute(
            "ALTER TABLE person ADD COLUMN signup_time VARCHAR", &[]
        );
    let _r = conn.execute(
            "ALTER TABLE person ADD COLUMN signed_in
            BOOLEAN NOT NULL DEFAULT FALSE",
        &[]
        );
    let _r = conn.execute(
            "ALTER TABLE person ADD COLUMN signed_in_time VARCHAR", &[]
        );

    let _r = conn.execute(
            "ALTER TABLE person DROP CONSTRAINT person_pkey", &[]
        );

    let _r = conn.execute(
            "ALTER TABLE person ADD PRIMARY KEY (id, year)", &[]
        );
}

fn main() {
    let mut app = Nickel::new();

    let postgres_url = env_err!("DATABASE");
    let dbpool =
        PostgresMiddleware::new(&*postgres_url, TlsMode::None, 5, Box::new(NopErrorHandler))
            .expect("Failed to start PostgresMiddleware");

    create_table(dbpool.pool.clone().get().unwrap());
    app.utilize(dbpool);

    app.get("/callback", middleware! { |request, mut response|
        let conn = request.db_conn();
        let redirect_success = env_err!("FINALREDIRECT");
        let redirect_failure = env_err!("REDIRECTERR");
        let year = env_err!("YEAR").parse::<i32>().unwrap();
        let code = match request.query().get("code") {
            Some(s) => s,
            None => {
                println!("No code, quitting");
                return response.error(StatusCode::BadRequest, "Failed");
            }
        };
        let user_data = match do_request(code) {
            Ok(s) => s,
            Err(e) => {
                println!("Get user data failed with error: {:?}", e);
                return response
                    .error(StatusCode::InternalServerError, "Failed");
            }
        }.data;

        let now = now();
        let now_s = format!("{}", now.rfc3339());
        // TODO: make this a function
        let r = conn.execute(
                "INSERT INTO person (id, email, created_at, updated_at,
                first_name, last_name, major, shirt_size,
                dietary_restrictions, special_needs, date_of_birth, gender,
                phone_number, school_id, school_name, year, signup_time) VALUES
                ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,
                $15, $16, $17)",
                &[&user_data.id, &user_data.email, &user_data.created_at,
                  &user_data.updated_at, &user_data.first_name,
                  &user_data.last_name, &user_data.major,
                  &user_data.shirt_size, &user_data.dietary_restrictions,
                  &user_data.special_needs, &user_data.date_of_birth,
                  &user_data.gender, &user_data.phone_number,
                  &user_data.school.id, &user_data.school.name, &year, &now_s]
            );
        let redirect = match r {
            Ok(v) => {
                println!("Add to database succeeded with status {:?}", v);
                match slack_send(user_data) {
                    Ok(_) => println!("Slack send worked"),
                    Err(e) => println!("Slack send failed with error: {:?}", e)
                }
                redirect_success
            },
            Err(e) => {
                println!("Add to database failed: {:?}", e);
                redirect_failure
            }
        };

        return response.redirect(&redirect[..]);
    });

    app.get("/start", middleware! { |_req, response|
        let id = env_err!("ID");
        let redirect = env_err!("REDIRECT");
        return response.redirect(
            format!(
                    "http://my.mlh.io/oauth/authorize?client_id={}&\
                    redirect_uri={}&response_type=code",
                    id, redirect
                )
            );
    });

    app.post("/email", middleware! { |req, res|
        let conn = req.db_conn();
        let email = req.param("email").unwrap();
        let redirect_success = env_err!("FINALREDIRECT");
        let redirect_failure = env_err!("REDIRECTERR");
        let r = conn.execute("INSERT INTO email VALEUS $1", &[&email]);
        let redirect = match r {
            Ok(v) => {
                println!("Add to database succeeded with status {:?}", v);
                redirect_success
            },
            Err(e) => {
                println!("Add to database failed: {:?}", e);
                redirect_failure
            }
        };

        return res.redirect(&redirect[..]);
    });

    let bind = match env::var("BIND") {
        Ok(v) => v,
        Err(_) => "127.0.0.1:8080".to_string(),
    };

    let _ = app.listen(&bind[..]);
}
<commit_msg>Fix post -> get<commit_after>//#![feature(convert)]

#[macro_use]
extern crate nickel;
extern crate rustc_serialize;
extern crate hyper;
extern crate nickel_postgres;
extern crate postgres;
extern crate r2d2_postgres;
extern crate r2d2;
extern crate time;

use nickel::{Nickel, HttpRouter, QueryString};
use nickel::extensions::Redirect;
use nickel::status::StatusCode;
use rustc_serialize::json;
use hyper::Client;
use hyper::header::Connection;
use hyper::status::StatusClass;
use hyper::client::response::Response;
use std::io::Read;
use std::env;
use r2d2::{NopErrorHandler, PooledConnection};
use r2d2_postgres::{TlsMode, PostgresConnectionManager};
use nickel_postgres::{PostgresMiddleware, PostgresRequestExtensions};
use time::now;

#[derive(RustcDecodable, Debug)]
struct Data {
    data: User,
}

#[derive(RustcDecodable, Debug)]
struct User {
    id: i32,
    email: String,
    created_at: String,
    updated_at: String,
    first_name: String,
    last_name: String,
    major: String,
    shirt_size: String,
    dietary_restrictions: String,
    special_needs: Option<String>,
    date_of_birth: String,
    gender: String,
    phone_number: String,
    school: School,
}

#[derive(RustcDecodable, Debug)]
struct School {
    id: i32,
    name: String,
}

#[derive(RustcDecodable, Debug)]
struct TokenResp {
    access_token: String,
    token_type: String,
    scope: String,
    created_at: u64,
}

#[derive(RustcEncodable, Debug)]
struct Payload {
    channel: String,
    username: String,
    text: String,
    icon_emoji: String,
}

#[derive(Debug)]
enum ApiError {
    ClientError,
    ServerError,
}

#[derive(Debug)]
enum RequestError {
    Hyper(hyper::error::Error),
    Io(std::io::Error),
    JsonEnc(rustc_serialize::json::EncoderError),
    JsonDec(rustc_serialize::json::DecoderError),
    Api(ApiError),
}

// `env_err!(var, message)` gets `var` from the environment, and panics with
// `message` if that fails
// `env_err!(var)` gets `var` from the environment and panics with `"Failed to
// get env var $var"` if that fails
macro_rules! env_err {
    ( $var:expr, $error:expr ) => {
        env::var($var).expect($error)
    };
    ( $var:expr ) => {
        env_err!($var, &format!("Failed to get env var {}", $var))
    }
}

// Error handling code.  Expands to impl-ing From for enum_t from from_t to to_t
// See https://doc.rust-lang.org/book/error-handling.html for a full description
macro_rules! impl_from {
    ( $from_t:path, $to_t:path, $enum_t:path ) => {
        impl From<$from_t> for $enum_t {
            fn from(err: $from_t) -> $enum_t {
                $to_t(err)
            }
        }
    }
}

// All the impls for RequestError
impl_from!(hyper::error::Error, RequestError::Hyper, RequestError);
impl_from!(std::io::Error, RequestError::Io, RequestError);
impl_from!(rustc_serialize::json::DecoderError,
           RequestError::JsonDec,
           RequestError);
impl_from!(rustc_serialize::json::EncoderError,
           RequestError::JsonEnc,
           RequestError);
impl_from!(ApiError, RequestError::Api, RequestError);

// Checks for 4xx or 5xx errors and returns the appropriate ApiError
fn check_http_error(res: &Response) -> Result<(), ApiError> {
    match res.status.class() {
        StatusClass::ClientError => Err(ApiError::ClientError),
        StatusClass::ServerError => Err(ApiError::ServerError),
        _ => Ok(()),
    }
}

// Do the OAUTH stuff for my.mlh.io
// TODO: Something better about the long api urls
fn do_request(code: &str) -> Result<Data, RequestError> {
    let id = env_err!("ID");
    let secret = env_err!("SECRET");
    let redirect = env_err!("REDIRECT");

    let url = format!("https://my.mlh.io/oauth/token?client_id={}&\
                      client_secret={}&code={}&redirect_uri={}&\
                      grant_type=authorization_code",
                      id,
                      secret,
                      code,
                      redirect);

    let client = Client::new();
    let mut res = try!(client.post(&url)
        .header(Connection::close())
        .send());

    try!(check_http_error(&res));

    let mut body = String::new();
    try!(res.read_to_string(&mut body));

    let token: TokenResp = try!(json::decode(&body));
    let url2 = format!("https://my.mlh.io/api/v2/user?access_token={}",
                       token.access_token);

    res = try!(client.get(&url2)
        .header(Connection::close())
        .send());

    try!(check_http_error(&res));

    body = String::new();
    try!(res.read_to_string(&mut body));

    let person_data: Data = try!(json::decode(&body));

    Ok(person_data)
}

// Send a message to slack when a new user signs up
fn slack_send(user: User) -> Result<(), RequestError> {
    let url = env_err!("SLACKURL");
    let client = Client::new();
    let payload = Payload {
        channel: "#signups".to_string(),
        username: "Signup bot".to_string(),
        icon_emoji: ":hackcwru:".to_string(),
        text: format!("{}, a {} major from {}, has signed up!",
                      user.first_name,
                      user.major,
                      user.school.name),
    };
    let payload_str = try!(json::encode(&payload));
    let res = try!(client.post(&url)
        .body(&payload_str)
        .send());

    try!(check_http_error(&res));

    Ok(())
}

// Create the table if it doesn't exist.  Runs on each startup
fn create_table(conn: PooledConnection<PostgresConnectionManager>) {
    let _r =
        conn.execute("CREATE TABLE IF NOT EXISTS person (
                id SERIAL PRIMARY KEY,
                email VARCHAR NOT NULL,
                created_at VARCHAR NOT NULL,
                updated_at VARCHAR NOT NULL,
                first_name VARCHAR NOT NULL,
                last_name VARCHAR NOT NULL,
                graduation VARCHAR,
                major VARCHAR NOT NULL,
                shirt_size VARCHAR NOT NULL,
                dietary_restrictions VARCHAR NOT NULL,
                special_needs VARCHAR,
                date_of_birth VARCHAR NOT NULL,
                gender VARCHAR NOT NULL,
                phone_number VARCHAR NOT NULL,
                school_id integer,
                school_name VARCHAR
                )",
            &[]
        );
    let _r = conn.execute("CREATE TABLE IF NOT EXISTS email (email VARCHAR \
                          PRIMARY KEY)",
                          &[]);
    let _r = conn.execute("ALTER TABLE person ADD COLUMN year integer \
                          NOT NULL DEFAULT 2016",
                          &[]);
    let _r = conn.execute("ALTER TABLE person ALTER COLUMN graduation \
                          DROP NOT NULL",
                          &[]);
    let _r = conn.execute(
            "ALTER TABLE person ADD COLUMN signup_time VARCHAR", &[]
        );
    let _r = conn.execute(
            "ALTER TABLE person ADD COLUMN signed_in
            BOOLEAN NOT NULL DEFAULT FALSE",
        &[]
        );
    let _r = conn.execute(
            "ALTER TABLE person ADD COLUMN signed_in_time VARCHAR", &[]
        );

    let _r = conn.execute(
            "ALTER TABLE person DROP CONSTRAINT person_pkey", &[]
        );

    let _r = conn.execute(
            "ALTER TABLE person ADD PRIMARY KEY (id, year)", &[]
        );
}

fn main() {
    let mut app = Nickel::new();

    let postgres_url = env_err!("DATABASE");
    let dbpool =
        PostgresMiddleware::new(&*postgres_url, TlsMode::None, 5, Box::new(NopErrorHandler))
            .expect("Failed to start PostgresMiddleware");

    create_table(dbpool.pool.clone().get().unwrap());
    app.utilize(dbpool);

    app.get("/callback", middleware! { |request, mut response|
        let conn = request.db_conn();
        let redirect_success = env_err!("FINALREDIRECT");
        let redirect_failure = env_err!("REDIRECTERR");
        let year = env_err!("YEAR").parse::<i32>().unwrap();
        let code = match request.query().get("code") {
            Some(s) => s,
            None => {
                println!("No code, quitting");
                return response.error(StatusCode::BadRequest, "Failed");
            }
        };
        let user_data = match do_request(code) {
            Ok(s) => s,
            Err(e) => {
                println!("Get user data failed with error: {:?}", e);
                return response
                    .error(StatusCode::InternalServerError, "Failed");
            }
        }.data;

        let now = now();
        let now_s = format!("{}", now.rfc3339());
        // TODO: make this a function
        let r = conn.execute(
                "INSERT INTO person (id, email, created_at, updated_at,
                first_name, last_name, major, shirt_size,
                dietary_restrictions, special_needs, date_of_birth, gender,
                phone_number, school_id, school_name, year, signup_time) VALUES
                ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,
                $15, $16, $17)",
                &[&user_data.id, &user_data.email, &user_data.created_at,
                  &user_data.updated_at, &user_data.first_name,
                  &user_data.last_name, &user_data.major,
                  &user_data.shirt_size, &user_data.dietary_restrictions,
                  &user_data.special_needs, &user_data.date_of_birth,
                  &user_data.gender, &user_data.phone_number,
                  &user_data.school.id, &user_data.school.name, &year, &now_s]
            );
        let redirect = match r {
            Ok(v) => {
                println!("Add to database succeeded with status {:?}", v);
                match slack_send(user_data) {
                    Ok(_) => println!("Slack send worked"),
                    Err(e) => println!("Slack send failed with error: {:?}", e)
                }
                redirect_success
            },
            Err(e) => {
                println!("Add to database failed: {:?}", e);
                redirect_failure
            }
        };

        return response.redirect(&redirect[..]);
    });

    app.get("/start", middleware! { |_req, response|
        let id = env_err!("ID");
        let redirect = env_err!("REDIRECT");
        return response.redirect(
            format!(
                    "http://my.mlh.io/oauth/authorize?client_id={}&\
                    redirect_uri={}&response_type=code",
                    id, redirect
                )
            );
    });

    app.get("/email", middleware! { |req, res|
        let conn = req.db_conn();
        let email = req.param("email").unwrap();
        let redirect_success = env_err!("FINALREDIRECT");
        let redirect_failure = env_err!("REDIRECTERR");
        let r = conn.execute("INSERT INTO email VALEUS $1", &[&email]);
        let redirect = match r {
            Ok(v) => {
                println!("Add to database succeeded with status {:?}", v);
                redirect_success
            },
            Err(e) => {
                println!("Add to database failed: {:?}", e);
                redirect_failure
            }
        };

        return res.redirect(&redirect[..]);
    });

    let bind = match env::var("BIND") {
        Ok(v) => v,
        Err(_) => "127.0.0.1:8080".to_string(),
    };

    let _ = app.listen(&bind[..]);
}
<|endoftext|>


<commit_before>extern crate cargo;
extern crate tabwriter;

extern crate serde;
#[macro_use]
extern crate serde_derive;

use cargo::core::Package;
use cargo::core::Workspace;
use cargo::ops;
use cargo::util::Config;

use std::env;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::path;

#[derive(Deserialize)]
struct Options {
    flag_verbose: u32,
    flag_quiet: Option<bool>,
    flag_color: Option<String>,
    flag_frozen: bool,
    flag_locked: bool,
    flag_unstable: Vec<String>,
}

#[derive(Debug)]
enum Licenses {
    Licenses(Vec<String>),
    File(String),
    Missing,
}

impl fmt::Display for Licenses {
    fn fmt(self: &Self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            Licenses::File(_) => Ok(write!(f, "Specified in license file")?),
            Licenses::Missing => Ok(write!(f, "Missing")?),
            Licenses::Licenses(ref lic_names) => Ok(write!(f, "{}", lic_names.join(", "))?),
        }
    }
}

const USAGE_STR: &'static str = r#"
Produce Bill of Materials from Cargo project's depencies
Usage:
    cargo bom [options]
Options:
    -h, --help               Print this message
    -V, --version            Print version information
    -v, --verbose ...        Use verbose output
    --frozen                 Require Cargo.lock and cache are up to date
    --locked                 Require Cargo.lock is up to date
    --color WHEN             Coloring: auto, always, never
This cargo subcommand will produce Bill of Materials (BOM) from crates the
project depends on.
"#;

fn main() {
    let config = Config::default().expect("cargo config");
    let args: Vec<String> = env::args().collect();

    let res = cargo::call_main_without_stdin(real_main, &config, USAGE_STR, &args, false);
    if let Err(e) = res {
        cargo::exit_with_error(e, &mut *config.shell());
    }
}

fn real_main(options: Options, config: &Config) -> cargo::CliResult {
    config.configure(
        options.flag_verbose,
        options.flag_quiet,
        &options.flag_color,
        options.flag_frozen,
        options.flag_locked,
        &options.flag_unstable,
    )?;

    let manifest = config.cwd().join("Cargo.toml");
    let ws = Workspace::new(&manifest, config)?;
    let members: Vec<&Package> = ws.members().collect();
    let (package_ids, resolve) = ops::resolve_ws(&ws)?;

    let mut packages = Vec::new();
    for package_id in resolve.iter() {
        let package = package_ids.get(package_id)?;
        if members.contains(&package) {
            // Skip listing our own packages in our workspace
            continue;
        }
        let name = package.name().to_owned();
        let version = format!("{}", package.version());
        let licenses = format!("{}", package_licenses(package));
        let license_files = package_license_files(package);
        packages.push((name, version, licenses, license_files));
    }

    packages.sort();

    let mut tw = tabwriter::TabWriter::new(io::stdout());

    writeln!(tw, "Name\t| Version\t| Licenses").expect("write");

    for (name, version, licenses, _) in packages.clone() {
        writeln!(tw, "{}\t| {}\t| {}", &name, &version, &licenses).expect("write");
    }

    tw.flush().expect("tw.flush"); // TabWriter flush() makes the actual write to stdout.

    println!("");

    for (name, version, _, license_files) in packages {
        if license_files.is_empty() {
            continue;
        }

        println!("-----BEGIN {} {} LICENSES-----", name, version);

        let mut buf = String::new();
        for file in license_files {
            let mut fs = std::fs::File::open(file).expect("File::open");
            fs.read_to_string(&mut buf).expect("read_to_string");
            println!("{}", buf);
            buf.clear();
        }

        println!("-----END {} {} LICENSES-----", name, version);
        println!("");
    }

    Ok(())
}

fn package_licenses(package: &Package) -> Licenses {
    let metadata = package.manifest().metadata();

    if let Some(ref license_str) = metadata.license {
        let mut licenses: Vec<String> = license_str
            .split('/')
            .map(|s| s.trim().to_owned())
            .collect();
        licenses.sort();
        licenses.dedup();
        return Licenses::Licenses(licenses);
    }

    if let Some(ref license_file) = metadata.license_file {
        return Licenses::File(license_file.to_owned());
    }

    Licenses::Missing
}

fn package_license_files(package: &Package) -> Vec<path::PathBuf> {
    let mut result = Vec::new();

    if let Some(path) = package.manifest_path().parent() {
        for entry in path.read_dir().expect("read_dir call failed") {
            if let Ok(entry) = entry {
                if let Ok(name) = entry.file_name().into_string() {
                    if name.starts_with("LICENSE") {
                        result.push(entry.path())
                    }
                }
            }
        }
    }

    result
}
<commit_msg>Fix Clippy nags<commit_after>extern crate cargo;
extern crate tabwriter;

extern crate serde;
#[macro_use]
extern crate serde_derive;

use cargo::core::Package;
use cargo::core::Workspace;
use cargo::ops;
use cargo::util::Config;

use std::env;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::path;

#[derive(Deserialize)]
struct Options {
    flag_verbose: u32,
    flag_quiet: Option<bool>,
    flag_color: Option<String>,
    flag_frozen: bool,
    flag_locked: bool,
    flag_unstable: Vec<String>,
}

#[derive(Debug)]
enum Licenses {
    Licenses(Vec<String>),
    File(String),
    Missing,
}

impl fmt::Display for Licenses {
    fn fmt(self: &Self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            Licenses::File(_) => Ok(write!(f, "Specified in license file")?),
            Licenses::Missing => Ok(write!(f, "Missing")?),
            Licenses::Licenses(ref lic_names) => Ok(write!(f, "{}", lic_names.join(", "))?),
        }
    }
}

const USAGE_STR: &str = r#"
Produce Bill of Materials from Cargo project's depencies
Usage:
    cargo bom [options]
Options:
    -h, --help               Print this message
    -V, --version            Print version information
    -v, --verbose ...        Use verbose output
    --frozen                 Require Cargo.lock and cache are up to date
    --locked                 Require Cargo.lock is up to date
    --color WHEN             Coloring: auto, always, never
This cargo subcommand will produce Bill of Materials (BOM) from crates the
project depends on.
"#;

fn main() {
    let config = Config::default().expect("cargo config");
    let args: Vec<String> = env::args().collect();

    let res = cargo::call_main_without_stdin(real_main, &config, USAGE_STR, &args, false);
    if let Err(e) = res {
        cargo::exit_with_error(e, &mut *config.shell());
    }
}

fn real_main(options: Options, config: &Config) -> cargo::CliResult {
    config.configure(
        options.flag_verbose,
        options.flag_quiet,
        &options.flag_color,
        options.flag_frozen,
        options.flag_locked,
        &options.flag_unstable,
    )?;

    let manifest = config.cwd().join("Cargo.toml");
    let ws = Workspace::new(&manifest, config)?;
    let members: Vec<&Package> = ws.members().collect();
    let (package_ids, resolve) = ops::resolve_ws(&ws)?;

    let mut packages = Vec::new();
    for package_id in resolve.iter() {
        let package = package_ids.get(package_id)?;
        if members.contains(&package) {
            // Skip listing our own packages in our workspace
            continue;
        }
        let name = package.name().to_owned();
        let version = format!("{}", package.version());
        let licenses = format!("{}", package_licenses(package));
        let license_files = package_license_files(package);
        packages.push((name, version, licenses, license_files));
    }

    packages.sort();

    let mut tw = tabwriter::TabWriter::new(io::stdout());

    writeln!(tw, "Name\t| Version\t| Licenses").expect("write");

    for (name, version, licenses, _) in packages.clone() {
        writeln!(tw, "{}\t| {}\t| {}", &name, &version, &licenses).expect("write");
    }

    tw.flush().expect("tw.flush"); // TabWriter flush() makes the actual write to stdout.

    println!();

    for (name, version, _, license_files) in packages {
        if license_files.is_empty() {
            continue;
        }

        println!("-----BEGIN {} {} LICENSES-----", name, version);

        let mut buf = String::new();
        for file in license_files {
            let mut fs = std::fs::File::open(file).expect("File::open");
            fs.read_to_string(&mut buf).expect("read_to_string");
            println!("{}", buf);
            buf.clear();
        }

        println!("-----END {} {} LICENSES-----", name, version);
        println!();
    }

    Ok(())
}

fn package_licenses(package: &Package) -> Licenses {
    let metadata = package.manifest().metadata();

    if let Some(ref license_str) = metadata.license {
        let mut licenses: Vec<String> = license_str
            .split('/')
            .map(|s| s.trim().to_owned())
            .collect();
        licenses.sort();
        licenses.dedup();
        return Licenses::Licenses(licenses);
    }

    if let Some(ref license_file) = metadata.license_file {
        return Licenses::File(license_file.to_owned());
    }

    Licenses::Missing
}

fn package_license_files(package: &Package) -> Vec<path::PathBuf> {
    let mut result = Vec::new();

    if let Some(path) = package.manifest_path().parent() {
        for entry in path.read_dir().expect("read_dir call failed") {
            if let Ok(entry) = entry {
                if let Ok(name) = entry.file_name().into_string() {
                    if name.starts_with("LICENSE") {
                        result.push(entry.path())
                    }
                }
            }
        }
    }

    result
}
<|endoftext|>


<commit_before>#![feature(plugin)]
#![plugin(docopt_macros)]

#![feature(test)]

extern crate jsrs_common;
extern crate jsrs_parser;
extern crate french_press;

extern crate walkdir;
extern crate unescape;
extern crate rustyline;
extern crate rustc_serialize;
extern crate docopt;

extern crate test;

mod js_error;
mod var;

mod eval;
mod native;
mod number;
mod bench;
mod preprocess;

use std::cell::RefCell;
use std::fs::{File, metadata};
use std::io::{self, BufReader};
use std::io::prelude::*;
use std::path::Path;
use std::process::exit;
use std::rc::Rc;

use rustyline::error::ReadlineError;
use rustyline::Editor;
use walkdir::WalkDir;

use jsrs_common::types::js_var::JsPtrEnum;
use french_press::{init_gc, ScopeManager};

use eval::eval_string;
use native::add_pervasives;
use preprocess::clean_string;

docopt!(Args derive Debug, "
js.rs - a javascript interpreter

Usage:
jsrs
jsrs <file>
jsrs --test
");

fn eval_file(filename: String, debug: bool, should_repl: bool,
             scope_manager: Rc<RefCell<ScopeManager>>) -> js_error::Result<()> {
    if debug {
        println!("Reading from \"{}\"", filename);
    }

    let path = Path::new(&filename);
    let file = File::open(&path)
        .expect(&format!("Cannot open \"{}\": no such file or directory", filename));
    let file_buffer = BufReader::new(file);

    let mut line_builder = String::new();
    let mut braces = Vec::new();

    let mut file_iter = file_buffer.lines();
    loop {
        if let Some(line) = file_iter.next() {
            let input = String::from(line.expect(&format!("Cannot read from {}", filename))
                                         .trim());
            if let Some(input) = clean_string(input) {
                let mut last = '\0';
                // Match braces to see if we should wait for more input
                for c in input.chars() {
                    if c == '(' {
                        braces.push('(');
                    } else if c == '{' {
                        braces.push('{');
                    } else if c == '*' && last == '/' {
                        braces.push('/');
                    } else if c == ')' {
                        if braces.pop() != Some('(') {
                            panic!("parse error: unexpected token {}", c);
                        }
                    } else if c == '}' {
                        if braces.pop() != Some('{') {
                            panic!("parse error: unexpected token {}", c);
                        }
                    } else if c == '/' && last == '*' {
                        if braces.pop() != Some('/') {
                            panic!("parse error: unexpected token {}", c);
                        }
                    }
                    last = c;
                }

                line_builder.push_str(&input);

                if braces.len() == 0 {
                    if let Some(js_string) = clean_string(line_builder.clone()) {
                        line_builder = String::new();
                        if debug {
                            println!("\n{}", js_string);
                        }

                        let ret = try!(eval_string(&js_string, scope_manager.clone()));
                        if debug {
                            println!("=> {:?}", ret);
                        }
                    }
                }
            }
        } else {
            break;
        }
    }
    if should_repl {
        repl(scope_manager);
    }
    Ok(())
}

fn test_dir(dir_name: String) {
    for entry in WalkDir::new(dir_name) {
        let entry = entry.unwrap();
        if !entry.path().is_dir() {
            let entry_path = entry.path().display().to_string();
            let scope_manager = Rc::new(RefCell::new(init_gc()));
            add_pervasives(scope_manager.clone());
            match eval_file(entry_path.clone(), false, false, scope_manager.clone()) {
                Ok(_) => {
                    println!("{}: {}", entry_path, "OK");
                }
                Err(e) => {
                    println!("{}: {}", entry_path, e);
                }
            }
        }
    }
}

fn repl(scope_manager: Rc<RefCell<ScopeManager>>) -> i32 {
    let mut rl = Editor::new();
    let mut stderr = io::stderr();

    if metadata(".history").is_ok() && rl.load_history(".history").is_err() {
        writeln!(stderr, "Error: unable to load history on startup").unwrap();
    }

    loop {
        // prompt
        let readline = rl.readline(">> ");

        match readline {
            Ok(line) => {
                rl.add_history_entry(&line);
                let input = String::from(line.trim());
                clean_string(input).map(|input| {
                    rl.add_history_entry(&input);

                    match eval_string(&input, scope_manager.clone()) {
                        Ok((var, ptr)) => {
                            match ptr {
                                Some(JsPtrEnum::JsSym(s)) => println!("=> Symbol({:?})", s),
                                Some(JsPtrEnum::JsStr(s)) => println!("=> {:?}", s.text),
                                _ => println!("=> {:?}", var.t),
                            }
                        },
                        Err(e) => {
                            println!("{:?}", e);
                        }
                    }
                });
            },
            Err(ReadlineError::Interrupted) => {
                if rl.save_history(".history").is_err() {
                    writeln!(stderr, "Error: unable to save history on exit").unwrap();
                    return 2;
                }
                return 1;
            },
            Err(ReadlineError::Eof) => {
                if rl.save_history(".history").is_err() {
                    writeln!(stderr, "Error: unable to save history on exit").unwrap();
                    return 2;
                }
                break
            },
            Err(err) => {
                println!("Error: {:?}", err);

                if rl.save_history(".history").is_err() {
                    writeln!(stderr, "Error: unable to save history on exit").unwrap();
                    return 2;
                }
                return 3;
            }
        }
    }
    0
}

fn main() {
    let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
    if args.flag_test {
        let dir_name = "sputnik/11.6_Additive_Operators";

        test_dir(String::from(dir_name))
    } else {
        let scope_manager = Rc::new(RefCell::new(init_gc()));
        add_pervasives(scope_manager.clone());

        if args.arg_file == "" {
            let ret = repl(scope_manager.clone());
            exit(ret)
        } else {
            eval_file(args.arg_file, true, true, scope_manager.clone());
        }
    }
}
<commit_msg>Test all sputnik tests, not a subdirectory<commit_after>#![feature(plugin)]
#![plugin(docopt_macros)]

#![feature(test)]

extern crate jsrs_common;
extern crate jsrs_parser;
extern crate french_press;

extern crate walkdir;
extern crate unescape;
extern crate rustyline;
extern crate rustc_serialize;
extern crate docopt;

extern crate test;

mod js_error;
mod var;

mod eval;
mod native;
mod number;
mod bench;
mod preprocess;

use std::cell::RefCell;
use std::fs::{File, metadata};
use std::io::{self, BufReader};
use std::io::prelude::*;
use std::path::Path;
use std::process::exit;
use std::rc::Rc;

use rustyline::error::ReadlineError;
use rustyline::Editor;
use walkdir::WalkDir;

use jsrs_common::types::js_var::JsPtrEnum;
use french_press::{init_gc, ScopeManager};

use eval::eval_string;
use native::add_pervasives;
use preprocess::clean_string;

docopt!(Args derive Debug, "
js.rs - a javascript interpreter

Usage:
jsrs
jsrs <file>
jsrs --test
");

fn eval_file(filename: String, debug: bool, should_repl: bool,
             scope_manager: Rc<RefCell<ScopeManager>>) -> js_error::Result<()> {
    if debug {
        println!("Reading from \"{}\"", filename);
    }

    let path = Path::new(&filename);
    let file = File::open(&path)
        .expect(&format!("Cannot open \"{}\": no such file or directory", filename));
    let file_buffer = BufReader::new(file);

    let mut line_builder = String::new();
    let mut braces = Vec::new();

    let mut file_iter = file_buffer.lines();
    loop {
        if let Some(line) = file_iter.next() {
            let input = String::from(line.expect(&format!("Cannot read from {}", filename))
                                         .trim());
            if let Some(input) = clean_string(input) {
                let mut last = '\0';
                // Match braces to see if we should wait for more input
                for c in input.chars() {
                    if c == '(' {
                        braces.push('(');
                    } else if c == '{' {
                        braces.push('{');
                    } else if c == '*' && last == '/' {
                        braces.push('/');
                    } else if c == ')' {
                        if braces.pop() != Some('(') {
                            panic!("parse error: unexpected token {}", c);
                        }
                    } else if c == '}' {
                        if braces.pop() != Some('{') {
                            panic!("parse error: unexpected token {}", c);
                        }
                    } else if c == '/' && last == '*' {
                        if braces.pop() != Some('/') {
                            panic!("parse error: unexpected token {}", c);
                        }
                    }
                    last = c;
                }

                line_builder.push_str(&input);

                if braces.len() == 0 {
                    if let Some(js_string) = clean_string(line_builder.clone()) {
                        line_builder = String::new();
                        if debug {
                            println!("\n{}", js_string);
                        }

                        let ret = try!(eval_string(&js_string, scope_manager.clone()));
                        if debug {
                            println!("=> {:?}", ret);
                        }
                    }
                }
            }
        } else {
            break;
        }
    }
    if should_repl {
        repl(scope_manager);
    }
    Ok(())
}

fn test_dir(dir_name: String) {
    for entry in WalkDir::new(dir_name) {
        let entry = entry.unwrap();
        if !entry.path().is_dir() {
            let entry_path = entry.path().display().to_string();
            let scope_manager = Rc::new(RefCell::new(init_gc()));
            add_pervasives(scope_manager.clone());
            match eval_file(entry_path.clone(), false, false, scope_manager.clone()) {
                Ok(_) => {
                    println!("{}: {}", entry_path, "OK");
                }
                Err(e) => {
                    println!("{}: {}", entry_path, e);
                }
            }
        }
    }
}

fn repl(scope_manager: Rc<RefCell<ScopeManager>>) -> i32 {
    let mut rl = Editor::new();
    let mut stderr = io::stderr();

    if metadata(".history").is_ok() && rl.load_history(".history").is_err() {
        writeln!(stderr, "Error: unable to load history on startup").unwrap();
    }

    loop {
        // prompt
        let readline = rl.readline(">> ");

        match readline {
            Ok(line) => {
                rl.add_history_entry(&line);
                let input = String::from(line.trim());
                clean_string(input).map(|input| {
                    rl.add_history_entry(&input);

                    match eval_string(&input, scope_manager.clone()) {
                        Ok((var, ptr)) => {
                            match ptr {
                                Some(JsPtrEnum::JsSym(s)) => println!("=> Symbol({:?})", s),
                                Some(JsPtrEnum::JsStr(s)) => println!("=> {:?}", s.text),
                                _ => println!("=> {:?}", var.t),
                            }
                        },
                        Err(e) => {
                            println!("{:?}", e);
                        }
                    }
                });
            },
            Err(ReadlineError::Interrupted) => {
                if rl.save_history(".history").is_err() {
                    writeln!(stderr, "Error: unable to save history on exit").unwrap();
                    return 2;
                }
                return 1;
            },
            Err(ReadlineError::Eof) => {
                if rl.save_history(".history").is_err() {
                    writeln!(stderr, "Error: unable to save history on exit").unwrap();
                    return 2;
                }
                break
            },
            Err(err) => {
                println!("Error: {:?}", err);

                if rl.save_history(".history").is_err() {
                    writeln!(stderr, "Error: unable to save history on exit").unwrap();
                    return 2;
                }
                return 3;
            }
        }
    }
    0
}

fn main() {
    let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
    if args.flag_test {
        let dir_name = "sputnik";

        test_dir(String::from(dir_name))
    } else {
        let scope_manager = Rc::new(RefCell::new(init_gc()));
        add_pervasives(scope_manager.clone());

        if args.arg_file == "" {
            let ret = repl(scope_manager.clone());
            exit(ret)
        } else {
            eval_file(args.arg_file, true, true, scope_manager.clone());
        }
    }
}
<|endoftext|>


<commit_before>#![feature(custom_attribute, custom_derive, plugin)]
#![plugin(serde_macros)]

extern crate hyper;
extern crate serde;

mod entity;
mod error;

use entity::ZipResult;
use error::ZipError;
use hyper::Client;
use serde::json;
use std::io::Read;

fn main() {
    let result = std::env::args().nth(1).ok_or(ZipError::Input)
        .and_then(|candidate| query(&mut Client::new(), candidate))
        .and_then(|(candidate, response)| parse_result(candidate, response));

    match result {
        Ok(zip_result) => println!("{}", zip_result),
        Err(e) => println!("{}", e),
    }
}

fn query(client: &mut Client, candidate: String) -> Result<(String, String), ZipError> {
    match client.get(&format!("http://api.zippopotam.us/us/{}", candidate)).send() {
        Ok(mut res) => Ok((candidate, read_response(&mut res))),
        _ => Err(ZipError::API),
    }
}

#[allow(unused)]
fn read_response(response: &mut hyper::client::response::Response) -> String {
    let mut buf = String::new();
    response.read_to_string(&mut buf);
    buf
}

fn parse_result(candidate: String, result: String) -> Result<ZipResult, ZipError> {
    match json::from_str(&result) {
        Ok(result) => Ok(result),
        Err(_) => Err(ZipError::Invalid(candidate)),
    }
}
<commit_msg>Use return statement<commit_after>#![feature(custom_attribute, custom_derive, plugin)]
#![plugin(serde_macros)]

extern crate hyper;
extern crate serde;

mod entity;
mod error;

use entity::ZipResult;
use error::ZipError;
use hyper::Client;
use serde::json;
use std::io::Read;

fn main() {
    let result = std::env::args().nth(1).ok_or(ZipError::Input)
        .and_then(|candidate| query(candidate))
        .and_then(|(candidate, response)| parse_result(candidate, response));

    match result {
        Ok(zip_result) => println!("{}", zip_result),
        Err(e) => println!("{}", e),
    }
}

fn query(candidate: String) -> Result<(String, String), ZipError> {
    let mut client = Client::new();

    // return statement -> expression as soon as rustc gets fixed
    return match client.get(&format!("http://api.zippopotam.us/us/{}", candidate)).send() {
        Ok(mut res) => Ok((candidate, read_response(&mut res))),
        _ => Err(ZipError::API),
    };
}

#[allow(unused)]
fn read_response(response: &mut hyper::client::response::Response) -> String {
    let mut buf = String::new();
    response.read_to_string(&mut buf);
    buf
}

fn parse_result(candidate: String, result: String) -> Result<ZipResult, ZipError> {
    match json::from_str(&result) {
        Ok(result) => Ok(result),
        Err(_) => Err(ZipError::Invalid(candidate)),
    }
}
<|endoftext|>


<commit_before>use crate::repository::Repository;
use clap::{crate_version, App, Arg, SubCommand};
use std::path::PathBuf;
use std::process::exit;

mod repository;

const UPDATE_COMMAND: &str = "update";

fn main() {
    let matches = App::new("alfred-gitignore")
        .version(crate_version!())
        .author("Jan David <jandavid@6a64.com>")
        .about("An Alfred workflow to generate .gitignore files")
        .arg(
            Arg::with_name("repository")
                .help("Provide a custom directory for development and testing")
                .short("r")
                .long("repository")
                .takes_value(true),
        )
        .subcommand(
            SubCommand::with_name(UPDATE_COMMAND)
                .about("Download the latest .gitignore templates from GitHub"),
        )
        .get_matches();

    let _repository = initialize_repository(matches.value_of("repository"));
}

fn initialize_repository(path: Option<&str>) -> Repository {
    let repository_path = match path {
        Some(path) => PathBuf::from(path),
        None => match alfred::env::workflow_data() {
            Some(path) => path,
            None => {
                eprintln!("Failed to set up data directory. Either run the CLI through Alfred, or pass the --repository option.");
                exit(1);
            }
        },
    };

    match Repository::new(repository_path) {
        Ok(repository) => repository,
        Err(error) => {
            eprintln!("Failed to initialize repository with the following error:");
            eprintln!("{}", error);
            exit(1);
        }
    }
}
<commit_msg>Add function that prints error and exits program<commit_after>use crate::repository::Repository;
use alfred::ItemBuilder;
use clap::{crate_version, App, Arg, SubCommand};
use std::io::{stdout, Error, ErrorKind};
use std::path::PathBuf;
use std::process::exit;

mod repository;

const UPDATE_COMMAND: &str = "update";

fn main() {
    let matches = App::new("alfred-gitignore")
        .version(crate_version!())
        .author("Jan David <jandavid@6a64.com>")
        .about("An Alfred workflow to generate .gitignore files")
        .arg(
            Arg::with_name("repository")
                .help("Provide a custom directory for development and testing")
                .short("r")
                .long("repository")
                .takes_value(true),
        )
        .subcommand(
            SubCommand::with_name(UPDATE_COMMAND)
                .about("Download the latest .gitignore templates from GitHub"),
        )
        .get_matches();

    let _repository = initialize_repository(matches.value_of("repository"));
}

fn initialize_repository(path: Option<&str>) -> Repository {
    let repository_path = match path {
        Some(path) => PathBuf::from(path),
        None => match alfred::env::workflow_data() {
            Some(path) => path,
            None => exit_with_error(&Error::new(
                ErrorKind::NotFound,
                "Alfred did not provide a data directory to the workflow",
            )),
        },
    };

    match Repository::new(repository_path) {
        Ok(repository) => repository,
        Err(error) => exit_with_error(&error),
    }
}

fn exit_with_error(error: &Error) -> ! {
    alfred::json::write_items(
        stdout(),
        &[ItemBuilder::new("Error running gitignore workflow")
            .subtitle(error.to_string())
            .into_item()],
    )
    .unwrap();

    exit(1);
}
<|endoftext|>


<commit_before>extern crate regex;
extern crate irc;

mod starred_message;

use irc::client::prelude::*;
use std::default::Default;
use starred_message::StarredMessage;

fn main() {
	let server = IrcServer::from_config(Config{
		owners   : Some(vec!["nabijaczleweli".to_string()]),
		nickname : Some("NabBot".to_string()),
		username : Some("NabBot".to_string()),
		realname : Some("наб's IRC bot".to_string()),
		server   : Some("chat.freenode.net".to_string()),
		use_ssl  : Some(true),
		channels : Some(vec!["#loungecpp".to_string()]),
		user_info: Some("наб's IRC bot".to_string()),
		..Default::default()
	}).unwrap();
	server.identify().unwrap();

	let mut starred: Vec<StarredMessage> = Vec::new();

	for message in server.iter() {
		if let Ok(message) = message {
			let sender = message.get_source_nickname().map(String::from);

			match Command::from_message_io(Ok(message)) {
				Ok(Command::JOIN(_, _, _))        => println!("I'm in"),
				Ok(Command::PRIVMSG(target, msg)) => {
					let to_self = target == "NabBot";

					if (to_self && msg == "Navaer") || msg == "Navaer, NabBot" {
						server.send_quit("Mára mesta").unwrap();
					} else if to_self && msg.starts_with("add ") {
						if let Some(star_message) = StarredMessage::from_message_content(&msg[4..], sender) {
							if match starred.iter_mut().find(|fmsg| (&fmsg.sender, &fmsg.message) == (&star_message.sender, &star_message.message)) {
								Some(ref mut existing_message) => {
									existing_message.stars += 1;
									existing_message.starrers.extend(star_message.starrers.clone());
									false
								},
								None => true,
							} {
								starred.push(star_message);  // Can't do it in match arm because it'd borrow starred as &mut twice
							}
						}
					} else if to_self && msg.starts_with("remove ") {
						if let Some(star_message) = StarredMessage::from_message_content(&msg[7..], sender) {
							if let Some(index) = match starred.iter_mut().enumerate().find(
								|fmsg| (&fmsg.1.sender, &fmsg.1.message) == (&star_message.sender, &star_message.message)
							) {
								Some((idx, ref mut existing_message)) =>
									if let Some(starrer_pos) = existing_message.starrers.iter().position(|starrer| starrer == &existing_message.starrers[0]) {
										existing_message.stars -= 1;
										existing_message.starrers.swap_remove(starrer_pos);
										Some(idx)
									} else {
										None
									},
								None => None,
							} {
								starred.swap_remove(index);  // Can't do it in match arm because it'd borrow starred as &mut twice
							}
						}
					} else if to_self && msg == "help" && sender.is_some() {
						let sender = &*&sender.unwrap();

						server.send_notice(sender, r#"Cummands:"#).unwrap();
						server.send_notice(sender, r#"  "add <" username ">" message content -- add your star to a message"#).unwrap();
						server.send_notice(sender, r#"  "help" -- send this help notice to sender"#).unwrap();
						server.send_notice(sender, r#"  "board" -- pretty-print the starboard, snackchat-style"#).unwrap();
						server.send_notice(sender, r#"  "dump" -- dump all star data to sender"#).unwrap();
						server.send_notice(sender, r#"Execute via sending a PRIVMSG (as by "/msg") to NabBot"#).unwrap();
					} else if to_self && msg == "board" && sender.is_some() {
						let sender = &*&sender.unwrap();
						let mut sorted_stars = starred.clone();
						sorted_stars.sort_by(|lhs, rhs| lhs.stars.cmp(&rhs.stars));

						for message in sorted_stars.iter().take(10) {
							server.send_notice(sender, &*&format!("{}", message)).unwrap();
						}
					} else if to_self && msg == "dump" && sender.is_some() {
						server.send_privmsg(&*&sender.unwrap(), &*&format!("{:?}", starred)).unwrap();
					}
				}
				_ => (),
			}
		}
	}
}
<commit_msg>Add levels to help command<commit_after>extern crate regex;
extern crate irc;

mod starred_message;

use irc::client::prelude::*;
use std::default::Default;
use starred_message::StarredMessage;

fn main() {
	let server = IrcServer::from_config(Config{
		owners   : Some(vec!["nabijaczleweli".to_string()]),
		nickname : Some("NabBot".to_string()),
		username : Some("NabBot".to_string()),
		realname : Some("наб's IRC bot".to_string()),
		server   : Some("chat.freenode.net".to_string()),
		use_ssl  : Some(true),
		channels : Some(vec!["#loungecpp".to_string()]),
		user_info: Some("наб's IRC bot".to_string()),
		..Default::default()
	}).unwrap();
	server.identify().unwrap();

	let mut starred: Vec<StarredMessage> = Vec::new();

	for message in server.iter() {
		if let Ok(message) = message {
			let sender = message.get_source_nickname().map(String::from);

			match Command::from_message_io(Ok(message)) {
				Ok(Command::JOIN(_, _, _))        => println!("I'm in"),
				Ok(Command::PRIVMSG(target, msg)) => {
					let to_self = target == "NabBot";

					if (to_self && msg == "Navaer") || msg == "Navaer, NabBot" {
						server.send_quit("Mára mesta").unwrap();
					} else if to_self && msg.starts_with("add ") {
						if let Some(star_message) = StarredMessage::from_message_content(&msg[4..], sender) {
							if match starred.iter_mut().find(|fmsg| (&fmsg.sender, &fmsg.message) == (&star_message.sender, &star_message.message)) {
								Some(ref mut existing_message) => {
									existing_message.stars += 1;
									existing_message.starrers.extend(star_message.starrers.clone());
									false
								},
								None => true,
							} {
								starred.push(star_message);  // Can't do it in match arm because it'd borrow starred as &mut twice
							}
						}
					} else if to_self && msg.starts_with("remove ") {
						if let Some(star_message) = StarredMessage::from_message_content(&msg[7..], sender) {
							if let Some(index) = match starred.iter_mut().enumerate().find(
								|fmsg| (&fmsg.1.sender, &fmsg.1.message) == (&star_message.sender, &star_message.message)
							) {
								Some((idx, ref mut existing_message)) =>
									if let Some(starrer_pos) = existing_message.starrers.iter().position(|starrer| starrer == &existing_message.starrers[0]) {
										existing_message.stars -= 1;
										existing_message.starrers.swap_remove(starrer_pos);
										Some(idx)
									} else {
										None
									},
								None => None,
							} {
								starred.swap_remove(index);  // Can't do it in match arm because it'd borrow starred as &mut twice
							}
						}
					} else if to_self && msg.ends_with("help") && sender.is_some() {
						let sender = &*&sender.unwrap();
						let msg = msg.trim();

						let level = msg.find("help").unwrap();
						if msg[..level].chars().all(|c| c == '_') {
							server.send_notice(sender, r#"Cummands, level 0:"#).unwrap();
							server.send_notice(sender, r#"  "add <" username ">" message content -- add your star to a message"#).unwrap();
							server.send_notice(sender, r#"  "help" -- send this help notice to sender"#).unwrap();
							server.send_notice(sender, r#"  "board" -- pretty-print the starboard, snackchat-style"#).unwrap();
							server.send_notice(sender, r#"Execute via sending a PRIVMSG (as by "/msg") to NabBot"#).unwrap();
							if level >= 1 {
								server.send_notice(sender, r#"Cummands, level 1:"#).unwrap();
								server.send_notice(sender, r#"  "Navaer" -- murder NabBot"#).unwrap();
								server.send_notice(sender, r#"  "_dump" -- dump raw star data to sender"#).unwrap();
								server.send_notice(sender, r#"Execute via sending a PRIVMSG (as by "/msg") to NabBot"#).unwrap();
							}
							if level >= 2 {
								server.send_notice(sender, r#"Cummands, level 2:"#).unwrap();
								server.send_notice(sender, r#"  "Navaer, NabBot" -- murder NabBot"#).unwrap();
								server.send_notice(sender, r#"Execute via sending a PRIVMSG any channel NabBot is listening to"#).unwrap();
							}
						}
					} else if to_self && msg == "board" && sender.is_some() {
						let sender = &*&sender.unwrap();
						let mut sorted_stars = starred.clone();
						sorted_stars.sort_by(|lhs, rhs| lhs.stars.cmp(&rhs.stars));

						for message in sorted_stars.iter().take(10) {
							server.send_notice(sender, &*&format!("{}", message)).unwrap();
						}
					} else if to_self && msg == "_dump" && sender.is_some() {
						server.send_privmsg(&*&sender.unwrap(), &*&format!("{:?}", starred)).unwrap();
					}
				}
				_ => (),
			}
		}
	}
}
<|endoftext|>


<commit_before>use anyhow::Context as _;
use snowchains::TtyOrPiped;
use std::{
    env,
    io::{self, Write as _},
    process::{self, Stdio},
};
use termcolor::{BufferedStandardStream, Color, ColorSpec, WriteColor as _};

fn main() {
    let opt = snowchains::Opt::from_args_with_workaround_for_clap_issue_1538();

    let color = opt.color();

    let stdin = io::stdin();
    let stdin = TtyOrPiped::auto(&stdin);
    let stdout = BufferedStandardStream::stdout(termcolor_color(color, atty::Stream::Stdout));
    let mut stderr = BufferedStandardStream::stderr(termcolor_color(color, atty::Stream::Stdout));

    let result = (|| -> _ {
        let ctx = snowchains::Context {
            cwd: env::current_dir().with_context(|| "Failed to get the current directory")?,
            stdin,
            stdout,
            stderr: &mut stderr,
            stdin_process_redirection: Stdio::inherit(),
            stdout_process_redirection: Stdio::inherit(),
            stderr_process_redirection: Stdio::inherit(),
            draw_progress: true,
        };

        snowchains::run(opt, ctx)
    })();

    if let Err(err) = result {
        for (i, s) in format!("{:?}", err).splitn(2, "Caused by:\n").enumerate() {
            let _ = stderr.set_color(
                ColorSpec::new()
                    .set_reset(false)
                    .set_bold(true)
                    .set_fg(Some(Color::Red)),
            );

            if i == 0 {
                let _ = stderr.write_all(b"Error:");
                let _ = stderr.reset();
                let _ = stderr.write_all(b" ");
            } else {
                let _ = stderr.write_all(b"Caused by:");
                let _ = stderr.reset();
                let _ = stderr.write_all(b"\n");
            }

            let _ = stderr.write_all(s.as_ref());
        }

        let _ = stderr.write_all(b"\n");
        let _ = stderr.flush();

        process::exit(1);
    }
}

fn termcolor_color(color: snowchains::ColorChoice, stream: atty::Stream) -> termcolor::ColorChoice {
    if atty::is(stream) {
        match color {
            snowchains::ColorChoice::Auto => termcolor::ColorChoice::Auto,
            snowchains::ColorChoice::Always => termcolor::ColorChoice::Always,
            snowchains::ColorChoice::Never => termcolor::ColorChoice::Never,
        }
    } else {
        termcolor::ColorChoice::Never
    }
}
<commit_msg>Fix the `atty::Stream` for STDERR<commit_after>use anyhow::Context as _;
use snowchains::TtyOrPiped;
use std::{
    env,
    io::{self, Write as _},
    process::{self, Stdio},
};
use termcolor::{BufferedStandardStream, Color, ColorSpec, WriteColor as _};

fn main() {
    let opt = snowchains::Opt::from_args_with_workaround_for_clap_issue_1538();

    let color = opt.color();

    let stdin = io::stdin();
    let stdin = TtyOrPiped::auto(&stdin);
    let stdout = BufferedStandardStream::stdout(termcolor_color(color, atty::Stream::Stdout));
    let mut stderr = BufferedStandardStream::stderr(termcolor_color(color, atty::Stream::Stderr));

    let result = (|| -> _ {
        let ctx = snowchains::Context {
            cwd: env::current_dir().with_context(|| "Failed to get the current directory")?,
            stdin,
            stdout,
            stderr: &mut stderr,
            stdin_process_redirection: Stdio::inherit(),
            stdout_process_redirection: Stdio::inherit(),
            stderr_process_redirection: Stdio::inherit(),
            draw_progress: true,
        };

        snowchains::run(opt, ctx)
    })();

    if let Err(err) = result {
        for (i, s) in format!("{:?}", err).splitn(2, "Caused by:\n").enumerate() {
            let _ = stderr.set_color(
                ColorSpec::new()
                    .set_reset(false)
                    .set_bold(true)
                    .set_fg(Some(Color::Red)),
            );

            if i == 0 {
                let _ = stderr.write_all(b"Error:");
                let _ = stderr.reset();
                let _ = stderr.write_all(b" ");
            } else {
                let _ = stderr.write_all(b"Caused by:");
                let _ = stderr.reset();
                let _ = stderr.write_all(b"\n");
            }

            let _ = stderr.write_all(s.as_ref());
        }

        let _ = stderr.write_all(b"\n");
        let _ = stderr.flush();

        process::exit(1);
    }
}

fn termcolor_color(color: snowchains::ColorChoice, stream: atty::Stream) -> termcolor::ColorChoice {
    if atty::is(stream) {
        match color {
            snowchains::ColorChoice::Auto => termcolor::ColorChoice::Auto,
            snowchains::ColorChoice::Always => termcolor::ColorChoice::Always,
            snowchains::ColorChoice::Never => termcolor::ColorChoice::Never,
        }
    } else {
        termcolor::ColorChoice::Never
    }
}
<|endoftext|>


<commit_before>extern crate image;

use std::env::args;
use std::process::exit;
//use std::fs::File;
use std::path::Path;
use image::{
		GenericImage,
//		imageops
};

fn get_top_left(in_path: &str) -> u32 {
    let im = image::open(&Path::new(in_path)).unwrap();
	for x in 0..(im.dimensions().1) {
		for y in 0..(im.dimensions().0) {
			let col = im.get_pixel(y, x);
			if col[0] != 255 && col[1] != 255 && col[2] != 255 {
				return y;
			}
		}
	}
	unreachable!();
}

fn get_top_right(in_path: &str) -> u32 {
    let im = image::open(&Path::new(in_path)).unwrap();
	for x in 0..(im.dimensions().0) {
		for y in 0..(im.dimensions().1) {
			let col = im.get_pixel(x, y);
			if col[0] != 255 && col[1] != 255 && col[2] != 255 {
				return y;
			}
		}
	}
	unreachable!();
}

fn get_lower_left(in_path: &str) -> u32 {
    let im = image::open(&Path::new(in_path)).unwrap();
	let mut x = im.dimensions().1 as i32 - 1;
	let mut y = im.dimensions().0 as i32 - 1;
	while x >= 0 {
		while y >= 0 {
			let col = im.get_pixel(y as u32, x as u32);
			if col[0] != 255 && col[1] != 255 && col[2] != 255 {
				return y as u32 + 1;
			}
			x -= 1;
			y -= 1;
		}
	}
	unreachable!();
}

fn get_lower_right(in_path: &str) -> u32 {
    let im = image::open(&Path::new(in_path)).unwrap();
	let mut x = im.dimensions().0 as i32 - 1;
	let mut y = im.dimensions().1 as i32 - 1;
	while x >= 0 {
		while y >= 0 {
			let col = im.get_pixel(x as u32, y as u32);
			if col[0] != 255 && col[1] != 255 && col[2] != 255 {
				return y as u32 + 1;
			}
			x -= 1;
			y -= 1;
		}
	}
	unreachable!();
}

fn main() {
	let args: Vec<_> = args().collect();

	let in_path: &str = if args.len() == 3 {
		args[1].as_str()
	} else {
		println!("usage: {} <input_image> <output_image>", args[0]);
		exit(1)
	};

	println!("{}", in_path); //, out_path);

	let a = get_top_left(in_path);
	let b = get_top_right(in_path);
	let x = get_lower_left(in_path);
	let y = get_lower_right(in_path);
	println!("({0}, {1}, {2}, {3})", a, b, x, y)

   /*let mut im = image::open(&Path::new(in_path)).unwrap();
	let subim = imageops::crop(&mut im, a, b, x, y);

    let ref mut fout = File::create(&Path::new(out_path)).unwrap();

    let _ = subim.save(fout, image::PNG).unwrap();*/
}
<commit_msg>Optimize command line arguments<commit_after>extern crate image;

use std::env::args;
use std::process::exit;
//use std::fs::File;
use std::path::Path;
use image::{
		GenericImage,
//		imageops
};

fn get_top_left(in_path: &str) -> u32 {
    let im = image::open(&Path::new(in_path)).unwrap();
	for x in 0..(im.dimensions().1) {
		for y in 0..(im.dimensions().0) {
			let col = im.get_pixel(y, x);
			if col[0] != 255 && col[1] != 255 && col[2] != 255 {
				return y;
			}
		}
	}
	unreachable!();
}

fn get_top_right(in_path: &str) -> u32 {
    let im = image::open(&Path::new(in_path)).unwrap();
	for x in 0..(im.dimensions().0) {
		for y in 0..(im.dimensions().1) {
			let col = im.get_pixel(x, y);
			if col[0] != 255 && col[1] != 255 && col[2] != 255 {
				return y;
			}
		}
	}
	unreachable!();
}

fn get_lower_left(in_path: &str) -> u32 {
    let im = image::open(&Path::new(in_path)).unwrap();
	let mut x = im.dimensions().1 as i32 - 1;
	let mut y = im.dimensions().0 as i32 - 1;
	while x >= 0 {
		while y >= 0 {
			let col = im.get_pixel(y as u32, x as u32);
			if col[0] != 255 && col[1] != 255 && col[2] != 255 {
				return y as u32 + 1;
			}
			x -= 1;
			y -= 1;
		}
	}
	unreachable!();
}

fn get_lower_right(in_path: &str) -> u32 {
    let im = image::open(&Path::new(in_path)).unwrap();
	let mut x = im.dimensions().0 as i32 - 1;
	let mut y = im.dimensions().1 as i32 - 1;
	while x >= 0 {
		while y >= 0 {
			let col = im.get_pixel(x as u32, y as u32);
			if col[0] != 255 && col[1] != 255 && col[2] != 255 {
				return y as u32 + 1;
			}
			x -= 1;
			y -= 1;
		}
	}
	unreachable!();
}

fn main() {
	let args: Vec<_> = args().collect();

	let (in_path, out_path) = if args.len() == 3 {
		(args[1].as_str(), args[2].as_str())
	} else {
		println!("usage: {} <input_image> <output_image>", args[0]);
		exit(1)
	};

	let (a, b) = (get_top_left(in_path), get_top_right(in_path));
	let (x, y) = (get_lower_left(in_path), get_lower_right(in_path));
	println!("({0}, {1}, {2}, {3})", a, b, x, y)

   /*let mut im = image::open(&Path::new(in_path)).unwrap();
	let subim = imageops::crop(&mut im, a, b, x, y);

    let ref mut fout = File::create(&Path::new(out_path)).unwrap();

    let _ = subim.save(fout, image::PNG).unwrap();*/
}
<|endoftext|>


<commit_before>extern crate sdl;
extern crate rand;

use self::sdl::video::{SurfaceFlag, VideoFlag};
use self::sdl::event::{Event};

pub fn real_main() {
    sdl::init(&[sdl::InitFlag::Video]);
    sdl::wm::set_caption("RustyCast", "RustyCast");

    let screen = match sdl::video::set_video_mode(320, 240, 32,
                                                  &[SurfaceFlag::HWSurface],
                                                  &[VideoFlag::DoubleBuf]) {
        Ok(screen) => screen,
        Err(err) => panic!("failed to set video mode: {}", err)
    };

    let mut t = 0;

    'main : loop {
        'event : loop {
            match sdl::event::poll_event() {
                Event::Quit => break 'main,
                Event::None => break 'event,
                _ => {}
            }
        }

        screen.with_lock(|pixels| {
            for x in 0..320 {
                for y in 0..240 {
                    let r = rand::random::<u8>();
                    let g = rand::random::<u8>();
                    let b = rand::random::<u8>();

                    pixels[4*(320*y+x) + 0] = 0xFF;
                    pixels[4*(320*y+x) + 1] = r;
                    pixels[4*(320*y+x) + 2] = g;
                    pixels[4*(320*y+x) + 3] = b;
                }
            }
            true
        });

        t = t + 1;

        screen.flip();
    }

    sdl::quit();
}
<commit_msg>Added get_color, WIDTH, and HEIGHT<commit_after>extern crate sdl;
extern crate rand;

use self::sdl::video::{SurfaceFlag, VideoFlag};
use self::sdl::event::{Event};

static WIDTH:  usize = 320;
static HEIGHT: usize = 240;

fn get_color() -> (u8, u8, u8) {
    (rand::random::<u8>(),
     rand::random::<u8>(),
     rand::random::<u8>())
}

pub fn real_main() {
    sdl::init(&[sdl::InitFlag::Video]);
    sdl::wm::set_caption("RustyCast", "RustyCast");

    let screen = match sdl::video::set_video_mode(WIDTH as isize, HEIGHT as isize, 32,
                                                  &[SurfaceFlag::HWSurface],
                                                  &[VideoFlag::DoubleBuf]) {
        Ok(screen) => screen,
        Err(err) => panic!("failed to set video mode: {}", err)
    };

    let mut t = 0;

    'main : loop {
        'event : loop {
            match sdl::event::poll_event() {
                Event::Quit => break 'main,
                Event::None => break 'event,
                _ => {}
            }
        }

        screen.with_lock(|pixels| {
            for x in 0..WIDTH {
                for y in 0..HEIGHT {
                    let (r, g, b) = get_color();
                    pixels[4*(WIDTH*y+x) + 0] = 0xFF;
                    pixels[4*(WIDTH*y+x) + 1] = r;
                    pixels[4*(WIDTH*y+x) + 2] = g;
                    pixels[4*(WIDTH*y+x) + 3] = b;
                }
            }
            true
        });

        t = t + 1;

        screen.flip();
    }

    sdl::quit();
}
<|endoftext|>


<commit_before>#[macro_use(accepts, to_sql_checked)]
extern crate postgres;
extern crate chrono;
extern crate byteorder;
extern crate num;
extern crate clap;

mod currency;

use postgres::{Connection, SslMode};
use chrono::NaiveDateTime;
use currency::Currency;
use clap::{App, SubCommand, ArgMatches};

// Define the data in the database.
struct Account {
    id: i32,
    name: String,
    kind: String,
}

struct Balance {
    id: i32,
    account: i32,
    as_of: chrono::NaiveDateTime,
    balance: Currency
}

struct Deposit {
    id: i32,
    account: i32,
    at: chrono::NaiveDateTime,
    amount: Currency
}

fn prepare_interface<'a, 'b>() -> ArgMatches<'a, 'b> {
    // Top level command.
    let mut app = App::new("investments")
                      .about("Keeps track of investments");

    // Subcommands for the 'account' subcommand.
    let mut accounts_sub = SubCommand::with_name("account")
                                  .about("manage accounts");
    let accounts_list = SubCommand::with_name("list")
                                   .about("list accounts");
    accounts_sub = accounts_sub.subcommand(accounts_list);

    // Subcommands for the 'balance' subcommand.
    let mut balances_sub = SubCommand::with_name("balance")
                                  .about("manage balances");
    let accounts_list = SubCommand::with_name("list")
                                   .about("list balances by account");
    balances_sub = balances_sub.subcommand(accounts_list);

    // Register top-level subcommands.
    app = app.subcommand(accounts_sub);
    app = app.subcommand(balances_sub);

    return app.get_matches();
}

// List the accounts stored and their balances.
fn list_balances() {
    let conn = Connection::connect("postgres://cory@localhost:5432/finances", &SslMode::None).unwrap();

    let stmt = conn.prepare("
        SELECT DISTINCT ON (balance.account) accounts.id, accounts.name, balance.balance
        FROM balance
        INNER JOIN accounts ON balance.account=accounts.id
        ORDER BY balance.account, balance.as_of DESC"
    ).unwrap();

    println!("Balances:");

    for row in stmt.query(&[]).unwrap() {
        let account_id: i32 = row.get(0);
        let name: String = row.get(1);
        let balance: Currency = row.get(2);
        println!("\t({}) {}: {}", account_id, name, balance);
    }
}

// Show the accounts in the system.
fn list_accounts() {
    let conn = Connection::connect("postgres://cory@localhost:5432/finances", &SslMode::None).unwrap();

    let stmt = conn.prepare("
        SELECT accounts.id, accounts.name
        FROM accounts
        ORDER BY accounts.id"
    ).unwrap();

    println!("Accounts:");

    for row in stmt.query(&[]).unwrap() {
        let account_id: i32 = row.get(0);
        let name: String = row.get(1);
        println!("\t{}: {}", account_id, name);
    }

}

// Handle the account subcommand.
fn handle_accounts(matches: &ArgMatches) {
    match matches.subcommand() {
        ("list", Some(matches)) => {list_accounts()},
        _                       => {},
    }
}

// Handle the balance subcommand.
fn handle_balances(matches: &ArgMatches) {
    match matches.subcommand() {
        ("list", Some(matches)) => {list_balances()},
        _                       => {},
    }
}

fn main() {
    let matches = prepare_interface();

    match matches.subcommand() {
        ("account", Some(matches)) => {handle_accounts(matches)},
        ("balance", Some(matches)) => {handle_balances(matches)},
        _                          => {},
    }
}
<commit_msg>Fixup duplicate field.<commit_after>#[macro_use(accepts, to_sql_checked)]
extern crate postgres;
extern crate chrono;
extern crate byteorder;
extern crate num;
extern crate clap;

mod currency;

use postgres::{Connection, SslMode};
use chrono::NaiveDateTime;
use currency::Currency;
use clap::{App, SubCommand, ArgMatches};

// Define the data in the database.
struct Account {
    id: i32,
    name: String,
    kind: String,
}

struct Balance {
    id: i32,
    account: i32,
    as_of: chrono::NaiveDateTime,
    balance: Currency
}

struct Deposit {
    id: i32,
    account: i32,
    at: chrono::NaiveDateTime,
    amount: Currency
}

fn prepare_interface<'a, 'b>() -> ArgMatches<'a, 'b> {
    // Top level command.
    let mut app = App::new("investments")
                      .about("Keeps track of investments");

    // Subcommands for the 'account' subcommand.
    let mut accounts_sub = SubCommand::with_name("account")
                                  .about("manage accounts");
    let accounts_list = SubCommand::with_name("list")
                                   .about("list accounts");
    accounts_sub = accounts_sub.subcommand(accounts_list);

    // Subcommands for the 'balance' subcommand.
    let mut balances_sub = SubCommand::with_name("balance")
                                  .about("manage balances");
    let balances_list = SubCommand::with_name("list")
                                   .about("list balances by account");
    balances_sub = balances_sub.subcommand(balances_list);

    // Register top-level subcommands.
    app = app.subcommand(accounts_sub);
    app = app.subcommand(balances_sub);

    return app.get_matches();
}

// List the accounts stored and their balances.
fn list_balances() {
    let conn = Connection::connect("postgres://cory@localhost:5432/finances", &SslMode::None).unwrap();

    let stmt = conn.prepare("
        SELECT DISTINCT ON (balance.account) accounts.id, accounts.name, balance.balance
        FROM balance
        INNER JOIN accounts ON balance.account=accounts.id
        ORDER BY balance.account, balance.as_of DESC"
    ).unwrap();

    println!("Balances:");

    for row in stmt.query(&[]).unwrap() {
        let account_id: i32 = row.get(0);
        let name: String = row.get(1);
        let balance: Currency = row.get(2);
        println!("\t({}) {}: {}", account_id, name, balance);
    }
}

// Show the accounts in the system.
fn list_accounts() {
    let conn = Connection::connect("postgres://cory@localhost:5432/finances", &SslMode::None).unwrap();

    let stmt = conn.prepare("
        SELECT accounts.id, accounts.name
        FROM accounts
        ORDER BY accounts.id"
    ).unwrap();

    println!("Accounts:");

    for row in stmt.query(&[]).unwrap() {
        let account_id: i32 = row.get(0);
        let name: String = row.get(1);
        println!("\t{}: {}", account_id, name);
    }

}

// Handle the account subcommand.
fn handle_accounts(matches: &ArgMatches) {
    match matches.subcommand() {
        ("list", Some(matches)) => {list_accounts()},
        _                       => {},
    }
}

// Handle the balance subcommand.
fn handle_balances(matches: &ArgMatches) {
    match matches.subcommand() {
        ("list", Some(matches)) => {list_balances()},
        _                       => {},
    }
}

fn main() {
    let matches = prepare_interface();

    match matches.subcommand() {
        ("account", Some(matches)) => {handle_accounts(matches)},
        ("balance", Some(matches)) => {handle_balances(matches)},
        _                          => {},
    }
}
<|endoftext|>