<commit_before>
extern crate ndarray;
extern crate ndarray_linalg;
extern crate ndarray_rand;
extern crate rand;

use ndarray::prelude::*;
use ndarray_linalg::prelude::*;
use rand::distributions::*;
use ndarray_rand::RandomExt;

fn all_close(a: Array<f64, (Ix, Ix)>, b: Array<f64, (Ix, Ix)>) {
    if !a.all_close(&b, 1.0e-7) {
        panic!("\nTwo matrices are not equal:\na = \n{:?}\nb = \n{:?}\n",
               a,
               b);
    }
}
#[test]
fn permutate() {
    let a = arr2(&[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]);
    println!("a= \n{:?}", &a);
    let p = vec![2, 2, 3]; // replace 1-2
    let pa = a.permutated(&p);
    println!("permutated = \n{:?}", &pa);
    all_close(pa, arr2(&[[4., 5., 6.], [1., 2., 3.], [7., 8., 9.]]))
}

#[test]
fn permutate_t() {
    let a = arr2(&[[1., 4., 7.], [2., 5., 8.], [3., 6., 9.]]).reversed_axes();
    println!("a= \n{:?}", &a);
    let p = vec![2, 2, 3]; // replace 1-2
    let pa = a.permutated(&p);
    println!("permutated = \n{:?}", &pa);
    all_close(pa, arr2(&[[4., 5., 6.], [1., 2., 3.], [7., 8., 9.]]))
}

#[test]
fn permutate_3x4() {
    let a = arr2(&[[1., 4., 7., 10.], [2., 5., 8., 11.], [3., 6., 9., 12.]]);
    println!("a= \n{:?}", &a);
    let p = vec![1, 3, 3]; // replace 2-3
    println!("permutation = \n{:?}", &p);
    let pa = a.permutated(&p);
    println!("permutated = \n{:?}", &pa);
    all_close(pa,
              arr2(&[[1., 4., 7., 10.], [3., 6., 9., 12.], [2., 5., 8., 11.]]));
}

#[test]
fn permutate_3x4_t() {
    let a = arr2(&[[1., 5., 9.], [2., 6., 10.], [3., 7., 11.], [4., 8., 12.]]).reversed_axes();
    println!("a= \n{:?}", &a);
    let p = vec![1, 3, 3]; // replace 2-3
    println!("permutation = \n{:?}", &p);
    let pa = a.permutated(&p);
    println!("permutated = \n{:?}", &pa);
    all_close(pa,
              arr2(&[[1., 2., 3., 4.], [9., 10., 11., 12.], [5., 6., 7., 8.]]));
}

#[test]
fn permutate_4x3() {
    let a = arr2(&[[1., 5., 9.], [2., 6., 10.], [3., 7., 11.], [4., 8., 12.]]);
    println!("a= \n{:?}", &a);
    let p = vec![4, 2, 3, 4]; // replace 1-4
    println!("permutation = \n{:?}", &p);
    let pa = a.permutated(&p);
    println!("permutated = \n{:?}", &pa);
    all_close(pa,
              arr2(&[[4., 8., 12.], [2., 6., 10.], [3., 7., 11.], [1., 5., 9.]]))
}

#[test]
fn permutate_4x3_t() {
    let a = arr2(&[[1., 4., 7., 10.], [2., 5., 8., 11.], [3., 6., 9., 12.]]).reversed_axes();
    println!("a= \n{:?}", &a);
    let p = vec![4, 2, 3, 4]; // replace 1-4
    println!("permutation = \n{:?}", &p);
    let pa = a.permutated(&p);
    println!("permutated = \n{:?}", &pa);
    all_close(pa,
              arr2(&[[10., 11., 12.], [4., 5., 6.], [7., 8., 9.], [1., 2., 3.]]))
}

#[test]
fn lu_square_upper() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 3), r_dist);
    for ((i, j), val) in a.indexed_iter_mut() {
        if i > j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square_upper_t() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 3), r_dist).reversed_axes();
    for ((i, j), val) in a.indexed_iter_mut() {
        if i > j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square_lower() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 3), r_dist);
    for ((i, j), val) in a.indexed_iter_mut() {
        if i < j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    println!("LU = \n{:?}", l.dot(&u));
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square_lower_t() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 3), r_dist).reversed_axes();
    for ((i, j), val) in a.indexed_iter_mut() {
        if i < j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    println!("LU = \n{:?}", l.dot(&u));
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square() {
    let r_dist = Range::new(0., 1.);
    let a = Array::<f64, _>::random((3, 3), r_dist);
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    println!("LU = \n{:?}", l.dot(&u));
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square_t() {
    let r_dist = Range::new(0., 1.);
    let a = Array::<f64, _>::random((3, 3), r_dist).reversed_axes();
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    all_close(l.dot(&u).permutated(&p), a);
}

// #[test]
// fn lu_3x4() {
//     let r_dist = Range::new(0., 1.);
//     let a = Array::<f64, _>::random((3, 4), r_dist);
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     println!("LU = \n{:?}", l.dot(&u));
//     all_close(l.dot(&u).permutated(&p), a);
// }
//
// #[test]
// fn lu_3x4_t() {
//     let r_dist = Range::new(0., 1.);
//     let a = Array::<f64, _>::random((4, 3), r_dist).reversed_axes();
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     all_close(l.dot(&u).permutated(&p), a);
// }

// #[test]
// fn lu_4x3_upper() {
//     let r_dist = Range::new(0., 1.);
//     let mut a = Array::<f64, _>::random((4, 3), r_dist);
//     for ((i, j), val) in a.indexed_iter_mut() {
//         if i > j {
//             *val = 0.0;
//         }
//     }
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     println!("LU = \n{:?}", l.dot(&u));
//     all_close(l.dot(&u).permutated(&p), a);
// }
//
// #[test]
// fn lu_4x3_lower() {
//     let r_dist = Range::new(0., 1.);
//     let mut a = Array::<f64, _>::random((4, 3), r_dist);
//     for ((i, j), val) in a.indexed_iter_mut() {
//         if i < j {
//             *val = 0.0;
//         }
//     }
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     println!("LU = \n{:?}", l.dot(&u));
//     all_close(l.dot(&u).permutated(&p), a);
// }

#[test]
fn lu_4x3_upper_t() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 4), r_dist).reversed_axes();
    for ((i, j), val) in a.indexed_iter_mut() {
        if i > j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    println!("LU = \n{:?}", l.dot(&u));
    all_close(l.dot(&u).permutated(&p), a);
}

// #[test]
// fn lu_4x3() {
//     let r_dist = Range::new(0., 1.);
//     let a = Array::<f64, _>::random((4, 3), r_dist);
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     println!("LU = \n{:?}", l.dot(&u));
//     all_close(l.dot(&u).permutated(&p), a);
// }
//
// #[test]
// fn lu_4x3_t() {
//     let r_dist = Range::new(0., 1.);
//     let a = Array::<f64, _>::random((3, 4), r_dist).reversed_axes();
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     all_close(l.dot(&u).permutated(&p), a);
// }
<commit_msg>Use macro for testing permutate<commit_after>
extern crate ndarray;
extern crate ndarray_linalg;
extern crate ndarray_rand;
extern crate rand;

use ndarray::prelude::*;
use ndarray_linalg::prelude::*;
use rand::distributions::*;
use ndarray_rand::RandomExt;

fn all_close(a: Array<f64, (Ix, Ix)>, b: Array<f64, (Ix, Ix)>) {
    if !a.all_close(&b, 1.0e-7) {
        panic!("\nTwo matrices are not equal:\na = \n{:?}\nb = \n{:?}\n",
               a,
               b);
    }
}

macro_rules! test_permutate {
    ($testname:ident, $permutate:expr, $input:expr, $answer:expr) => {
#[test]
fn $testname() {
    let a = arr2($input);
    println!("a= \n{:?}", &a);
    let p = $permutate; // replace 1-2
    let pa = a.permutated(&p);
    println!("permutated = \n{:?}", &pa);
    all_close(pa, arr2($answer))
}
    }
}

macro_rules! test_permutate_t {
    ($testname:ident, $permutate:expr, $input:expr, $answer:expr) => {
#[test]
fn $testname() {
    let a = arr2($input).reversed_axes();
    println!("a= \n{:?}", &a);
    let p = $permutate; // replace 1-2
    let pa = a.permutated(&p);
    println!("permutated = \n{:?}", &pa);
    all_close(pa, arr2($answer))
}
    }
}

test_permutate!(permutate,
                vec![2, 2, 3],
                &[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],
                &[[4., 5., 6.], [1., 2., 3.], [7., 8., 9.]]);
test_permutate_t!(permutate_t,
                  vec![2, 2, 3],
                  &[[1., 4., 7.], [2., 5., 8.], [3., 6., 9.]],
                  &[[4., 5., 6.], [1., 2., 3.], [7., 8., 9.]]);
test_permutate!(permutate_3x4,
                vec![1, 3, 3],
                &[[1., 4., 7., 10.], [2., 5., 8., 11.], [3., 6., 9., 12.]],
                &[[1., 4., 7., 10.], [3., 6., 9., 12.], [2., 5., 8., 11.]]);
test_permutate_t!(permutate_3x4_t,
                  vec![1, 3, 3],
                  &[[1., 5., 9.], [2., 6., 10.], [3., 7., 11.], [4., 8., 12.]],
                  &[[1., 2., 3., 4.], [9., 10., 11., 12.], [5., 6., 7., 8.]]);
test_permutate!(permutate_4x3,
                vec![4, 2, 3, 4],
                &[[1., 5., 9.], [2., 6., 10.], [3., 7., 11.], [4., 8., 12.]],
                &[[4., 8., 12.], [2., 6., 10.], [3., 7., 11.], [1., 5., 9.]]);
test_permutate_t!(permutate_4x3_t,
                  vec![4, 2, 3, 4],
                  &[[1., 4., 7., 10.], [2., 5., 8., 11.], [3., 6., 9., 12.]],
                  &[[10., 11., 12.], [4., 5., 6.], [7., 8., 9.], [1., 2., 3.]]);

#[test]
fn lu_square_upper() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 3), r_dist);
    for ((i, j), val) in a.indexed_iter_mut() {
        if i > j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square_upper_t() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 3), r_dist).reversed_axes();
    for ((i, j), val) in a.indexed_iter_mut() {
        if i > j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square_lower() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 3), r_dist);
    for ((i, j), val) in a.indexed_iter_mut() {
        if i < j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    println!("LU = \n{:?}", l.dot(&u));
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square_lower_t() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 3), r_dist).reversed_axes();
    for ((i, j), val) in a.indexed_iter_mut() {
        if i < j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    println!("LU = \n{:?}", l.dot(&u));
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square() {
    let r_dist = Range::new(0., 1.);
    let a = Array::<f64, _>::random((3, 3), r_dist);
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    println!("LU = \n{:?}", l.dot(&u));
    all_close(l.dot(&u).permutated(&p), a);
}

#[test]
fn lu_square_t() {
    let r_dist = Range::new(0., 1.);
    let a = Array::<f64, _>::random((3, 3), r_dist).reversed_axes();
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    all_close(l.dot(&u).permutated(&p), a);
}

// #[test]
// fn lu_3x4() {
//     let r_dist = Range::new(0., 1.);
//     let a = Array::<f64, _>::random((3, 4), r_dist);
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     println!("LU = \n{:?}", l.dot(&u));
//     all_close(l.dot(&u).permutated(&p), a);
// }
//
// #[test]
// fn lu_3x4_t() {
//     let r_dist = Range::new(0., 1.);
//     let a = Array::<f64, _>::random((4, 3), r_dist).reversed_axes();
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     all_close(l.dot(&u).permutated(&p), a);
// }

// #[test]
// fn lu_4x3_upper() {
//     let r_dist = Range::new(0., 1.);
//     let mut a = Array::<f64, _>::random((4, 3), r_dist);
//     for ((i, j), val) in a.indexed_iter_mut() {
//         if i > j {
//             *val = 0.0;
//         }
//     }
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     println!("LU = \n{:?}", l.dot(&u));
//     all_close(l.dot(&u).permutated(&p), a);
// }
//
// #[test]
// fn lu_4x3_lower() {
//     let r_dist = Range::new(0., 1.);
//     let mut a = Array::<f64, _>::random((4, 3), r_dist);
//     for ((i, j), val) in a.indexed_iter_mut() {
//         if i < j {
//             *val = 0.0;
//         }
//     }
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     println!("LU = \n{:?}", l.dot(&u));
//     all_close(l.dot(&u).permutated(&p), a);
// }

#[test]
fn lu_4x3_upper_t() {
    let r_dist = Range::new(0., 1.);
    let mut a = Array::<f64, _>::random((3, 4), r_dist).reversed_axes();
    for ((i, j), val) in a.indexed_iter_mut() {
        if i > j {
            *val = 0.0;
        }
    }
    println!("a = \n{:?}", &a);
    let (p, l, u) = a.clone().lu().unwrap();
    println!("P = \n{:?}", &p);
    println!("L = \n{:?}", &l);
    println!("U = \n{:?}", &u);
    println!("LU = \n{:?}", l.dot(&u));
    all_close(l.dot(&u).permutated(&p), a);
}

// #[test]
// fn lu_4x3() {
//     let r_dist = Range::new(0., 1.);
//     let a = Array::<f64, _>::random((4, 3), r_dist);
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     println!("LU = \n{:?}", l.dot(&u));
//     all_close(l.dot(&u).permutated(&p), a);
// }
//
// #[test]
// fn lu_4x3_t() {
//     let r_dist = Range::new(0., 1.);
//     let a = Array::<f64, _>::random((3, 4), r_dist).reversed_axes();
//     println!("a = \n{:?}", &a);
//     let (p, l, u) = a.clone().lu().unwrap();
//     println!("P = \n{:?}", &p);
//     println!("L = \n{:?}", &l);
//     println!("U = \n{:?}", &u);
//     all_close(l.dot(&u).permutated(&p), a);
// }
<|endoftext|>


<commit_before>extern crate rand;

use std::io;
use rand::{thread_rng, sample};

struct Stack {
    content: Vec<i32>,
    digits: Vec<i32>,
}

impl Stack {
    fn push(&mut self, d: i32) -> Result<i32, &str> {
        self.content.push(d);
        Ok(d)
    }

    fn pop(&mut self) -> Option<i32> {
        self.content.pop()
    }

    fn consume_digit(&mut self, d: i32) {
        let i = self.digits.iter().position(|&i| i == d).expect("Cannot consume!");
        self.digits.remove(i);
    }

    fn valid_digit(&self, d: i32) -> bool {
        self.digits.contains(&d)
    }

    fn reveal<'a>(&self) -> Result<i32, &'a str> {
        match self.content.len() {
            1 => match self.digits.len() {
                0 => Ok(self.content[0]),
                _ => Err("Did not use all digits!"),
            },
            _ => Err("Invalid formula!"),
        }
    }

    fn add_digit(&mut self, c: char) -> Result<i32, &str> {
        match c.to_digit(10) {
            Some(n) => match self.valid_digit(n as i32) {
                true => {
                    self.consume_digit(n as i32);
                    self.push(n as i32)
                },
                false => Err("Invalid or duplicate digit!"),
            },
            None => Err("Invalid character"),
        }
    }

    fn apply<F>(&mut self, f: F) -> Result<i32, &str>
        where F : Fn(i32, i32) -> i32 {

        let r = self.pop();
        let l = self.pop();

        match l {
            Some(n) => match r {
                Some(i) => self.push(f(n, i)),
                None => Err("Stack empty"),
            },
            None => Err("Stack empty"),
        }
    }
}

fn evaluate<'a>(program: Vec<char>, digits: Vec<i32>) -> Result<i32, &'a str> {
    let mut stack = Stack {
        content: vec![],
        digits: digits,
    };

    for c in program {
        let answer: Result<i32, &str> = match c {
            '*' => stack.apply(|l, r| l * r),
            '+' => stack.apply(|l, r| l + r),
            '-' => stack.apply(|l, r| l - r),
            '/' => stack.apply(|l, r| l / r),
            _ => stack.add_digit(c),
        };

        if answer.is_err() {
            // TODO: Fix this. Work out how to return "answer" without compiler error.
            //return answer;
            println!("Actual: {}", answer.unwrap_err());
            return Err("Program error");
        }
    }

    stack.reveal()
}

fn main() {
    let goal: i32 = 24;
    let mut rng = thread_rng();
    let mut program = String::new();

    println!("GUESSING GAME!\n");

    loop {
        let digits = sample(&mut rng, 1..9, 4);

        println!("Your digits are: {}\n", digits.iter().fold("".to_string(), |acc, &d| acc + &d.to_string()[..] + ", "));
        println!("Enter an expression:\n");

        io::stdin().read_line(&mut program)
            .ok()
            .expect("Could not read input.");

        let parsed = program
            .trim()
            .chars()
            .filter(|&c| c != ' ')
            .collect();

        match evaluate(parsed, digits) {
            Ok(n) => if n == goal {
                println!("Well done!");
            } else {
                println!("Nice try, but {} is not {}!", n, goal);
            },
            Err(s) => {
                println!("Oops: {}", s);
            },
        }
    }

}
<commit_msg>Some formatting<commit_after>extern crate rand;

use std::io;
use rand::{thread_rng, sample};

struct Stack {
    content: Vec<i32>,
    digits: Vec<i32>,
}

impl Stack {
    fn push(&mut self, d: i32) -> Result<i32, &str> {
        self.content.push(d);
        Ok(d)
    }

    fn pop(&mut self) -> Option<i32> {
        self.content.pop()
    }

    fn consume_digit(&mut self, d: i32) {
        let i = self.digits.iter().position(|&i| i == d).expect("Cannot consume!");
        self.digits.remove(i);
    }

    fn valid_digit(&self, d: i32) -> bool {
        self.digits.contains(&d)
    }

    fn reveal<'a>(&self) -> Result<i32, &'a str> {
        match self.content.len() {
            1 => match self.digits.len() {
                0 => Ok(self.content[0]),
                _ => Err("Did not use all digits!"),
            },
            _ => Err("Invalid formula!"),
        }
    }

    fn add_digit(&mut self, c: char) -> Result<i32, &str> {
        match c.to_digit(10) {
            Some(n) => match self.valid_digit(n as i32) {
                true => {
                    self.consume_digit(n as i32);
                    self.push(n as i32)
                },
                false => Err("Invalid or duplicate digit!"),
            },
            None => Err("Invalid character"),
        }
    }

    fn apply<F>(&mut self, f: F) -> Result<i32, &str>
        where F : Fn(i32, i32) -> i32 {

        let r = self.pop();
        let l = self.pop();

        match l {
            Some(n) => match r {
                Some(i) => self.push(f(n, i)),
                None => Err("Stack empty"),
            },
            None => Err("Stack empty"),
        }
    }
}

fn evaluate<'a>(program: Vec<char>, digits: Vec<i32>) -> Result<i32, &'a str> {
    let mut stack = Stack {
        content: vec![],
        digits: digits,
    };

    for c in program {
        let answer: Result<i32, &str> = match c {
            '*' => stack.apply(|l, r| l * r),
            '+' => stack.apply(|l, r| l + r),
            '-' => stack.apply(|l, r| l - r),
            '/' => stack.apply(|l, r| l / r),
            _ => stack.add_digit(c),
        };

        if answer.is_err() {
            // TODO: Fix this. Work out how to return "answer" without compiler error.
            //return answer;
            println!("Actual: {}", answer.unwrap_err());
            return Err("Program error");
        }
    }

    stack.reveal()
}

fn main() {
    let goal: i32 = 24;
    let mut rng = thread_rng();
    let mut program = String::new();

    println!("GUESSING GAME!\n");

    loop {
        let digits = sample(&mut rng, 1..9, 4);

        println!("Your digits are: {}\n", digits.iter().fold("".to_string(), |acc, &d| acc + &d.to_string()[..] + ", "));
        println!("Enter an expression:\n");

        io::stdin().read_line(&mut program)
            .ok()
            .expect("Could not read input.");

        let parsed = program
            .trim()
            .chars()
            .filter(|&c| c != ' ')
            .collect();

        match evaluate(parsed, digits) {
            Ok(n) => if n == goal {
                println!("\nWell done!\n");
                break;
            } else {
                println!("\nNice try, but {} is not {}!\n", n, goal);
            },
            Err(s) => {
                println!("\nOops: {}\n", s);
            },
        }
    }

}
<|endoftext|>


<commit_before>extern crate rand;

use std::io;
use rand::{thread_rng, sample};

struct Stack {
    content: Vec<i32>,
    digits: Vec<i32>,
}

impl Stack {
    fn push(&mut self, d: i32) -> Result<i32, &str> {
        self.content.push(d);
        Ok(d)
    }

    fn pop(&mut self) -> Option<i32> {
        self.content.pop()
    }

    fn consume_digit(&mut self, d: i32) {
        let i = self.digits.iter().position(|&i| i == d).expect("Cannot consume!");
        self.digits.remove(i);
    }

    fn valid_digit(&self, d: i32) -> bool {
        self.digits.contains(&d)
    }

    fn reveal<'a>(&self) -> Result<i32, &'a str> {
        match (self.content.len(), self.digits.len()) {
            (1, 0) => Ok(self.content[0]),
            (1, _) => Err("Did not use all digits!"),
            _ => Err("Invalid formula!"),
        }
    }

    fn add_digit(&mut self, c: char) -> Result<i32, &str> {
        match c.to_digit(10) {
            Some(n) => match self.valid_digit(n as i32) {
                true => {
                    self.consume_digit(n as i32);
                    self.push(n as i32)
                },
                false => Err("Invalid or duplicate digit!"),
            },
            None => Err("Invalid character"),
        }
    }

    fn apply<F>(&mut self, f: F) -> Result<i32, &str>
        where F : Fn(i32, i32) -> i32 {

        let (r, l) = (self.pop(), self.pop());

        match (l, r) {
            (Some(x), Some(y)) => self.push(f(x, y)),
            _ => Err("Stack empty"),
        }
    }
}

fn evaluate<'a>(program: Vec<char>, digits: Vec<i32>) -> Result<i32, &'a str> {
    let mut stack = Stack {
        content: vec![],
        digits: digits,
    };

    for c in program {
        let answer: Result<i32, &str> = match c {
            '*' => stack.apply(|l, r| l * r),
            '+' => stack.apply(|l, r| l + r),
            '-' => stack.apply(|l, r| l - r),
            '/' => stack.apply(|l, r| l / r),
            _ => stack.add_digit(c),
        };

        if answer.is_err() {
            // TODO: Fix this. Work out how to return "answer" without compiler error.
          //return answer;
          //return Err("Program error");
          println!("Actual: {}", answer.unwrap_err());
          break;
        }
    }

    stack.reveal()
}

fn main() {
    let goal: i32 = 24;
    let mut rng = thread_rng();

    println!("GUESSING GAME!

RULES

  * Using only the given digits, create an expression that evaluates to 24.
  * All digits must be used.
  * Each digit may only be used once.
  * Expressions must be in Reverse-Polish Notation (RPN).
  * Only +, -, * and / are allowed.
  * Order of the digits is not important.\n");

    loop {
        let mut program = String::new();
        let digits = sample(&mut rng, 1..9, 4);

        println!("Your digits are: {}, {}, {} and {}\n", digits[0], digits[1], digits[2], digits[3]);
        println!("Enter an expression:\n");

        io::stdin().read_line(&mut program)
            .ok()
            .expect("Could not read input.");

        let parsed = program
            .trim()
            .chars()
            .filter(|&c| c != ' ')
            .collect();

        match evaluate(parsed, digits) {
            Ok(n) => if n == goal {
                println!("\nWell done!\n");
                break;
            } else {
                println!("\nNice try, but {} is not {}!\n", n, goal);
            },
            Err(s) => {
                println!("\nOops: {}\n", s);
            },
        }
    }
}
<commit_msg>Indentation<commit_after>extern crate rand;

use std::io;
use rand::{thread_rng, sample};

struct Stack {
    content: Vec<i32>,
    digits: Vec<i32>,
}

impl Stack {
    fn push(&mut self, d: i32) -> Result<i32, &str> {
        self.content.push(d);
        Ok(d)
    }

    fn pop(&mut self) -> Option<i32> {
        self.content.pop()
    }

    fn consume_digit(&mut self, d: i32) {
        let i = self.digits.iter().position(|&i| i == d).expect("Cannot consume!");
        self.digits.remove(i);
    }

    fn valid_digit(&self, d: i32) -> bool {
        self.digits.contains(&d)
    }

    fn reveal<'a>(&self) -> Result<i32, &'a str> {
        match (self.content.len(), self.digits.len()) {
            (1, 0) => Ok(self.content[0]),
            (1, _) => Err("Did not use all digits!"),
            _ => Err("Invalid formula!"),
        }
    }

    fn add_digit(&mut self, c: char) -> Result<i32, &str> {
        match c.to_digit(10) {
            Some(n) => match self.valid_digit(n as i32) {
                true => {
                    self.consume_digit(n as i32);
                    self.push(n as i32)
                },
                false => Err("Invalid or duplicate digit!"),
            },
            None => Err("Invalid character"),
        }
    }

    fn apply<F>(&mut self, f: F) -> Result<i32, &str>
        where F : Fn(i32, i32) -> i32 {

        let (r, l) = (self.pop(), self.pop());

        match (l, r) {
            (Some(x), Some(y)) => self.push(f(x, y)),
            _ => Err("Stack empty"),
        }
    }
}

fn evaluate<'a>(program: Vec<char>, digits: Vec<i32>) -> Result<i32, &'a str> {
    let mut stack = Stack {
        content: vec![],
        digits: digits,
    };

    for c in program {
        let answer: Result<i32, &str> = match c {
            '*' => stack.apply(|l, r| l * r),
            '+' => stack.apply(|l, r| l + r),
            '-' => stack.apply(|l, r| l - r),
            '/' => stack.apply(|l, r| l / r),
            _ => stack.add_digit(c),
        };

        if answer.is_err() {
            // TODO: Fix this. Work out how to return "answer" without compiler error.
            //return answer;
            //return Err("Program error");
            println!("Actual: {}", answer.unwrap_err());
            break;
        }
    }

    stack.reveal()
}

fn main() {
    let goal: i32 = 24;
    let mut rng = thread_rng();

    println!("GUESSING GAME!

RULES

  * Using only the given digits, create an expression that evaluates to 24.
  * All digits must be used.
  * Each digit may only be used once.
  * Expressions must be in Reverse-Polish Notation (RPN).
  * Only +, -, * and / are allowed.
  * Order of the digits is not important.\n");

    loop {
        let mut program = String::new();
        let digits = sample(&mut rng, 1..9, 4);

        println!("Your digits are: {}, {}, {} and {}\n", digits[0], digits[1], digits[2], digits[3]);
        println!("Enter an expression:\n");

        io::stdin().read_line(&mut program)
            .ok()
            .expect("Could not read input.");

        let parsed = program
            .trim()
            .chars()
            .filter(|&c| c != ' ')
            .collect();

        match evaluate(parsed, digits) {
            Ok(n) => if n == goal {
                println!("\nWell done!\n");
                break;
            } else {
                println!("\nNice try, but {} is not {}!\n", n, goal);
            },
            Err(s) => {
                println!("\nOops: {}\n", s);
            },
        }
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// For simd (currently x86_64/aarch64)
#![cfg_attr(any(target_os = "linux", target_os = "android", target_os = "windows"), feature(heap_api))]

#![feature(alloc)]
#![feature(box_syntax)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![feature(str_char)]
#![feature(unique)]

#![plugin(heapsize_plugin)]
#![plugin(plugins)]
#![plugin(serde_macros)]

extern crate alloc;
extern crate app_units;
extern crate azure;
#[macro_use]
extern crate bitflags;
extern crate canvas_traits;

// Mac OS-specific library dependencies
#[cfg(target_os = "macos")] extern crate core_foundation;
#[cfg(target_os = "macos")] extern crate core_graphics;
#[cfg(target_os = "macos")] extern crate core_text;

extern crate euclid;
extern crate fnv;

// Platforms that use Freetype/Fontconfig library dependencies
#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
extern crate fontconfig;
#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
extern crate freetype;

extern crate gfx_traits;

// Eventually we would like the shaper to be pluggable, as many operating systems have their own
// shapers. For now, however, this is a hard dependency.
extern crate harfbuzz_sys as harfbuzz;

extern crate heapsize;
extern crate ipc_channel;
extern crate layers;
#[macro_use]
extern crate lazy_static;
extern crate libc;
#[macro_use]
extern crate log;
extern crate mime;
extern crate msg;
extern crate net_traits;
#[macro_use]
extern crate profile_traits;
extern crate rand;
#[macro_use]
extern crate range;
extern crate rustc_serialize;
extern crate serde;

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
extern crate simd;

extern crate skia;
extern crate smallvec;
extern crate string_cache;
extern crate style;
extern crate style_traits;
extern crate time;
extern crate unicode_script;
extern crate url;
extern crate util;
extern crate webrender_traits;

pub use paint_context::PaintContext;

// Misc.
mod filters;

// Private painting modules
mod paint_context;

#[deny(unsafe_code)]
#[path = "display_list/mod.rs"]
pub mod display_list;

// Fonts
pub mod font;
pub mod font_cache_thread;
pub mod font_context;
pub mod font_template;

pub mod paint_thread;

// Platform-specific implementations.
#[path = "platform/mod.rs"]
pub mod platform;

// Text
#[path = "text/mod.rs"]
pub mod text;
<commit_msg>Remove unnecessary path attributes from gfx/lib.rs.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// For simd (currently x86_64/aarch64)
#![cfg_attr(any(target_os = "linux", target_os = "android", target_os = "windows"), feature(heap_api))]

#![feature(alloc)]
#![feature(box_syntax)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![feature(str_char)]
#![feature(unique)]

#![plugin(heapsize_plugin)]
#![plugin(plugins)]
#![plugin(serde_macros)]

extern crate alloc;
extern crate app_units;
extern crate azure;
#[macro_use]
extern crate bitflags;
extern crate canvas_traits;

// Mac OS-specific library dependencies
#[cfg(target_os = "macos")] extern crate core_foundation;
#[cfg(target_os = "macos")] extern crate core_graphics;
#[cfg(target_os = "macos")] extern crate core_text;

extern crate euclid;
extern crate fnv;

// Platforms that use Freetype/Fontconfig library dependencies
#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
extern crate fontconfig;
#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
extern crate freetype;

extern crate gfx_traits;

// Eventually we would like the shaper to be pluggable, as many operating systems have their own
// shapers. For now, however, this is a hard dependency.
extern crate harfbuzz_sys as harfbuzz;

extern crate heapsize;
extern crate ipc_channel;
extern crate layers;
#[macro_use]
extern crate lazy_static;
extern crate libc;
#[macro_use]
extern crate log;
extern crate mime;
extern crate msg;
extern crate net_traits;
#[macro_use]
extern crate profile_traits;
extern crate rand;
#[macro_use]
extern crate range;
extern crate rustc_serialize;
extern crate serde;

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
extern crate simd;

extern crate skia;
extern crate smallvec;
extern crate string_cache;
extern crate style;
extern crate style_traits;
extern crate time;
extern crate unicode_script;
extern crate url;
extern crate util;
extern crate webrender_traits;

pub use paint_context::PaintContext;

// Misc.
mod filters;

// Private painting modules
mod paint_context;

#[deny(unsafe_code)]
pub mod display_list;

// Fonts
pub mod font;
pub mod font_cache_thread;
pub mod font_context;
pub mod font_template;

pub mod paint_thread;

// Platform-specific implementations.
pub mod platform;

// Text
pub mod text;
<|endoftext|>


<commit_before>// Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! The normal and derived distributions.

use crate::utils::ziggurat;
use num_traits::Float;
use crate::{ziggurat_tables, Distribution, Open01};
use rand::Rng;
use core::fmt;

/// Samples floating-point numbers according to the normal distribution
/// `N(0, 1)` (a.k.a. a standard normal, or Gaussian). This is equivalent to
/// `Normal::new(0.0, 1.0)` but faster.
///
/// See `Normal` for the general normal distribution.
///
/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method.
///
/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
///       Generate Normal Random Samples*](
///       https://www.doornik.com/research/ziggurat.pdf).
///       Nuffield College, Oxford
///
/// # Example
/// ```
/// use rand::prelude::*;
/// use rand_distr::StandardNormal;
///
/// let val: f64 = thread_rng().sample(StandardNormal);
/// println!("{}", val);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct StandardNormal;

impl Distribution<f32> for StandardNormal {
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f32 {
        // TODO: use optimal 32-bit implementation
        let x: f64 = self.sample(rng);
        x as f32
    }
}

impl Distribution<f64> for StandardNormal {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
        #[inline]
        fn pdf(x: f64) -> f64 {
            (-x * x / 2.0).exp()
        }
        #[inline]
        fn zero_case<R: Rng + ?Sized>(rng: &mut R, u: f64) -> f64 {
            // compute a random number in the tail by hand

            // strange initial conditions, because the loop is not
            // do-while, so the condition should be true on the first
            // run, they get overwritten anyway (0 < 1, so these are
            // good).
            let mut x = 1.0f64;
            let mut y = 0.0f64;

            while -2.0 * y < x * x {
                let x_: f64 = rng.sample(Open01);
                let y_: f64 = rng.sample(Open01);

                x = x_.ln() / ziggurat_tables::ZIG_NORM_R;
                y = y_.ln();
            }

            if u < 0.0 {
                x - ziggurat_tables::ZIG_NORM_R
            } else {
                ziggurat_tables::ZIG_NORM_R - x
            }
        }

        ziggurat(
            rng,
            true, // this is symmetric
            &ziggurat_tables::ZIG_NORM_X,
            &ziggurat_tables::ZIG_NORM_F,
            pdf,
            zero_case,
        )
    }
}

/// The normal distribution `N(mean, std_dev**2)`.
///
/// This uses the ZIGNOR variant of the Ziggurat method, see [`StandardNormal`]
/// for more details.
///
/// Note that [`StandardNormal`] is an optimised implementation for mean 0, and
/// standard deviation 1.
///
/// # Example
///
/// ```
/// use rand_distr::{Normal, Distribution};
///
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0).unwrap();
/// let v = normal.sample(&mut rand::thread_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
///
/// [`StandardNormal`]: crate::StandardNormal
#[derive(Clone, Copy, Debug)]
pub struct Normal<F>
where F: Float, StandardNormal: Distribution<F>
{
    mean: F,
    std_dev: F,
}

/// Error type returned from `Normal::new` and `LogNormal::new`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    /// The mean value is too small (log-normal samples must be positive)
    MeanTooSmall,
    /// The standard deviation or other dispersion parameter is negative,
    /// infinite, or not-a-number.
    BadVariance,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Error::MeanTooSmall => "mean < 0 or NaN in log-normal distribution",
            Error::BadVariance => "variation parameter is negative or non-finite in (log)normal distribution",
        })
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl<F> Normal<F>
where F: Float, StandardNormal: Distribution<F>
{
    /// Construct, from mean and standard deviation
    ///
    /// Parameters:
    ///
    /// -   mean (`μ`, unrestricted)
    /// -   standard deviation (`σ`, must be finite)
    #[inline]
    pub fn new(mean: F, std_dev: F) -> Result<Normal<F>, Error> {
        if !std_dev.is_finite() {
            return Err(Error::BadVariance);
        }
        Ok(Normal { mean, std_dev })
    }

    /// Construct, from mean and coefficient of variation
    ///
    /// Parameters:
    ///
    /// -   mean (`μ`, unrestricted)
    /// -   coefficient of variation (`cv = abs(σ / μ)`)
    #[inline]
    pub fn from_mean_cv(mean: F, cv: F) -> Result<Normal<F>, Error> {
        if !cv.is_finite() || cv < F::zero() {
            return Err(Error::BadVariance);
        }
        let std_dev = cv * mean;
        Ok(Normal { mean, std_dev })
    }

    /// Sample from a z-score
    ///
    /// This may be useful for generating correlated samples, as follows.
    /// ```
    /// # use rand::prelude::*;
    /// # use rand_distr::{Normal, StandardNormal};
    /// let mut rng = thread_rng();
    /// let z = StandardNormal.sample(&mut rng);
    /// let x1 = Normal::new(0.0, 1.0).unwrap().from_zscore(z);
    /// let x2 = Normal::new(2.0, -1.0).unwrap().from_zscore(z);
    /// ```
    #[inline]
    pub fn from_zscore(&self, zscore: F) -> F {
        self.mean + self.std_dev * zscore
    }
}

impl<F> Distribution<F> for Normal<F>
where F: Float, StandardNormal: Distribution<F>
{
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> F {
        self.from_zscore(rng.sample(StandardNormal))
    }
}

/// The log-normal distribution `ln N(mean, std_dev**2)`.
///
/// If `X` is log-normal distributed, then `ln(X)` is `N(mean, std_dev**2)`
/// distributed.
///
/// # Example
///
/// ```
/// use rand_distr::{LogNormal, Distribution};
///
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0).unwrap();
/// let v = log_normal.sample(&mut rand::thread_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy, Debug)]
pub struct LogNormal<F>
where F: Float, StandardNormal: Distribution<F>
{
    norm: Normal<F>,
}

impl<F> LogNormal<F>
where F: Float, StandardNormal: Distribution<F>
{
    /// Construct, from (log-space) mean and standard deviation
    ///
    /// Parameters are the "standard" log-space measures (these are the mean
    /// and standard deviation of the logarithm of samples):
    ///
    /// -   `mu` (`μ`, unrestricted) is the mean of the underlying distribution
    /// -   `sigma` (`σ`, must be finite) is the standard deviation of the
    ///     underlying Normal distribution
    #[inline]
    pub fn new(mu: F, sigma: F) -> Result<LogNormal<F>, Error> {
        let norm = Normal::new(mu, sigma)?;
        Ok(LogNormal { norm })
    }

    /// Construct, from (linear-space) mean and coefficient of variation
    ///
    /// Parameters are linear-space measures:
    ///
    /// -   mean (`μ > 0`) is the (real) mean of the distribution
    /// -   coefficient of variation (`cv = σ / μ`, requiring `cv ≥ 0`) is a
    ///     standardized measure of dispersion
    ///
    /// As a special exception, `μ = 0, cv = 0` is allowed (samples are `-inf`).
    #[inline]
    pub fn from_mean_cv(mean: F, cv: F) -> Result<LogNormal<F>, Error> {
        if cv == F::zero() {
            let mu = mean.ln();
            let norm = Normal::new(mu, F::zero()).unwrap();
            return Ok(LogNormal { norm });
        }
        if !(mean > F::zero()) {
            return Err(Error::MeanTooSmall);
        }
        if !(cv >= F::zero()) {
            return Err(Error::BadVariance);
        }

        // Using X ~ lognormal(μ, σ), CV² = Var(X) / E(X)²
        // E(X) = exp(μ + σ² / 2) = exp(μ) × exp(σ² / 2)
        // Var(X) = exp(2μ + σ²)(exp(σ²) - 1) = E(X)² × (exp(σ²) - 1)
        // but Var(X) = (CV × E(X))² so CV² = exp(σ²) - 1
        // thus σ² = log(CV² + 1)
        // and exp(μ) = E(X) / exp(σ² / 2) = E(X) / sqrt(CV² + 1)
        let a = F::one() + cv * cv; // e
        // let mu = F::from(0.5).unwrap() * (mean * mean / a).ln();
        let mu = (mean / a.sqrt()).ln();
        let sigma = a.ln().sqrt();
        let norm = Normal::new(mu, sigma)?;
        Ok(LogNormal { norm })
    }

    /// Sample from a z-score
    ///
    /// This may be useful for generating correlated samples, as follows.
    /// ```
    /// # use rand::prelude::*;
    /// # use rand_distr::{LogNormal, StandardNormal};
    /// let mut rng = thread_rng();
    /// let z = StandardNormal.sample(&mut rng);
    /// let x1 = LogNormal::from_mean_cv(3.0, 1.0).unwrap().from_zscore(z);
    /// let x2 = LogNormal::from_mean_cv(2.0, 1.0).unwrap().from_zscore(z);
    /// ```
    #[inline]
    pub fn from_zscore(&self, zscore: F) -> F {
        self.norm.from_zscore(zscore).exp()
    }
}

impl<F> Distribution<F> for LogNormal<F>
where F: Float, StandardNormal: Distribution<F>
{
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> F {
        self.norm.sample(rng).exp()
    }
}

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

    #[test]
    fn test_normal() {
        let norm = Normal::new(10.0, 10.0).unwrap();
        let mut rng = crate::test::rng(210);
        for _ in 0..1000 {
            norm.sample(&mut rng);
        }
    }
    #[test]
    fn test_normal_cv() {
        let norm = Normal::from_mean_cv(1024.0, 1.0 / 256.0).unwrap();
        assert_eq!((norm.mean, norm.std_dev), (1024.0, 4.0));
    }
    #[test]
    fn test_normal_invalid_sd() {
        assert!(Normal::from_mean_cv(10.0, -1.0).is_err());
    }

    #[test]
    fn test_log_normal() {
        let lnorm = LogNormal::new(10.0, 10.0).unwrap();
        let mut rng = crate::test::rng(211);
        for _ in 0..1000 {
            lnorm.sample(&mut rng);
        }
    }
    #[test]
    fn test_log_normal_cv() {
        let lnorm = LogNormal::from_mean_cv(0.0, 0.0).unwrap();
        assert_eq!((lnorm.norm.mean, lnorm.norm.std_dev), (-std::f64::INFINITY, 0.0));

        let lnorm = LogNormal::from_mean_cv(1.0, 0.0).unwrap();
        assert_eq!((lnorm.norm.mean, lnorm.norm.std_dev), (0.0, 0.0));

        let e = std::f64::consts::E;
        let lnorm = LogNormal::from_mean_cv(e.sqrt(), (e - 1.0).sqrt()).unwrap();
        assert_eq!((lnorm.norm.mean, lnorm.norm.std_dev), (0.0, 1.0));

        let lnorm = LogNormal::from_mean_cv(e.powf(1.5), (e - 1.0).sqrt()).unwrap();
        assert_eq!((lnorm.norm.mean, lnorm.norm.std_dev), (1.0, 1.0));
    }
    #[test]
    fn test_log_normal_invalid_sd() {
        assert!(LogNormal::from_mean_cv(-1.0, 1.0).is_err());
        assert!(LogNormal::from_mean_cv(0.0, 1.0).is_err());
        assert!(LogNormal::from_mean_cv(1.0, -1.0).is_err());
    }
}
<commit_msg>Use more efficent code and slightly relax precision of test<commit_after>// Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! The normal and derived distributions.

use crate::utils::ziggurat;
use num_traits::Float;
use crate::{ziggurat_tables, Distribution, Open01};
use rand::Rng;
use core::fmt;

/// Samples floating-point numbers according to the normal distribution
/// `N(0, 1)` (a.k.a. a standard normal, or Gaussian). This is equivalent to
/// `Normal::new(0.0, 1.0)` but faster.
///
/// See `Normal` for the general normal distribution.
///
/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method.
///
/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
///       Generate Normal Random Samples*](
///       https://www.doornik.com/research/ziggurat.pdf).
///       Nuffield College, Oxford
///
/// # Example
/// ```
/// use rand::prelude::*;
/// use rand_distr::StandardNormal;
///
/// let val: f64 = thread_rng().sample(StandardNormal);
/// println!("{}", val);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct StandardNormal;

impl Distribution<f32> for StandardNormal {
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f32 {
        // TODO: use optimal 32-bit implementation
        let x: f64 = self.sample(rng);
        x as f32
    }
}

impl Distribution<f64> for StandardNormal {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
        #[inline]
        fn pdf(x: f64) -> f64 {
            (-x * x / 2.0).exp()
        }
        #[inline]
        fn zero_case<R: Rng + ?Sized>(rng: &mut R, u: f64) -> f64 {
            // compute a random number in the tail by hand

            // strange initial conditions, because the loop is not
            // do-while, so the condition should be true on the first
            // run, they get overwritten anyway (0 < 1, so these are
            // good).
            let mut x = 1.0f64;
            let mut y = 0.0f64;

            while -2.0 * y < x * x {
                let x_: f64 = rng.sample(Open01);
                let y_: f64 = rng.sample(Open01);

                x = x_.ln() / ziggurat_tables::ZIG_NORM_R;
                y = y_.ln();
            }

            if u < 0.0 {
                x - ziggurat_tables::ZIG_NORM_R
            } else {
                ziggurat_tables::ZIG_NORM_R - x
            }
        }

        ziggurat(
            rng,
            true, // this is symmetric
            &ziggurat_tables::ZIG_NORM_X,
            &ziggurat_tables::ZIG_NORM_F,
            pdf,
            zero_case,
        )
    }
}

/// The normal distribution `N(mean, std_dev**2)`.
///
/// This uses the ZIGNOR variant of the Ziggurat method, see [`StandardNormal`]
/// for more details.
///
/// Note that [`StandardNormal`] is an optimised implementation for mean 0, and
/// standard deviation 1.
///
/// # Example
///
/// ```
/// use rand_distr::{Normal, Distribution};
///
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0).unwrap();
/// let v = normal.sample(&mut rand::thread_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
///
/// [`StandardNormal`]: crate::StandardNormal
#[derive(Clone, Copy, Debug)]
pub struct Normal<F>
where F: Float, StandardNormal: Distribution<F>
{
    mean: F,
    std_dev: F,
}

/// Error type returned from `Normal::new` and `LogNormal::new`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    /// The mean value is too small (log-normal samples must be positive)
    MeanTooSmall,
    /// The standard deviation or other dispersion parameter is negative,
    /// infinite, or not-a-number.
    BadVariance,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Error::MeanTooSmall => "mean < 0 or NaN in log-normal distribution",
            Error::BadVariance => "variation parameter is negative or non-finite in (log)normal distribution",
        })
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl<F> Normal<F>
where F: Float, StandardNormal: Distribution<F>
{
    /// Construct, from mean and standard deviation
    ///
    /// Parameters:
    ///
    /// -   mean (`μ`, unrestricted)
    /// -   standard deviation (`σ`, must be finite)
    #[inline]
    pub fn new(mean: F, std_dev: F) -> Result<Normal<F>, Error> {
        if !std_dev.is_finite() {
            return Err(Error::BadVariance);
        }
        Ok(Normal { mean, std_dev })
    }

    /// Construct, from mean and coefficient of variation
    ///
    /// Parameters:
    ///
    /// -   mean (`μ`, unrestricted)
    /// -   coefficient of variation (`cv = abs(σ / μ)`)
    #[inline]
    pub fn from_mean_cv(mean: F, cv: F) -> Result<Normal<F>, Error> {
        if !cv.is_finite() || cv < F::zero() {
            return Err(Error::BadVariance);
        }
        let std_dev = cv * mean;
        Ok(Normal { mean, std_dev })
    }

    /// Sample from a z-score
    ///
    /// This may be useful for generating correlated samples, as follows.
    /// ```
    /// # use rand::prelude::*;
    /// # use rand_distr::{Normal, StandardNormal};
    /// let mut rng = thread_rng();
    /// let z = StandardNormal.sample(&mut rng);
    /// let x1 = Normal::new(0.0, 1.0).unwrap().from_zscore(z);
    /// let x2 = Normal::new(2.0, -1.0).unwrap().from_zscore(z);
    /// ```
    #[inline]
    pub fn from_zscore(&self, zscore: F) -> F {
        self.mean + self.std_dev * zscore
    }
}

impl<F> Distribution<F> for Normal<F>
where F: Float, StandardNormal: Distribution<F>
{
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> F {
        self.from_zscore(rng.sample(StandardNormal))
    }
}

/// The log-normal distribution `ln N(mean, std_dev**2)`.
///
/// If `X` is log-normal distributed, then `ln(X)` is `N(mean, std_dev**2)`
/// distributed.
///
/// # Example
///
/// ```
/// use rand_distr::{LogNormal, Distribution};
///
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0).unwrap();
/// let v = log_normal.sample(&mut rand::thread_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
#[derive(Clone, Copy, Debug)]
pub struct LogNormal<F>
where F: Float, StandardNormal: Distribution<F>
{
    norm: Normal<F>,
}

impl<F> LogNormal<F>
where F: Float, StandardNormal: Distribution<F>
{
    /// Construct, from (log-space) mean and standard deviation
    ///
    /// Parameters are the "standard" log-space measures (these are the mean
    /// and standard deviation of the logarithm of samples):
    ///
    /// -   `mu` (`μ`, unrestricted) is the mean of the underlying distribution
    /// -   `sigma` (`σ`, must be finite) is the standard deviation of the
    ///     underlying Normal distribution
    #[inline]
    pub fn new(mu: F, sigma: F) -> Result<LogNormal<F>, Error> {
        let norm = Normal::new(mu, sigma)?;
        Ok(LogNormal { norm })
    }

    /// Construct, from (linear-space) mean and coefficient of variation
    ///
    /// Parameters are linear-space measures:
    ///
    /// -   mean (`μ > 0`) is the (real) mean of the distribution
    /// -   coefficient of variation (`cv = σ / μ`, requiring `cv ≥ 0`) is a
    ///     standardized measure of dispersion
    ///
    /// As a special exception, `μ = 0, cv = 0` is allowed (samples are `-inf`).
    #[inline]
    pub fn from_mean_cv(mean: F, cv: F) -> Result<LogNormal<F>, Error> {
        if cv == F::zero() {
            let mu = mean.ln();
            let norm = Normal::new(mu, F::zero()).unwrap();
            return Ok(LogNormal { norm });
        }
        if !(mean > F::zero()) {
            return Err(Error::MeanTooSmall);
        }
        if !(cv >= F::zero()) {
            return Err(Error::BadVariance);
        }

        // Using X ~ lognormal(μ, σ), CV² = Var(X) / E(X)²
        // E(X) = exp(μ + σ² / 2) = exp(μ) × exp(σ² / 2)
        // Var(X) = exp(2μ + σ²)(exp(σ²) - 1) = E(X)² × (exp(σ²) - 1)
        // but Var(X) = (CV × E(X))² so CV² = exp(σ²) - 1
        // thus σ² = log(CV² + 1)
        // and exp(μ) = E(X) / exp(σ² / 2) = E(X) / sqrt(CV² + 1)
        let a = F::one() + cv * cv; // e
        let mu = F::from(0.5).unwrap() * (mean * mean / a).ln();
        let sigma = a.ln().sqrt();
        let norm = Normal::new(mu, sigma)?;
        Ok(LogNormal { norm })
    }

    /// Sample from a z-score
    ///
    /// This may be useful for generating correlated samples, as follows.
    /// ```
    /// # use rand::prelude::*;
    /// # use rand_distr::{LogNormal, StandardNormal};
    /// let mut rng = thread_rng();
    /// let z = StandardNormal.sample(&mut rng);
    /// let x1 = LogNormal::from_mean_cv(3.0, 1.0).unwrap().from_zscore(z);
    /// let x2 = LogNormal::from_mean_cv(2.0, 1.0).unwrap().from_zscore(z);
    /// ```
    #[inline]
    pub fn from_zscore(&self, zscore: F) -> F {
        self.norm.from_zscore(zscore).exp()
    }
}

impl<F> Distribution<F> for LogNormal<F>
where F: Float, StandardNormal: Distribution<F>
{
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> F {
        self.norm.sample(rng).exp()
    }
}

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

    #[test]
    fn test_normal() {
        let norm = Normal::new(10.0, 10.0).unwrap();
        let mut rng = crate::test::rng(210);
        for _ in 0..1000 {
            norm.sample(&mut rng);
        }
    }
    #[test]
    fn test_normal_cv() {
        let norm = Normal::from_mean_cv(1024.0, 1.0 / 256.0).unwrap();
        assert_eq!((norm.mean, norm.std_dev), (1024.0, 4.0));
    }
    #[test]
    fn test_normal_invalid_sd() {
        assert!(Normal::from_mean_cv(10.0, -1.0).is_err());
    }

    #[test]
    fn test_log_normal() {
        let lnorm = LogNormal::new(10.0, 10.0).unwrap();
        let mut rng = crate::test::rng(211);
        for _ in 0..1000 {
            lnorm.sample(&mut rng);
        }
    }
    #[test]
    fn test_log_normal_cv() {
        let lnorm = LogNormal::from_mean_cv(0.0, 0.0).unwrap();
        assert_eq!((lnorm.norm.mean, lnorm.norm.std_dev), (-std::f64::INFINITY, 0.0));

        let lnorm = LogNormal::from_mean_cv(1.0, 0.0).unwrap();
        assert_eq!((lnorm.norm.mean, lnorm.norm.std_dev), (0.0, 0.0));

        let e = std::f64::consts::E;
        let lnorm = LogNormal::from_mean_cv(e.sqrt(), (e - 1.0).sqrt()).unwrap();
        assert_almost_eq!(lnorm.norm.mean, 0.0, 2e-16);
        assert_almost_eq!(lnorm.norm.std_dev, 1.0, 2e-16);

        let lnorm = LogNormal::from_mean_cv(e.powf(1.5), (e - 1.0).sqrt()).unwrap();
        assert_eq!((lnorm.norm.mean, lnorm.norm.std_dev), (1.0, 1.0));
    }
    #[test]
    fn test_log_normal_invalid_sd() {
        assert!(LogNormal::from_mean_cv(-1.0, 1.0).is_err());
        assert!(LogNormal::from_mean_cv(0.0, 1.0).is_err());
        assert!(LogNormal::from_mean_cv(1.0, -1.0).is_err());
    }
}
<|endoftext|>


<commit_before>//! Wrapper around a wl_output

use std::fmt;

use wlroots::{Area, Size, Origin};
use wayland_client::protocol::wl_output::WlOutput;
use wayland_client::{Proxy, NewProxy};

use lua::LUA;
use objects::screen::{self, Screen};

/// Wrapper around WlOutput.
#[derive(Clone, Eq, PartialEq)]
pub struct Output {
    proxy: Proxy<WlOutput>,
}

/// The cached state for the WlOutput.
#[derive(Debug, Default, Clone, Eq, PartialEq)]
struct OutputState {
    name: String,
    resolution: (i32, i32)
}

impl <'this> Into<&'this Proxy<WlOutput>> for &'this Output {
    fn into(self) -> &'this Proxy<WlOutput> {
        &self.proxy
    }
}

impl Output {
    pub fn new(new_proxy: Result<NewProxy<WlOutput>, u32>, _: ()) {
        let new_proxy = new_proxy.expect("Could not create WlOutput");
        let state = Box::new(OutputState::default());
        let proxy = new_proxy.implement(move |event, mut proxy: Proxy<WlOutput>| {
            use wayland_client::protocol::wl_output::Event;
            let output = Output { proxy: proxy.clone() };
            let state = unwrap_state_mut(&mut proxy);
            LUA.with(|lua| {
                let lua = lua.borrow();
                let lua = &*lua;
                match event {
                    Event::Geometry { make, model,  .. } => {
                        state.name = format!("{} ({})", make, model);
                    },
                    Event::Mode { width, height, .. } => {
                        state.resolution = (width, height);
                        let geometry = Area { origin: Origin { x: 0, y: 0 },
                                              size: Size { width, height }
                        };
                        if let Ok(mut screen) = screen::get_screen(lua, output) {
                            screen.set_geometry(geometry)
                                .expect("could not set geometry");
                            screen.set_workarea(geometry)
                                .expect("could not set workarea ");
                        }
                    }
                    Event::Done => {
                        let mut screen = Screen::new(lua)
                            .expect("Could not allocate new screen");
                        screen.init_screens(output.clone(), vec![output])
                            .expect("Could not initilize new output with a screen");
                        screen::add_screen(lua, screen)
                            .expect("Could not add screen to the list of screens");
                    }
                    _ => {/* TODO */}
                }
            });
        });
        proxy.set_user_data(Box::into_raw(state) as _);
        let output = Output { proxy };
        LUA.with(|lua| {
            let lua = lua.borrow();
            let lua = &*lua;
            let mut screen = Screen::new(lua)
                .expect("Could not allocate new screen");
            screen.init_screens(output.clone(), vec![output])
                .expect("Could not initilize new output with a screen");
            screen::add_screen(lua, screen)
                .expect("Could not add screen to the list of screens");
        });
    }

    pub fn resolution(&self) -> (i32, i32) {
        unwrap_state(self).resolution
    }

    pub fn name(&self) -> &str {
        unwrap_state(self).name.as_str()
    }
}

impl fmt::Debug for Output {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self.proxy.c_ptr())
    }
}

fn unwrap_state_mut<'this, I: Into<&'this mut Proxy<WlOutput>>>(proxy: I) -> &'this mut OutputState {
    unsafe {
        let user_data = proxy.into().get_user_data() as *mut OutputState;
        if user_data.is_null() {
            panic!("User data has not been set yet");
        }
        &mut *user_data
    }
}

fn unwrap_state<'this, I: Into<&'this Proxy<WlOutput>>>(proxy: I) -> &'this OutputState {
    unsafe {
        let user_data = proxy.into().get_user_data() as *const OutputState;
        if user_data.is_null() {
            panic!("User data has not been set yet");
        }
        &*user_data
    }
}
<commit_msg>Added Awesome TODO<commit_after>//! Wrapper around a wl_output

use std::fmt;

use wlroots::{Area, Size, Origin};
use wayland_client::protocol::wl_output::WlOutput;
use wayland_client::{Proxy, NewProxy};

use lua::LUA;
use objects::screen::{self, Screen};

/// Wrapper around WlOutput.
#[derive(Clone, Eq, PartialEq)]
pub struct Output {
    proxy: Proxy<WlOutput>,
}

/// The cached state for the WlOutput.
#[derive(Debug, Default, Clone, Eq, PartialEq)]
struct OutputState {
    name: String,
    resolution: (i32, i32)
}

impl <'this> Into<&'this Proxy<WlOutput>> for &'this Output {
    fn into(self) -> &'this Proxy<WlOutput> {
        &self.proxy
    }
}

impl Output {
    pub fn new(new_proxy: Result<NewProxy<WlOutput>, u32>, _: ()) {
        let new_proxy = new_proxy.expect("Could not create WlOutput");
        let state = Box::new(OutputState::default());
        let proxy = new_proxy.implement(move |event, mut proxy: Proxy<WlOutput>| {
            use wayland_client::protocol::wl_output::Event;
            let output = Output { proxy: proxy.clone() };
            let state = unwrap_state_mut(&mut proxy);
            LUA.with(|lua| {
                let lua = lua.borrow();
                let lua = &*lua;
                match event {
                    Event::Geometry { make, model,  .. } => {
                        state.name = format!("{} ({})", make, model);
                    },
                    Event::Mode { width, height, .. } => {
                        state.resolution = (width, height);
                        let geometry = Area { origin: Origin { x: 0, y: 0 },
                                              size: Size { width, height }
                        };
                        if let Ok(mut screen) = screen::get_screen(lua, output) {
                            screen.set_geometry(geometry)
                                .expect("could not set geometry");
                            screen.set_workarea(geometry)
                                .expect("could not set workarea ");
                        }
                    }
                    Event::Done => {
                        // TODO We may not always want to add a new screen
                        // see how awesome does it and fix this.
                        let mut screen = Screen::new(lua)
                            .expect("Could not allocate new screen");
                        screen.init_screens(output.clone(), vec![output])
                            .expect("Could not initilize new output with a screen");
                        screen::add_screen(lua, screen)
                            .expect("Could not add screen to the list of screens");
                    }
                    _ => {/* TODO */}
                }
            });
        });
        proxy.set_user_data(Box::into_raw(state) as _);
        let output = Output { proxy };
        LUA.with(|lua| {
            let lua = lua.borrow();
            let lua = &*lua;
            let mut screen = Screen::new(lua)
                .expect("Could not allocate new screen");
            screen.init_screens(output.clone(), vec![output])
                .expect("Could not initilize new output with a screen");
            screen::add_screen(lua, screen)
                .expect("Could not add screen to the list of screens");
        });
    }

    pub fn resolution(&self) -> (i32, i32) {
        unwrap_state(self).resolution
    }

    pub fn name(&self) -> &str {
        unwrap_state(self).name.as_str()
    }
}

impl fmt::Debug for Output {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self.proxy.c_ptr())
    }
}

fn unwrap_state_mut<'this, I: Into<&'this mut Proxy<WlOutput>>>(proxy: I) -> &'this mut OutputState {
    unsafe {
        let user_data = proxy.into().get_user_data() as *mut OutputState;
        if user_data.is_null() {
            panic!("User data has not been set yet");
        }
        &mut *user_data
    }
}

fn unwrap_state<'this, I: Into<&'this Proxy<WlOutput>>>(proxy: I) -> &'this OutputState {
    unsafe {
        let user_data = proxy.into().get_user_data() as *const OutputState;
        if user_data.is_null() {
            panic!("User data has not been set yet");
        }
        &*user_data
    }
}
<|endoftext|>


<commit_before>// xfail-stage0
// xfail-stage1
// xfail-stage2
// error-pattern: unknown module item

// rustboot has a different error message than rustc
// this test can die with rustboot, or rustc's error can change

mod foo {
  export x;
  fn x(int y) {
    log y;
  }
  fn z(int y) {
    log y;
  }
}

fn main() {
  foo::z(10);
}
<commit_msg>test: Remove compile-fail/export-boot.rs<commit_after><|endoftext|>


<commit_before>// -*- rust -*-
// error-pattern:1 == 2
use std;
import std::task;
import std::comm::chan;
import std::comm::port;
import std::comm::recv;

fn child() { assert (1 == 2); }

fn parent() {
    let p = port::<int>();
    let f = child;
    task::spawn(f);
    let x = recv(p);
}

// This task is not linked to the failure chain, but since the other
// tasks are going to fail the kernel, this one will fail too
fn sleeper() {
    let p = port::<int>();
    let x = recv(p);
}

fn main() {
    let g = sleeper;
    task::spawn(g);
    let f = parent;
    task::spawn(f);
}<commit_msg>XFAIL run-fail/linked-failure4. Deadlocks on mac<commit_after>// -*- rust -*-
// error-pattern:1 == 2
// xfail-test Been deadlocking on mac
use std;
import std::task;
import std::comm::chan;
import std::comm::port;
import std::comm::recv;

fn child() { assert (1 == 2); }

fn parent() {
    let p = port::<int>();
    let f = child;
    task::spawn(f);
    let x = recv(p);
}

// This task is not linked to the failure chain, but since the other
// tasks are going to fail the kernel, this one will fail too
fn sleeper() {
    let p = port::<int>();
    let x = recv(p);
}

fn main() {
    let g = sleeper;
    task::spawn(g);
    let f = parent;
    task::spawn(f);
}<|endoftext|>


<commit_before>extern crate semver;
extern crate uuid;
extern crate toml;
#[macro_use] extern crate log;
extern crate serde_json;

#[macro_use] extern crate libimagstore;
#[macro_use] extern crate libimagerror;
extern crate task_hookrs;

module_entry_path_mod!("todo", "0.1.0");

pub mod error;
pub mod result;
pub mod task;

<commit_msg>libimagtodo: Deny warnings<commit_after>#![deny(
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_mut,
    unused_qualifications,
    while_true,
)]

extern crate semver;
extern crate uuid;
extern crate toml;
#[macro_use] extern crate log;
extern crate serde_json;

#[macro_use] extern crate libimagstore;
#[macro_use] extern crate libimagerror;
extern crate task_hookrs;

module_entry_path_mod!("todo", "0.1.0");

pub mod error;
pub mod result;
pub mod task;

<|endoftext|>


<commit_before>
fn main () {
  // dummy
  println!("cargo:rustc-flags=-l sodium");
}<commit_msg>Whitespace changes<commit_after>fn main () {
    println!("cargo:rustc-flags=-l sodium");
}
<|endoftext|>


<commit_before>pub struct PascalsTriangle;

impl PascalsTriangle {
    pub fn new(row_count: u32) -> Self {
        unimplemented!();
    }

    pub fn rows(&self) -> Vec<Vec<u32>> {
        unimplemented!();
    }
}
<commit_msg>Add rust code for pascals-triangle case<commit_after>pub struct PascalsTriangle {
    row: u32,
}

impl PascalsTriangle {
    pub fn new(row_count: u32) -> Self {
        PascalsTriangle { row: row_count }
    }

    fn pascal(row: u32) -> Vec<u32> {
        let mut result = Vec::with_capacity(row as usize);

        result.push(1);

        for k in 0..row {
            let v = result[k as usize] * (row - k) / (k + 1);

            result.push(v);
        }

        result
    }

    pub fn rows(&self) -> Vec<Vec<u32>> {
        (0..self.row).map(PascalsTriangle::pascal).collect()
    }
}
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

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

extern crate dirs;
extern crate nalgebra;
extern crate num_complex;
extern crate num_traits;
extern crate rand;
extern crate sfml;
extern crate serde;
extern crate serde_json;
extern crate serde_yaml;
extern crate simple_logger;

extern crate specs;
extern crate circle_collision;
extern crate gravity;
extern crate xsecurelock_saver;

use std::fs;
use std::fs::File;
use std::io::{BufReader, ErrorKind};
use std::path::{Path, PathBuf};

use gravity::{
    GravitationalConstant,
    GravitySource,
    GravitySystem,
    GravityTarget,
};
use circle_collision::{
    BruteForceCollisionDetector,
    ClearCollisionsInvolvingSceneEntities,
    CircleCollider,
    CollisionMatrix,
    LastUpdateCollisions,
};
use xsecurelock_saver::engine::{
    EngineBuilder,
    systems::physics::{
        SympleticEulerForceStep,
        SympleticEulerVelocityStep,
    },
};

use collision::{
    DeleteCollidedPlanets,
    MergeCollidedPlanets,
    MergedInto,
};
use config::GeneticOrbitsConfig;
use statustracker::{ActiveWorld, ScoreKeeper};
use storage::sqlite::SqliteStorage;
use worldgenerator::WorldGenerator;

mod collision;
mod config;
mod model;
mod storage;
mod statustracker;
mod worldgenerator;

fn main() {
    simple_logger::init().unwrap();

    let config = get_config();
    let storage = match &config.database.database_path {
        Some(path) => {
            info!("using database {}", path);
            SqliteStorage::open(path).unwrap()
        },
        None => open_default_storage(),
    };

    let GeneticOrbitsConfig { scoring, generator, .. } = config;

    EngineBuilder::new()
        .with_initial_sceneloader(WorldGenerator::<SqliteStorage>::default())
        .with_resource(GravitationalConstant(1000.))
        .with_resource(LastUpdateCollisions::default())
        .with_resource({
            let mut matrix = CollisionMatrix::default();
            matrix.enable_collision(collision::planet(), collision::planet());
            matrix
        })
        .with_resource(scoring)
        .with_resource(generator)
        .with_resource(storage)
        .with_resource(ActiveWorld::default())
        .with_component::<CircleCollider>()
        .with_component::<GravitySource>()
        .with_component::<GravityTarget>()
        .with_component::<MergedInto>()
        .with_scene_change_sys(ClearCollisionsInvolvingSceneEntities, "", &[])
        // Run the real merge just before scoring.
        .with_physics_update_sys(
            MergeCollidedPlanets, "merge-collided", &[])
        .with_physics_update_sys(
            DeleteCollidedPlanets, "delete-collided", &["merge-collided"])
        .with_physics_update_barrier()
        // Run scorekeeping before integrating.
        .with_physics_update_sys(ScoreKeeper::<SqliteStorage>::default(), "score-keeper", &[])
        .with_physics_update_sys(GravitySystem, "apply-gravity", &[])
        // Barrier between adding forces and adding integration.
        .with_physics_update_barrier()
        .with_physics_update_sys(SympleticEulerForceStep, "integrate-forces", &[])
        .with_physics_update_sys(
            BruteForceCollisionDetector, "detect-collisions", &["integrate-forces"])
        .with_physics_update_sys(
            SympleticEulerVelocityStep, "integrate-velocities", &["detect-collisions"])
        .build()
        .run();
}

/// The screensaver folder name, used both for saving the database in the user data directory and
/// for looking for configs in the
const SAVER_DIR: &'static str = "xsecurelock-saver-genetic-orbits";

/// Open SqliteStorage somewhere, either in the user data dir or in memory.
fn open_default_storage() -> SqliteStorage {
    if let Some(mut data_dir) = dirs::data_dir() {
        data_dir.push(SAVER_DIR);
        let create_res = fs::create_dir(&data_dir)
            .or_else(|err| if err.kind() == ErrorKind::AlreadyExists {
                Ok(())
            } else {
                Err(err)
            });
        match create_res {
            Ok(()) => {
                data_dir.push("scenario-db.sqlite3");
                info!("using database {:?}", data_dir);
                return SqliteStorage::open(data_dir).unwrap();
            },
            Err(err) => error!("Unable to create storage directory ({}), opening in memory", err),
        }
    }
    info!("using in-memory database");
    SqliteStorage::open_in_memory().unwrap()
}

/// Load the config from the user config directory.
fn get_config() -> GeneticOrbitsConfig {
    match find_config_file() {
        Some(config_file) => {
            match serde_yaml::from_reader::<_, GeneticOrbitsConfig>(config_file) {
                Ok(mut config) => {
                    config.fix_invalid();
                    config
                },
                Err(err) => {
                    error!("Error loading config: {}", err);
                    Default::default()
                },
            }
        },
        None => Default::default(),
    }
}

fn find_config_file() -> Option<BufReader<File>> {
    let config_file = dirs::home_dir()
        .and_then(|mut home| {
            home.push(".xsecurelock-saver-genetic-orbits.yaml");
            try_open_config_file(home)
        })
        .or_else(|| {
            dirs::config_dir()
                .and_then(|mut config| {
                    config.push(SAVER_DIR);
                    config.push("config.yaml");
                    try_open_config_file(config)
                })
        });
    let config_file = if cfg!(target_family = "unix") {
        config_file.or_else(|| try_open_config_file(
                PathBuf::from(r"/etc/xsecurelock-saver-genetic-orbits/config.yaml")))
    } else {
        config_file
    };
    config_file.map(BufReader::new)
}

fn try_open_config_file<P: AsRef<Path>>(b: P) -> Option<File> {
    File::open(b.as_ref())
        .or_else(|err| if err.kind() == ErrorKind::NotFound {
            Err(())
        } else {
            error!("unable to read config file {:?}: {}", b.as_ref(), err);
            Err(())
        })
        .ok()
}
<commit_msg>log more about config loading<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

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

extern crate dirs;
extern crate nalgebra;
extern crate num_complex;
extern crate num_traits;
extern crate rand;
extern crate sfml;
extern crate serde;
extern crate serde_json;
extern crate serde_yaml;
extern crate simple_logger;

extern crate specs;
extern crate circle_collision;
extern crate gravity;
extern crate xsecurelock_saver;

use std::fs;
use std::fs::File;
use std::io::{BufReader, ErrorKind};
use std::path::{Path, PathBuf};

use gravity::{
    GravitationalConstant,
    GravitySource,
    GravitySystem,
    GravityTarget,
};
use circle_collision::{
    BruteForceCollisionDetector,
    ClearCollisionsInvolvingSceneEntities,
    CircleCollider,
    CollisionMatrix,
    LastUpdateCollisions,
};
use xsecurelock_saver::engine::{
    EngineBuilder,
    systems::physics::{
        SympleticEulerForceStep,
        SympleticEulerVelocityStep,
    },
};

use collision::{
    DeleteCollidedPlanets,
    MergeCollidedPlanets,
    MergedInto,
};
use config::GeneticOrbitsConfig;
use statustracker::{ActiveWorld, ScoreKeeper};
use storage::sqlite::SqliteStorage;
use worldgenerator::WorldGenerator;

mod collision;
mod config;
mod model;
mod storage;
mod statustracker;
mod worldgenerator;

fn main() {
    simple_logger::init().unwrap();

    let config = get_config();
    let storage = match &config.database.database_path {
        Some(path) => {
            info!("using database {}", path);
            SqliteStorage::open(path).unwrap()
        },
        None => open_default_storage(),
    };

    let GeneticOrbitsConfig { scoring, generator, .. } = config;

    EngineBuilder::new()
        .with_initial_sceneloader(WorldGenerator::<SqliteStorage>::default())
        .with_resource(GravitationalConstant(1000.))
        .with_resource(LastUpdateCollisions::default())
        .with_resource({
            let mut matrix = CollisionMatrix::default();
            matrix.enable_collision(collision::planet(), collision::planet());
            matrix
        })
        .with_resource(scoring)
        .with_resource(generator)
        .with_resource(storage)
        .with_resource(ActiveWorld::default())
        .with_component::<CircleCollider>()
        .with_component::<GravitySource>()
        .with_component::<GravityTarget>()
        .with_component::<MergedInto>()
        .with_scene_change_sys(ClearCollisionsInvolvingSceneEntities, "", &[])
        // Run the real merge just before scoring.
        .with_physics_update_sys(
            MergeCollidedPlanets, "merge-collided", &[])
        .with_physics_update_sys(
            DeleteCollidedPlanets, "delete-collided", &["merge-collided"])
        .with_physics_update_barrier()
        // Run scorekeeping before integrating.
        .with_physics_update_sys(ScoreKeeper::<SqliteStorage>::default(), "score-keeper", &[])
        .with_physics_update_sys(GravitySystem, "apply-gravity", &[])
        // Barrier between adding forces and adding integration.
        .with_physics_update_barrier()
        .with_physics_update_sys(SympleticEulerForceStep, "integrate-forces", &[])
        .with_physics_update_sys(
            BruteForceCollisionDetector, "detect-collisions", &["integrate-forces"])
        .with_physics_update_sys(
            SympleticEulerVelocityStep, "integrate-velocities", &["detect-collisions"])
        .build()
        .run();
}

/// The screensaver folder name, used both for saving the database in the user data directory and
/// for looking for configs in the
const SAVER_DIR: &'static str = "xsecurelock-saver-genetic-orbits";

/// Open SqliteStorage somewhere, either in the user data dir or in memory.
fn open_default_storage() -> SqliteStorage {
    if let Some(mut data_dir) = dirs::data_dir() {
        data_dir.push(SAVER_DIR);
        let create_res = fs::create_dir(&data_dir)
            .or_else(|err| if err.kind() == ErrorKind::AlreadyExists {
                Ok(())
            } else {
                Err(err)
            });
        match create_res {
            Ok(()) => {
                data_dir.push("scenario-db.sqlite3");
                info!("using database {:?}", data_dir);
                return SqliteStorage::open(data_dir).unwrap();
            },
            Err(err) => error!("Unable to create storage directory ({}), opening in memory", err),
        }
    }
    info!("using in-memory database");
    SqliteStorage::open_in_memory().unwrap()
}

/// Load the config from the user config directory.
fn get_config() -> GeneticOrbitsConfig {
    match find_config_file() {
        Some(config_file) => {
            match serde_yaml::from_reader::<_, GeneticOrbitsConfig>(config_file) {
                Ok(mut config) => {
                    info!("Successfully loaded config");
                    config.fix_invalid();
                    config
                },
                Err(err) => {
                    error!("Error loading config: {}", err);
                    Default::default()
                },
            }
        },
        None => {
            info!("No config file found, using default config");
            Default::default()
        },
    }
}

fn find_config_file() -> Option<BufReader<File>> {
    let config_file = dirs::home_dir()
        .and_then(|mut home| {
            home.push(".xsecurelock-saver-genetic-orbits.yaml");
            try_open_config_file(home)
        })
        .or_else(|| {
            dirs::config_dir()
                .and_then(|mut config| {
                    config.push(SAVER_DIR);
                    config.push("config.yaml");
                    try_open_config_file(config)
                })
        });
    let config_file = if cfg!(target_family = "unix") {
        config_file.or_else(|| try_open_config_file(
                PathBuf::from(r"/etc/xsecurelock-saver-genetic-orbits/config.yaml")))
    } else {
        config_file
    };
    config_file.map(BufReader::new)
}

fn try_open_config_file<P: AsRef<Path>>(b: P) -> Option<File> {
    let config_load = File::open(b.as_ref())
        .or_else(|err| if err.kind() == ErrorKind::NotFound {
            Err(())
        } else {
            error!("Unable to read config file {:?}: {}", b.as_ref(), err);
            Err(())
        });
    match config_load {
        Err(()) => None,
        Ok(config) => {
            info!("Using config file {:?}", b.as_ref());
            Some(config)
        },
    }
}
<|endoftext|>