<commit_before><commit_msg>Add Base Logic For Script<commit_after>extern crate regex;
use regex::Regex;
use std::env;
use std::process::{Command, exit};
use std::fs::{OpenOptions, File};
use std::io::prelude::*;
use std::io::BufReader;

fn main() {
    /*let pass = "PASS!";
    let fail = "FAIL!";
    let key_one = gpg_import_key_one();
    let key_two = gpg_import_key_two();
    let key_three = gpg_import_key_three();

    if key_one && key_two && key_three{
        println!("1st Key Import {}", pass);
        println!("2nd Key Import {}", pass);
        println!("3rd Key Import {}", pass);
    }else if !key_one {
        println!("1st Key Import {}", fail);
        exit(1);
    }else if key_one &! key_two{
        println!("2nd Key Import {}", fail);
        exit(1);
    }else if key_one && key_two &!key_three {
        println!("3rd Key Import {}", fail);
        exit(1);
    }

    let init_check = gpg_init();

    if init_check {
        println!("Pacman Key Init {}", pass);
    }else {
        println!("Pacman Key Init {}", fail);
    }*/
    //modify_pacman_conf();
    check_pacman_conf();
}

fn gpg_import_key_one() -> bool{
    let output = Command::new("gpg")
        .arg("--receive-keys")
        .arg("AEFB411B072836CD48FF0381AE252C284B5DBA5D")
        .output()
        .expect("Process Failed to Execute!");
    let check = String::from_utf8(output.stdout).is_ok();
    return check
}

fn gpg_import_key_two() -> bool{

    let output = Command::new("gpg")
        .arg("--receive-keys")
        .arg("9E4F11C6A072942A7B3FD3B0B81EB14A09A25EB0")
        .output()
        .expect("Process Failed to Execute!");
    let check = String::from_utf8(output.stdout).is_ok();
    return check

}
fn gpg_import_key_three() -> bool{

    let output = Command::new("gpg")
        .arg("--receive-keys")
        .arg("35F52A02854DCCAEC9DD5CC410443C7F54B00041")
        .output()
        .expect("Process Failed to Execute!");
    let check = String::from_utf8(output.stdout).is_ok();
    return check

}

fn gpg_init() -> bool{

    let output = Command::new("pacman-key")
        .arg("--init")
        .output()
        .expect("Process Failed to Execute!");
    let check = String::from_utf8(output.stdout).is_ok();
    return check

}

fn gpg_remove_key_one() -> bool{
    let output = Command::new("gpg")
        .arg("-r")
        .arg("AEFB411B072836CD48FF0381AE252C284B5DBA5D")
        .output()
        .expect("Process Failed to Execute!");
    let check = String::from_utf8(output.stdout).is_ok();
    return check
}

fn gpg_remove_key_two() -> bool{

    let output = Command::new("gpg")
        .arg("-r")
        .arg("9E4F11C6A072942A7B3FD3B0B81EB14A09A25EB0")
        .output()
        .expect("Process Failed to Execute!");
    let check = String::from_utf8(output.stdout).is_ok();
    return check

}

fn gpg_remove_key_three() -> bool {
    let output = Command::new("gpg")
        .arg("-r")
        .arg("35F52A02854DCCAEC9DD5CC410443C7F54B00041")
        .output()
        .expect("Process Failed to Execute!");
    let check = String::from_utf8(output.stdout).is_ok();
    return check;
}

fn modify_pacman_conf(){

    let mut f = OpenOptions::new()
        .write(true)
        .append(true)
        .open("/etc/pacman.conf.test")
        .unwrap();
    if let Err(e) =
    writeln!(f, "[archlabs-repo]"){
        println!("{}", e);
    }
    if let Err(e) =
    writeln!(f, "SigLevel = Never"){
        println!("{}", e);
    }
    if let Err(e) =
    writeln!(f, "Server = https://archlabs.github.io/archlabs_repo/$arch"){
        println!("{}", e);
    }
    if let Err(e) =
    writeln!(f, "Server = https://downloads.sourceforge.net/project/archlabs-repo/archlabs_repo/$arch"){
        println!("{}", e);
    }

}

fn check_pacman_conf(){
    let mut one = 0;
    let mut two = 0;
    let mut three = 0;
    let mut four = 0;
    let mut count = 0;
    let mut recount = 0;
    let mut contents = vec![];
    let check_str_one:String =
        "#[archlabs_repo]".to_string();
    let check_str_two:String =
        "[archlabs_repo]".to_string();
    let check_str_three:String =
        "#SigLevel = Never".to_string();
    let check_str_four:String =
        "SigLevel = Never".to_string();
    let check_str_five:String =
        "#Server = https://archlabs.github.io/archlabs_repo/$arch".to_string();
    let check_str_six:String =
        "Server = https://archlabs.github.io/archlabs_repo/$arch".to_string();
    let check_str_seven:String =
        "#Server = https://downloads.sourceforge.net/project/\
        archlabs-repo/archlabs_repo/$arch".to_string();
    let check_str_eight:String =
        "Server = https://downloads.sourceforge.net/project/\
        archlabs-repo/archlabs_repo/$arch".to_string();
    let filename = r"/etc/pacman.conf.test";
    let mut f =
        File::open(filename).expect("File Not Found!");
    for line in BufReader::new(f).lines(){
        contents.push(line.unwrap());
        count +=1;
    }

    while recount <= (count - 1) {

        if check_str_one.eq(contents.get(recount).unwrap()){
            one = recount;
            println!("{:?}", contents.get(one).unwrap());
            recount += 1;
        }else if check_str_two.eq(contents.get(recount).unwrap()){
            one = recount;
            println!("{:?}", contents.get(one).unwrap());
            recount += 1;
        }else {
            recount += 1;
        }

        if check_str_three.eq(contents.get(recount).unwrap()){
            two = recount;
            println!("{:?}", contents.get(two).unwrap());
            recount += 1;
        }else if check_str_four.eq(contents.get(recount).unwrap()){
            two = recount;
            println!("{:?}", contents.get(two).unwrap());
            recount += 1;
        }else {
            recount += 1;
        }

        if check_str_five.eq(contents.get(recount).unwrap()){
            three = recount;
            println!("{:?}", contents.get(three).unwrap());
            recount += 1;
        }else if check_str_six.eq(contents.get(recount).unwrap()){
            three = recount;
            println!("{:?}", contents.get(three).unwrap());
            recount += 1;

        }else {
            recount += 1;
        }

        if check_str_seven.eq(contents.get(recount).unwrap()){
            four = recount;
            let str:&str = contents.get(four).unwrap();
            let modstr = str.replace("#", "");

            println!("{:?}", contents.get(four).unwrap());
            recount += 1;
        }else if check_str_eight.eq(contents.get(recount).unwrap()){
            four = recount;
            println!("{:?}", contents.get(four).unwrap());
            recount += 1;

        }else {
            recount += 1;
        }

    }
    /*
    let re = Regex::new(r"![[:punct:]]|\bSigLevel = Never").unwrap();
    let caps = re.captures(contents.as_str()).unwrap();
    println!("{:?}", caps.get(0).unwrap().as_str().replace
    ("SigLevel = Never", "SigLevel = Optional Trustall"));*/

}<|endoftext|>


<commit_before><commit_msg>Fixed the error handling with the help of the awesome people in *#rust*<commit_after><|endoftext|>


<commit_before><commit_msg>Bring up to date with @rust-lang/rust@504ca6f4221b5745c5d72902c1c30415845afa26<commit_after><|endoftext|>


<commit_before><commit_msg>Update<commit_after>use std::io;
fn main(){
    let mut input = String::new();
    io::stdin().read_line(&mut input)
            .expect("Failed read line");
    let mut num:i32 = input.trim()
                .parse()
                .expect("Falied convert to i32");
    let mut times = 0;
    while num != 1 {
        if num % 2 == 0 {
            num /= 2;
        }else{
            num = (3*num + 1) / 2;
        }
        times += 1;
    }
    println!("{}", times);
}<|endoftext|>


<commit_before><commit_msg>questlog<commit_after><|endoftext|>


<commit_before><commit_msg>Provide valid Log Level Specification on log init<commit_after><|endoftext|>


<commit_before>// TODO: Refactor using a matrix for performance

use redox::*;

mod cmd;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
        if self.offset > 0 {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset - 1].to_string() +
                &self.string[self.offset .. self.string.len()];
            self.offset -= 1;
        }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    // TODO: Add methods for multiple movements
    fn up(&mut self) {
        if self.cur() == '\n' || self.cur() == '\0' {
            self.left();
            while self.cur() != '\n' &&
                  self.cur() != '\0' &&
                  self.offset >= 1 {
                self.left();
            }
        } else {
            let x = self.get_x(); //- if self.cur() == '\n' { 1 } else { 0 };

            while self.cur() != '\n' &&
                  self.offset >= 1 {
                self.left();
            }
            self.right();
            let mut new_offset = 0;

            for i in 2..self.offset {
                match self.string.as_bytes()[self.offset - i] {
                    0 => break,
                    10 => {
                        new_offset = self.offset - i + 1;
                        break;
                    }
                    _ => (),
                }
            }
            self.offset = new_offset;
            for _ in 1..x {
                if self.cur() != '\n' {
                    self.right();
                } else {
                    break;
                }
            }
        }
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let x = self.get_x(); //- if self.cur() == '\n' { 1 } else { 0 };
        let original_c = self.cur();

        while self.offset < self.string.len() &&
              self.cur() != '\n' &&
              self.cur() != '\0' {
            self.right();
        }
        self.right();

        if original_c == '\n' {
            while self.cur() != '\n' &&
                  self.cur() != '\0' &&
                  self.offset < self.string.len() {
                self.right();
            }
        } else {
            for _ in 1..x {
                if self.cur() != '\n' {
                    self.right();
                } else {
                    break;
                }
            }
        }
    }

    fn cur(&self) -> char {
        self.string.chars().nth(self.offset).unwrap_or('\0')
    }

    fn insert(&mut self, c: char, window: &mut Window) {
        let ind = if c == '\n' {
            let mut mov = 0;

            for _ in 0..self.get_x() {
                self.left();
                mov += 1;
            }

            let mut ind = String::new();
            while (self.cur() == ' ' ||
                  self.cur() == '\t') &&
                  self.offset < self.string.len() {
                ind.push(self.cur());
                self.right();
                mov -= 1;
            }

            for _ in 0..mov {
                self.right();
            }

            ind
        } else {
            String::new()
        };

        window.set_title(&format!("{}{}{}","self (", &self.url, ") Changed"));
        self.string = self.string[0 .. self.offset].to_string() +
            &c.to_string() +
            &self.string[self.offset .. self.string.len()];

        self.right();

        if c == '\n' {
            for c in ind.chars() {
                self.insert(c, window);
            }

        }
    }

    fn reload(&mut self) {
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Some(ref mut file) => {
                file.seek(SeekFrom::Start(0));
                let mut string = String::new();
                file.read_to_string(&mut string);
                self.string = string;
            }
            None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &Window) {
        match self.file {
            Some(ref mut file) => {
                file.seek(SeekFrom::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            None => {
                let mut save_window = {
                    const width: usize = 400;
                    const height: usize = 200;
                    Window::new((window.x() + (window.width()/2 - width/2) as isize),
                                (window.y() + (window.height()/2 - height/2) as isize),
                                width,
                                height,
                                "Save As").unwrap()
                };
                if let Some(event) = save_window.poll() {
                    //TODO: Create a Save/Cancel button for file saving
                    // and prompt the user for asking to save
                }
            }
        }
    }

    fn get_x(&self) -> usize {
        let mut x = 0;
        for (n, c) in self.string.chars().enumerate() {
            if c == '\n' {
                x = 0;
            } else {
                x += 1;
            }
            if n >= self.offset {
                break;
            }
        }
        x
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.rect(8 * col, 16 * row, 8, 16, [128, 128, 128, 128]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                     &("Editor (".to_string() + url + ")")).unwrap();

        self.url = url.to_string();
        self.file = File::open(&self.url);

        self.reload();
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;
        let mut swap = 0;
        let mut period = String::new();
        let mut is_recording = false;
        let mut clipboard = String::new();

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window, &mut swap, &mut period, &mut is_recording, &mut clipboard);
                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Some(arg) => Editor::new().main(&arg),
        None => Editor::new().main("none://"),
    }
}
<commit_msg>More block cursors<commit_after>// TODO: Refactor using a matrix for performance

use redox::*;

mod cmd;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
        if self.offset > 0 {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset - 1].to_string() +
                &self.string[self.offset .. self.string.len()];
            self.offset -= 1;
        }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    // TODO: Add methods for multiple movements
    fn up(&mut self) {
        if self.cur() == '\n' || self.cur() == '\0' {
            self.left();
            while self.cur() != '\n' &&
                  self.cur() != '\0' &&
                  self.offset >= 1 {
                self.left();
            }
        } else {
            let x = self.get_x(); //- if self.cur() == '\n' { 1 } else { 0 };

            while self.cur() != '\n' &&
                  self.offset >= 1 {
                self.left();
            }
            self.right();
            let mut new_offset = 0;

            for i in 2..self.offset {
                match self.string.as_bytes()[self.offset - i] {
                    0 => break,
                    10 => {
                        new_offset = self.offset - i + 1;
                        break;
                    }
                    _ => (),
                }
            }
            self.offset = new_offset;
            for _ in 1..x {
                if self.cur() != '\n' {
                    self.right();
                } else {
                    break;
                }
            }
        }
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let x = self.get_x(); //- if self.cur() == '\n' { 1 } else { 0 };
        let original_c = self.cur();

        while self.offset < self.string.len() &&
              self.cur() != '\n' &&
              self.cur() != '\0' {
            self.right();
        }
        self.right();

        if original_c == '\n' {
            while self.cur() != '\n' &&
                  self.cur() != '\0' &&
                  self.offset < self.string.len() {
                self.right();
            }
        } else {
            for _ in 1..x {
                if self.cur() != '\n' {
                    self.right();
                } else {
                    break;
                }
            }
        }
    }

    fn cur(&self) -> char {
        self.string.chars().nth(self.offset).unwrap_or('\0')
    }

    fn insert(&mut self, c: char, window: &mut Window) {
        let ind = if c == '\n' {
            let mut mov = 0;

            for _ in 0..self.get_x() {
                self.left();
                mov += 1;
            }

            let mut ind = String::new();
            while (self.cur() == ' ' ||
                  self.cur() == '\t') &&
                  self.offset < self.string.len() {
                ind.push(self.cur());
                self.right();
                mov -= 1;
            }

            for _ in 0..mov {
                self.right();
            }

            ind
        } else {
            String::new()
        };

        window.set_title(&format!("{}{}{}","self (", &self.url, ") Changed"));
        self.string = self.string[0 .. self.offset].to_string() +
            &c.to_string() +
            &self.string[self.offset .. self.string.len()];

        self.right();

        if c == '\n' {
            for c in ind.chars() {
                self.insert(c, window);
            }

        }
    }

    fn reload(&mut self) {
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Some(ref mut file) => {
                file.seek(SeekFrom::Start(0));
                let mut string = String::new();
                file.read_to_string(&mut string);
                self.string = string;
            }
            None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &Window) {
        match self.file {
            Some(ref mut file) => {
                file.seek(SeekFrom::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            None => {
                let mut save_window = {
                    const width: usize = 400;
                    const height: usize = 200;
                    Window::new((window.x() + (window.width()/2 - width/2) as isize),
                                (window.y() + (window.height()/2 - height/2) as isize),
                                width,
                                height,
                                "Save As").unwrap()
                };
                if let Some(event) = save_window.poll() {
                    //TODO: Create a Save/Cancel button for file saving
                    // and prompt the user for asking to save
                }
            }
        }
    }

    fn get_x(&self) -> usize {
        let mut x = 0;
        for (n, c) in self.string.chars().enumerate() {
            if c == '\n' {
                x = 0;
            } else {
                x += 1;
            }
            if n >= self.offset {
                break;
            }
        }
        x
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.rect(8 * col, 16 * row, 8, 16, [128, 128, 128, 128]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.rect(8 * col, 16 * row, 8, 16, [128, 128, 128, 128]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                     &("Editor (".to_string() + url + ")")).unwrap();

        self.url = url.to_string();
        self.file = File::open(&self.url);

        self.reload();
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;
        let mut swap = 0;
        let mut period = String::new();
        let mut is_recording = false;
        let mut clipboard = String::new();

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window, &mut swap, &mut period, &mut is_recording, &mut clipboard);
                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Some(arg) => Editor::new().main(&arg),
        None => Editor::new().main("none://"),
    }
}
<|endoftext|>


<commit_before>extern crate piston;
extern crate ai_behavior;
extern crate sprite;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;

use std::path::Path;
use std::cell::RefCell;
use std::rc::Rc;

use sprite::*;
use ai_behavior::{
    Action,
    Sequence,
    Wait,
    WaitForever,
    While,
};

use sdl2_window::Sdl2Window;
use opengl_graphics::{
    GlGraphics,
    OpenGL,
    Texture,
};
use piston::window::{ WindowSettings, Size };

fn main() {
    let (width, height) = (300, 300);
    let opengl = OpenGL::_3_2;
    let window = Sdl2Window::new(
        opengl,
        WindowSettings::new(
            "piston-example-sprite".to_string(),
            Size { width: width, height: height }
        )
        .exit_on_esc(true)
    );

    let id;
    let mut scene = Scene::new();
    let tex = Path::new("./bin/assets/rust-logo.png");
    let tex = Rc::new(Texture::from_path(&tex).unwrap());
    let mut sprite = Sprite::from_texture(tex.clone());
    sprite.set_position(width as f64 / 2.0, height as f64 / 2.0);

    id = scene.add_child(sprite);

    // Run a sequence or animations.
    let seq = Sequence(vec![
        Action(Ease(EaseFunction::CubicOut, Box::new(ScaleTo(2.0, 0.5, 0.5)))),
        Action(Ease(EaseFunction::BounceOut, Box::new(MoveBy(1.0, 0.0, 100.0)))),
        Action(Ease(EaseFunction::ElasticOut, Box::new(MoveBy(2.0, 0.0, -100.0)))),
        Action(Ease(EaseFunction::BackInOut, Box::new(MoveBy(1.0, 0.0, -100.0)))),
        Wait(0.5),
        Action(Ease(EaseFunction::ExponentialInOut, Box::new(MoveBy(1.0, 0.0, 100.0)))),
        Action(Blink(1.0, 5)),
        While(Box::new(WaitForever), vec![
            Action(Ease(EaseFunction::QuadraticIn, Box::new(FadeOut(1.0)))),
            Action(Ease(EaseFunction::QuadraticOut, Box::new(FadeIn(1.0)))),
        ]),
    ]);
    scene.run(id, &seq);

    // This animation and the one above can run in parallel.
    let rotate = Action(Ease(EaseFunction::ExponentialInOut,
        Box::new(RotateTo(2.0, 360.0))));
    scene.run(id, &rotate);

    println!("Press any key to pause/resume the animation!");

    let ref mut gl = GlGraphics::new(opengl);
    let window = Rc::new(RefCell::new(window));
    for e in piston::events(window) {
        use piston::event::*;

        scene.event(&e);

        if let Some(args) = e.render_args() {
            use graphics::*;
            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                graphics::clear([1.0, 1.0, 1.0, 1.0], gl);
                scene.draw(c.transform, gl);
            });
        }
        if let Some(_) = e.press_args() {
            scene.toggle(id, &seq);
            scene.toggle(id, &rotate);
        }
    }
}
<commit_msg>Updated "sprite" example<commit_after>extern crate piston;
extern crate ai_behavior;
extern crate sprite;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;

use std::path::Path;
use std::cell::RefCell;
use std::rc::Rc;

use sprite::*;
use ai_behavior::{
    Action,
    Sequence,
    Wait,
    WaitForever,
    While,
};

use sdl2_window::Sdl2Window;
use opengl_graphics::{
    GlGraphics,
    OpenGL,
    Texture,
};
use piston::window::{ WindowSettings, Size };
use piston::event::*;

fn main() {
    let (width, height) = (300, 300);
    let opengl = OpenGL::_3_2;
    let window = Sdl2Window::new(
        opengl,
        WindowSettings::new(
            "piston-example-sprite".to_string(),
            Size { width: width, height: height }
        )
        .exit_on_esc(true)
    );

    let id;
    let mut scene = Scene::new();
    let tex = Path::new("./bin/assets/rust-logo.png");
    let tex = Rc::new(Texture::from_path(&tex).unwrap());
    let mut sprite = Sprite::from_texture(tex.clone());
    sprite.set_position(width as f64 / 2.0, height as f64 / 2.0);

    id = scene.add_child(sprite);

    // Run a sequence or animations.
    let seq = Sequence(vec![
        Action(Ease(EaseFunction::CubicOut, Box::new(ScaleTo(2.0, 0.5, 0.5)))),
        Action(Ease(EaseFunction::BounceOut, Box::new(MoveBy(1.0, 0.0, 100.0)))),
        Action(Ease(EaseFunction::ElasticOut, Box::new(MoveBy(2.0, 0.0, -100.0)))),
        Action(Ease(EaseFunction::BackInOut, Box::new(MoveBy(1.0, 0.0, -100.0)))),
        Wait(0.5),
        Action(Ease(EaseFunction::ExponentialInOut, Box::new(MoveBy(1.0, 0.0, 100.0)))),
        Action(Blink(1.0, 5)),
        While(Box::new(WaitForever), vec![
            Action(Ease(EaseFunction::QuadraticIn, Box::new(FadeOut(1.0)))),
            Action(Ease(EaseFunction::QuadraticOut, Box::new(FadeIn(1.0)))),
        ]),
    ]);
    scene.run(id, &seq);

    // This animation and the one above can run in parallel.
    let rotate = Action(Ease(EaseFunction::ExponentialInOut,
        Box::new(RotateTo(2.0, 360.0))));
    scene.run(id, &rotate);

    println!("Press any key to pause/resume the animation!");

    let ref mut gl = GlGraphics::new(opengl);
    let window = Rc::new(RefCell::new(window));
    for e in window.events() {
        scene.event(&e);

        if let Some(args) = e.render_args() {
            use graphics::*;
            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                graphics::clear([1.0, 1.0, 1.0, 1.0], gl);
                scene.draw(c.transform, gl);
            });
        }
        if let Some(_) = e.press_args() {
            scene.toggle(id, &seq);
            scene.toggle(id, &rotate);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add unit test<commit_after><|endoftext|>


<commit_before>use quote::{ToTokens, Tokens};
use syn::spanned::Spanned;
use syn::{Field, Ident, Lit, Meta, NestedMeta};

use api::strip_serde_attrs;

pub struct Request {
    fields: Vec<RequestField>,
}

impl Request {
    pub fn add_headers_to_request(&self) -> Tokens {
        self.header_fields().fold(Tokens::new(), |mut header_tokens, request_field| {
            let (field, header_name_string) = match request_field {
                RequestField::Header(field, header_name_string) => (field, header_name_string),
                _ => panic!("expected request field to be header variant"),
            };

            let field_name = &field.ident;
            let header_name = Ident::from(header_name_string.as_ref());

            header_tokens.append_all(quote! {
                headers.append(
                    ::http::header::#header_name,
                    ::http::header::HeaderValue::from_str(request.#field_name.as_ref())
                        .expect("failed to convert value into HeaderValue"),
                );
            });

            header_tokens
        })
    }

    pub fn has_body_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_body())
    }

    pub fn has_header_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_header())
    }
    pub fn has_path_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_path())
    }

    pub fn has_query_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_query())
    }

    pub fn header_fields(&self) -> impl Iterator<Item = &RequestField> {
        self.fields.iter().filter(|field| field.is_header())
    }

    pub fn path_field_count(&self) -> usize {
        self.fields.iter().filter(|field| field.is_path()).count()
    }

    pub fn newtype_body_field(&self) -> Option<&Field> {
        for request_field in self.fields.iter() {
            match *request_field {
                RequestField::NewtypeBody(ref field) => {
                    return Some(field);
                }
                _ => continue,
            }
        }

        None
    }

    pub fn request_body_init_fields(&self) -> Tokens {
        self.struct_init_fields(RequestFieldKind::Body)
    }

    pub fn request_path_init_fields(&self) -> Tokens {
        self.struct_init_fields(RequestFieldKind::Path)
    }

    pub fn request_query_init_fields(&self) -> Tokens {
        self.struct_init_fields(RequestFieldKind::Query)
    }

    fn struct_init_fields(&self, request_field_kind: RequestFieldKind) -> Tokens {
        let mut tokens = Tokens::new();

        for field in self.fields.iter().flat_map(|f| f.field_(request_field_kind)) {
            let field_name = field.ident.expect("expected field to have an identifier");
            let span = field.span();

            tokens.append_all(quote_spanned! {span=>
                #field_name: request.#field_name,
            });
        }

        tokens
    }
}

impl From<Vec<Field>> for Request {
    fn from(fields: Vec<Field>) -> Self {
        let mut has_newtype_body = false;

        let fields = fields.into_iter().map(|mut field| {
            let mut field_kind = RequestFieldKind::Body;
            let mut header = None;

            field.attrs = field.attrs.into_iter().filter(|attr| {
                let meta = attr.interpret_meta()
                    .expect("ruma_api! could not parse request field attributes");

                let meta_list = match meta {
                    Meta::List(meta_list) => meta_list,
                    _ => return true,
                };

                if meta_list.ident.as_ref() != "ruma_api" {
                    return true;
                }

                for nested_meta_item in meta_list.nested {
                    match nested_meta_item {
                        NestedMeta::Meta(meta_item) => {
                            match meta_item {
                                Meta::Word(ident) => {
                                    match ident.as_ref() {
                                        "body" => {
                                            has_newtype_body = true;
                                            field_kind = RequestFieldKind::NewtypeBody;
                                        }
                                        "path" => field_kind = RequestFieldKind::Path,
                                        "query" => field_kind = RequestFieldKind::Query,
                                        _ => panic!("ruma_api! single-word attribute on requests must be: body, path, or query"),
                                    }
                                }
                                Meta::NameValue(name_value) => {
                                    match name_value.ident.as_ref() {
                                        "header" => {
                                            match name_value.lit {
                                                Lit::Str(lit_str) => header = Some(lit_str.value()),
                                                _ => panic!("ruma_api! header attribute's value must be a string literal"),
                                            }

                                            field_kind = RequestFieldKind::Header;
                                        }
                                        _ => panic!("ruma_api! name/value pair attribute on requests must be: header"),
                                    }
                                }
                                _ => panic!("ruma_api! attributes on requests must be a single word or a name/value pair"),
                            }
                        }
                        NestedMeta::Literal(_) => panic!(
                            "ruma_api! attributes on requests must be: body, header, path, or query"
                        ),
                    }
                }

                false
            }).collect();

            if field_kind == RequestFieldKind::Body {
                assert!(
                    !has_newtype_body,
                    "ruma_api! requests cannot have both normal body fields and a newtype body field"
                );
            }

            RequestField::new(field_kind, field, header)
        }).collect();

        Request {
            fields,
        }
    }
}

impl ToTokens for Request {
    fn to_tokens(&self, tokens: &mut Tokens) {
        let request_struct_header = quote! {
            /// Data for a request to this API endpoint.
            #[derive(Debug)]
            pub struct Request
        };

        let request_struct_body = if self.fields.len() == 0 {
            quote!(;)
        } else {
            let fields = self.fields.iter().fold(Tokens::new(), |mut field_tokens, request_field| {
                let field = request_field.field();
                let span = field.span();

                strip_serde_attrs(field);

                field_tokens.append_all(quote_spanned!(span=> #field,));

                field_tokens
            });

            quote! {
                {
                    #fields
                }
            }
        };

        let request_body_struct;

        if let Some(newtype_body_field) = self.newtype_body_field() {
            let mut field = newtype_body_field.clone();
            let ty = &field.ty;
            let span = field.span();

            request_body_struct = quote_spanned! {span=>
                /// Data in the request body.
                #[derive(Debug, Serialize)]
                struct RequestBody(#ty);
            };
        } else if self.has_body_fields() {
            let fields = self.fields.iter().fold(Tokens::new(), |mut field_tokens, request_field| {
                match *request_field {
                    RequestField::Body(ref field) => {
                        let span = field.span();

                        field_tokens.append_all(quote_spanned!(span=> #field,));

                        field_tokens
                    }
                    _ => field_tokens,
                }
            });

            request_body_struct = quote! {
                /// Data in the request body.
                #[derive(Debug, Serialize)]
                struct RequestBody {
                    #fields
                }
            };
        } else {
            request_body_struct = Tokens::new();
        }

        let request_path_struct;

        if self.has_path_fields() {
            let fields = self.fields.iter().fold(Tokens::new(), |mut field_tokens, request_field| {
                match *request_field {
                    RequestField::Path(ref field) => {
                        let span = field.span();

                        field_tokens.append_all(quote_spanned!(span=> #field,));

                        field_tokens
                    }
                    _ => field_tokens,
                }
            });

            request_path_struct = quote! {
                /// Data in the request path.
                #[derive(Debug, Serialize)]
                struct RequestPath {
                    #fields
                }
            };
        } else {
            request_path_struct = Tokens::new();
        }

        let request_query_struct;

        if self.has_query_fields() {
            let fields = self.fields.iter().fold(Tokens::new(), |mut field_tokens, request_field| {
                match *request_field {
                    RequestField::Query(ref field) => {
                        let span = field.span();

                        field_tokens.append_all(quote_spanned!(span=> #field));

                        field_tokens
                    }
                    _ => field_tokens,
                }
            });

            request_query_struct = quote! {
                /// Data in the request's query string.
                #[derive(Debug, Serialize)]
                struct RequestQuery {
                    #fields
                }
            };
        } else {
            request_query_struct = Tokens::new();
        }

        tokens.append_all(quote! {
            #request_struct_header
            #request_struct_body
            #request_body_struct
            #request_path_struct
            #request_query_struct
        });
    }
}

pub enum RequestField {
    Body(Field),
    Header(Field, String),
    NewtypeBody(Field),
    Path(Field),
    Query(Field),
}

impl RequestField {
    fn new(kind: RequestFieldKind, field: Field, header: Option<String>) -> RequestField {
        match kind {
            RequestFieldKind::Body => RequestField::Body(field),
            RequestFieldKind::Header => RequestField::Header(field, header.expect("missing header name")),
            RequestFieldKind::NewtypeBody => RequestField::NewtypeBody(field),
            RequestFieldKind::Path => RequestField::Path(field),
            RequestFieldKind::Query => RequestField::Query(field),
        }
    }

    fn kind(&self) -> RequestFieldKind {
        match *self {
            RequestField::Body(..) => RequestFieldKind::Body,
            RequestField::Header(..) => RequestFieldKind::Header,
            RequestField::NewtypeBody(..) => RequestFieldKind::NewtypeBody,
            RequestField::Path(..) => RequestFieldKind::Path,
            RequestField::Query(..) => RequestFieldKind::Query,
        }
    }

    fn is_body(&self) -> bool {
        self.kind() == RequestFieldKind::Body
    }

    fn is_header(&self) -> bool {
        self.kind() == RequestFieldKind::Header
    }

    fn is_path(&self) -> bool {
        self.kind() == RequestFieldKind::Path
    }

    fn is_query(&self) -> bool {
        self.kind() == RequestFieldKind::Query
    }

    fn field(&self) -> &Field {
        match *self {
            RequestField::Body(ref field) => field,
            RequestField::Header(ref field, _) => field,
            RequestField::NewtypeBody(ref field) => field,
            RequestField::Path(ref field) => field,
            RequestField::Query(ref field) => field,
        }
    }

    fn field_(&self, kind: RequestFieldKind) -> Option<&Field> {
        if self.kind() == kind {
            Some(self.field())
        } else {
            None
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum RequestFieldKind {
    Body,
    Header,
    NewtypeBody,
    Path,
    Query,
}
<commit_msg>Add missing commas after each query field.<commit_after>use quote::{ToTokens, Tokens};
use syn::spanned::Spanned;
use syn::{Field, Ident, Lit, Meta, NestedMeta};

use api::strip_serde_attrs;

pub struct Request {
    fields: Vec<RequestField>,
}

impl Request {
    pub fn add_headers_to_request(&self) -> Tokens {
        self.header_fields().fold(Tokens::new(), |mut header_tokens, request_field| {
            let (field, header_name_string) = match request_field {
                RequestField::Header(field, header_name_string) => (field, header_name_string),
                _ => panic!("expected request field to be header variant"),
            };

            let field_name = &field.ident;
            let header_name = Ident::from(header_name_string.as_ref());

            header_tokens.append_all(quote! {
                headers.append(
                    ::http::header::#header_name,
                    ::http::header::HeaderValue::from_str(request.#field_name.as_ref())
                        .expect("failed to convert value into HeaderValue"),
                );
            });

            header_tokens
        })
    }

    pub fn has_body_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_body())
    }

    pub fn has_header_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_header())
    }
    pub fn has_path_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_path())
    }

    pub fn has_query_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_query())
    }

    pub fn header_fields(&self) -> impl Iterator<Item = &RequestField> {
        self.fields.iter().filter(|field| field.is_header())
    }

    pub fn path_field_count(&self) -> usize {
        self.fields.iter().filter(|field| field.is_path()).count()
    }

    pub fn newtype_body_field(&self) -> Option<&Field> {
        for request_field in self.fields.iter() {
            match *request_field {
                RequestField::NewtypeBody(ref field) => {
                    return Some(field);
                }
                _ => continue,
            }
        }

        None
    }

    pub fn request_body_init_fields(&self) -> Tokens {
        self.struct_init_fields(RequestFieldKind::Body)
    }

    pub fn request_path_init_fields(&self) -> Tokens {
        self.struct_init_fields(RequestFieldKind::Path)
    }

    pub fn request_query_init_fields(&self) -> Tokens {
        self.struct_init_fields(RequestFieldKind::Query)
    }

    fn struct_init_fields(&self, request_field_kind: RequestFieldKind) -> Tokens {
        let mut tokens = Tokens::new();

        for field in self.fields.iter().flat_map(|f| f.field_(request_field_kind)) {
            let field_name = field.ident.expect("expected field to have an identifier");
            let span = field.span();

            tokens.append_all(quote_spanned! {span=>
                #field_name: request.#field_name,
            });
        }

        tokens
    }
}

impl From<Vec<Field>> for Request {
    fn from(fields: Vec<Field>) -> Self {
        let mut has_newtype_body = false;

        let fields = fields.into_iter().map(|mut field| {
            let mut field_kind = RequestFieldKind::Body;
            let mut header = None;

            field.attrs = field.attrs.into_iter().filter(|attr| {
                let meta = attr.interpret_meta()
                    .expect("ruma_api! could not parse request field attributes");

                let meta_list = match meta {
                    Meta::List(meta_list) => meta_list,
                    _ => return true,
                };

                if meta_list.ident.as_ref() != "ruma_api" {
                    return true;
                }

                for nested_meta_item in meta_list.nested {
                    match nested_meta_item {
                        NestedMeta::Meta(meta_item) => {
                            match meta_item {
                                Meta::Word(ident) => {
                                    match ident.as_ref() {
                                        "body" => {
                                            has_newtype_body = true;
                                            field_kind = RequestFieldKind::NewtypeBody;
                                        }
                                        "path" => field_kind = RequestFieldKind::Path,
                                        "query" => field_kind = RequestFieldKind::Query,
                                        _ => panic!("ruma_api! single-word attribute on requests must be: body, path, or query"),
                                    }
                                }
                                Meta::NameValue(name_value) => {
                                    match name_value.ident.as_ref() {
                                        "header" => {
                                            match name_value.lit {
                                                Lit::Str(lit_str) => header = Some(lit_str.value()),
                                                _ => panic!("ruma_api! header attribute's value must be a string literal"),
                                            }

                                            field_kind = RequestFieldKind::Header;
                                        }
                                        _ => panic!("ruma_api! name/value pair attribute on requests must be: header"),
                                    }
                                }
                                _ => panic!("ruma_api! attributes on requests must be a single word or a name/value pair"),
                            }
                        }
                        NestedMeta::Literal(_) => panic!(
                            "ruma_api! attributes on requests must be: body, header, path, or query"
                        ),
                    }
                }

                false
            }).collect();

            if field_kind == RequestFieldKind::Body {
                assert!(
                    !has_newtype_body,
                    "ruma_api! requests cannot have both normal body fields and a newtype body field"
                );
            }

            RequestField::new(field_kind, field, header)
        }).collect();

        Request {
            fields,
        }
    }
}

impl ToTokens for Request {
    fn to_tokens(&self, tokens: &mut Tokens) {
        let request_struct_header = quote! {
            /// Data for a request to this API endpoint.
            #[derive(Debug)]
            pub struct Request
        };

        let request_struct_body = if self.fields.len() == 0 {
            quote!(;)
        } else {
            let fields = self.fields.iter().fold(Tokens::new(), |mut field_tokens, request_field| {
                let field = request_field.field();
                let span = field.span();

                strip_serde_attrs(field);

                field_tokens.append_all(quote_spanned!(span=> #field,));

                field_tokens
            });

            quote! {
                {
                    #fields
                }
            }
        };

        let request_body_struct;

        if let Some(newtype_body_field) = self.newtype_body_field() {
            let mut field = newtype_body_field.clone();
            let ty = &field.ty;
            let span = field.span();

            request_body_struct = quote_spanned! {span=>
                /// Data in the request body.
                #[derive(Debug, Serialize)]
                struct RequestBody(#ty);
            };
        } else if self.has_body_fields() {
            let fields = self.fields.iter().fold(Tokens::new(), |mut field_tokens, request_field| {
                match *request_field {
                    RequestField::Body(ref field) => {
                        let span = field.span();

                        field_tokens.append_all(quote_spanned!(span=> #field,));

                        field_tokens
                    }
                    _ => field_tokens,
                }
            });

            request_body_struct = quote! {
                /// Data in the request body.
                #[derive(Debug, Serialize)]
                struct RequestBody {
                    #fields
                }
            };
        } else {
            request_body_struct = Tokens::new();
        }

        let request_path_struct;

        if self.has_path_fields() {
            let fields = self.fields.iter().fold(Tokens::new(), |mut field_tokens, request_field| {
                match *request_field {
                    RequestField::Path(ref field) => {
                        let span = field.span();

                        field_tokens.append_all(quote_spanned!(span=> #field,));

                        field_tokens
                    }
                    _ => field_tokens,
                }
            });

            request_path_struct = quote! {
                /// Data in the request path.
                #[derive(Debug, Serialize)]
                struct RequestPath {
                    #fields
                }
            };
        } else {
            request_path_struct = Tokens::new();
        }

        let request_query_struct;

        if self.has_query_fields() {
            let fields = self.fields.iter().fold(Tokens::new(), |mut field_tokens, request_field| {
                match *request_field {
                    RequestField::Query(ref field) => {
                        let span = field.span();

                        field_tokens.append_all(quote_spanned!(span=> #field,));

                        field_tokens
                    }
                    _ => field_tokens,
                }
            });

            request_query_struct = quote! {
                /// Data in the request's query string.
                #[derive(Debug, Serialize)]
                struct RequestQuery {
                    #fields
                }
            };
        } else {
            request_query_struct = Tokens::new();
        }

        tokens.append_all(quote! {
            #request_struct_header
            #request_struct_body
            #request_body_struct
            #request_path_struct
            #request_query_struct
        });
    }
}

pub enum RequestField {
    Body(Field),
    Header(Field, String),
    NewtypeBody(Field),
    Path(Field),
    Query(Field),
}

impl RequestField {
    fn new(kind: RequestFieldKind, field: Field, header: Option<String>) -> RequestField {
        match kind {
            RequestFieldKind::Body => RequestField::Body(field),
            RequestFieldKind::Header => RequestField::Header(field, header.expect("missing header name")),
            RequestFieldKind::NewtypeBody => RequestField::NewtypeBody(field),
            RequestFieldKind::Path => RequestField::Path(field),
            RequestFieldKind::Query => RequestField::Query(field),
        }
    }

    fn kind(&self) -> RequestFieldKind {
        match *self {
            RequestField::Body(..) => RequestFieldKind::Body,
            RequestField::Header(..) => RequestFieldKind::Header,
            RequestField::NewtypeBody(..) => RequestFieldKind::NewtypeBody,
            RequestField::Path(..) => RequestFieldKind::Path,
            RequestField::Query(..) => RequestFieldKind::Query,
        }
    }

    fn is_body(&self) -> bool {
        self.kind() == RequestFieldKind::Body
    }

    fn is_header(&self) -> bool {
        self.kind() == RequestFieldKind::Header
    }

    fn is_path(&self) -> bool {
        self.kind() == RequestFieldKind::Path
    }

    fn is_query(&self) -> bool {
        self.kind() == RequestFieldKind::Query
    }

    fn field(&self) -> &Field {
        match *self {
            RequestField::Body(ref field) => field,
            RequestField::Header(ref field, _) => field,
            RequestField::NewtypeBody(ref field) => field,
            RequestField::Path(ref field) => field,
            RequestField::Query(ref field) => field,
        }
    }

    fn field_(&self, kind: RequestFieldKind) -> Option<&Field> {
        if self.kind() == kind {
            Some(self.field())
        } else {
            None
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum RequestFieldKind {
    Body,
    Header,
    NewtypeBody,
    Path,
    Query,
}
<|endoftext|>


<commit_before><commit_msg>only remove when all paths exist (#36)<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1894<commit_after>// https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/
pub fn chalk_replacer(chalk: Vec<i32>, k: i32) -> i32 {
    todo!()
}

fn main() {
    println!("{}", chalk_replacer(vec![5, 1, 5], 22)); // 0
    println!("{}", chalk_replacer(vec![3, 4, 1, 2], 25)); // 1
}
<|endoftext|>


<commit_before><commit_msg>Refactor scene initialization into function<commit_after><|endoftext|>


<commit_before><commit_msg>Make all fields in get_message_event response optional<commit_after><|endoftext|>


<commit_before><commit_msg>Implement itunes api client<commit_after>extern crate rustc_serialize;
use std::io::Read;
use rustc_serialize::json;
use hyper::Client;

static BASE_URL: &'static str = "https://itunes.apple.com/";

#[allow(non_snake_case)]
#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct Track {
    pub wrapperType:            String, // track
    pub kind:                   Option<String>,
    pub artistId:               i32,
    pub collectionId:           i32,
    pub trackId:                Option<i32>,
    pub artistName:             String,
    pub collectionName:         String,
    pub trackName:              Option<String>,
    pub collectionCensoredName: String,
    pub trackCensoredName:      Option<String>,
    pub artistViewUrl:          String,
    pub collectionViewUrl:      String,
    pub trackViewUrl:           Option<String>,
    pub previewUrl:             Option<String>,
    pub artworkUrl30:           Option<String>,
    pub artworkUrl60:           Option<String>,
    pub artworkUrl100:          Option<String>,
    pub collectionPrice:        f32,
    pub trackPrice:             f32,
    pub releaseDate:            String,
    pub collectionExplicitness: String,
    pub trackExplicitness:      Option<String>,
    pub discCount:              Option<i32>,
    pub discNumber:             Option<i32>,
    pub trackCount:             i32,
    pub trackNumber:            Option<i32>,
    pub trackTimeMillis:        Option<i32>,
    pub country:                String,
    pub currency:               String,
    pub primaryGenreName:       String,
    pub isStreamable:           Option<bool>,
}

#[allow(non_snake_case)]
#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct Album {
    pub wrapperType:            String, // collection
    pub kind:                   String,
    pub artistId:               i32,
    pub collectionId:           i32,
    pub artistName:             String,
    pub collectionName:         String,
    pub collectionCensoredName: String,
    pub artistViewUrl:          String,
    pub collectionViewUrl:      String,
    pub collectionPrice:        String,
    pub releaseDate:            String,
    pub collectionExplicitness: String,
    pub trackCount:             i32,
    pub country:                String,
    pub currency:               String,
    pub primaryGenreName:       String,
}

#[allow(non_snake_case)]
#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct LookupResponse<T> {
    pub resultCount: i32,
    pub results:     Vec<T>,
}

pub fn fetch_songs(id: &str, country: &str) -> json::DecodeResult<LookupResponse<Track>> {
    let client = Client::new();
    let url = format!("{}/lookup/?id={}&country={}&entity=song", BASE_URL, id, country);
    let mut res = client.get(&url)
                        .send().unwrap();
    let mut body = String::new();
    res.read_to_string(&mut body).unwrap();
    json::decode::<LookupResponse<Track>>(&body)
}

#[cfg(test)]
mod test {
    use super::fetch_songs;
    #[test]
    fn test_fetch_songs() {
        let response = fetch_songs("1160715126", "jp").unwrap();
        assert_eq!(response.resultCount, 14);
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix(password): use fallback method on msys/cygwin, rpassword doesn't handle these<commit_after><|endoftext|>


<commit_before><commit_msg>Break out printing to separate struct<commit_after><|endoftext|>


<commit_before><commit_msg>Add test to ensure const-prop fails gracefully<commit_after>#[inline(never)]
fn read(_: usize) { }

fn main() {
    const FOO: &i32 = &1;
    let x = FOO as *const i32 as usize;
    read(x);
}

// END RUST SOURCE
// START rustc.main.ConstProp.before.mir
//  bb0: {
//      ...
//      _3 = _4;
//      _2 = move _3 as *const i32 (Misc);
//      ...
//      _1 = move _2 as usize (Misc);
//      ...
//      _6 = _1;
//      _5 = const read(move _6) -> bb1;
//  }
// END rustc.main.ConstProp.before.mir
// START rustc.main.ConstProp.after.mir
//  bb0: {
//      ...
//      _3 = _4;
//      _2 = move _3 as *const i32 (Misc);
//      ...
//      _1 = move _2 as usize (Misc);
//      ...
//      _6 = _1;
//      _5 = const read(move _6) -> bb1;
//  }
// END rustc.main.ConstProp.after.mir
<|endoftext|>


<commit_before>use std::num::One;
use std::ptr;
use std::cast;
use std::borrow;
use extra::rc::{Rc, RcMut};
use gl;
use gl::types::*;
use nalgebra::mat::{Indexable, ToHomogeneous, Transformation, Transform, Rotation, Rotate, Translation};
use nalgebra::mat::{Mat3, Mat4};
use nalgebra::vec::Vec3;
use nalgebra::types::Iso3f64;
use resources::shaders_manager::ObjectShaderContext;
use resources::textures_manager;
use resources::textures_manager::Texture;
use mesh::Mesh;

#[path = "error.rs"]
mod error;

type Transform3d = Iso3f64;
type Scale3d     = Mat3<GLfloat>;

/// Set of datas identifying a scene node.
pub struct ObjectData {
    priv texture:   Rc<Texture>,
    priv scale:     Scale3d,
    priv transform: Transform3d,
    priv color:     Vec3<f32>,
}

/// Structure of all 3d objects on the scene. This is the only interface to manipulate the object
/// position, color, vertices and texture.
#[deriving(Clone)]
pub struct Object {
    priv data:    RcMut<ObjectData>,
    priv mesh:    RcMut<Mesh>
}

impl Object {
    #[doc(hidden)]
    pub fn new(mesh:     RcMut<Mesh>,
               r:        f32,
               g:        f32,
               b:        f32,
               texture:  Rc<Texture>,
               sx:       GLfloat,
               sy:       GLfloat,
               sz:       GLfloat) -> Object {
        let data = ObjectData {
            scale:     Mat3::new(sx, 0.0, 0.0,
                                 0.0, sy, 0.0,
                                 0.0, 0.0, sz),
            transform: One::one(),
            color:     Vec3::new(r, g, b),
            texture: texture,
        };

        Object {
            data:    RcMut::from_freeze(data),
            mesh:    mesh,
        }
    }

    #[doc(hidden)]
    pub fn upload(&self, context: &ObjectShaderContext) {
        do self.data.with_borrow |data| {
            let formated_transform:  Mat4<f64> = data.transform.to_homogeneous();
            let formated_ntransform: Mat3<f64> = data.transform.submat().submat();

            // we convert the matrix elements and do the transposition at the same time
            let transform_glf = Mat4::new(
                formated_transform.at((0, 0)) as GLfloat,
                formated_transform.at((1, 0)) as GLfloat,
                formated_transform.at((2, 0)) as GLfloat,
                formated_transform.at((3, 0)) as GLfloat,

                formated_transform.at((0, 1)) as GLfloat,
                formated_transform.at((1, 1)) as GLfloat,
                formated_transform.at((2, 1)) as GLfloat,
                formated_transform.at((3, 1)) as GLfloat,

                formated_transform.at((0, 2)) as GLfloat,
                formated_transform.at((1, 2)) as GLfloat,
                formated_transform.at((2, 2)) as GLfloat,
                formated_transform.at((3, 2)) as GLfloat,

                formated_transform.at((0, 3)) as GLfloat,
                formated_transform.at((1, 3)) as GLfloat,
                formated_transform.at((2, 3)) as GLfloat,
                formated_transform.at((3, 3)) as GLfloat
                );

            let ntransform_glf = Mat3::new(
                formated_ntransform.at((0, 0)) as GLfloat,
                formated_ntransform.at((1, 0)) as GLfloat,
                formated_ntransform.at((2, 0)) as GLfloat,
                formated_ntransform.at((0, 1)) as GLfloat,
                formated_ntransform.at((1, 1)) as GLfloat,
                formated_ntransform.at((2, 1)) as GLfloat,
                formated_ntransform.at((0, 2)) as GLfloat,
                formated_ntransform.at((1, 2)) as GLfloat,
                formated_ntransform.at((2, 2)) as GLfloat
                );

            unsafe {
                verify!(gl::UniformMatrix4fv(context.transform,
                                             1,
                                             gl::FALSE as u8,
                                             cast::transmute(&transform_glf)));

                verify!(gl::UniformMatrix3fv(context.ntransform,
                                             1,
                                             gl::FALSE as u8,
                                             cast::transmute(&ntransform_glf)));

                verify!(gl::UniformMatrix3fv(context.scale, 1, gl::FALSE as u8, cast::transmute(&data.scale)));

                verify!(gl::Uniform3f(context.color, data.color.x, data.color.y, data.color.z));

                // FIXME: we should not switch the buffers if the last drawn shape uses the same.
                self.mesh.with_borrow(|m| m.bind(context.pos, context.normal, context.tex_coord));

                verify!(gl::ActiveTexture(gl::TEXTURE0));
                verify!(gl::BindTexture(gl::TEXTURE_2D, self.data.with_borrow(|d| d.texture.borrow().id())));

                verify!(gl::DrawElements(gl::TRIANGLES,
                                         self.mesh.with_borrow(|m| m.num_pts()) as GLint,
                                         gl::UNSIGNED_INT,
                                         ptr::null()));

                self.mesh.with_borrow(|m| m.unbind());
            }
        }
    }

    /// Sets the local scaling factor of the object.
    pub fn set_scale(&mut self, sx: f64, sy: f64, sz: f64) {
        do self.data.with_mut_borrow |d| {
            d.scale = Mat3::new(
                sx as GLfloat, 0.0, 0.0,
                0.0, sy as GLfloat, 0.0,
                0.0, 0.0, sz as GLfloat)
        }
    }

    /// Get a write access to the geometry mesh. Return true if the geometry needs to be
    /// re-uploaded to the GPU.
    pub fn modify_mesh(&mut self, f: &fn(&mut Mesh) -> bool) {
        do self.mesh.with_mut_borrow |m| {
            if f(m) {
                // FIXME: find a way to upload only the modified parts.
                m.upload()
            }
        }
    }

    /// Sets the color of the object. Colors components must be on the range `[0.0, 1.0]`.
    pub fn set_color(&mut self, r: f32, g: f32, b: f32) {
        do self.data.with_mut_borrow |d| {
            d.color.x = r;
            d.color.y = g;
            d.color.z = b;
        }
    }

    /// Sets the texture of the object.
    ///
    /// # Arguments
    ///   * `path` - relative path of the texture on the disk
    pub fn set_texture(&mut self, path: &str) {
        self.data.with_mut_borrow(|d| d.texture = textures_manager::singleton().add(path));
    }

    /// Move and orient the object such that it is placed at the point `eye` and have its `x` axis
    /// oriented toward `at`.
    pub fn look_at(&mut self, eye: &Vec3<f64>, at: &Vec3<f64>, up: &Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.look_at(eye, at, up))
    }

    /// Move and orient the object such that it is placed at the point `eye` and have its `z` axis
    /// oriented toward `at`.
    pub fn look_at_z(&mut self, eye: &Vec3<f64>, at: &Vec3<f64>, up: &Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.look_at_z(eye, at, up))
    }
}

impl Transformation<Transform3d> for Object {
    fn transformation(&self) -> Transform3d {
        self.data.with_borrow(|d| d.transform.clone())
    }

    fn inv_transformation(&self) -> Transform3d {
        self.data.with_borrow(|d| d.transform.inv_transformation())
    }

    fn transform_by(&mut self, t: &Transform3d) {
        self.data.with_mut_borrow(|d| d.transform.transform_by(t))
    }

    fn transformed(&self, _: &Transform3d) -> Object {
        fail!("Cannot clone an object.")
    }

    fn set_transformation(&mut self, t: Transform3d) {
        self.data.with_mut_borrow(|d| d.transform.set_transformation(t))
    }
}

impl Transform<Vec3<f64>> for Object {
    fn transform(&self, v: &Vec3<f64>) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.transform(v))
    }

    fn inv_transform(&self, v: &Vec3<f64>) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.inv_transform(v))
    }
}

impl Rotation<Vec3<f64>> for Object {
    fn rotation(&self) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.rotation())
    }

    fn inv_rotation(&self) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.inv_rotation())
    }

    fn rotate_by(&mut self, t: &Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.rotate_by(t))
    }

    fn rotated(&self, _: &Vec3<f64>) -> Object {
        fail!("Cannot clone an object.")
    }

    fn set_rotation(&mut self, r: Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.set_rotation(r))
    }
}

impl Rotate<Vec3<f64>> for Object {
    fn rotate(&self, v: &Vec3<f64>) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.rotate(v))
    }

    fn inv_rotate(&self, v: &Vec3<f64>) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.inv_rotate(v))
    }
}

impl Translation<Vec3<f64>> for Object {
    fn translation(&self) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.translation())
    }

    fn inv_translation(&self) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.inv_translation())
    }

    fn translate_by(&mut self, t: &Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.translate_by(t))
    }

    fn translated(&self, _: &Vec3<f64>) -> Object {
        fail!("Cannot clone an object.")
    }

    fn set_translation(&mut self, t: Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.set_translation(t))
    }
}

impl Eq for Object {
    fn eq(&self, other: &Object) -> bool {
        self.data.with_borrow(|d1| other.data.with_borrow(|d2| borrow::ref_eq(d1, d2)))
    }
}
<commit_msg>Add a method to make an Object visible or not.<commit_after>use std::num::One;
use std::ptr;
use std::cast;
use std::borrow;
use extra::rc::{Rc, RcMut};
use gl;
use gl::types::*;
use nalgebra::mat::{Indexable, ToHomogeneous, Transformation, Transform, Rotation, Rotate, Translation};
use nalgebra::mat::{Mat3, Mat4};
use nalgebra::vec::Vec3;
use nalgebra::types::Iso3f64;
use resources::shaders_manager::ObjectShaderContext;
use resources::textures_manager;
use resources::textures_manager::Texture;
use mesh::Mesh;

#[path = "error.rs"]
mod error;

type Transform3d = Iso3f64;
type Scale3d     = Mat3<GLfloat>;

/// Set of datas identifying a scene node.
pub struct ObjectData {
    priv texture:   Rc<Texture>,
    priv scale:     Scale3d,
    priv transform: Transform3d,
    priv color:     Vec3<f32>,
    priv visible:   bool
}

/// Structure of all 3d objects on the scene. This is the only interface to manipulate the object
/// position, color, vertices and texture.
#[deriving(Clone)]
pub struct Object {
    priv data:    RcMut<ObjectData>,
    priv mesh:    RcMut<Mesh>
}

impl Object {
    #[doc(hidden)]
    pub fn new(mesh:     RcMut<Mesh>,
               r:        f32,
               g:        f32,
               b:        f32,
               texture:  Rc<Texture>,
               sx:       GLfloat,
               sy:       GLfloat,
               sz:       GLfloat) -> Object {
        let data = ObjectData {
            scale:     Mat3::new(sx, 0.0, 0.0,
                                 0.0, sy, 0.0,
                                 0.0, 0.0, sz),
            transform: One::one(),
            color:     Vec3::new(r, g, b),
            texture:   texture,
            visible:   true
        };

        Object {
            data:    RcMut::from_freeze(data),
            mesh:    mesh,
        }
    }

    #[doc(hidden)]
    pub fn upload(&self, context: &ObjectShaderContext) {
        do self.data.with_borrow |data| {
            if data.visible {
                let formated_transform:  Mat4<f64> = data.transform.to_homogeneous();
                let formated_ntransform: Mat3<f64> = data.transform.submat().submat();

                // we convert the matrix elements and do the transposition at the same time
                let transform_glf = Mat4::new(
                    formated_transform.at((0, 0)) as GLfloat,
                    formated_transform.at((1, 0)) as GLfloat,
                    formated_transform.at((2, 0)) as GLfloat,
                    formated_transform.at((3, 0)) as GLfloat,

                    formated_transform.at((0, 1)) as GLfloat,
                    formated_transform.at((1, 1)) as GLfloat,
                    formated_transform.at((2, 1)) as GLfloat,
                    formated_transform.at((3, 1)) as GLfloat,

                    formated_transform.at((0, 2)) as GLfloat,
                    formated_transform.at((1, 2)) as GLfloat,
                    formated_transform.at((2, 2)) as GLfloat,
                    formated_transform.at((3, 2)) as GLfloat,

                    formated_transform.at((0, 3)) as GLfloat,
                    formated_transform.at((1, 3)) as GLfloat,
                    formated_transform.at((2, 3)) as GLfloat,
                    formated_transform.at((3, 3)) as GLfloat
                    );

                let ntransform_glf = Mat3::new(
                    formated_ntransform.at((0, 0)) as GLfloat,
                    formated_ntransform.at((1, 0)) as GLfloat,
                    formated_ntransform.at((2, 0)) as GLfloat,
                    formated_ntransform.at((0, 1)) as GLfloat,
                    formated_ntransform.at((1, 1)) as GLfloat,
                    formated_ntransform.at((2, 1)) as GLfloat,
                    formated_ntransform.at((0, 2)) as GLfloat,
                    formated_ntransform.at((1, 2)) as GLfloat,
                    formated_ntransform.at((2, 2)) as GLfloat
                    );

                unsafe {
                    verify!(gl::UniformMatrix4fv(context.transform,
                                                 1,
                                                 gl::FALSE as u8,
                                                 cast::transmute(&transform_glf)));

                    verify!(gl::UniformMatrix3fv(context.ntransform,
                                                 1,
                                                 gl::FALSE as u8,
                                                 cast::transmute(&ntransform_glf)));

                    verify!(gl::UniformMatrix3fv(context.scale, 1, gl::FALSE as u8, cast::transmute(&data.scale)));

                    verify!(gl::Uniform3f(context.color, data.color.x, data.color.y, data.color.z));

                    // FIXME: we should not switch the buffers if the last drawn shape uses the same.
                    self.mesh.with_borrow(|m| m.bind(context.pos, context.normal, context.tex_coord));

                    verify!(gl::ActiveTexture(gl::TEXTURE0));
                    verify!(gl::BindTexture(gl::TEXTURE_2D, self.data.with_borrow(|d| d.texture.borrow().id())));

                    verify!(gl::DrawElements(gl::TRIANGLES,
                                             self.mesh.with_borrow(|m| m.num_pts()) as GLint,
                                             gl::UNSIGNED_INT,
                                             ptr::null()));

                    self.mesh.with_borrow(|m| m.unbind());
                }
            }
        }
    }

    /// Sets the visible state of this object. An invisible object does not draw itself.
    pub fn set_visible(&mut self, visible: bool) {
        self.data.with_mut_borrow(|d| d.visible = visible)
    }

    /// Returns true if this object can be visible.
    pub fn visible(&self) -> bool {
        self.data.with_borrow(|d| d.visible)
    }

    /// Sets the local scaling factor of the object.
    pub fn set_scale(&mut self, sx: f64, sy: f64, sz: f64) {
        do self.data.with_mut_borrow |d| {
            d.scale = Mat3::new(
                sx as GLfloat, 0.0, 0.0,
                0.0, sy as GLfloat, 0.0,
                0.0, 0.0, sz as GLfloat)
        }
    }

    /// Get a write access to the geometry mesh. Return true if the geometry needs to be
    /// re-uploaded to the GPU.
    pub fn modify_mesh(&mut self, f: &fn(&mut Mesh) -> bool) {
        do self.mesh.with_mut_borrow |m| {
            if f(m) {
                // FIXME: find a way to upload only the modified parts.
                m.upload()
            }
        }
    }

    /// Sets the color of the object. Colors components must be on the range `[0.0, 1.0]`.
    pub fn set_color(&mut self, r: f32, g: f32, b: f32) {
        do self.data.with_mut_borrow |d| {
            d.color.x = r;
            d.color.y = g;
            d.color.z = b;
        }
    }

    /// Sets the texture of the object.
    ///
    /// # Arguments
    ///   * `path` - relative path of the texture on the disk
    pub fn set_texture(&mut self, path: &str) {
        self.data.with_mut_borrow(|d| d.texture = textures_manager::singleton().add(path));
    }

    /// Move and orient the object such that it is placed at the point `eye` and have its `x` axis
    /// oriented toward `at`.
    pub fn look_at(&mut self, eye: &Vec3<f64>, at: &Vec3<f64>, up: &Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.look_at(eye, at, up))
    }

    /// Move and orient the object such that it is placed at the point `eye` and have its `z` axis
    /// oriented toward `at`.
    pub fn look_at_z(&mut self, eye: &Vec3<f64>, at: &Vec3<f64>, up: &Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.look_at_z(eye, at, up))
    }
}

impl Transformation<Transform3d> for Object {
    fn transformation(&self) -> Transform3d {
        self.data.with_borrow(|d| d.transform.clone())
    }

    fn inv_transformation(&self) -> Transform3d {
        self.data.with_borrow(|d| d.transform.inv_transformation())
    }

    fn transform_by(&mut self, t: &Transform3d) {
        self.data.with_mut_borrow(|d| d.transform.transform_by(t))
    }

    fn transformed(&self, _: &Transform3d) -> Object {
        fail!("Cannot clone an object.")
    }

    fn set_transformation(&mut self, t: Transform3d) {
        self.data.with_mut_borrow(|d| d.transform.set_transformation(t))
    }
}

impl Transform<Vec3<f64>> for Object {
    fn transform(&self, v: &Vec3<f64>) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.transform(v))
    }

    fn inv_transform(&self, v: &Vec3<f64>) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.inv_transform(v))
    }
}

impl Rotation<Vec3<f64>> for Object {
    fn rotation(&self) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.rotation())
    }

    fn inv_rotation(&self) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.inv_rotation())
    }

    fn rotate_by(&mut self, t: &Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.rotate_by(t))
    }

    fn rotated(&self, _: &Vec3<f64>) -> Object {
        fail!("Cannot clone an object.")
    }

    fn set_rotation(&mut self, r: Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.set_rotation(r))
    }
}

impl Rotate<Vec3<f64>> for Object {
    fn rotate(&self, v: &Vec3<f64>) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.rotate(v))
    }

    fn inv_rotate(&self, v: &Vec3<f64>) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.inv_rotate(v))
    }
}

impl Translation<Vec3<f64>> for Object {
    fn translation(&self) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.translation())
    }

    fn inv_translation(&self) -> Vec3<f64> {
        self.data.with_borrow(|d| d.transform.inv_translation())
    }

    fn translate_by(&mut self, t: &Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.translate_by(t))
    }

    fn translated(&self, _: &Vec3<f64>) -> Object {
        fail!("Cannot clone an object.")
    }

    fn set_translation(&mut self, t: Vec3<f64>) {
        self.data.with_mut_borrow(|d| d.transform.set_translation(t))
    }
}

impl Eq for Object {
    fn eq(&self, other: &Object) -> bool {
        self.data.with_borrow(|d1| other.data.with_borrow(|d2| borrow::ref_eq(d1, d2)))
    }
}
<|endoftext|>


<commit_before><commit_msg>docs(groups): adds examples of ArgGroup usage<commit_after>/// `ArgGroup`s are a family of related arguments and way for you to say, "Any of these arguments".
/// By placing arguments in a logical group, you can make easier requirement and exclusion rules
/// intead of having to list each individually, or when you want a rule to apply "any but not all"
/// arguments.
///
/// For instance, you can make an entire ArgGroup required, this means that one (and *only* one)
/// argument. from that group must be present. Using more than one argument from an ArgGroup causes
/// a failure (graceful exit).
///
/// You can also do things such as name an ArgGroup as a confliction or requirement, meaning any
/// of the arguments that belong to that group will cause a failure if present, or must present
/// respectively.
///
/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be
/// present out of a given set. Imagine that you had multiple arguments, and you want one of them to
/// be required, but making all of them required isn't feasible because perhaps they conflict with
/// each other. For example, lets say that you were building an application where one could set a
/// given version number by supplying a string with an option argument, i.e. `--set-ver v1.2.3`, you
/// also wanted to support automatically using a previous version number and simply incrementing one
/// of the three numbers. So you create three flags `--major`, `--minor`, and `--patch`. All of
/// these arguments shouldn't be used at one time but you want to specify that *at least one* of
/// them is used. For this, you can create a group.

extern crate clap;

use clap::{App, Arg, ArgGroup};

fn main() {
    // Create application like normal
    let matches = App::new("myapp")
                      // Add the version arguments
                      .args_from_usage("--set-ver [ver] 'set version manually'
                                        --major         'auto inc major'
                                        --minor         'auto inc minor'
                                        --patch         'auto inc patch'")
                      // Create a group, make it required, and add the above arguments
                      .arg_group(ArgGroup::with_name("vers")
                                          .required(true)
                                          .add_all(vec!["vers", "major", "minor", "patch"]))
                      // Arguments can also be added to a group individually, these two arguments
                      // are part of the "input" group which is not required
                      .arg(Arg::from_usage("[INPUT_FILE] 'some regular input'").group("input"))
                      .arg(Arg::from_usage("--spec-in [SPEC_IN] 'some special input argument'").group("input"))
                      // Now let's assume we have a -c [config] argument which requires one of
                      // (but **not** both) the "input" arguments
                      .arg(Arg::with_name("config").short("c").takes_value(true).requires("input"))
                      .get_matches();

    // Let's assume the old version 1.2.3
    let mut major = 1;
    let mut minor = 2;
    let mut patch = 3;

    // See if --set-ver was used to set the version manually
    let version = if let Some(ver) = matches.value_of("ver") {
        format!("{}", ver)
    } else {
        // Increment the one requested (in a real program, we'd reset the lower numbers)
        let (maj, min, pat) = (matches.is_present("major"),
                                     matches.is_present("minor"),
                                     matches.is_present("patch"));
        match (maj, min, pat) {
            (true, _, _) => major += 1,
            (_, true, _) => minor += 1,
            (_, _, true) => patch += 1,
            _            => unreachable!(),
        };
        format!("{}.{}.{}", major, minor, patch)
    };

    println!("Version: {}", version);

    // Check for usage of -c
    if matches.is_present("config") {
        let input = matches.value_of("INPUT_FILE").unwrap_or(matches.value_of("SPEC_IN").unwrap());
        println!("Doing work using input {} and config {}",
                                                     input,
                                                     matches.value_of("config").unwrap());
    }

}    <|endoftext|>


<commit_before><commit_msg>Added documentation and comments to the rect struct<commit_after><|endoftext|>


<commit_before><commit_msg>Add codegen test for integers compare<commit_after>// This is test for more optimal Ord implementation for integers.
// See <https://github.com/rust-lang/rust/issues/63758> for more info.

// compile-flags: -C opt-level=3

#![crate_type = "lib"]

use std::cmp::Ordering;

// CHECK-LABEL: @cmp_signed
#[no_mangle]
pub fn cmp_signed(a: i64, b: i64) -> Ordering {
// CHECK: icmp slt
// CHECK: icmp sgt
// CHECK: zext i1
// CHECK: select i1
    a.cmp(&b)
}

// CHECK-LABEL: @cmp_unsigned
#[no_mangle]
pub fn cmp_unsigned(a: u32, b: u32) -> Ordering {
// CHECK: icmp ult
// CHECK: icmp ugt
// CHECK: zext i1
// CHECK: select i1
    a.cmp(&b)
}
<|endoftext|>


<commit_before><commit_msg>Remove call to format_err!(), use err_msg() instead<commit_after><|endoftext|>


<commit_before><commit_msg>Add Entry type<commit_after>use std::ops::Deref;
use std::ops::DerefMut;

use libimagstore::store::FileLockEntry;
use libimagrt::edit::Edit;
use libimagrt::edit::EditResult;
use libimagrt::runtime::Runtime;

#[derive(Debug)]
pub struct Entry<'a>(FileLockEntry<'a>);

impl<'a> Deref for Entry<'a> {
    type Target = FileLockEntry<'a>;

    fn deref(&self) -> &FileLockEntry<'a> {
        &self.0
    }

}

impl<'a> DerefMut for Entry<'a> {

    fn deref_mut(&mut self) -> &mut FileLockEntry<'a> {
        &mut self.0
    }

}

impl<'a> Entry<'a> {

    pub fn new(fle: FileLockEntry<'a>) -> Entry<'a> {
        Entry(fle)
    }

    /// Get the diary id for this entry.
    ///
    /// TODO: calls Option::unwrap() as it assumes that an existing Entry has an ID that is parsable
    pub fn diary_id(&self) -> DiaryId {
        DiaryId::from_storeid(&self.0.get_location().clone()).unwrap()
    }

}

impl<'a> Into<FileLockEntry<'a>> for Entry<'a> {

    fn into(self) -> FileLockEntry<'a> {
        self.0
    }

}

impl<'a> From<FileLockEntry<'a>> for Entry<'a> {

    fn from(fle: FileLockEntry<'a>) -> Entry<'a> {
        Entry::new(fle)
    }

}

impl<'a> Edit for Entry<'a> {

    fn edit_content(&mut self, rt: &Runtime) -> EditResult<()> {
        self.0.edit_content(rt)
    }

}

<|endoftext|>