<commit_before>// Copyright (C) 2016 Élisabeth HENRY.
//
// This file is part of Crowbook.
//
// Crowbook is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// Caribon is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received ba copy of the GNU Lesser General Public License
// along with Crowbook.  If not, see <http://www.gnu.org/licenses/>.

//! This module contains the `Cleaner` traits and various implementations of it.

use std::borrow::Cow;

/// Custom function because we don't really want to touch \t or \n
fn is_whitespace(c: char) -> bool {
    c == ' ' || c == ' ' || c == ' '
}

/// Trait for cleaning a string.
///
/// This trait must be called for text that is e.g. in a paragraph, a title,
/// NOT for code blocks, hyperlinks and so on!
pub trait Cleaner: Sync {
    /// Cleans a string. The default implementation is to remove multiple consecutive whitespaces
    ///
    /// # Argumets
    ///
    /// * `str`: the string that must be cleaned
    /// * `latex`: a bool specifying whether output is Latex code or not
    fn clean<'a>(&self, str: Cow<'a, str>, _latex: bool) -> Cow<'a, str> {
        str
    }
}

/// Cleaner implementation that does nothing
///
/// # Examples
///
/// ```
/// use crowbook::Cleaner;
/// use crowbook::cleaner::Off;
/// let off = Off;
/// let mut s = "  A string   that won't be cleaned ".to_owned();
/// off.clean(&mut s, false);
/// assert_eq!(&s, "  A string   that won't be cleaned ");
/// ```
pub struct Off;
impl Cleaner for Off {}

/// Default implementation of cleaner trait.
///
/// Only removes unnecessary whitespaces.
///
/// # Examples
///
/// ```
/// use crowbook::Cleaner;
/// use crowbook::cleaner::Default;
/// let default = Default;
/// let mut s = "  A  string   with   more   whitespaces  than  needed   ".to_owned();
/// default.clean(&mut s, false);
/// assert_eq!(&s, " A string with more whitespaces than needed ");
/// ```
pub struct Default;
impl Cleaner for Default {
    /// Remove unnecessary whitespaces
    fn clean<'a>(&self, s: Cow<'a, str>, _: bool) -> Cow<'a, str> {
        if s.contains(is_whitespace) { // if not, no need to do anything
            let mut new_s = String::with_capacity(s.len());
            let mut previous_space = false;
            for c in s.chars() {
                if is_whitespace(c) {
                    if previous_space {
                        // previous char already a space, don't copy it
                    } else {
                        new_s.push(c);
                        previous_space = true;
                    }
                } else {
                    previous_space = false;
                    new_s.push(c);
                }
            }

            Cow::Owned(new_s)
        } else {
            s
        }
    }
}

/// Implementation for french 'cleaning'
///
/// This implementation replaces spaces before some characters (e.g. `?` or `;` with non-breaking spaces
///
/// # Examples
///
/// ```
/// use crowbook::Cleaner;
/// use crowbook::cleaner::French;
/// let french = French;
/// let mut s = "  Bonjour ! Comment allez-vous   ?   ".to_owned();
/// french.clean(&mut s, true); // clean for latex so we see the non-breaking spaces easily
/// assert_eq!(&s, " Bonjour~! Comment allez-vous~? ");
/// ```
pub struct French;

impl Cleaner for French {
    /// Puts non breaking spaces before/after `:`, `;`, `?`, `!`, `«`, `»`, `—`
    fn clean<'a>(&self, s: Cow<'a, str>, latex: bool) -> Cow<'a, str> {
        fn is_trouble(c: char) -> bool {
            match c {
                '?'|'!'|';'|':'|'»'|'«'|'—' => true,
                _ => false
            }
        }
        if !s.contains(is_trouble) { // if not, no need to do anything
            return Default.clean(s, latex);
        }
        let nb_char = if latex {
            '~'
        } else {
            ' '
        };
        let nb_char_narrow = if latex {
            '~'
        } else {
            '\u{202F}' // narrow non breaking space
        };
        let nb_char_em = if latex {
            '~'
        } else {
            '\u{2002}' // demi em space
        };

        let s = Default.clean(s, latex); // first pass with default impl
        let mut new_s = String::with_capacity(s.len());
        {
            let mut chars = s.chars();
            if let Some(mut current) = chars.next() {
                while let Some(next) = chars.next() {
                    if is_whitespace(current) {
                        match next {
                            // handle narrow nb space before char
                            '?' | '!' | ';' => new_s.push(nb_char_narrow),
                            ':' | '»' => new_s.push(nb_char),
                            _ => new_s.push(current)
                        }
                    } else {
                        new_s.push(current);
                        match current {
                            // handle nb space after char
                            '—' | '«' => {
                                if is_whitespace(next) {
                                    let replacing_char = match current {
                                        '—' => nb_char_em,
                                        '«' => nb_char,
                                        _ => unreachable!(),
                                    };
                                    if let Some(next) = chars.next() {
                                        new_s.push(replacing_char);
                                        current = next;
                                        continue;
                                    } else {
                                        // current will be added after the loop, do don't do it now
                                        current = replacing_char;
                                        break;
                                    }
                                }
                            },
                            _ => (),
                        }
                    }
                    current = next;
                }
                new_s.push(current);
            }
        }

        Cow::Owned(new_s)
    }
}

<commit_msg>Update cleaner doctests<commit_after>// Copyright (C) 2016 Élisabeth HENRY.
//
// This file is part of Crowbook.
//
// Crowbook is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// Caribon is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received ba copy of the GNU Lesser General Public License
// along with Crowbook.  If not, see <http://www.gnu.org/licenses/>.

//! This module contains the `Cleaner` traits and various implementations of it.

use std::borrow::Cow;

/// Custom function because we don't really want to touch \t or \n
fn is_whitespace(c: char) -> bool {
    c == ' ' || c == ' ' || c == ' '
}

/// Trait for cleaning a string.
///
/// This trait must be called for text that is e.g. in a paragraph, a title,
/// NOT for code blocks, hyperlinks and so on!
pub trait Cleaner: Sync {
    /// Cleans a string. The default implementation is to remove multiple consecutive whitespaces
    ///
    /// # Argumets
    ///
    /// * `str`: the string that must be cleaned
    /// * `latex`: a bool specifying whether output is Latex code or not
    fn clean<'a>(&self, str: Cow<'a, str>, _latex: bool) -> Cow<'a, str> {
        str
    }
}

/// Cleaner implementation that does nothing
///
/// # Examples
///
/// ```
/// use crowbook::Cleaner;
/// use crowbook::cleaner::Off;
/// use std::borrow::Cow;
/// let off = Off;
/// let s = off.clean(Cow::Borrowed("  A string   that won't be cleaned "), false);
/// assert_eq!(&s, "  A string   that won't be cleaned ");
/// ```
pub struct Off;
impl Cleaner for Off {}

/// Default implementation of cleaner trait.
///
/// Only removes unnecessary whitespaces.
///
/// # Examples
///
/// ```
/// use crowbook::Cleaner;
/// use crowbook::cleaner::Default;
/// use std::borrow::Cow;
/// let s = Default.clean(Cow::Borrowed("  A  string   with   more   whitespaces  than  needed   "), false);
/// assert_eq!(&s, " A string with more whitespaces than needed ");
/// ```
pub struct Default;
impl Cleaner for Default {
    /// Remove unnecessary whitespaces
    fn clean<'a>(&self, s: Cow<'a, str>, _: bool) -> Cow<'a, str> {
        if s.contains(is_whitespace) { // if not, no need to do anything
            let mut new_s = String::with_capacity(s.len());
            let mut previous_space = false;
            for c in s.chars() {
                if is_whitespace(c) {
                    if previous_space {
                        // previous char already a space, don't copy it
                    } else {
                        new_s.push(c);
                        previous_space = true;
                    }
                } else {
                    previous_space = false;
                    new_s.push(c);
                }
            }

            Cow::Owned(new_s)
        } else {
            s
        }
    }
}

/// Implementation for french 'cleaning'
///
/// This implementation replaces spaces before some characters (e.g. `?` or `;` with non-breaking spaces
///
/// # Examples
///
/// ```
/// use crowbook::Cleaner;
/// use crowbook::cleaner::French;
/// use std::borrow::Cow;
/// let s =  French.clean(Cow::Borrowed("  Bonjour ! Comment allez-vous   ?   "), true);
/// assert_eq!(&s, " Bonjour~! Comment allez-vous~? ");
/// ```
pub struct French;

impl Cleaner for French {
    /// Puts non breaking spaces before/after `:`, `;`, `?`, `!`, `«`, `»`, `—`
    fn clean<'a>(&self, s: Cow<'a, str>, latex: bool) -> Cow<'a, str> {
        fn is_trouble(c: char) -> bool {
            match c {
                '?'|'!'|';'|':'|'»'|'«'|'—' => true,
                _ => false
            }
        }
        if !s.contains(is_trouble) { // if not, no need to do anything
            return Default.clean(s, latex);
        }
        let nb_char = if latex {
            '~'
        } else {
            ' '
        };
        let nb_char_narrow = if latex {
            '~'
        } else {
            '\u{202F}' // narrow non breaking space
        };
        let nb_char_em = if latex {
            '~'
        } else {
            '\u{2002}' // demi em space
        };

        let s = Default.clean(s, latex); // first pass with default impl
        let mut new_s = String::with_capacity(s.len());
        {
            let mut chars = s.chars();
            if let Some(mut current) = chars.next() {
                while let Some(next) = chars.next() {
                    if is_whitespace(current) {
                        match next {
                            // handle narrow nb space before char
                            '?' | '!' | ';' => new_s.push(nb_char_narrow),
                            ':' | '»' => new_s.push(nb_char),
                            _ => new_s.push(current)
                        }
                    } else {
                        new_s.push(current);
                        match current {
                            // handle nb space after char
                            '—' | '«' => {
                                if is_whitespace(next) {
                                    let replacing_char = match current {
                                        '—' => nb_char_em,
                                        '«' => nb_char,
                                        _ => unreachable!(),
                                    };
                                    if let Some(next) = chars.next() {
                                        new_s.push(replacing_char);
                                        current = next;
                                        continue;
                                    } else {
                                        // current will be added after the loop, do don't do it now
                                        current = replacing_char;
                                        break;
                                    }
                                }
                            },
                            _ => (),
                        }
                    }
                    current = next;
                }
                new_s.push(current);
            }
        }

        Cow::Owned(new_s)
    }
}

<|endoftext|>


<commit_before>#[crate_id = "rlua#0.3.0"];
#[crate_type = "lib"];
#[license = "MIT"];

#[feature(globs)];
#[feature(macro_rules)];

pub use lua::Lua;

pub mod ffi;

pub mod lua;
pub mod state;

pub mod traits;
pub mod types;
pub mod status;

pub mod macros;
<commit_msg>Allow non camel-case types for FFI<commit_after>#[crate_id = "rlua#0.3.0"];
#[crate_type = "lib"];
#[license = "MIT"];

#[feature(globs)];
#[feature(macro_rules)];

pub use lua::Lua;

#[allow(non_camel_case_types)]
pub mod ffi;

pub mod lua;
pub mod state;

pub mod traits;
pub mod types;
pub mod status;

pub mod macros;
<|endoftext|>


<commit_before>use ::nfa::{State, Edge, NFA};

#[cfg(test)] mod spec;

#[derive(Clone,PartialEq,Debug)]
struct PotentialMatch {
    current_state: Option<State>,
    remaining_text: String
}

impl PotentialMatch {
    pub fn advance(&self, nfa: &NFA) -> Vec<PotentialMatch> {
        if self.current_state.is_none() {
            return vec![self.clone()];
        }

        let current_state = self.current_state.clone().unwrap();

        match current_state {
            State::State{ref edge, ref out} => {
                match edge {
                    &Some(val) => {
                        if self.remaining_text.is_empty() {
                            return vec![];
                        }

                        if val == self.remaining_text.as_bytes()[0] as char {
                            // can consume char and advance along edge
                            match out {
                                &Edge::End => {
                                    vec![PotentialMatch::new(None,
                                                             &self.remaining_text[1..])]
                                },
                                &Edge::Id(id) => {
                                    vec![PotentialMatch::new(nfa.get_state(id),
                                                             &self.remaining_text[1..])]
                                },
                                _ => panic!()
                            }
                        } else { // cannot proceed
                            vec![]
                        }
                    },
                    &None => {
                        // can advance along empty edge
                        match out {
                            &Edge::End => {
                                vec![PotentialMatch::new(None,
                                                         &self.remaining_text)]
                            },
                            &Edge::Id(id) => {
                                vec![PotentialMatch::new(
                                        nfa.get_state(id),
                                        &self.remaining_text)]
                            },
                            _ => panic!()
                        }
                    }
                }
            },
            State::Split{ref s1, ref out1, ref s2, ref out2} => {
                vec![]
            }
        }
    }

    pub fn is_match(&self) -> bool {
        self.current_state.is_none()
    }

    pub fn new(state: Option<State>, remaining_text: &str) -> PotentialMatch {
        PotentialMatch {
            current_state: state,
            remaining_text: remaining_text.to_owned()
        }
    }
}

pub struct Matcher {
    nfa: NFA,
    text: String
}

impl Matcher {
    pub fn new(nfa: NFA, text: &str) -> Matcher {
        Matcher {
            nfa: nfa,
            text: text.to_owned()
        }
    }

    pub fn run(&mut self) -> bool {

        if self.nfa.num_states() == 0 { // regex is empty
            return true;
        }

        let mut states = vec![
            PotentialMatch::new(Some(self.nfa.get_start().unwrap()),
                                &self.text)
        ];

        while Self::has_valid_state(&states) {

            let mut updated_states = Vec::new();

            for state in states {
                let new_states = state.advance(&self.nfa);

                for s in new_states {
                    if s.is_match() {
                        return true;
                    } else {
                        updated_states.push(s);
                    }
                }
            }

            states = updated_states;
        }

        false
    }

    fn has_valid_state(states: &Vec<PotentialMatch>) -> bool {
        states.len() > 0
    }
}

<commit_msg>handle split state case<commit_after>use ::nfa::{State, Edge, NFA};

#[cfg(test)] mod spec;

#[derive(Clone,PartialEq,Debug)]
struct PotentialMatch {
    current_state: Option<State>,
    remaining_text: String
}

impl PotentialMatch {
    pub fn advance(&self, nfa: &NFA) -> Vec<PotentialMatch> {
        if self.current_state.is_none() {
            return vec![self.clone()];
        }

        let current_state = self.current_state.clone().unwrap();

        match current_state {
            State::State{ref edge, ref out} => {
                self.next(nfa, edge, out)
            },
            State::Split{ref s1, ref out1, ref s2, ref out2} => {
                let mut s1_next = self.next(nfa, s1, out1);
                let mut s2_next = self.next(nfa, s2, out2);
                s1_next.append(&mut s2_next);
                s1_next
            }
        }
    }

    fn next(&self, nfa: &NFA, edge: &Option<char>, out: &Edge) -> Vec<PotentialMatch> {
        match edge {
            &Some(val) => {
                if self.remaining_text.is_empty() {
                    // no character to consume, this potential match cannot continue
                    return vec![];
                }

                if val == self.remaining_text.as_bytes()[0] as char {
                    // can consume char and advance along edge
                    match out {
                        &Edge::End => {
                            vec![PotentialMatch::new(None,
                                                     &self.remaining_text[1..])]
                        },
                        &Edge::Id(id) => {
                            vec![PotentialMatch::new(nfa.get_state(id),
                            &self.remaining_text[1..])]
                        },
                        _ => panic!()
                    }
                } else { // cannot proceed
                    vec![]
                }
            },
            &None => {
                // can advance along empty edge
                match out {
                    &Edge::End => {
                        vec![PotentialMatch::new(None,
                                                 &self.remaining_text)]
                    },
                    &Edge::Id(id) => {
                        vec![PotentialMatch::new(
                            nfa.get_state(id),
                            &self.remaining_text)]
                    },
                    _ => panic!()
                }
            }
        }

    }

    pub fn is_match(&self) -> bool {
        self.current_state.is_none()
    }

    pub fn new(state: Option<State>, remaining_text: &str) -> PotentialMatch {
        PotentialMatch {
            current_state: state,
            remaining_text: remaining_text.to_owned()
        }
    }
}

pub struct Matcher {
    nfa: NFA,
    text: String
}

impl Matcher {
    pub fn new(nfa: NFA, text: &str) -> Matcher {
        Matcher {
            nfa: nfa,
            text: text.to_owned()
        }
    }

    pub fn run(&mut self) -> bool {

        if self.nfa.num_states() == 0 { // regex is empty
            return true;
        }

        let mut states = vec![
            PotentialMatch::new(Some(self.nfa.get_start().unwrap()),
                                &self.text)
        ];

        while Self::has_valid_state(&states) {

            let mut updated_states = Vec::new();

            for state in states {
                let new_states = state.advance(&self.nfa);

                for s in new_states {
                    if s.is_match() {
                        return true;
                    } else {
                        updated_states.push(s);
                    }
                }
            }

            states = updated_states;
        }

        false
    }

    fn has_valid_state(states: &Vec<PotentialMatch>) -> bool {
        states.len() > 0
    }
}

<|endoftext|>


<commit_before>use std::borrow::ToOwned;
use std::collections::HashSet;
use std::ffi::AsOsStr;
use std::fs::PathExt;
use std::fs;
use std::io::{Read,Write};
use std::io;
use std::path::AsPath;
use std::path;
use std::process;

use atomicwrites::{AtomicFile,DisallowOverwrite};
use email::rfc5322::Rfc5322Parser;
use uuid::Uuid;
use vobject::{Component,Property,parse_component,write_component};

use cli::Configuration;

pub fn handle_process(process: &mut process::Child) -> io::Result<()> {
    let exitcode = try!(process.wait());
    if !exitcode.success() {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            "",
            Some(format!("{}", exitcode))
        ));
    };
    Ok(())
}

struct IndexIterator {
    linebuffer: Vec<String>
}

impl IndexIterator {
    fn new(output: &String) -> IndexIterator {
        let rv = output.split('\n').map(|x| x.to_string()).collect();
        IndexIterator {
            linebuffer: rv
        }
    }
}

impl Iterator for IndexIterator {
    type Item = IndexItem;

    fn next(&mut self) -> Option<IndexItem> {
        match self.linebuffer.pop() {
            Some(x) => Some(IndexItem::new(x)),
            None => None
        }
    }
}

struct IndexItem {
    pub email: String,
    pub name: String,
    pub filepath: Option<path::PathBuf>
}

impl IndexItem {
    fn new(line: String) -> IndexItem {
        let mut parts = line.split('\t');

        IndexItem {
            email: parts.next().unwrap_or("").to_string(),
            name: parts.next().unwrap_or("").to_string(),
            filepath: match parts.next() {
                Some(x) => Some(path::PathBuf::new(x)),
                None => None
            }
        }
    }
}

pub struct Contact {
    pub component: Component,
    pub path: path::PathBuf
}

impl Contact {
    pub fn from_file<P: AsOsStr + path::AsPath + ?Sized>(path: &P) -> io::Result<Contact> {
        // FIXME: Why is "AsOsStr" above necessary? File::open has a sig w/o it
        let mut contact_file = try!(fs::File::open(&path));
        let contact_string = {
            let mut x = String::new();
            try!(contact_file.read_to_string(&mut x));
            x
        };

        let item = match parse_component(contact_string.as_slice()) {
            Ok(x) => x,
            Err(e) => return Err(io::Error::new(
                io::ErrorKind::Other,
                "Error while parsing contact",
                Some(format!("{}", e))
            ))
        };

        Ok(Contact { component: item, path: path.as_path().to_owned() })
    }

    pub fn generate(fullname: Option<&str>, email: Option<&str>, dir: &path::Path) -> Contact {
        let (uid, contact_path) = {
            let mut uid;
            let mut contact_path;
            loop {
                uid = Uuid::new_v4().to_simple_string();
                contact_path = dir.join(&format!("{}.vcf", uid));
                if !(*contact_path).exists() {
                    break
                }
            };
            (uid, contact_path)
        };
        Contact { path: contact_path, component: generate_component(uid, fullname, email) }
    }

    pub fn write_create(&self) -> io::Result<()> {
        let string = write_component(&self.component);
        let af = AtomicFile::new(&self.path, DisallowOverwrite);

        af.write(|f| {
            f.write_all(string.as_bytes())
        })
    }
}

fn generate_component(uid: String, fullname: Option<&str>, email: Option<&str>) -> Component {
    let mut comp = Component::new("VCARD");

    match fullname {
        Some(x) => comp.all_props_mut("FN").push(Property::new(x)),
        None => ()
    };

    match email {
        Some(x) => comp.all_props_mut("EMAIL").push(Property::new(x)),
        None => ()
    };
    comp.all_props_mut("UID").push(Property::new(uid.as_slice()));
    comp
}

pub fn index_query<'a>(config: &Configuration, query: &str) -> io::Result<IndexIterator> {
    let mut process = try!(
        command_from_config(config.grep_cmd.as_slice())
        .arg(query.as_slice())
        .stdin(process::Stdio::piped())
        .stderr(process::Stdio::inherit())
        .spawn());

    {
        let mut index_fp = try!(fs::File::open(&config.index_path));
        let mut stdin = process.stdin.take().unwrap();
        let mut line: Vec<u8> = vec![];
        try!(index_fp.read_to_end(&mut line));
        try!(stdin.write_all(line.as_slice()));
    }

    try!(handle_process(&mut process));

    let stream = match process.stdout.as_mut() {
        Some(x) => x,
        None => return Err(io::Error::new(
            io::ErrorKind::ResourceUnavailable,
            "Failed to get stdout from grep process.",
            None
        ))
    };

    let mut output = String::new();
    try!(stream.read_to_string(&mut output));
    Ok(IndexIterator::new(&output))
}

/// Better than index_query if you're only interested in the filepath, as duplicate entries will be
/// removed.
pub fn file_query(config: &Configuration, query: &str) -> io::Result<HashSet<path::PathBuf>> {
    let mut rv: HashSet<path::PathBuf> = HashSet::new();
    rv.extend(
        try!(index_query(config, query)).filter_map(|x| x.filepath)
    );
    Ok(rv)
}

pub fn index_item_from_contact(contact: &Contact) -> io::Result<String> {
    let name = match contact.component.single_prop("FN") {
        Some(name) => name.value_as_string(),
        None => return Err(io::Error::new(
            io::ErrorKind::Other,
            "No name found.",
            None
        ))
    };

    let emails = contact.component.all_props("EMAIL");
    let mut rv = String::new();
    for email in emails.iter() {
        rv.push_str(format!("{}\t{}\t{}\n", email.value_as_string(), name, contact.path.display()).as_slice());
    };
    Ok(rv)
}

/// Return a tuple (fullname, email)
pub fn parse_from_header<'a>(s: &'a String) -> (Option<&'a str>, Option<&'a str>) {
    let mut split = s.rsplitn(1, ' ');
    let email = match split.next() {
        Some(x) => Some(x.trim_left_matches('<').trim_right_matches('>')),
        None => Some(s.as_slice())
    };
    let name = split.next();
    (name, email)
}

/// Given an email, return value of From header.
pub fn read_sender_from_email(email: &str) -> Option<String> {
    let mut parser = Rfc5322Parser::new(email);
    while !parser.eof() {
        match parser.consume_header() {
            Some(header) => {
                if header.name == "From" {
                    return header.get_value().ok()
                };
            },
            None => return None
        };
    };
    None
}

/// Write sender from given email as .vcf file to given directory.
pub fn add_contact_from_email(contact_dir: &path::Path, email_input: &str) -> io::Result<Contact> {
    let from_header = match read_sender_from_email(email_input) {
        Some(x) => x,
        None => return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "Couldn't find From-header in email.",
            None
        ))
    };
    let (fullname, email) = parse_from_header(&from_header);
    let contact = Contact::generate(fullname, email, contact_dir);
    try!(contact.write_create());
    Ok(contact)
}

fn command_from_config(config_val: &str) -> process::Command {
    let mut parts = config_val.split(' ');
    let main = parts.next().unwrap();
    let rest: Vec<_> = parts.map(|x| x.to_string()).collect();
    let mut rv = process::Command::new(main);
    rv.args(rest.as_slice());
    rv
}
<commit_msg>Fix another grep problem<commit_after>use std::borrow::ToOwned;
use std::collections::HashSet;
use std::ffi::AsOsStr;
use std::fs::PathExt;
use std::fs;
use std::io::{Read,Write};
use std::io;
use std::path::AsPath;
use std::path;
use std::process;

use atomicwrites::{AtomicFile,DisallowOverwrite};
use email::rfc5322::Rfc5322Parser;
use uuid::Uuid;
use vobject::{Component,Property,parse_component,write_component};

use cli::Configuration;

pub fn handle_process(process: &mut process::Child) -> io::Result<()> {
    let exitcode = try!(process.wait());
    if !exitcode.success() {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            "",
            Some(format!("{}", exitcode))
        ));
    };
    Ok(())
}

struct IndexIterator {
    linebuffer: Vec<String>
}

impl IndexIterator {
    fn new(output: &String) -> IndexIterator {
        let rv = output.split('\n').map(|x| x.to_string()).collect();
        IndexIterator {
            linebuffer: rv
        }
    }
}

impl Iterator for IndexIterator {
    type Item = IndexItem;

    fn next(&mut self) -> Option<IndexItem> {
        match self.linebuffer.pop() {
            Some(x) => Some(IndexItem::new(x)),
            None => None
        }
    }
}

struct IndexItem {
    pub email: String,
    pub name: String,
    pub filepath: Option<path::PathBuf>
}

impl IndexItem {
    fn new(line: String) -> IndexItem {
        let mut parts = line.split('\t');

        IndexItem {
            email: parts.next().unwrap_or("").to_string(),
            name: parts.next().unwrap_or("").to_string(),
            filepath: match parts.next() {
                Some(x) => Some(path::PathBuf::new(x)),
                None => None
            }
        }
    }
}

pub struct Contact {
    pub component: Component,
    pub path: path::PathBuf
}

impl Contact {
    pub fn from_file<P: AsOsStr + path::AsPath + ?Sized>(path: &P) -> io::Result<Contact> {
        // FIXME: Why is "AsOsStr" above necessary? File::open has a sig w/o it
        let mut contact_file = try!(fs::File::open(&path));
        let contact_string = {
            let mut x = String::new();
            try!(contact_file.read_to_string(&mut x));
            x
        };

        let item = match parse_component(contact_string.as_slice()) {
            Ok(x) => x,
            Err(e) => return Err(io::Error::new(
                io::ErrorKind::Other,
                "Error while parsing contact",
                Some(format!("{}", e))
            ))
        };

        Ok(Contact { component: item, path: path.as_path().to_owned() })
    }

    pub fn generate(fullname: Option<&str>, email: Option<&str>, dir: &path::Path) -> Contact {
        let (uid, contact_path) = {
            let mut uid;
            let mut contact_path;
            loop {
                uid = Uuid::new_v4().to_simple_string();
                contact_path = dir.join(&format!("{}.vcf", uid));
                if !(*contact_path).exists() {
                    break
                }
            };
            (uid, contact_path)
        };
        Contact { path: contact_path, component: generate_component(uid, fullname, email) }
    }

    pub fn write_create(&self) -> io::Result<()> {
        let string = write_component(&self.component);
        let af = AtomicFile::new(&self.path, DisallowOverwrite);

        af.write(|f| {
            f.write_all(string.as_bytes())
        })
    }
}

fn generate_component(uid: String, fullname: Option<&str>, email: Option<&str>) -> Component {
    let mut comp = Component::new("VCARD");

    match fullname {
        Some(x) => comp.all_props_mut("FN").push(Property::new(x)),
        None => ()
    };

    match email {
        Some(x) => comp.all_props_mut("EMAIL").push(Property::new(x)),
        None => ()
    };
    comp.all_props_mut("UID").push(Property::new(uid.as_slice()));
    comp
}

pub fn index_query<'a>(config: &Configuration, query: &str) -> io::Result<IndexIterator> {
    let mut process = try!(
        command_from_config(config.grep_cmd.as_slice())
        .arg(query.as_slice())
        .stdin(process::Stdio::piped())
        .stdout(process::Stdio::piped())
        .stderr(process::Stdio::inherit())
        .spawn());

    {
        let mut index_fp = try!(fs::File::open(&config.index_path));
        let mut stdin = process.stdin.take().unwrap();
        let mut line: Vec<u8> = vec![];
        try!(index_fp.read_to_end(&mut line));
        try!(stdin.write_all(line.as_slice()));
    }

    try!(handle_process(&mut process));

    let stream = match process.stdout.as_mut() {
        Some(x) => x,
        None => return Err(io::Error::new(
            io::ErrorKind::ResourceUnavailable,
            "Failed to get stdout from grep process.",
            None
        ))
    };

    let mut output = String::new();
    try!(stream.read_to_string(&mut output));
    Ok(IndexIterator::new(&output))
}

/// Better than index_query if you're only interested in the filepath, as duplicate entries will be
/// removed.
pub fn file_query(config: &Configuration, query: &str) -> io::Result<HashSet<path::PathBuf>> {
    let mut rv: HashSet<path::PathBuf> = HashSet::new();
    rv.extend(
        try!(index_query(config, query)).filter_map(|x| x.filepath)
    );
    Ok(rv)
}

pub fn index_item_from_contact(contact: &Contact) -> io::Result<String> {
    let name = match contact.component.single_prop("FN") {
        Some(name) => name.value_as_string(),
        None => return Err(io::Error::new(
            io::ErrorKind::Other,
            "No name found.",
            None
        ))
    };

    let emails = contact.component.all_props("EMAIL");
    let mut rv = String::new();
    for email in emails.iter() {
        rv.push_str(format!("{}\t{}\t{}\n", email.value_as_string(), name, contact.path.display()).as_slice());
    };
    Ok(rv)
}

/// Return a tuple (fullname, email)
pub fn parse_from_header<'a>(s: &'a String) -> (Option<&'a str>, Option<&'a str>) {
    let mut split = s.rsplitn(1, ' ');
    let email = match split.next() {
        Some(x) => Some(x.trim_left_matches('<').trim_right_matches('>')),
        None => Some(s.as_slice())
    };
    let name = split.next();
    (name, email)
}

/// Given an email, return value of From header.
pub fn read_sender_from_email(email: &str) -> Option<String> {
    let mut parser = Rfc5322Parser::new(email);
    while !parser.eof() {
        match parser.consume_header() {
            Some(header) => {
                if header.name == "From" {
                    return header.get_value().ok()
                };
            },
            None => return None
        };
    };
    None
}

/// Write sender from given email as .vcf file to given directory.
pub fn add_contact_from_email(contact_dir: &path::Path, email_input: &str) -> io::Result<Contact> {
    let from_header = match read_sender_from_email(email_input) {
        Some(x) => x,
        None => return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "Couldn't find From-header in email.",
            None
        ))
    };
    let (fullname, email) = parse_from_header(&from_header);
    let contact = Contact::generate(fullname, email, contact_dir);
    try!(contact.write_create());
    Ok(contact)
}

fn command_from_config(config_val: &str) -> process::Command {
    let mut parts = config_val.split(' ');
    let main = parts.next().unwrap();
    let rest: Vec<_> = parts.map(|x| x.to_string()).collect();
    let mut rv = process::Command::new(main);
    rv.args(rest.as_slice());
    rv
}
<|endoftext|>


<commit_before>use std::any::Any;
use std::mem;

use runtime::{Class, Object, Sel, Super};

/// Types that may be sent Objective-C messages.
/// For example: objects, classes, and blocks.
pub unsafe trait Message { }

unsafe impl Message for Object { }

unsafe impl Message for Class { }

#[cfg(target_arch = "x86")]
#[path = "x86.rs"]
mod platform;
#[cfg(target_arch = "x86_64")]
#[path = "x86_64.rs"]
mod platform;
#[cfg(target_arch = "arm")]
#[path = "arm.rs"]
mod platform;
#[cfg(all(target_arch = "aarch64", not(feature = "gnustep")))]
#[path = "arm64.rs"]
mod platform;

#[cfg(feature= "gnustep")]
mod gnustep;

#[cfg(not(feature = "gnustep"))]
use self::platform::{msg_send_fn, msg_send_super_fn};
#[cfg(feature = "gnustep")]
use self::gnustep::{msg_send_fn, msg_send_super_fn};

/// Types that may be used as the arguments of an Objective-C message.
pub trait MessageArguments {
    /// Sends a message to the given obj with the given selector and self as
    /// the arguments.
    ///
    /// The correct version of `objc_msgSend` will be chosen based on the
    /// return type. For more information, see Apple's documenation:
    /// https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/doc/uid/TP40001418-CH1g-88778
    ///
    /// It is recommended to use the `msg_send!` macro rather than calling this
    /// method directly.
    unsafe fn send<T, R>(self, obj: *mut T, sel: Sel) -> R
            where T: Message, R: Any;

    /// Sends a message to the superclass of an instance of a class with self
    /// as the arguments.
    unsafe fn send_super<T, R>(self, obj: *mut T, superclass: &Class, sel: Sel) -> R
            where T: Message, R: Any;
}

macro_rules! message_args_impl {
    ($($a:ident : $t:ident),*) => (
        impl<$($t),*> MessageArguments for ($($t,)*) {
            unsafe fn send<T, R>(self, obj: *mut T, sel: Sel) -> R
                    where T: Message, R: Any {
                let (msg_send_fn, receiver) = msg_send_fn::<R>(obj as *mut Object, sel);
                let msg_send_fn: unsafe extern fn(*mut Object, Sel $(, $t)*) -> R =
                    mem::transmute(msg_send_fn);
                let ($($a,)*) = self;
                objc_try!({
                    msg_send_fn(receiver, sel $(, $a)*)
                })
            }

            unsafe fn send_super<T, R>(self, obj: *mut T, superclass: &Class, sel: Sel) -> R
                    where T: Message, R: Any {
                let sup = Super { receiver: obj as *mut Object, superclass: superclass };
                let (msg_send_fn, receiver) = msg_send_super_fn::<R>(&sup, sel);
                let msg_send_fn: unsafe extern fn(*mut Object, Sel $(, $t)*) -> R =
                    mem::transmute(msg_send_fn);
                let ($($a,)*) = self;
                objc_try!({
                    msg_send_fn(receiver, sel $(, $a)*)
                })
            }
        }
    );
}

message_args_impl!();
message_args_impl!(a: A);
message_args_impl!(a: A, b: B);
message_args_impl!(a: A, b: B, c: C);
message_args_impl!(a: A, b: B, c: C, d: D);
message_args_impl!(a: A, b: B, c: C, d: D, e: E);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L);

#[doc(hidden)]
#[inline(always)]
#[cfg(not(feature = "verify_message"))]
pub unsafe fn send_message<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    Ok(args.send(obj as *mut T, sel))
}

#[doc(hidden)]
#[inline(always)]
#[cfg(feature = "verify_message")]
pub unsafe fn send_message<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String>
        where T: Message, A: MessageArguments + ::verify::EncodeArguments,
        R: Any + ::Encode {
    use verify::verify_message_signature;

    let cls = if obj.is_null() {
        return Err(format!("Messaging {:?} to nil", sel));
    } else {
        (*(obj as *const Object)).class()
    };

    verify_message_signature::<A, R>(cls, sel).map(|_| {
        args.send(obj as *mut T, sel)
    })
}

#[doc(hidden)]
#[inline(always)]
#[cfg(not(feature = "verify_message"))]
pub unsafe fn send_super_message<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    Ok(args.send_super(obj as *mut T, superclass, sel))
}

#[doc(hidden)]
#[inline(always)]
#[cfg(feature = "verify_message")]
pub unsafe fn send_super_message<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments + ::verify::EncodeArguments,
        R: Any + ::Encode {
    use verify::verify_message_signature;

    if obj.is_null() {
        return Err(format!("Messaging {:?} to nil", sel));
    }

    verify_message_signature::<A, R>(superclass, sel).map(|_| {
        args.send_super(obj as *mut T, superclass, sel)
    })
}

#[cfg(test)]
mod tests {
    use runtime::Object;
    use test_utils;

    #[test]
    fn test_send_message() {
        let obj = test_utils::custom_object();
        let result: u32 = unsafe {
            let _: () = msg_send![obj, setFoo:4u32];
            msg_send![obj, foo]
        };
        assert!(result == 4);
    }

    #[test]
    fn test_send_message_stret() {
        let obj = test_utils::custom_object();
        let result: test_utils::CustomStruct = unsafe {
            msg_send![obj, customStruct]
        };
        let expected = test_utils::CustomStruct { a: 1, b:2, c: 3, d: 4 };
        assert!(result == expected);
    }

    #[test]
    fn test_send_message_nil() {
        let nil: *mut Object = ::std::ptr::null_mut();
        let result: usize = unsafe {
            msg_send![nil, hash]
        };
        assert!(result == 0);

        let result: *mut Object = unsafe {
            msg_send![nil, description]
        };
        assert!(result.is_null());

        let result: f64 = unsafe {
            msg_send![nil, doubleValue]
        };
        assert!(result == 0.0);
    }

    #[test]
    fn test_send_message_super() {
        let obj = test_utils::custom_subclass_object();
        let superclass = test_utils::custom_class();
        unsafe {
            let _: () = msg_send![obj, setFoo:4u32];
            let foo: u32 = msg_send![super(obj, superclass), foo];
            assert!(foo == 4);

            // The subclass is overriden to return foo + 2
            let foo: u32 = msg_send![obj, foo];
            assert!(foo == 6);
        }
    }
}
<commit_msg>Made MessageArguments send and send_super provided methods.<commit_after>use std::any::Any;
use std::mem;

use runtime::{Class, Imp, Object, Sel, Super};

/// Types that may be sent Objective-C messages.
/// For example: objects, classes, and blocks.
pub unsafe trait Message { }

unsafe impl Message for Object { }

unsafe impl Message for Class { }

#[cfg(target_arch = "x86")]
#[path = "x86.rs"]
mod platform;
#[cfg(target_arch = "x86_64")]
#[path = "x86_64.rs"]
mod platform;
#[cfg(target_arch = "arm")]
#[path = "arm.rs"]
mod platform;
#[cfg(all(target_arch = "aarch64", not(feature = "gnustep")))]
#[path = "arm64.rs"]
mod platform;

#[cfg(feature= "gnustep")]
mod gnustep;

#[cfg(not(feature = "gnustep"))]
use self::platform::{msg_send_fn, msg_send_super_fn};
#[cfg(feature = "gnustep")]
use self::gnustep::{msg_send_fn, msg_send_super_fn};

/// Types that may be used as the arguments of an Objective-C message.
pub trait MessageArguments: Sized {
    unsafe fn invoke<R>(imp: Imp, obj: *mut Object, sel: Sel, args: Self) -> R
            where R: Any;

    /// Sends a message to the given obj with the given selector and self as
    /// the arguments.
    ///
    /// The correct version of `objc_msgSend` will be chosen based on the
    /// return type. For more information, see Apple's documenation:
    /// https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/doc/uid/TP40001418-CH1g-88778
    ///
    /// It is recommended to use the `msg_send!` macro rather than calling this
    /// method directly.
    unsafe fn send<T, R>(self, obj: *mut T, sel: Sel) -> R
            where T: Message, R: Any {
        let (msg_send_fn, receiver) = msg_send_fn::<R>(obj as *mut Object, sel);
        objc_try!({
            Self::invoke(msg_send_fn, receiver, sel, self)
        })
    }

    /// Sends a message to the superclass of an instance of a class with self
    /// as the arguments.
    unsafe fn send_super<T, R>(self, obj: *mut T, superclass: &Class, sel: Sel) -> R
            where T: Message, R: Any {
        let sup = Super { receiver: obj as *mut Object, superclass: superclass };
        let (msg_send_fn, receiver) = msg_send_super_fn::<R>(&sup, sel);
        objc_try!({
            Self::invoke(msg_send_fn, receiver, sel, self)
        })
    }
}

macro_rules! message_args_impl {
    ($($a:ident : $t:ident),*) => (
        impl<$($t),*> MessageArguments for ($($t,)*) {
            unsafe fn invoke<R>(imp: Imp, obj: *mut Object, sel: Sel, ($($a,)*): Self) -> R
                    where R: Any {
                let imp: unsafe extern fn(*mut Object, Sel $(, $t)*) -> R =
                    mem::transmute(imp);
                imp(obj, sel $(, $a)*)
            }
        }
    );
}

message_args_impl!();
message_args_impl!(a: A);
message_args_impl!(a: A, b: B);
message_args_impl!(a: A, b: B, c: C);
message_args_impl!(a: A, b: B, c: C, d: D);
message_args_impl!(a: A, b: B, c: C, d: D, e: E);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L);

#[doc(hidden)]
#[inline(always)]
#[cfg(not(feature = "verify_message"))]
pub unsafe fn send_message<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    Ok(args.send(obj as *mut T, sel))
}

#[doc(hidden)]
#[inline(always)]
#[cfg(feature = "verify_message")]
pub unsafe fn send_message<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String>
        where T: Message, A: MessageArguments + ::verify::EncodeArguments,
        R: Any + ::Encode {
    use verify::verify_message_signature;

    let cls = if obj.is_null() {
        return Err(format!("Messaging {:?} to nil", sel));
    } else {
        (*(obj as *const Object)).class()
    };

    verify_message_signature::<A, R>(cls, sel).map(|_| {
        args.send(obj as *mut T, sel)
    })
}

#[doc(hidden)]
#[inline(always)]
#[cfg(not(feature = "verify_message"))]
pub unsafe fn send_super_message<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    Ok(args.send_super(obj as *mut T, superclass, sel))
}

#[doc(hidden)]
#[inline(always)]
#[cfg(feature = "verify_message")]
pub unsafe fn send_super_message<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments + ::verify::EncodeArguments,
        R: Any + ::Encode {
    use verify::verify_message_signature;

    if obj.is_null() {
        return Err(format!("Messaging {:?} to nil", sel));
    }

    verify_message_signature::<A, R>(superclass, sel).map(|_| {
        args.send_super(obj as *mut T, superclass, sel)
    })
}

#[cfg(test)]
mod tests {
    use runtime::Object;
    use test_utils;

    #[test]
    fn test_send_message() {
        let obj = test_utils::custom_object();
        let result: u32 = unsafe {
            let _: () = msg_send![obj, setFoo:4u32];
            msg_send![obj, foo]
        };
        assert!(result == 4);
    }

    #[test]
    fn test_send_message_stret() {
        let obj = test_utils::custom_object();
        let result: test_utils::CustomStruct = unsafe {
            msg_send![obj, customStruct]
        };
        let expected = test_utils::CustomStruct { a: 1, b:2, c: 3, d: 4 };
        assert!(result == expected);
    }

    #[test]
    fn test_send_message_nil() {
        let nil: *mut Object = ::std::ptr::null_mut();
        let result: usize = unsafe {
            msg_send![nil, hash]
        };
        assert!(result == 0);

        let result: *mut Object = unsafe {
            msg_send![nil, description]
        };
        assert!(result.is_null());

        let result: f64 = unsafe {
            msg_send![nil, doubleValue]
        };
        assert!(result == 0.0);
    }

    #[test]
    fn test_send_message_super() {
        let obj = test_utils::custom_subclass_object();
        let superclass = test_utils::custom_class();
        unsafe {
            let _: () = msg_send![obj, setFoo:4u32];
            let foo: u32 = msg_send![super(obj, superclass), foo];
            assert!(foo == 4);

            // The subclass is overriden to return foo + 2
            let foo: u32 = msg_send![obj, foo];
            assert!(foo == 6);
        }
    }
}
<|endoftext|>


<commit_before>extern crate conv;
extern crate rand;

use self::conv::prelude::*;
use neat::genome::Genome;
use neat::organism::Organism;
use self::rand::distributions::{IndependentSample, Range};

#[derive(Debug, Clone)]
pub struct Specie{
    representative: Genome,
    fitness: f64,
    pub organisms: Vec<Organism>
}

const MUTATION_PROBABILITY: f64 = 0.25f64;
const INTERSPECIE_MATE_PROBABILITY: f64 = 0.001f64;

impl Specie{
    pub fn new(genome: Genome) -> Specie{
        Specie{ organisms: vec![], representative: genome, fitness: 0f64 }
    }

    pub fn add(&mut self, organism: Organism){
        self.organisms.push(organism);
    }

    pub fn match_genome(&self, organism: &Organism) -> bool{
        self.representative.is_same_specie(&organism.genome)
    }

    pub fn average_fitness(&mut self) -> f64{
        let organisms_count = self.organisms.len().value_as::<f64>().unwrap();
        let total_fitness = self.organisms.iter().fold(0f64, |total, organism| total + organism.fitness);
        self.fitness = total_fitness / organisms_count;
        self.fitness
    }

    pub fn generate_offspring(&mut self, num_of_organisms: usize, population_organisms: &Vec<Organism>){

        let copy_champion = if num_of_organisms > 5 { 1 } else { 0 };

        let mut rng = rand::thread_rng();
        let mut offspring: Vec<Organism> = {
            let mut selected_organisms = vec![];
            let range = Range::new(0, self.organisms.len());
            for _ in 0..num_of_organisms - copy_champion {
                selected_organisms.push(range.ind_sample(&mut rng));
            }
            selected_organisms.iter().map(|organism_pos| self.create_child(&self.organisms[*organism_pos], population_organisms)).collect::<Vec<Organism>>()
        };

        if copy_champion == 1 {
            let champion: Option<Organism> = self.organisms.iter().fold(None, |champion, organism| {
                if champion.is_none() || champion.as_ref().unwrap().fitness < organism.fitness {
                    Some(organism.clone())
                } else {
                    champion
                }
            });

            offspring.push(champion.unwrap());
        }
        self.organisms = offspring;
    }

    pub fn get_representative_genome(&self) -> Genome {
        self.representative.clone()
    }

    pub fn remove_organisms(&mut self) {
        self.organisms = vec![];
    }

    fn create_child(&self, organism: &Organism, population_organisms: &Vec<Organism>) -> Organism {
        if rand::random::<f64>() < MUTATION_PROBABILITY || population_organisms.len() < 2 {
            self.create_child_by_mutation(organism)
        } else {
            self.create_child_by_mate(organism, population_organisms)
        }
    }

    fn create_child_by_mutation(&self, organism: &Organism) -> Organism {
        organism.mutate()
    }

    fn create_child_by_mate(&self, organism: &Organism, population_organisms: &Vec<Organism>) -> Organism {
        let mut rng = rand::thread_rng();
        if rand::random::<f64>() > INTERSPECIE_MATE_PROBABILITY {
            let selected_mate = rand::sample(&mut rng, 0..self.organisms.len(), 1)[0];
            organism.mate(&self.organisms[selected_mate])
        }else{
            let selected_mate = rand::sample(&mut rng, 0..population_organisms.len(), 1)[0];
            organism.mate(&population_organisms[selected_mate])
        }
    }
}

#[cfg(test)]
mod tests {
    use neat::*;

    #[test]
    fn specie_should_return_correct_average_fitness(){
        let mut specie = Specie::new(Genome::new());
        let mut organism1 = Organism::new(Genome::new());
        organism1.fitness = 10f64;

        let mut organism2 = Organism::new(Genome::new());
        organism2.fitness = 15f64;

        let mut organism3 = Organism::new(Genome::new());
        organism3.fitness = 20f64;

        specie.add(organism1);
        specie.add(organism2);
        specie.add(organism3);

        assert!(specie.average_fitness() == 15f64);
    }
}

<commit_msg>Adding specie age<commit_after>extern crate conv;
extern crate rand;

use self::conv::prelude::*;
use neat::genome::Genome;
use neat::organism::Organism;
use self::rand::distributions::{IndependentSample, Range};

#[derive(Debug, Clone)]
pub struct Specie{
    representative: Genome,
    fitness: f64,
    age: usize,
    pub organisms: Vec<Organism>
}

const MUTATION_PROBABILITY: f64 = 0.25f64;
const INTERSPECIE_MATE_PROBABILITY: f64 = 0.001f64;

impl Specie{
    pub fn new(genome: Genome) -> Specie{
        Specie{ organisms: vec![], representative: genome, fitness: 0f64, age: 0 }
    }

    pub fn add(&mut self, organism: Organism){
        self.organisms.push(organism);
    }

    pub fn match_genome(&self, organism: &Organism) -> bool{
        self.representative.is_same_specie(&organism.genome)
    }

    pub fn average_fitness(&mut self) -> f64{
        let organisms_count = self.organisms.len().value_as::<f64>().unwrap();
        let total_fitness = self.organisms.iter().fold(0f64, |total, organism| total + organism.fitness);
        self.fitness = total_fitness / organisms_count;
        self.fitness
    }

    pub fn generate_offspring(&mut self, num_of_organisms: usize, population_organisms: &Vec<Organism>){

        let copy_champion = if num_of_organisms > 5 { 1 } else { 0 };

        let mut rng = rand::thread_rng();
        let mut offspring: Vec<Organism> = {
            let mut selected_organisms = vec![];
            let range = Range::new(0, self.organisms.len());
            for _ in 0..num_of_organisms - copy_champion {
                selected_organisms.push(range.ind_sample(&mut rng));
            }
            selected_organisms.iter().map(|organism_pos| self.create_child(&self.organisms[*organism_pos], population_organisms)).collect::<Vec<Organism>>()
        };

        if copy_champion == 1 {
            let champion: Option<Organism> = self.organisms.iter().fold(None, |champion, organism| {
                if champion.is_none() || champion.as_ref().unwrap().fitness < organism.fitness {
                    Some(organism.clone())
                } else {
                    champion
                }
            });

            offspring.push(champion.unwrap());
        }
        self.organisms = offspring;
    }

    pub fn get_representative_genome(&self) -> Genome {
        self.representative.clone()
    }

    pub fn remove_organisms(&mut self) {
        self.organisms = vec![];
        self.age += 1;
    }

    fn create_child(&self, organism: &Organism, population_organisms: &Vec<Organism>) -> Organism {
        if rand::random::<f64>() < MUTATION_PROBABILITY || population_organisms.len() < 2 {
            self.create_child_by_mutation(organism)
        } else {
            self.create_child_by_mate(organism, population_organisms)
        }
    }

    fn create_child_by_mutation(&self, organism: &Organism) -> Organism {
        organism.mutate()
    }

    fn create_child_by_mate(&self, organism: &Organism, population_organisms: &Vec<Organism>) -> Organism {
        let mut rng = rand::thread_rng();
        if rand::random::<f64>() > INTERSPECIE_MATE_PROBABILITY {
            let selected_mate = rand::sample(&mut rng, 0..self.organisms.len(), 1)[0];
            organism.mate(&self.organisms[selected_mate])
        }else{
            let selected_mate = rand::sample(&mut rng, 0..population_organisms.len(), 1)[0];
            organism.mate(&population_organisms[selected_mate])
        }
    }
}

#[cfg(test)]
mod tests {
    use neat::*;

    #[test]
    fn specie_should_return_correct_average_fitness(){
        let mut specie = Specie::new(Genome::new());
        let mut organism1 = Organism::new(Genome::new());
        organism1.fitness = 10f64;

        let mut organism2 = Organism::new(Genome::new());
        organism2.fitness = 15f64;

        let mut organism3 = Organism::new(Genome::new());
        organism3.fitness = 20f64;

        specie.add(organism1);
        specie.add(organism2);
        specie.add(organism3);

        assert!(specie.average_fitness() == 15f64);
    }
}

<|endoftext|>


<commit_before>//Following semver here
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct Version {
    pub major: u16,
    pub minor: u16,
    pub patch: u32
}

#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct Package {
    pub name: String,
    pub version: Version,
    pub crc32: u32,
    pub child_url: String, // Examples: /some_dir/something.exe
    pub dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    pub packages: Vec<Package>,
    pub parent_url: String, // Examples: https://www.foo.bar
    pub version: u32
}

impl PartialEq for Version {
    fn eq(&self, other: &Version) -> bool {
        self.major == other.major &&
        self.minor == other.minor &&
        self.patch == other.patch
    }
}

impl PartialEq for Package {
    fn eq(&self, other: &Package) -> bool {
        self.name == other.name &&
        self.version == other.version &&
        self.crc32 == other.crc32 &&
        self.dependencies == other.dependencies
    }
}<commit_msg>Implement methods for Version for easier creation<commit_after>use std::error::Error;

//Following semver here
#[derive(Clone, PartialOrd, RustcDecodable, RustcEncodable)]
pub struct Version {
    pub major: u16,
    pub minor: u16,
    pub patch: u32
}

#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct Package {
    pub name: String,
    pub version: Version,
    pub crc32: u32,
    pub child_url: String, // Examples: /some_dir/something.exe
    pub dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    pub packages: Vec<Package>,
    pub parent_url: String, // Examples: https://www.foo.bar
    pub version: u32
}

impl Version {
    fn new() -> Version {
        Version {
            major: 0u16,
            minor: 0u16,
            patch: 0u32
        }
    }

    fn from(major: u16, minor: u16, patch: u32) -> Version {
        Version {
            major: major,
            minor: minor,
            patch: patch
        }
    }

    fn from_str(input: &str) -> Result<Version, String> {
        let versions: Vec<&str> = input.split('.').collect();
        if versions.len() == 3 {
            return Ok(
                Version {
                    major: get!(versions[0].parse::<u16>(),"Version: Unable to parse &str into u16 (major)"),
                    minor: get!(versions[1].parse::<u16>(),"Version: Unable to parse &str into u16 (minor)"),
                    patch: get!(versions[2].parse::<u32>(),"Version: Unable to parse &str into u32 (patch)")
                }
            )
        } else {
            return Err("Version::from_str() cannot parse provided input into Version".to_string())
        }
    }
}

impl PartialEq for Version {
    fn eq(&self, other: &Version) -> bool {
        self.major == other.major &&
        self.minor == other.minor &&
        self.patch == other.patch
    }
}

impl PartialEq for Package {
    fn eq(&self, other: &Package) -> bool {
        self.name == other.name &&
        self.version == other.version &&
        self.crc32 == other.crc32 &&
        self.dependencies == other.dependencies
    }
}<|endoftext|>


<commit_before>//! Just run this program: It will ask you for authorization to view metadata,
//! and then display you the contents of your Google Drive root directory.
//!
//! This example demonstrates how to use the [interactive OAuth 2 flow for installed
//! applications.](https://developers.google.com/identity/protocols/OAuth2InstalledApp)
//!
//! Copyright (c) 2016 Google, Inc. (Lewin Bormann <lbo@spheniscida.de>)

use std::path::Path;

use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;

use google_drive3::Drive;
use yup_oauth2::{
    read_application_secret, ApplicationSecret, Authenticator, DefaultAuthenticatorDelegate,
    DiskTokenStorage, FlowType,
};

const CLIENT_SECRET_FILE: &'static str = "example_client_secret.json";

// reads the provided example client secret, the quick and dirty way.
fn read_client_secret(file: String) -> ApplicationSecret {
    read_application_secret(Path::new(&file)).unwrap()
}

fn main() {
    let secret = read_client_secret(CLIENT_SECRET_FILE.to_string());
    let client =
        hyper::Client::with_connector(HttpsConnector::new(NativeTlsClient::new().unwrap()));
    let authenticator = Authenticator::new(
        &secret,
        DefaultAuthenticatorDelegate,
        client,
        DiskTokenStorage::new(&"token_store.json".to_string()).unwrap(),
        Some(FlowType::InstalledInteractive),
    );
    let client =
        hyper::Client::with_connector(HttpsConnector::new(NativeTlsClient::new().unwrap()));
    let hub = Drive::new(client, authenticator);

    let (_resp, list_result) = hub
        .files()
        .list()
        .q("'root' in parents and trashed = false")
        .doit()
        .unwrap();

    for file in list_result.files.unwrap_or(vec![]) {
        println!(
            "{} ({})",
            file.name.unwrap_or(String::new()),
            file.mime_type.unwrap_or(String::new())
        );
    }
}
<commit_msg>drive_example: Make example compile again. Fixes #134<commit_after>//! Just run this program: It will ask you for authorization to view metadata,
//! and then display you the contents of your Google Drive root directory.
//!
//! This example demonstrates how to use the [interactive OAuth 2 flow for installed
//! applications.](https://developers.google.com/identity/protocols/OAuth2InstalledApp)
//!
//! Copyright (c) 2016 Google, Inc. (Lewin Bormann <lbo@spheniscida.de>)

use std::path::Path;

use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;

use google_drive3::DriveHub;
use yup_oauth2::{
    read_application_secret, ApplicationSecret, Authenticator, DefaultAuthenticatorDelegate,
    DiskTokenStorage, FlowType,
};

const CLIENT_SECRET_FILE: &'static str = "example_client_secret.json";

// reads the provided example client secret, the quick and dirty way.
fn read_client_secret(file: String) -> ApplicationSecret {
    read_application_secret(Path::new(&file)).unwrap()
}

fn main() {
    let secret = read_client_secret(CLIENT_SECRET_FILE.to_string());
    let client =
        hyper::Client::with_connector(HttpsConnector::new(NativeTlsClient::new().unwrap()));
    let authenticator = Authenticator::new(
        &secret,
        DefaultAuthenticatorDelegate,
        client,
        DiskTokenStorage::new(&"token_store.json".to_string()).unwrap(),
        Some(FlowType::InstalledInteractive),
    );
    let client =
        hyper::Client::with_connector(HttpsConnector::new(NativeTlsClient::new().unwrap()));
    let hub = DriveHub::new(client, authenticator);

    let (_resp, list_result) = hub
        .files()
        .list()
        .q("'root' in parents and trashed = false")
        .doit()
        .unwrap();

    for file in list_result.files.unwrap_or(vec![]) {
        println!(
            "{} ({})",
            file.name.unwrap_or(String::new()),
            file.mime_type.unwrap_or(String::new())
        );
    }
}
<|endoftext|>


<commit_before>extern crate rustty;

use rustty::{
    Terminal,
    Event,
};

const BLOCK: char = '\u{25AA}';
const BUFF_ALIGN: usize = 35;

fn write_word(term: &mut Terminal, row: usize, word: String) {

    let cols = term.cols() as usize;

    for (idx, ch) in word.chars().enumerate() {

        let x = cols - BUFF_ALIGN;

        let mut cell = &mut term[(x as usize + idx, row)];
        cell.set_ch(ch);
    }
}

fn main() {
    let mut term = Terminal::new().unwrap();
    let mut radius = 10u32;
    'main: loop {
        while let Some(Event::Key(ch)) = term.get_event(0).unwrap() {
            match ch {
                'q' => break 'main,
                '+' => radius = radius.saturating_add(1),
                '-' => radius = radius.saturating_sub(1),
                _ => {},
            }
        }

        let (cols, rows) = term.size();
        let (cols, rows) = (cols as isize, (rows - 4) as isize);

        let (a, b) = (cols / 2, rows / 2);

        for i in 0..cols*rows {
            let y = i as isize / cols;
            let x = i as isize % cols;

            let mut cell = &mut term[(x as usize, y as usize)];

            if ((x - a).pow(2)/4 + (y - b).pow(2)) <= radius.pow(2) as isize {
                cell.set_ch(BLOCK);
            } else {
                cell.set_ch(' ');
            }
        }

        let i = cols*rows;
        let y = i as isize / cols;
        write_word(&mut term, y as usize, "+ -> Increase Radius".to_string());
        write_word(&mut term, (y+1) as usize, "- -> Decrease Radius".to_string());
        write_word(&mut term, (y+2) as usize, "q -> Quit".to_string());
        term.swap_buffers().unwrap();
    }
}
<commit_msg>Circle example refactoring<commit_after>extern crate rustty;

use rustty::{
    Terminal,
    Event,
};

const BLOCK: char = '\u{25AA}';
const BUFF_ALIGN: usize = 35;

fn write_word(term: &mut Terminal, row: usize, word: String) {
    // Helper function to write right-aligned text to the passed
    // row, aligns via the BUFF_ALIGN constant
    let cols = term.cols() as usize;

    for (idx, ch) in word.chars().enumerate() {
        let x = cols - BUFF_ALIGN;
        term[(x + idx, row)].set_ch(ch);
    }
}

fn main() {
    let mut term = Terminal::new().unwrap();
    let mut radius = 10u32;
    'main: loop {
        while let Some(Event::Key(ch)) = term.get_event(0).unwrap() {
            match ch {
                'q' => break 'main,
                '+' => radius = radius.saturating_add(1),
                '-' => radius = radius.saturating_sub(1),
                _ => {},
            }
        }

        // Grab the size of the console, and reserve 4 rows at the bottom
        // to write text to. These bottom 4 will NOT be rendered
        let (cols, rows) = term.size();
        let (cols, rows) = (cols as isize, (rows - 4) as isize);

        let (a, b) = (cols / 2, rows / 2);

        // Main render loop, draws the circle
        for i in 0..cols*rows {
            let y = i as isize / cols;
            let x = i as isize % cols;

            let mut cell = &mut term[(x as usize, y as usize)];

            if ((x - a).pow(2)/4 + (y - b).pow(2)) <= radius.pow(2) as isize {
                cell.set_ch(BLOCK);
            } else {
                cell.set_ch(' ');
            }
        }

        // Render text at bottom
        let i = cols*rows;
        let y = i as isize / cols;
        write_word(&mut term, y as usize, "+ -> Increase Radius".to_string());
        write_word(&mut term, (y+1) as usize, "- -> Decrease Radius".to_string());
        write_word(&mut term, (y+2) as usize, "q -> Quit".to_string());

        // Swap buffers
        term.swap_buffers().unwrap();
    }
}
<|endoftext|>


<commit_before>// Most of this is just standard vulkano setup
// Check the code following the UNIQUE CODE comments

#[macro_use]
extern crate vulkano;
extern crate winit;
extern crate vulkano_win;
extern crate vulkano_text;

use vulkano_text::{DrawText, DrawTextTrait, UpdateTextCache};

use vulkano_win::VkSurfaceBuild;
use vulkano::command_buffer;
use vulkano::command_buffer::PrimaryCommandBufferBuilder;
use vulkano::command_buffer::Submission;
use vulkano::device::Device;
use vulkano::framebuffer::Framebuffer;
use vulkano::instance::Instance;
use vulkano::swapchain::SurfaceTransform;
use vulkano::swapchain::Swapchain;

use std::sync::Arc;
use std::time::Duration;

mod render_pass {
    use vulkano::format::Format;

    single_pass_renderpass!{
        attachments: {
            color: {
                load: Clear,
                store: Store,
                format: Format,
            }
        },
        pass: {
            color: [color],
            depth_stencil: {}
        }
    }
}

fn main() {
    let instance = {
        let extensions = vulkano_win::required_extensions();
        Instance::new(None, &extensions, None).expect("failed to create Vulkan instance")
    };
    let physical = vulkano::instance::PhysicalDevice::enumerate(&instance).next().expect("no device available");
    let window = winit::WindowBuilder::new().build_vk_surface(&instance).unwrap();
    let queue = physical.queue_families().find(|q| {
        q.supports_graphics() && window.surface().is_supported(q).unwrap_or(false)
    }).expect("couldn't find a graphical queue family");

    let (device, mut queues) = {
        let device_ext = vulkano::device::DeviceExtensions {
            khr_swapchain: true,
            .. vulkano::device::DeviceExtensions::none()
        };

        Device::new(&physical, physical.supported_features(), &device_ext,
                    [(queue, 0.5)].iter().cloned()).expect("failed to create device")
    };

    let queue = queues.next().unwrap();
    let (swapchain, images) = {
        let caps = window.surface().get_capabilities(&physical)
                         .expect("failed to get surface capabilities");
        let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
        let present = caps.present_modes.iter().next().unwrap();
        let alpha = caps.supported_composite_alpha.iter().next().unwrap();
        let format = caps.supported_formats[0].0;
        Swapchain::new(&device, &window.surface(), caps.min_image_count, format, dimensions, 1,
           &caps.supported_usage_flags, &queue, SurfaceTransform::Identity, alpha,
           present, true, None).expect("failed to create swapchain")
    };

    let render_pass = render_pass::CustomRenderPass::new(&device, &render_pass::Formats {
        color: (images[0].format(), 1)
    }).unwrap();

    let framebuffers = images.iter().map(|image| {
        let dimensions = [image.dimensions()[0], image.dimensions()[1], 1];
        Framebuffer::new(&render_pass, dimensions, render_pass::AList {
            color: image
        }).unwrap()
    }).collect::<Vec<_>>();

    let mut submissions: Vec<Arc<Submission>> = Vec::new();

    // UNIQUE CODE: create DrawText
    let mut draw_text = DrawText::new(&device, &queue, &images);

    let mut x = -200.0;

    loop {
        let (width, height) = window.window().get_inner_size_points().unwrap();

        if x > width as f32 {
            x = 0.0;
        }
        else {
            x += 0.4;
        }

        // UNIQUE CODE: add queue text
        draw_text.queue_text(200.0, 50.0, 20.0, [1.0, 1.0, 1.0, 1.0], "The quick brown fox jumps over the lazy dog.");
        draw_text.queue_text(20.0, 200.0, 190.0, [1.0, 0.0, 0.0, 1.0], "Hello world!");
        draw_text.queue_text(x, 350.0, 70.0, [0.51, 0.6, 0.74, 1.0], "Lenny: ( ͡° ͜ʖ ͡°)");
        draw_text.queue_text(50.0, 350.0, 70.0, [1.0, 1.0, 1.0, 1.0], "Overlap");

        submissions.retain(|s| s.destroying_would_block());
        let image_num = swapchain.acquire_next_image(Duration::new(1, 0)).unwrap();

        let command_buffer = PrimaryCommandBufferBuilder::new(&device, queue.family())

        // UNIQUE CODE: update DrawTextData internal cache
        .update_text_cache(&mut draw_text)

        .draw_inline(&render_pass, &framebuffers[image_num], render_pass::ClearValues {
            color: [0.0, 0.0, 0.0, 1.0]
        })

        // UNIQUE CODE: draw the text
        .draw_text(&mut draw_text, &device, &queue, width, height)

        .draw_end()
        .build();

        submissions.push(command_buffer::submit(&command_buffer, &queue).unwrap());
        swapchain.present(&queue, image_num).unwrap();

        for ev in window.window().poll_events() {
            match ev {
                winit::Event::Closed => return,
                _ => ()
            }
        }
    }
}
<commit_msg>Add window resize to demo<commit_after>// Most of this is just standard vulkano setup
// Check the code following the UNIQUE CODE comments

#[macro_use]
extern crate vulkano;
extern crate winit;
extern crate vulkano_win;
extern crate vulkano_text;

use vulkano_text::{DrawText, DrawTextTrait, UpdateTextCache};

use vulkano_win::VkSurfaceBuild;
use vulkano::command_buffer;
use vulkano::command_buffer::PrimaryCommandBufferBuilder;
use vulkano::command_buffer::Submission;
use vulkano::device::Device;
use vulkano::framebuffer::Framebuffer;
use vulkano::instance::Instance;
use vulkano::swapchain::SurfaceTransform;
use vulkano::swapchain::Swapchain;

use std::sync::Arc;
use std::time::Duration;

mod render_pass {
    use vulkano::format::Format;

    single_pass_renderpass!{
        attachments: {
            color: {
                load: Clear,
                store: Store,
                format: Format,
            }
        },
        pass: {
            color: [color],
            depth_stencil: {}
        }
    }
}

fn main() {
    let instance = {
        let extensions = vulkano_win::required_extensions();
        Instance::new(None, &extensions, None).expect("failed to create Vulkan instance")
    };
    let physical = vulkano::instance::PhysicalDevice::enumerate(&instance).next().expect("no device available");
    let window = winit::WindowBuilder::new().build_vk_surface(&instance).unwrap();
    let queue = physical.queue_families().find(|q| {
        q.supports_graphics() && window.surface().is_supported(q).unwrap_or(false)
    }).expect("couldn't find a graphical queue family");

    let (device, mut queues) = {
        let device_ext = vulkano::device::DeviceExtensions {
            khr_swapchain: true,
            .. vulkano::device::DeviceExtensions::none()
        };

        Device::new(&physical, physical.supported_features(), &device_ext,
                    [(queue, 0.5)].iter().cloned()).expect("failed to create device")
    };

    let queue = queues.next().unwrap();
    let (mut swapchain, mut images) = {
        let caps = window.surface().get_capabilities(&physical)
                         .expect("failed to get surface capabilities");
        let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
        let present = caps.present_modes.iter().next().unwrap();
        let alpha = caps.supported_composite_alpha.iter().next().unwrap();
        let format = caps.supported_formats[0].0;
        Swapchain::new(&device, &window.surface(), caps.min_image_count, format, dimensions, 1,
           &caps.supported_usage_flags, &queue, SurfaceTransform::Identity, alpha,
           present, true, None).expect("failed to create swapchain")
    };

    let render_pass = render_pass::CustomRenderPass::new(&device, &render_pass::Formats {
        color: (images[0].format(), 1)
    }).unwrap();

    let mut framebuffers = images.iter().map(|image| {
        let dimensions = [image.dimensions()[0], image.dimensions()[1], 1];
        Framebuffer::new(&render_pass, dimensions, render_pass::AList {
            color: image
        }).unwrap()
    }).collect::<Vec<_>>();

    let mut submissions: Vec<Arc<Submission>> = Vec::new();

    // UNIQUE CODE: create DrawText
    let mut draw_text = DrawText::new(&device, &queue, &images);

    let mut x = -200.0;

    let (mut width, mut height) = window.window().get_inner_size_points().unwrap();

    loop {
        // TODO: https://github.com/tomaka/vulkano/issues/366 I guess we are waiting on the vulkano rewrite for this to not explode
        // TODO: Comment out all the draw_text code and resizing fails as described in the issue.
        let (new_width, new_height) = window.window().get_inner_size_points().unwrap();
        if width != new_width || height != new_height {
            width = new_width;
            height = new_height;

            let swapchain_results = swapchain.recreate_with_dimension([width, height]).unwrap();
            swapchain = swapchain_results.0;
            images = swapchain_results.1;

            framebuffers = images.iter().map(|image| {
                let dimensions = [image.dimensions()[0], image.dimensions()[1], 1];
                Framebuffer::new(&render_pass, dimensions, render_pass::AList {
                    color: image
                }).unwrap()
            }).collect::<Vec<_>>();

            // UNIQUE CODE: recreate DrawText due to new window size
            draw_text = DrawText::new(&device, &queue, &images);
        }

        if x > width as f32 {
            x = 0.0;
        }
        else {
            x += 0.4;
        }

        // UNIQUE CODE: add queue text
        draw_text.queue_text(200.0, 50.0, 20.0, [1.0, 1.0, 1.0, 1.0], "The quick brown fox jumps over the lazy dog.");
        draw_text.queue_text(20.0, 200.0, 190.0, [1.0, 0.0, 0.0, 1.0], "Hello world!");
        draw_text.queue_text(x, 350.0, 70.0, [0.51, 0.6, 0.74, 1.0], "Lenny: ( ͡° ͜ʖ ͡°)");
        draw_text.queue_text(50.0, 350.0, 70.0, [1.0, 1.0, 1.0, 1.0], "Overlap");

        submissions.retain(|s| s.destroying_would_block());
        let image_num = swapchain.acquire_next_image(Duration::new(1, 0)).unwrap();

        let command_buffer = PrimaryCommandBufferBuilder::new(&device, queue.family())

        // UNIQUE CODE: update DrawTextData internal cache
        .update_text_cache(&mut draw_text)

        .draw_inline(&render_pass, &framebuffers[image_num], render_pass::ClearValues {
            color: [0.0, 0.0, 0.0, 1.0]
        })

        // UNIQUE CODE: draw the text
        .draw_text(&mut draw_text, &device, &queue, width, height)

        .draw_end()
        .build();

        submissions.push(command_buffer::submit(&command_buffer, &queue).unwrap());
        swapchain.present(&queue, image_num).unwrap();

        for ev in window.window().poll_events() {
            match ev {
                winit::Event::Closed => return,
                _ => ()
            }
        }
    }
}
<|endoftext|>


<commit_before>use super::Input;

/// An `enum` which defines possible errors.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Error<Rule> {
    /// Generated parsing error with expected and unexpected `Rule`s and a position
    ParsingError(Vec<Rule>, Vec<Rule>, usize),
    /// Custom error with a message and a position
    CustomErrorPos(String, usize),
    /// Custom error with a message and a span defined by a start and end position
    CustomErrorSpan(String, usize, usize)
}

impl<Rule> Error<Rule> {
    /// Formats an `Error` according to an `Input`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pest::{Error, StringInput};
    /// let input = StringInput::new("ab\ncd\nef");
    /// let error: Error<()> = Error::CustomErrorPos("error: big one".to_owned(), 4);
    ///
    /// assert_eq!(error.format(&input), vec![
    ///     " --> 2:2",
    ///     "  |",
    ///     "2 | cd",
    ///     "  |  ^---",
    ///     "  |",
    ///     "  = error: big one"
    /// ].join("\n"));
    /// ```
    pub fn format(&self, input: &Input) -> String {
        self.format_option(input, None)
    }

    /// Formats an `Error` according to an `Input` while including a filename.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pest::{Error, StringInput};
    /// let input = StringInput::new("ab\ncd\nefghi");
    /// let error: Error<()> = Error::CustomErrorSpan("error: big one".to_owned(), 7, 11);
    ///
    /// assert_eq!(error.format_with_filename(&input, "file.ext"), vec![
    ///     " --> file.ext:3:2",
    ///     "  |",
    ///     "3 | efghi",
    ///     "  |  ^--^",
    ///     "  |",
    ///     "  = error: big one"
    /// ].join("\n"));
    /// ```
    pub fn format_with_filename(&self, input: &Input, filename: &str) -> String {
        self.format_option(input, Some(filename))
    }

    fn message(&self) -> &str {
        match self {
            &Error::ParsingError(_, _, _)         => unimplemented!(),
            &Error::CustomPos(ref message, _)     => message,
            &Error::CustomSpan(ref message, _, _) => message
        }
    }

    fn underline(&self, line: &str, offset: usize) -> String {
        let mut underline = String::new();

        for _ in 0..offset { underline.push(' '); }

        match self {
            &Error::CustomSpan(_, start, end) => {
                underline.push('^');
                for _ in 2..(end - start) { underline.push('-'); }
                underline.push('^');
            },
            _ => underline.push_str("^---")
        };

        underline
    }

    fn format_option(&self, input: &Input, option: Option<&str>) -> String {
        let pos = match self {
            &Error::ParsingError(_, _, pos) => pos,
            &Error::CustomPos(_, pos)       => pos,
            &Error::CustomSpan(_, pos, _)   => pos
        };
        let (line, col) = input.line_col(pos);
        let line_str_len = format!("{}", line).len();

        let mut spacing = String::new();
        for _ in 0..line_str_len { spacing.push(' '); }

        let mut result = match option {
            Some(filename) => format!("{}--> {}:{}:{}\n", spacing, filename, line, col),
            None           => format!("{}--> {}:{}\n", spacing, line, col)
        };

        result.push_str(&format!("{} |\n", spacing));
        result.push_str(&format!("{} | ", line));

        let line = input.line_of(pos);
        result.push_str(&format!("{}\n", line));
        result.push_str(&format!("{} | {}\n", spacing, self.underline(&line, col - 1)));
        result.push_str(&format!("{} |\n", spacing));
        result.push_str(&format!("{} = {}", spacing, self.message()));

        result
    }
}
<commit_msg>Fixed errors and removed unused arg.<commit_after>use super::Input;

/// An `enum` which defines possible errors.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Error<Rule> {
    /// Generated parsing error with expected and unexpected `Rule`s and a position
    ParsingError(Vec<Rule>, Vec<Rule>, usize),
    /// Custom error with a message and a position
    CustomErrorPos(String, usize),
    /// Custom error with a message and a span defined by a start and end position
    CustomErrorSpan(String, usize, usize)
}

impl<Rule> Error<Rule> {
    /// Formats an `Error` according to an `Input`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pest::{Error, StringInput};
    /// let input = StringInput::new("ab\ncd\nef");
    /// let error: Error<()> = Error::CustomErrorPos("error: big one".to_owned(), 4);
    ///
    /// assert_eq!(error.format(&input), vec![
    ///     " --> 2:2",
    ///     "  |",
    ///     "2 | cd",
    ///     "  |  ^---",
    ///     "  |",
    ///     "  = error: big one"
    /// ].join("\n"));
    /// ```
    pub fn format(&self, input: &Input) -> String {
        self.format_option(input, None)
    }

    /// Formats an `Error` according to an `Input` while including a filename.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pest::{Error, StringInput};
    /// let input = StringInput::new("ab\ncd\nefghi");
    /// let error: Error<()> = Error::CustomErrorSpan("error: big one".to_owned(), 7, 11);
    ///
    /// assert_eq!(error.format_with_filename(&input, "file.ext"), vec![
    ///     " --> file.ext:3:2",
    ///     "  |",
    ///     "3 | efghi",
    ///     "  |  ^--^",
    ///     "  |",
    ///     "  = error: big one"
    /// ].join("\n"));
    /// ```
    pub fn format_with_filename(&self, input: &Input, filename: &str) -> String {
        self.format_option(input, Some(filename))
    }

    fn message(&self) -> &str {
        match self {
            &Error::ParsingError(_, _, _)         => unimplemented!(),
            &Error::CustomErrorPos(ref message, _)     => message,
            &Error::CustomErrorSpan(ref message, _, _) => message
        }
    }

    fn underline(&self, offset: usize) -> String {
        let mut underline = String::new();

        for _ in 0..offset { underline.push(' '); }

        match self {
            &Error::CustomErrorSpan(_, start, end) => {
                underline.push('^');
                for _ in 2..(end - start) { underline.push('-'); }
                underline.push('^');
            },
            _ => underline.push_str("^---")
        };

        underline
    }

    fn format_option(&self, input: &Input, option: Option<&str>) -> String {
        let pos = match self {
            &Error::ParsingError(_, _, pos) => pos,
            &Error::CustomErrorPos(_, pos)       => pos,
            &Error::CustomErrorSpan(_, pos, _)   => pos
        };
        let (line, col) = input.line_col(pos);
        let line_str_len = format!("{}", line).len();

        let mut spacing = String::new();
        for _ in 0..line_str_len { spacing.push(' '); }

        let mut result = match option {
            Some(filename) => format!("{}--> {}:{}:{}\n", spacing, filename, line, col),
            None           => format!("{}--> {}:{}\n", spacing, line, col)
        };

        result.push_str(&format!("{} |\n", spacing));
        result.push_str(&format!("{} | ", line));

        let line = input.line_of(pos);
        result.push_str(&format!("{}\n", line));
        result.push_str(&format!("{} | {}\n", spacing, self.underline(col - 1)));
        result.push_str(&format!("{} |\n", spacing));
        result.push_str(&format!("{} = {}", spacing, self.message()));

        result
    }
}
<|endoftext|>


<commit_before>use std::cmp::min;

use time::SteadyTime;

#[derive(PartialEq, Eq, Debug)]
#[must_use]
pub enum Async<M, V> {
    Continue(M, V),
    Stop,
    Timeout(M, SteadyTime),
}

impl<M, V> Async<M, V> {
    pub fn and_then<T, R, F: FnOnce(M) -> Async<T, R>>(self, f: F)
        -> Async<T, R>
    {
        use self::Async::*;
        match self {
            Continue(m, _) => f(m),
            Stop => Stop,
            Timeout(m, t1) => match f(m) {
                Continue(m, v) => Continue(m, v),
                Stop => Stop,
                Timeout(m, t2) => Timeout(m, min(t1, t2)),
            },
        }
    }
    pub fn map<T, F: FnOnce(M) -> T>(self, f: F) -> Async<T, V> {
        use self::Async::*;
        match self {
            Continue(m, v) => Continue(f(m), v),
            Stop => Stop,
            Timeout(m, t) => Timeout(f(m), t),
        }
    }
    pub fn map_result<R, F: FnOnce(V) -> R>(self, f: F) -> Async<M, R> {
        use self::Async::*;
        match self {
            Continue(m, v) => Continue(m, f(v)),
            Stop => Stop,
            Timeout(m, t) => Timeout(m, t),
        }
    }
    pub fn done<R, F: FnOnce(M) -> R>(self, f: F) -> Option<R> {
        use self::Async::*;
        match self {
            Continue(m, _) => Some(f(m)),
            Stop => None,
            Timeout(m, _) => Some(f(m)),
        }
    }
}

#[macro_export]
macro_rules! async_try {
    ($e:expr) => {
        match $e {
            $crate::async::Async::Continue(m, v)
            => $crate::async::Async::Continue(m, v),
            $crate::async::Async::Timeout(m, t)
            => $crate::async::Async::Timeout(m, t),
            $crate::async::Async::Stop
            => return $crate::async::Async::Stop,
        }
    }
}
<commit_msg>Add `Async::wrap` method<commit_after>use std::cmp::min;

use time::SteadyTime;

#[derive(PartialEq, Eq, Debug)]
#[must_use]
pub enum Async<M, V> {
    Continue(M, V),
    Stop,
    Timeout(M, SteadyTime),
}

impl<M, V> Async<M, V> {
    pub fn and_then<T, R, F: FnOnce(M) -> Async<T, R>>(self, f: F)
        -> Async<T, R>
    {
        use self::Async::*;
        match self {
            Continue(m, _) => f(m),
            Stop => Stop,
            Timeout(m, t1) => match f(m) {
                Continue(m, v) => Continue(m, v),
                Stop => Stop,
                Timeout(m, t2) => Timeout(m, min(t1, t2)),
            },
        }
    }
    pub fn map<T, F: FnOnce(M) -> T>(self, f: F) -> Async<T, V> {
        use self::Async::*;
        match self {
            Continue(m, v) => Continue(f(m), v),
            Stop => Stop,
            Timeout(m, t) => Timeout(f(m), t),
        }
    }
    pub fn map_result<R, F: FnOnce(V) -> R>(self, f: F) -> Async<M, R> {
        use self::Async::*;
        match self {
            Continue(m, v) => Continue(m, f(v)),
            Stop => Stop,
            Timeout(m, t) => Timeout(m, t),
        }
    }
    pub fn done<R, F: FnOnce(M) -> R>(self, f: F) -> Option<R> {
        use self::Async::*;
        match self {
            Continue(m, _) => Some(f(m)),
            Stop => None,
            Timeout(m, _) => Some(f(m)),
        }
    }
}

impl<M> Async<M, Option<M>> {
    pub fn wrap<T, F: FnMut(M) -> T>(self, mut f: F) -> Async<T, Option<T>> {
        use self::Async::*;
        match self {
            Continue(m, v) => Continue(f(m), v.map(f)),
            Stop => Stop,
            Timeout(m, t) => Timeout(f(m), t),
        }
    }
}

#[macro_export]
macro_rules! async_try {
    ($e:expr) => {
        match $e {
            $crate::async::Async::Continue(m, v)
            => $crate::async::Async::Continue(m, v),
            $crate::async::Async::Timeout(m, t)
            => $crate::async::Async::Timeout(m, t),
            $crate::async::Async::Stop
            => return $crate::async::Async::Stop,
        }
    }
}
<|endoftext|>


<commit_before>#[macro_use] extern crate bencher;
extern crate kdtree;
extern crate rand;

use bencher::Bencher;

#[derive(Copy, Clone, PartialEq)]
pub struct Point2WithId {
    dims: [f64; 2],
    pub id: i32,
}

impl Point2WithId {
    pub fn new(id: i32, x: f64, y: f64) -> Point2WithId {
        Point2WithId {
            dims: [x, y],
            id: id,
        }
    }
}

impl kdtree::kdtree::KdtreePointTrait for Point2WithId {
    fn dims(&self) -> &[f64] {
        return &self.dims;
    }
}

#[derive(Copy, Clone, PartialEq)]
pub struct Point3WithId {
    dims: [f64; 3],
    pub id: i32,
}

impl Point3WithId {
    pub fn new(id: i32, x: f64, y: f64, z: f64) -> Point3WithId {
        Point3WithId {
            dims: [x, y, z],
            id: id,
        }
    }
}

impl kdtree::kdtree::KdtreePointTrait for Point3WithId {
    fn dims(&self) -> &[f64] {
        return &self.dims;
    }
}

fn bench_creating_1000_node_tree(b: &mut Bencher) {
    let len = 1000usize;
    let mut points: Vec<Point2WithId> = vec![];
    for id in 0..len {
        let x: f64 = rand::random();
        points.push(Point2WithId::new(id as i32, x, x));
    }

    b.iter(|| {
        kdtree::kdtree::Kdtree::new(points.clone());
    });
}

fn bench_single_loop_times_for_1000_node_tree(b: &mut Bencher) {
    let len = 1000usize;
    let mut points: Vec<Point3WithId> = vec![];

    for i in 0..len {
        points.push(Point3WithId::new(i as i32, rand::random(), rand::random(), rand::random()))
    }

    let tree = kdtree::kdtree::Kdtree::new(points.clone());

    b.iter(|| tree.nearest_search(&points[0]));
}

fn bench_creating_1000_000_node_tree(b: &mut Bencher) {
    let len = 1000_000usize;
    let mut points: Vec<Point2WithId> = vec![];
    for id in 0..len {
        let x: f64 = rand::random();
        points.push(Point2WithId::new(id as i32, x, x));
    }

    b.iter(|| {
        kdtree::kdtree::Kdtree::new(points.clone());
    });
}

benchmark_group!(benches, bench_creating_1000_node_tree,bench_single_loop_times_for_1000_node_tree, bench_creating_1000_000_node_tree);
benchmark_main!(benches);<commit_msg>Disabled 1mln bench<commit_after>#[macro_use] extern crate bencher;
extern crate kdtree;
extern crate rand;

use bencher::Bencher;

#[derive(Copy, Clone, PartialEq)]
pub struct Point2WithId {
    dims: [f64; 2],
    pub id: i32,
}

impl Point2WithId {
    pub fn new(id: i32, x: f64, y: f64) -> Point2WithId {
        Point2WithId {
            dims: [x, y],
            id: id,
        }
    }
}

impl kdtree::kdtree::KdtreePointTrait for Point2WithId {
    fn dims(&self) -> &[f64] {
        return &self.dims;
    }
}

#[derive(Copy, Clone, PartialEq)]
pub struct Point3WithId {
    dims: [f64; 3],
    pub id: i32,
}

impl Point3WithId {
    pub fn new(id: i32, x: f64, y: f64, z: f64) -> Point3WithId {
        Point3WithId {
            dims: [x, y, z],
            id: id,
        }
    }
}

impl kdtree::kdtree::KdtreePointTrait for Point3WithId {
    fn dims(&self) -> &[f64] {
        return &self.dims;
    }
}

fn bench_creating_1000_node_tree(b: &mut Bencher) {
    let len = 1000usize;
    let mut points: Vec<Point2WithId> = vec![];
    for id in 0..len {
        let x: f64 = rand::random();
        points.push(Point2WithId::new(id as i32, x, x));
    }

    b.iter(|| {
        kdtree::kdtree::Kdtree::new(points.clone());
    });
}

fn bench_single_loop_times_for_1000_node_tree(b: &mut Bencher) {
    let len = 1000usize;
    let mut points: Vec<Point3WithId> = vec![];

    for i in 0..len {
        points.push(Point3WithId::new(i as i32, rand::random(), rand::random(), rand::random()))
    }

    let tree = kdtree::kdtree::Kdtree::new(points.clone());

    b.iter(|| tree.nearest_search(&points[0]));
}

fn bench_creating_1000_000_node_tree(b: &mut Bencher) {
    let len = 1000_000usize;
    let mut points: Vec<Point2WithId> = vec![];
    for id in 0..len {
        let x: f64 = rand::random();
        points.push(Point2WithId::new(id as i32, x, x));
    }

    b.iter(|| {
        kdtree::kdtree::Kdtree::new(points.clone());
    });
}

benchmark_group!(benches, bench_creating_1000_node_tree,bench_single_loop_times_for_1000_node_tree);
benchmark_main!(benches);<|endoftext|>