<commit_before>//
// Sysinfo
//
// Copyright (c) 2015 Guillaume Gomez
//

use processus::*;
use process::*;
use std::old_io::fs;
use std::fs::{File, read_link, PathExt};
use std::io::Read;
use std::ffi::AsOsStr;
use std::old_io::fs::PathExtensions;
use std::old_path::posix::Path as PosixPath;
use std::str::FromStr;
use std::os;
use std::path::{Path, PathBuf};
use std::io;
use std::old_path;
use std::old_io;
use std::collections::VecMap;
use std::old_path::GenericPath;

pub struct System {
    processus_list: VecMap<Processus>,
    mem_total: u64,
    mem_free: u64,
    swap_total: u64,
    swap_free: u64,
    processes: Vec<Process>,
}

impl System {
    pub fn new() -> System {
        let mut s = System {
            processus_list: VecMap::new(),
            mem_total: 0,
            mem_free: 0,
            swap_total: 0,
            swap_free: 0,
            processes: Vec::new(),
        };

        s.refresh();
        s
    }

    pub fn refresh(&mut self) {
        match fs::readdir(&PosixPath::new("/proc")) {
            Ok(v) => {
                let mut proc_list : VecMap<Processus> = VecMap::new();

                for entry in v.iter() {
                    if entry.is_dir() {
                        match _get_processus_data(entry, &self.processus_list) {
                            Some(p) => {
                                proc_list.insert(p.pid as usize, p);
                            }
                            None => {}
                        };
                    } else {
                        match entry.as_os_str().to_str().unwrap() {
                            "/proc/meminfo" => {
                                let mut data = get_all_data(entry.as_str().unwrap());
                                let lines : Vec<&str> = data.split('\n').collect();
                                for line in lines.iter() {
                                    match *line {
                                        l if l.starts_with("MemTotal:") => {
                                            let parts : Vec<&str> = line.split(' ').collect();

                                            self.mem_total = u64::from_str(parts[parts.len() - 2]).unwrap();
                                        },
                                        l if l.starts_with("MemFree:") => {
                                            let parts : Vec<&str> = line.split(' ').collect();

                                            self.mem_free = u64::from_str(parts[parts.len() - 2]).unwrap();
                                        },
                                        l if l.starts_with("SwapTotal:") => {
                                            let parts : Vec<&str> = line.split(' ').collect();

                                            self.swap_total = u64::from_str(parts[parts.len() - 2]).unwrap();
                                        },
                                        l if l.starts_with("SwapFree:") => {
                                            let parts : Vec<&str> = line.split(' ').collect();

                                            self.swap_free = u64::from_str(parts[parts.len() - 2]).unwrap();
                                        },
                                        _ => continue,
                                    }
                                }
                            },
                            "/proc/stat" => {
                                let mut data = get_all_data(entry.as_str().unwrap());
                                let lines : Vec<&str> = data.split('\n').collect();
                                let mut i = 0;
                                let first = self.processes.len() == 0;
                                for line in lines.iter() {
                                    if !line.starts_with("cpu") {
                                        break;
                                    }

                                    let (parts, _) : (Vec<&str>, Vec<&str>) = line.split(' ').partition(|s| s.len() > 0);
                                    if first {
                                        self.processes.push(new_process(parts[0], u64::from_str(parts[1]).unwrap(),
                                            u64::from_str(parts[2]).unwrap(),
                                            u64::from_str(parts[3]).unwrap(),
                                            u64::from_str(parts[4]).unwrap()));
                                    } else {
                                        set_process(self.processes.get_mut(i).unwrap(),
                                            u64::from_str(parts[1]).unwrap(),
                                            u64::from_str(parts[2]).unwrap(),
                                            u64::from_str(parts[3]).unwrap(),
                                            u64::from_str(parts[4]).unwrap());
                                        i += 1;
                                    }
                                }
                            }
                           _ => {},
                        }
                    }
                }
                for (pid, proc_) in proc_list.iter_mut() {
                    match self.processus_list.get(&pid) {
                        Some(p) => {
                            let (new, old) = get_raw_times(&self.processes[0]);
                            let (pnew, pold) = get_raw_processus_times(&p);
                            compute_cpu_usage(proc_, pnew, pold, new, old);
                        }
                        None => {}
                    }
                }
                self.processus_list = proc_list;
            },
            Err(e) => {
                panic!("cannot read /proc ! error: {}", e);
            }
        }
    }

    pub fn get_processus_list<'a>(&'a self) -> &'a VecMap<Processus> {
        &self.processus_list
    }

    pub fn get_processus(&self, pid: i64) -> Option<&Processus> {
        self.processus_list.get(&(pid as usize))
    }

    // The first process in the array is the "main" process
    pub fn get_process_list<'a>(&'a self) -> &'a [Process] {
        self.processes.as_slice()
    }

    pub fn get_total_memory(&self) -> u64 {
        self.mem_total
    }

    pub fn get_free_memory(&self) -> u64 {
        self.mem_free
    }

    pub fn get_total_swap(&self) -> u64 {
        self.swap_total
    }

    pub fn get_free_swap(&self) -> u64 {
        self.swap_free
    }
}

fn get_all_data(file_path: &str) -> String {
    let mut file = File::open(file_path).unwrap();
    let mut data = String::new();

    file.read_to_string(&mut data);
    data
}

fn _get_processus_data(path: &PosixPath, proc_list: &VecMap<Processus>) -> Option<Processus> {
    if !path.exists() || !path.is_dir() {
        return None;
    }
    let paths : Vec<&str> = path.as_os_str().to_str().unwrap().split("/").collect();
    let last = paths[paths.len() - 1];
    match i64::from_str(last) {
        Ok(nb) => {
            let mut p = Processus::new(nb);
            let mut tmp = path.clone();

            tmp.push("cmdline");
            p.cmd = String::from_str(copy_from_file(&tmp)[0].as_slice());
            tmp = path.clone();
            tmp.push("environ");
            p.environ = copy_from_file(&tmp);
            tmp = path.clone();
            tmp.push("exe");
            let s = read_link(tmp.as_str().unwrap());
            if s.is_ok() {

                p.exe = String::from_str(s.unwrap().as_os_str().to_str().unwrap());
                {
                    let mut tmp_name : Vec<&str> = p.exe.split("/").collect();

                    p.name = String::from_str(tmp_name[tmp_name.len() - 1]);
                }
            }
            tmp = path.clone();
            tmp.push("cwd");
            p.cwd = String::from_str(realpath(Path::new(tmp.as_str().unwrap())).unwrap().as_os_str().to_str().unwrap());
            tmp = path.clone();
            tmp.push("root");
            p.root = String::from_str(realpath(Path::new(tmp.as_str().unwrap())).unwrap().as_os_str().to_str().unwrap());
            tmp = path.clone();
            tmp.push("status");
            let mut data = get_all_data(tmp.as_str().unwrap());

            let lines : Vec<&str> = data.split('\n').collect();
            for line in lines.iter() {
                match *line {
                    l if l.starts_with("VmRSS") => {
                        let parts : Vec<&str> = line.split(' ').collect();

                        p.memory = u64::from_str(parts[parts.len() - 2]).unwrap();
                        break;
                    }
                    _ => continue,
                }
            }
            tmp = path.clone();
            tmp.push("stat");
            let mut data2 = get_all_data(tmp.as_str().unwrap());
            // ne marche pas car il faut aussi les anciennes valeurs !!!!
            let (parts, _) : (Vec<&str>, Vec<&str>) = data2.split(' ').partition(|s| s.len() > 0);
            set_time(&mut p, u64::from_str(parts[13]).unwrap(), u64::from_str(parts[14]).unwrap());
            Some(p)
        }
        _ => None
    }
}

fn get_last(path: &PosixPath) -> &str {
    let t = path.as_os_str().to_str().unwrap();
    let v : Vec<&str> = t.split('/').collect();

    if v.len() > 0 {
        v[v.len() - 1]
    } else {
        ""
    }
}

fn copy_from_file(entry: &PosixPath) -> Vec<String> {
    match File::open(entry.as_str().unwrap()) {
        Ok(mut f) => {
            let mut d = String::new();

            f.read_to_string(&mut d);
            let mut v : Vec<&str> = d.split('\0').collect();
            let mut ret = Vec::new();

            for tmp in v.iter() {
                ret.push(String::from_str(tmp));
            }
            ret
        },
        Err(_) => Vec::new()
    }
}

fn old_realpath(original: &PosixPath) -> old_io::IoResult<old_path::Path> {
    const MAX_LINKS_FOLLOWED: usize = 256;
    let original = PosixPath::new(::std::env::current_dir().unwrap().as_os_str().to_str().unwrap()).join(original);
    // Right now lstat on windows doesn't work quite well
    if cfg!(windows) {
        return Ok(original)
    }
    let result = original.root_path();
    let mut result = result.expect("make_absolute has no root_path");
    let mut followed = 0;
    for part in original.components() {
        result.push(part);
        loop {
            if followed == MAX_LINKS_FOLLOWED {
                return Ok(old_path::Path::new(""));
            }
            match fs::lstat(&result) {
                Err(..) => break,
                Ok(ref stat) if stat.kind != old_io::FileType::Symlink => break,
                Ok(..) => {
                    followed += 1;
                    let path = try!(fs::readlink(&result));
                    result.pop();
                    result.push(path);
                }
            }
        }
    }
    return Ok(result);
}

fn realpath(original: &Path) -> io::Result<PathBuf> {
    let old = old_path::Path::new(original.to_str().unwrap());

    match old_realpath(&old) {
        Ok(p) => Ok(PathBuf::from(p.as_str().unwrap())),
        Err(_) => Ok(PathBuf::new())
    }
}
<commit_msg>Get executable name from another place<commit_after>//
// Sysinfo
//
// Copyright (c) 2015 Guillaume Gomez
//

use processus::*;
use process::*;
use std::old_io::fs;
use std::fs::{File, read_link, PathExt};
use std::io::Read;
use std::ffi::AsOsStr;
use std::old_io::fs::PathExtensions;
use std::old_path::posix::Path as PosixPath;
use std::str::FromStr;
use std::os;
use std::path::{Path, PathBuf};
use std::io;
use std::old_path;
use std::old_io;
use std::collections::VecMap;
use std::old_path::GenericPath;

pub struct System {
    processus_list: VecMap<Processus>,
    mem_total: u64,
    mem_free: u64,
    swap_total: u64,
    swap_free: u64,
    processes: Vec<Process>,
}

impl System {
    pub fn new() -> System {
        let mut s = System {
            processus_list: VecMap::new(),
            mem_total: 0,
            mem_free: 0,
            swap_total: 0,
            swap_free: 0,
            processes: Vec::new(),
        };

        s.refresh();
        s
    }

    pub fn refresh(&mut self) {
        match fs::readdir(&PosixPath::new("/proc")) {
            Ok(v) => {
                let mut proc_list : VecMap<Processus> = VecMap::new();

                for entry in v.iter() {
                    if entry.is_dir() {
                        match _get_processus_data(entry, &self.processus_list) {
                            Some(p) => {
                                proc_list.insert(p.pid as usize, p);
                            }
                            None => {}
                        };
                    } else {
                        match entry.as_os_str().to_str().unwrap() {
                            "/proc/meminfo" => {
                                let mut data = get_all_data(entry.as_str().unwrap());
                                let lines : Vec<&str> = data.split('\n').collect();
                                for line in lines.iter() {
                                    match *line {
                                        l if l.starts_with("MemTotal:") => {
                                            let parts : Vec<&str> = line.split(' ').collect();

                                            self.mem_total = u64::from_str(parts[parts.len() - 2]).unwrap();
                                        },
                                        l if l.starts_with("MemFree:") => {
                                            let parts : Vec<&str> = line.split(' ').collect();

                                            self.mem_free = u64::from_str(parts[parts.len() - 2]).unwrap();
                                        },
                                        l if l.starts_with("SwapTotal:") => {
                                            let parts : Vec<&str> = line.split(' ').collect();

                                            self.swap_total = u64::from_str(parts[parts.len() - 2]).unwrap();
                                        },
                                        l if l.starts_with("SwapFree:") => {
                                            let parts : Vec<&str> = line.split(' ').collect();

                                            self.swap_free = u64::from_str(parts[parts.len() - 2]).unwrap();
                                        },
                                        _ => continue,
                                    }
                                }
                            },
                            "/proc/stat" => {
                                let mut data = get_all_data(entry.as_str().unwrap());
                                let lines : Vec<&str> = data.split('\n').collect();
                                let mut i = 0;
                                let first = self.processes.len() == 0;
                                for line in lines.iter() {
                                    if !line.starts_with("cpu") {
                                        break;
                                    }

                                    let (parts, _) : (Vec<&str>, Vec<&str>) = line.split(' ').partition(|s| s.len() > 0);
                                    if first {
                                        self.processes.push(new_process(parts[0], u64::from_str(parts[1]).unwrap(),
                                            u64::from_str(parts[2]).unwrap(),
                                            u64::from_str(parts[3]).unwrap(),
                                            u64::from_str(parts[4]).unwrap()));
                                    } else {
                                        set_process(self.processes.get_mut(i).unwrap(),
                                            u64::from_str(parts[1]).unwrap(),
                                            u64::from_str(parts[2]).unwrap(),
                                            u64::from_str(parts[3]).unwrap(),
                                            u64::from_str(parts[4]).unwrap());
                                        i += 1;
                                    }
                                }
                            }
                           _ => {},
                        }
                    }
                }
                for (pid, proc_) in proc_list.iter_mut() {
                    match self.processus_list.get(&pid) {
                        Some(p) => {
                            let (new, old) = get_raw_times(&self.processes[0]);
                            let (pnew, pold) = get_raw_processus_times(&p);
                            compute_cpu_usage(proc_, pnew, pold, new, old);
                        }
                        None => {}
                    }
                }
                self.processus_list = proc_list;
            },
            Err(e) => {
                panic!("cannot read /proc ! error: {}", e);
            }
        }
    }

    pub fn get_processus_list<'a>(&'a self) -> &'a VecMap<Processus> {
        &self.processus_list
    }

    pub fn get_processus(&self, pid: i64) -> Option<&Processus> {
        self.processus_list.get(&(pid as usize))
    }

    // The first process in the array is the "main" process
    pub fn get_process_list<'a>(&'a self) -> &'a [Process] {
        self.processes.as_slice()
    }

    pub fn get_total_memory(&self) -> u64 {
        self.mem_total
    }

    pub fn get_free_memory(&self) -> u64 {
        self.mem_free
    }

    pub fn get_total_swap(&self) -> u64 {
        self.swap_total
    }

    pub fn get_free_swap(&self) -> u64 {
        self.swap_free
    }
}

fn get_all_data(file_path: &str) -> String {
    let mut file = File::open(file_path).unwrap();
    let mut data = String::new();

    file.read_to_string(&mut data);
    data
}

fn _get_processus_data(path: &PosixPath, proc_list: &VecMap<Processus>) -> Option<Processus> {
    if !path.exists() || !path.is_dir() {
        return None;
    }
    let paths : Vec<&str> = path.as_os_str().to_str().unwrap().split("/").collect();
    let last = paths[paths.len() - 1];
    match i64::from_str(last) {
        Ok(nb) => {
            let mut p = Processus::new(nb);
            let mut tmp = path.clone();

            tmp.push("cmdline");
            p.cmd = String::from_str(copy_from_file(&tmp)[0].as_slice());
            {
                let mut tmp_line : Vec<&str> = p.cmd.split(" ").collect();
                let mut tmp_name : Vec<&str> = tmp_line[0].split("/").collect();

                p.name = String::from_str(tmp_name[tmp_name.len() - 1]);
            }
            tmp = path.clone();
            tmp.push("environ");
            p.environ = copy_from_file(&tmp);
            tmp = path.clone();
            tmp.push("exe");
            let s = read_link(tmp.as_str().unwrap());
            if s.is_ok() {
                p.exe = String::from_str(s.unwrap().as_os_str().to_str().unwrap());
            }
            tmp = path.clone();
            tmp.push("cwd");
            p.cwd = String::from_str(realpath(Path::new(tmp.as_str().unwrap())).unwrap().as_os_str().to_str().unwrap());
            tmp = path.clone();
            tmp.push("root");
            p.root = String::from_str(realpath(Path::new(tmp.as_str().unwrap())).unwrap().as_os_str().to_str().unwrap());
            tmp = path.clone();
            tmp.push("status");
            let mut data = get_all_data(tmp.as_str().unwrap());

            let lines : Vec<&str> = data.split('\n').collect();
            for line in lines.iter() {
                match *line {
                    l if l.starts_with("VmRSS") => {
                        let parts : Vec<&str> = line.split(' ').collect();

                        p.memory = u64::from_str(parts[parts.len() - 2]).unwrap();
                        break;
                    }
                    _ => continue,
                }
            }
            tmp = path.clone();
            tmp.push("stat");
            let mut data2 = get_all_data(tmp.as_str().unwrap());
            // ne marche pas car il faut aussi les anciennes valeurs !!!!
            let (parts, _) : (Vec<&str>, Vec<&str>) = data2.split(' ').partition(|s| s.len() > 0);
            set_time(&mut p, u64::from_str(parts[13]).unwrap(), u64::from_str(parts[14]).unwrap());
            Some(p)
        }
        _ => None
    }
}

fn get_last(path: &PosixPath) -> &str {
    let t = path.as_os_str().to_str().unwrap();
    let v : Vec<&str> = t.split('/').collect();

    if v.len() > 0 {
        v[v.len() - 1]
    } else {
        ""
    }
}

fn copy_from_file(entry: &PosixPath) -> Vec<String> {
    match File::open(entry.as_str().unwrap()) {
        Ok(mut f) => {
            let mut d = String::new();

            f.read_to_string(&mut d);
            let mut v : Vec<&str> = d.split('\0').collect();
            let mut ret = Vec::new();

            for tmp in v.iter() {
                ret.push(String::from_str(tmp));
            }
            ret
        },
        Err(_) => Vec::new()
    }
}

fn old_realpath(original: &PosixPath) -> old_io::IoResult<old_path::Path> {
    const MAX_LINKS_FOLLOWED: usize = 256;
    let original = PosixPath::new(::std::env::current_dir().unwrap().as_os_str().to_str().unwrap()).join(original);
    // Right now lstat on windows doesn't work quite well
    if cfg!(windows) {
        return Ok(original)
    }
    let result = original.root_path();
    let mut result = result.expect("make_absolute has no root_path");
    let mut followed = 0;
    for part in original.components() {
        result.push(part);
        loop {
            if followed == MAX_LINKS_FOLLOWED {
                return Ok(old_path::Path::new(""));
            }
            match fs::lstat(&result) {
                Err(..) => break,
                Ok(ref stat) if stat.kind != old_io::FileType::Symlink => break,
                Ok(..) => {
                    followed += 1;
                    let path = try!(fs::readlink(&result));
                    result.pop();
                    result.push(path);
                }
            }
        }
    }
    return Ok(result);
}

fn realpath(original: &Path) -> io::Result<PathBuf> {
    let old = old_path::Path::new(original.to_str().unwrap());

    match old_realpath(&old) {
        Ok(p) => Ok(PathBuf::from(p.as_str().unwrap())),
        Err(_) => Ok(PathBuf::new())
    }
}
<|endoftext|>


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

use collect_slice::CollectSlice;

use consts::{SAMPLES_PER_FRAME, MAX_HARMONICS};
use descramble::VoiceDecisions;
use enhance::EnhancedSpectrals;
use noise::Noise;
use params::BaseParams;
use prev::PrevFrame;
use window;

pub struct PhaseBase([f32; MAX_HARMONICS]);

impl PhaseBase {
    pub fn new(params: &BaseParams, prev: &PrevFrame) -> PhaseBase {
        let mut phase_base = [0.0; MAX_HARMONICS];
        let common = (prev.params.fundamental + params.fundamental) *
            SAMPLES_PER_FRAME as f32 / 2.0;

        (1..57).map(|l| {
            prev.phase_base.get(l) + common * l as f32
        }).collect_slice_checked(&mut phase_base[..]);

        PhaseBase(phase_base)
    }

    pub fn get(&self, l: usize) -> f32 { self.0[l - 1] }
}

impl Default for PhaseBase {
    fn default() -> PhaseBase {
        PhaseBase([0.0; MAX_HARMONICS])
    }
}

pub struct Phase([f32; MAX_HARMONICS]);

impl Phase {
    pub fn new(params: &BaseParams, voice: &VoiceDecisions, base: &PhaseBase) -> Phase {
        let mut noise = Noise::new();
        let mut phase = [0.0; MAX_HARMONICS];

        let trans = params.harmonics as usize / 4;

        (1...trans).map(|l| {
            base.get(l)
        }).chain((trans+1...MAX_HARMONICS).map(|l| {
            base.get(l) + voice.unvoiced_count as f32 * noise.next_phase() /
                params.harmonics as f32
        })).collect_slice_checked(&mut phase[..]);

        Phase(phase)
    }

    pub fn get(&self, l: usize) -> f32 { self.0[l - 1] }
}

impl Default for Phase {
    fn default() -> Phase {
        Phase([0.0; MAX_HARMONICS])
    }
}

pub struct Voiced<'a, 'b, 'c, 'd> {
    prev: &'a PrevFrame,
    phase: &'b Phase,
    enhanced: &'c EnhancedSpectrals,
    voice: &'d VoiceDecisions,
    window: window::Window,
    fundamental: f32,
    end: usize,
}

impl<'a, 'b, 'c, 'd> Voiced<'a, 'b, 'c, 'd> {
    pub fn new(params: &BaseParams, prev: &'a PrevFrame, phase: &'b Phase,
               enhanced: &'c EnhancedSpectrals, voice: &'d VoiceDecisions)
        -> Voiced<'a, 'b, 'c, 'd>
    {
        Voiced {
            prev: prev,
            phase: phase,
            enhanced: enhanced,
            voice: voice,
            window: window::synthesis(),
            fundamental: params.fundamental,
            end: max(params.harmonics, prev.params.harmonics) as usize + 1,
        }
    }

    fn get_pair(&self, l: usize, n: isize) -> f32 {
        match (self.voice.is_voiced(l), self.prev.voice.is_voiced(l)) {
            (false, false) => 0.0,
            (false, true) => self.sig_prev(l, n),
            (true, false) => self.sig_cur(l, n),
            (true, true) => self.sig_prev(l, n) + self.sig_cur(l, n)
        }
    }

    fn sig_cur(&self, l: usize, n: isize) -> f32 {
        self.window.get(n - SAMPLES_PER_FRAME as isize) * self.enhanced.get(l) * (
            self.fundamental * (n - SAMPLES_PER_FRAME as isize) as f32 * l as f32 +
                self.phase.get(l)
        ).cos()
    }

    fn sig_prev(&self, l: usize, n: isize) -> f32 {
        self.window.get(n) * self.prev.enhanced.get(l) * (
            self.prev.params.fundamental * n as f32 * l as f32 +
                self.prev.phase.get(l)
        ).cos()
    }

    pub fn get(&self, n: usize) -> f32 {
        2.0 * (1..self.end)
            .map(|l| self.get_pair(l, n as isize))
            .fold(0.0, |s, x| s + x)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use params::BaseParams;
    use prev::PrevFrame;
    use descramble::Bootstrap;

    #[test]
    fn test_phase_base() {
        let chunks = [
            0b001000010010,
            0b110011001100,
            0b111000111000,
            0b111111111111,
            0b10101110101,
            0b00101111010,
            0b01110111011,
            0b00001000,
        ];

        let b = Bootstrap::new(&chunks);
        let p = BaseParams::new(b.unwrap_period());
        let prev = PrevFrame::default();

        assert!((p.fundamental - 0.17575344).abs() < 0.000001);
        assert!((prev.params.fundamental - 0.0937765407).abs() < 0.000001);

        let pb = PhaseBase::new(&p, &prev);

        assert!((pb.get(1) - 21.56239846).abs() < 0.0001);
        assert!((pb.get(2) - 43.12479691).abs() < 0.0001);
        assert!((pb.get(3) - 64.68719537).abs() < 0.0001);
        assert!((pb.get(4) - 86.24959382).abs() < 0.0001);
        assert!((pb.get(5) - 107.8119923).abs() < 0.0001);
        assert!((pb.get(6) - 129.3743907).abs() < 0.0001);
        assert!((pb.get(20) - 431.2479691).abs() < 0.0001);
        assert!((pb.get(56) - 1207.494314).abs() < 0.001);
    }
}
<commit_msg>Use inclusive ranges<commit_after>use std::cmp::max;

use collect_slice::CollectSlice;

use consts::{SAMPLES_PER_FRAME, MAX_HARMONICS};
use descramble::VoiceDecisions;
use enhance::EnhancedSpectrals;
use noise::Noise;
use params::BaseParams;
use prev::PrevFrame;
use window;

pub struct PhaseBase([f32; MAX_HARMONICS]);

impl PhaseBase {
    pub fn new(params: &BaseParams, prev: &PrevFrame) -> PhaseBase {
        let mut phase_base = [0.0; MAX_HARMONICS];
        let common = (prev.params.fundamental + params.fundamental) *
            SAMPLES_PER_FRAME as f32 / 2.0;

        (1...MAX_HARMONICS).map(|l| {
            prev.phase_base.get(l) + common * l as f32
        }).collect_slice_checked(&mut phase_base[..]);

        PhaseBase(phase_base)
    }

    pub fn get(&self, l: usize) -> f32 { self.0[l - 1] }
}

impl Default for PhaseBase {
    fn default() -> PhaseBase {
        PhaseBase([0.0; MAX_HARMONICS])
    }
}

pub struct Phase([f32; MAX_HARMONICS]);

impl Phase {
    pub fn new(params: &BaseParams, voice: &VoiceDecisions, base: &PhaseBase) -> Phase {
        let mut noise = Noise::new();
        let mut phase = [0.0; MAX_HARMONICS];

        let trans = params.harmonics as usize / 4;

        (1...trans).map(|l| {
            base.get(l)
        }).chain((trans+1...MAX_HARMONICS).map(|l| {
            base.get(l) + voice.unvoiced_count as f32 * noise.next_phase() /
                params.harmonics as f32
        })).collect_slice_checked(&mut phase[..]);

        Phase(phase)
    }

    pub fn get(&self, l: usize) -> f32 { self.0[l - 1] }
}

impl Default for Phase {
    fn default() -> Phase {
        Phase([0.0; MAX_HARMONICS])
    }
}

pub struct Voiced<'a, 'b, 'c, 'd> {
    prev: &'a PrevFrame,
    phase: &'b Phase,
    enhanced: &'c EnhancedSpectrals,
    voice: &'d VoiceDecisions,
    window: window::Window,
    fundamental: f32,
    end: usize,
}

impl<'a, 'b, 'c, 'd> Voiced<'a, 'b, 'c, 'd> {
    pub fn new(params: &BaseParams, prev: &'a PrevFrame, phase: &'b Phase,
               enhanced: &'c EnhancedSpectrals, voice: &'d VoiceDecisions)
        -> Voiced<'a, 'b, 'c, 'd>
    {
        Voiced {
            prev: prev,
            phase: phase,
            enhanced: enhanced,
            voice: voice,
            window: window::synthesis(),
            fundamental: params.fundamental,
            end: max(params.harmonics, prev.params.harmonics) as usize,
        }
    }

    fn get_pair(&self, l: usize, n: isize) -> f32 {
        match (self.voice.is_voiced(l), self.prev.voice.is_voiced(l)) {
            (false, false) => 0.0,
            (false, true) => self.sig_prev(l, n),
            (true, false) => self.sig_cur(l, n),
            (true, true) => self.sig_prev(l, n) + self.sig_cur(l, n)
        }
    }

    fn sig_cur(&self, l: usize, n: isize) -> f32 {
        self.window.get(n - SAMPLES_PER_FRAME as isize) * self.enhanced.get(l) * (
            self.fundamental * (n - SAMPLES_PER_FRAME as isize) as f32 * l as f32 +
                self.phase.get(l)
        ).cos()
    }

    fn sig_prev(&self, l: usize, n: isize) -> f32 {
        self.window.get(n) * self.prev.enhanced.get(l) * (
            self.prev.params.fundamental * n as f32 * l as f32 +
                self.prev.phase.get(l)
        ).cos()
    }

    pub fn get(&self, n: usize) -> f32 {
        2.0 * (1...self.end)
            .map(|l| self.get_pair(l, n as isize))
            .fold(0.0, |s, x| s + x)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use params::BaseParams;
    use prev::PrevFrame;
    use descramble::Bootstrap;

    #[test]
    fn test_phase_base() {
        let chunks = [
            0b001000010010,
            0b110011001100,
            0b111000111000,
            0b111111111111,
            0b10101110101,
            0b00101111010,
            0b01110111011,
            0b00001000,
        ];

        let b = Bootstrap::new(&chunks);
        let p = BaseParams::new(b.unwrap_period());
        let prev = PrevFrame::default();

        assert!((p.fundamental - 0.17575344).abs() < 0.000001);
        assert!((prev.params.fundamental - 0.0937765407).abs() < 0.000001);

        let pb = PhaseBase::new(&p, &prev);

        assert!((pb.get(1) - 21.56239846).abs() < 0.0001);
        assert!((pb.get(2) - 43.12479691).abs() < 0.0001);
        assert!((pb.get(3) - 64.68719537).abs() < 0.0001);
        assert!((pb.get(4) - 86.24959382).abs() < 0.0001);
        assert!((pb.get(5) - 107.8119923).abs() < 0.0001);
        assert!((pb.get(6) - 129.3743907).abs() < 0.0001);
        assert!((pb.get(20) - 431.2479691).abs() < 0.0001);
        assert!((pb.get(56) - 1207.494314).abs() < 0.001);
    }
}
<|endoftext|>


<commit_before>// CITA
// Copyright 2016-2017 Cryptape Technologies LLC.

// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.

// This program 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 General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! Account Permission manager.

use super::parse_string_to_addresses;
use libchain::call_request::CallRequest;
use libchain::chain::Chain;
use rustc_hex::FromHex;
use sha3::sha3_256;
use std::collections::HashSet;
use std::str::FromStr;
use types::ids::BlockId;
use util::*;

const METHOD_NAME: &'static [u8] = &*b"queryUsersOfPermission(uint8)";

lazy_static! {
    static ref METHOD_NAME_HASH: Vec<u8> = {
        let out :&mut[u8;32] = &mut [0;32];
        let outptr = out.as_mut_ptr();
        unsafe {
            sha3_256(outptr, 32, METHOD_NAME.as_ptr(), METHOD_NAME.len());
        }
        out[0..4].to_vec()
    };
    static ref QUERY_TX: Vec<u8> = "00000000000000000000000000000000000000000\
                                    00000000000000000000001".from_hex().unwrap().into();
    static ref QUERY_CONTRACT: Vec<u8> = "00000000000000000000000000000000000\
                                          00000000000000000000000000002".from_hex().unwrap().into();
    static ref CONTRACT_ADDRESS: H160 = H160::from_str(
        "00000000000000000000000000000000013241a4"
    ).unwrap();
}

pub struct AccountManager;

impl AccountManager {
    pub fn load_senders(chain: &Chain) -> HashSet<Address> {
        let mut senders = HashSet::new();
        let mut tx_data = METHOD_NAME_HASH.to_vec().clone();
        tx_data.extend(QUERY_TX.to_vec());
        let call_request = CallRequest {
            from: None,
            to: *CONTRACT_ADDRESS,
            data: Some(tx_data),
        };

        trace!("data: {:?}", call_request.data);
        let output = chain
            .eth_call(call_request, BlockId::Latest)
            .expect("load senders eth call");
        trace!("read account which has tx permission output: {:?}", output);
        let accounts: Vec<Address> = parse_string_to_addresses(&output);
        trace!("accounts: {:?}", accounts);
        for account in accounts {
            senders.insert(account);
        }
        senders
    }

    pub fn load_creators(chain: &Chain) -> HashSet<Address> {
        let mut creators = HashSet::new();
        let mut contract_data = METHOD_NAME_HASH.to_vec().clone();
        contract_data.extend(QUERY_CONTRACT.to_vec());
        let call_request = CallRequest {
            from: None,
            to: *CONTRACT_ADDRESS,
            data: Some(contract_data),
        };

        trace!("data: {:?}", call_request.data);
        let output = chain
            .eth_call(call_request, BlockId::Latest)
            .expect("load creators eth call");
        trace!(
            "read account which has contract permission output: {:?}",
            output
        );
        let accounts: Vec<Address> = parse_string_to_addresses(&output);
        trace!("accounts: {:?}", accounts);
        for account in accounts {
            creators.insert(account);
        }
        creators
    }
}
<commit_msg>there must be at least one creator in account manager<commit_after>// CITA
// Copyright 2016-2017 Cryptape Technologies LLC.

// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.

// This program 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 General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! Account Permission manager.

use super::parse_string_to_addresses;
use libchain::call_request::CallRequest;
use libchain::chain::Chain;
use rustc_hex::FromHex;
use sha3::sha3_256;
use std::collections::HashSet;
use std::str::FromStr;
use types::ids::BlockId;
use util::*;

const METHOD_NAME: &'static [u8] = &*b"queryUsersOfPermission(uint8)";

lazy_static! {
    static ref METHOD_NAME_HASH: Vec<u8> = {
        let out :&mut[u8;32] = &mut [0;32];
        let outptr = out.as_mut_ptr();
        unsafe {
            sha3_256(outptr, 32, METHOD_NAME.as_ptr(), METHOD_NAME.len());
        }
        out[0..4].to_vec()
    };
    static ref QUERY_TX: Vec<u8> = "00000000000000000000000000000000000000000\
                                    00000000000000000000001".from_hex().unwrap().into();
    static ref QUERY_CONTRACT: Vec<u8> = "00000000000000000000000000000000000\
                                          00000000000000000000000000002".from_hex().unwrap().into();
    static ref CONTRACT_ADDRESS: H160 = H160::from_str(
        "00000000000000000000000000000000013241a4"
    ).unwrap();
}

pub struct AccountManager;

impl AccountManager {
    pub fn load_senders(chain: &Chain) -> HashSet<Address> {
        let mut senders = HashSet::new();
        let mut tx_data = METHOD_NAME_HASH.to_vec().clone();
        tx_data.extend(QUERY_TX.to_vec());
        let call_request = CallRequest {
            from: None,
            to: *CONTRACT_ADDRESS,
            data: Some(tx_data),
        };

        trace!("data: {:?}", call_request.data);
        let output = chain
            .eth_call(call_request, BlockId::Latest)
            .expect("load senders eth call");
        trace!("read account which has tx permission output: {:?}", output);
        let accounts: Vec<Address> = parse_string_to_addresses(&output);
        trace!("accounts: {:?}", accounts);
        for account in accounts {
            senders.insert(account);
        }
        senders
    }

    pub fn load_creators(chain: &Chain) -> HashSet<Address> {
        let mut creators = HashSet::new();
        let mut contract_data = METHOD_NAME_HASH.to_vec().clone();
        contract_data.extend(QUERY_CONTRACT.to_vec());
        let call_request = CallRequest {
            from: None,
            to: *CONTRACT_ADDRESS,
            data: Some(contract_data),
        };

        trace!("data: {:?}", call_request.data);
        let output = chain
            .eth_call(call_request, BlockId::Latest)
            .expect("load creators eth call");
        trace!(
            "read account which has contract permission output: {:?}",
            output
        );
        let accounts: Vec<Address> = parse_string_to_addresses(&output);
        trace!("accounts: {:?}", accounts);
        for account in accounts {
            creators.insert(account);
        }
        assert!(!creators.is_empty(), "there must be at least one creator");
        creators
    }
}
<|endoftext|>


<commit_before>#![recursion_limit = "256"]
// http://stackoverflow.com/questions/25877285/how-to-disable-unused-code-warnings-in-rust
// https://users.rust-lang.org/t/turning-off-compiler-warning-messages/4975/2
#![allow(non_snake_case)]

mod api;
mod files;

use serde_derive::Serialize;

use dotenv::dotenv;
use std::env;

use actix_web::{guard, middleware, web, App, Error as ActixError, HttpResponse, HttpServer};

use typed_html::elements::FlowContent;
use typed_html::types::Metadata;
use typed_html::{dom::DOMTree, html, text, OutputType};

use tinytemplate::TinyTemplate;

use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod};
use tokio_postgres::NoTls;

static TEMPLATE: &str = "Hello {name}!";

#[derive(Serialize)]
struct Context {
    name: String,
}

#[derive(Serialize, Debug)]
struct TemplateContext {
    parent: String,
    name: String,
    content: String,
    items: Vec<String>,
}

use std::path;
use std::process::Command;

async fn template(ssr: web::Path<bool>) -> Result<HttpResponse, ActixError> {
    let s2 = getStr();
    let s: String = if *ssr { s2.to_owned() } else { "".to_owned() };
    let context = TemplateContext {
        parent: "index".to_owned(),
        name: "Roman".to_owned(),
        content: s,
        items: vec!["One", "Two", "Three"]
            .iter()
            .map(|s| s.to_string())
            .collect(),
    };

    let doc: DOMTree<String> = doc(
        html!(

"Hello Kitty"

                            "She is not a cat. She is a human girl."

                        { (0..3).map(|_| html!(

                                "Her name is Kitty White."

                        )) }

                            "We still don't know how she eats."

"Hello Kitty"

                        "DYNAMIC_CONTENT"

                ),
        context,
    );
    let mut doc_str = "<!doctype html>".to_owned() + &doc.to_string();

    // https://users.rust-lang.org/t/how-to-create-a-macro-from-dynamic-content/5079
    doc_str = doc_str.replacen("DYNAMIC_CONTENT", &s2, 1);

    Ok(HttpResponse::Ok().content_type("text/html").body(doc_str))
}

fn doc<T: OutputType + 'static + Send>(
    tree: Box<dyn FlowContent<T>>,
    context: TemplateContext,
) -> DOMTree<T> {
    let TemplateContext { name, items, .. } = context;
    html!(

                <title>"Hello Kitty"</title>
                <meta charset="utf-8" />
                <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                <link rel="icon" href="/favicon.ico?v=1" />
                <link href="/styles/normalize.css" rel="stylesheet" type="text/css" media="all" />
                <link href="/styles/style.css" rel="stylesheet" type="text/css" media="all" />
                <base href="/"></base>
                <meta name=Metadata::Author content="Not Sanrio Co., Ltd" />

{text!("{}", name)}

"Here are your items:"

                    {
                     items.iter().map(|item| html!(

{text!("{}", item)}

                     ))
                    }

                 { tree }

"Try going to ""/hello/YourName"

    )
}

use std::fs;
use std::fs::OpenOptions;
use std::io::prelude::*;

fn getStr() -> String {
    fs::copy(
        "../client/src/elm/Main.elm",
        "../client/src/elm/Main.elm.bak",
    )
    .expect("file not copied");
    let stdout: Vec<u8>;
    {
        let mut main_file = OpenOptions::new()
            .append(true)
            .open("../client/src/elm/Main.elm")
            .expect("file not opened");

        let str1 = format!(
            r#"
            view : Html Msg
            view =
                viewWithModel <|
                    Model [] HomeRoute <|
                        Flags "" {time} ""
            "#,
            time = time::OffsetDateTime::unix_epoch().second()
        );

        main_file
            .write_all(str1.as_bytes())
            .expect("file content not saved");

        stdout = Command::new("node")
            .current_dir(&path::Path::new("../client"))
            .arg("./node_modules/elm-static-html/index.js")
            .arg("-f")
            .arg("src/elm/Main.elm")
            .output()
            .expect("elm-static-html command failed to start")
            .stdout;
    }
    fs::rename(
        "../client/src/elm/Main.elm.bak",
        "../client/src/elm/Main.elm",
    )
    .expect("file not renamed");

    String::from_utf8_lossy(&*stdout)
        .lines()
        .skip_while(|x| x.find(r#"id="content""#).is_none())
        .collect()
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    env::set_var("RUST_LOG", "actix_web=info");
    env_logger::init();
    let endpoint = format!("127.0.0.1:{}", env::var("SERVER_PORT")?);

    let connection_string = format!(
        "postgres://{}:{}@{}:{}/{}",
        &env::var("DBUSER")?,
        &env::var("DBPASS")?,
        &env::var("DBHOST")?,
        &env::var("DBPORT")?,
        &env::var("DBNAME")?,
    );
    let pg_config: tokio_postgres::Config = connection_string.parse()?;
    let mgr_config = ManagerConfig {
        recycling_method: RecyclingMethod::Fast,
    };
    let mgr = Manager::from_config(pg_config, NoTls, mgr_config);
    let pool = Pool::new(mgr, 16);

    let mut tt = TinyTemplate::new();
    tt.add_template("hello", TEMPLATE)?;

    let context = Context {
        name: "TinyTemplate".to_string(),
    };

    let rendered = tt.render("hello", &context)?;
    println!("{}", rendered);

    let sys = actix_rt::System::new("app");
    HttpServer::new(move || {
        App::new()
            .data(pool.clone())
            .wrap(middleware::Logger::default())
            .service(web::resource("/template/{ssr}").route(web::get().to(template)))
            .service(web::resource("/userInformation").route(web::get().to(api::user_information)))
            .service(web::resource("/dataSets").route(web::get().to(api::data_sets)))
            .service(web::resource("/dataSets/{url}").route(web::get().to(api::data_set)))
            .service(
                web::resource("/dataSetsCategories")
                    .route(web::get().to(api::data_sets_categories)),
            )
            .service(
                web::resource("/dataSetsCategories/{url}")
                    .route(web::get().to(api::data_set_category)),
            )
            .service(web::resource("/favicon").route(web::get().to(files::favicon)))
            .service(web::resource("/styles/{file:.*}").route(web::get().to(files::styles)))
            .service(web::resource("/js/{file:.*}").route(web::get().to(files::js)))
            .default_service(
                // 404 for GET request
                web::resource("")
                    .route(web::get().to(files::index))
                    // all requests that are not `GET`
                    .route(
                        web::route()
                            .guard(guard::Not(guard::Get()))
                            .to(HttpResponse::MethodNotAllowed),
                    ),
            )
    })
    .bind(&endpoint)?
    .run();
    // If you do not return `Ok(())` but just `.run()`, this will happend:
    // When main returns `Result<(), Box<dyn std::error::Error + 'static + Send + Sync>> instead of
    // `io::Result<()>`, there is error and `into()` is needed.
    // expected struct `std::boxed::Box`, found struct `std::io::Error`
    // https://users.rust-lang.org/t/boxing-errors-in-result-throws-type-mismatch/36692/2
    //.map_err(|e| e.into())

    println!("Server running at {:?}", endpoint);
    let _ = sys.run();

    Ok(())
}
<commit_msg>server: comment about parse<commit_after>#![recursion_limit = "256"]
// http://stackoverflow.com/questions/25877285/how-to-disable-unused-code-warnings-in-rust
// https://users.rust-lang.org/t/turning-off-compiler-warning-messages/4975/2
#![allow(non_snake_case)]

mod api;
mod files;

use serde_derive::Serialize;

use dotenv::dotenv;
use std::env;

use actix_web::{guard, middleware, web, App, Error as ActixError, HttpResponse, HttpServer};

use typed_html::elements::FlowContent;
use typed_html::types::Metadata;
use typed_html::{dom::DOMTree, html, text, OutputType};

use tinytemplate::TinyTemplate;

use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod};
use tokio_postgres::NoTls;

static TEMPLATE: &str = "Hello {name}!";
#[derive(Serialize)]
struct Context {
    name: String,
}

#[derive(Serialize, Debug)]
struct TemplateContext {
    parent: String,
    name: String,
    content: String,
    items: Vec<String>,
}

use std::path;
use std::process::Command;

async fn template(ssr: web::Path<bool>) -> Result<HttpResponse, ActixError> {
    let s2 = getStr();
    let s: String = if *ssr { s2.to_owned() } else { "".to_owned() };
    let context = TemplateContext {
        parent: "index".to_owned(),
        name: "Roman".to_owned(),
        content: s,
        items: vec!["One", "Two", "Three"]
            .iter()
            .map(|s| s.to_string())
            .collect(),
    };

    let doc: DOMTree<String> = doc(
        html!(

"Hello Kitty"

                            "She is not a cat. She is a human girl."

                        { (0..3).map(|_| html!(

                                "Her name is Kitty White."

                        )) }

                            "We still don't know how she eats."

"Hello Kitty"

                        "DYNAMIC_CONTENT"

                ),
        context,
    );
    let mut doc_str = "<!doctype html>".to_owned() + &doc.to_string();

    // https://users.rust-lang.org/t/how-to-create-a-macro-from-dynamic-content/5079
    doc_str = doc_str.replacen("DYNAMIC_CONTENT", &s2, 1);

    Ok(HttpResponse::Ok().content_type("text/html").body(doc_str))
}

fn doc<T: OutputType + 'static + Send>(
    tree: Box<dyn FlowContent<T>>,
    context: TemplateContext,
) -> DOMTree<T> {
    let TemplateContext { name, items, .. } = context;
    html!(

                <title>"Hello Kitty"</title>
                <meta charset="utf-8" />
                <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                <link rel="icon" href="/favicon.ico?v=1" />
                <link href="/styles/normalize.css" rel="stylesheet" type="text/css" media="all" />
                <link href="/styles/style.css" rel="stylesheet" type="text/css" media="all" />
                <base href="/"></base>
                <meta name=Metadata::Author content="Not Sanrio Co., Ltd" />

{text!("{}", name)}

"Here are your items:"

                    {
                     items.iter().map(|item| html!(

{text!("{}", item)}

                     ))
                    }

                 { tree }

"Try going to ""/hello/YourName"

    )
}

use std::fs;
use std::fs::OpenOptions;
use std::io::prelude::*;

fn getStr() -> String {
    fs::copy(
        "../client/src/elm/Main.elm",
        "../client/src/elm/Main.elm.bak",
    )
    .expect("file not copied");
    let stdout: Vec<u8>;
    {
        let mut main_file = OpenOptions::new()
            .append(true)
            .open("../client/src/elm/Main.elm")
            .expect("file not opened");

        let str1 = format!(
            r#"
            view : Html Msg
            view =
                viewWithModel <|
                    Model [] HomeRoute <|
                        Flags "" {time} ""
            "#,
            time = time::OffsetDateTime::unix_epoch().second()
        );

        main_file
            .write_all(str1.as_bytes())
            .expect("file content not saved");

        stdout = Command::new("node")
            .current_dir(&path::Path::new("../client"))
            .arg("./node_modules/elm-static-html/index.js")
            .arg("-f")
            .arg("src/elm/Main.elm")
            .output()
            .expect("elm-static-html command failed to start")
            .stdout;
    }
    fs::rename(
        "../client/src/elm/Main.elm.bak",
        "../client/src/elm/Main.elm",
    )
    .expect("file not renamed");

    String::from_utf8_lossy(&*stdout)
        .lines()
        .skip_while(|x| x.find(r#"id="content""#).is_none())
        .collect()
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    env::set_var("RUST_LOG", "actix_web=info");
    env_logger::init();
    let endpoint = format!("127.0.0.1:{}", env::var("SERVER_PORT")?);

    let connection_string = format!(
        "postgres://{}:{}@{}:{}/{}",
        &env::var("DBUSER")?,
        &env::var("DBPASS")?,
        &env::var("DBHOST")?,
        &env::var("DBPORT")?,
        &env::var("DBNAME")?,
    );
    // Idea for parse from
    // https://github.com/OneSignal/L3-37/blob/2031639d1f3a7aa00a5a741b87b464e19d995d21/l337-postgres/src/lib.rs#L217
    let pg_config: tokio_postgres::Config = connection_string.parse()?;
    let mgr_config = ManagerConfig {
        recycling_method: RecyclingMethod::Fast,
    };
    let mgr = Manager::from_config(pg_config, NoTls, mgr_config);
    let pool = Pool::new(mgr, 16);

    let mut tt = TinyTemplate::new();
    tt.add_template("hello", TEMPLATE)?;

    let context = Context {
        name: "TinyTemplate".to_string(),
    };

    let rendered = tt.render("hello", &context)?;
    println!("{}", rendered);

    let sys = actix_rt::System::new("app");
    HttpServer::new(move || {
        App::new()
            .data(pool.clone())
            .wrap(middleware::Logger::default())
            .service(web::resource("/template/{ssr}").route(web::get().to(template)))
            .service(web::resource("/userInformation").route(web::get().to(api::user_information)))
            .service(web::resource("/dataSets").route(web::get().to(api::data_sets)))
            .service(web::resource("/dataSets/{url}").route(web::get().to(api::data_set)))
            .service(
                web::resource("/dataSetsCategories")
                    .route(web::get().to(api::data_sets_categories)),
            )
            .service(
                web::resource("/dataSetsCategories/{url}")
                    .route(web::get().to(api::data_set_category)),
            )
            .service(web::resource("/favicon").route(web::get().to(files::favicon)))
            .service(web::resource("/styles/{file:.*}").route(web::get().to(files::styles)))
            .service(web::resource("/js/{file:.*}").route(web::get().to(files::js)))
            .default_service(
                // 404 for GET request
                web::resource("")
                    .route(web::get().to(files::index))
                    // all requests that are not `GET`
                    .route(
                        web::route()
                            .guard(guard::Not(guard::Get()))
                            .to(HttpResponse::MethodNotAllowed),
                    ),
            )
    })
    .bind(&endpoint)?
    .run();
    // If you do not return `Ok(())` but just `.run()`, this will happend:
    // When main returns `Result<(), Box<dyn std::error::Error + 'static + Send + Sync>> instead of
    // `io::Result<()>`, there is error and `into()` is needed.
    // expected struct `std::boxed::Box`, found struct `std::io::Error`
    // https://users.rust-lang.org/t/boxing-errors-in-result-throws-type-mismatch/36692/2
    //.map_err(|e| e.into())

    println!("Server running at {:?}", endpoint);
    let _ = sys.run();

    Ok(())
}
<|endoftext|>


<commit_before>// CITA
// Copyright 2016-2018 Cryptape Technologies LLC.

// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.

// This program 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 General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use basic_types::LogBloom;
use cita_merklehash;
use cita_types::{Address, H256, U256};
use engines::Engine;
use error::Error;
use evm::env_info::{EnvInfo, LastHashes};
use factory::Factories;
use hashable::Hashable;
use libexecutor::auto_exec::auto_exec;
use libexecutor::sys_config::BlockSysConfig;
use libproto::executor::{ExecutedInfo, ReceiptWithOption};
use receipt::Receipt;
use rlp::*;
use state::State;
use state_db::StateDB;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use trace::FlatTrace;
pub use types::block::{Block, BlockBody, OpenBlock};
use types::transaction::SignedTransaction;

lazy_static! {
    /// Block Reward
    /// HardFork if need to change block reward
    pub static ref BLOCK_REWARD: U256 = U256::from(5_000_000_000_000_000_000 as i64);
}

/// Trait for a object that has a state database.
pub trait Drain {
    /// Drop this object and return the underlieing database.
    fn drain(self) -> StateDB;
}

#[derive(Debug)]
pub struct ExecutedBlock {
    pub block: OpenBlock,
    pub receipts: Vec<Receipt>,
    pub state: State<StateDB>,
    pub current_quota_used: U256,
    traces: Option<Vec<Vec<FlatTrace>>>,
    last_hashes: Arc<LastHashes>,
    account_gas_limit: U256,
    account_gas: HashMap<Address, U256>,
    eth_compatibility: bool,
}

impl Deref for ExecutedBlock {
    type Target = OpenBlock;

    fn deref(&self) -> &OpenBlock {
        &self.block
    }
}

impl DerefMut for ExecutedBlock {
    fn deref_mut(&mut self) -> &mut OpenBlock {
        &mut self.block
    }
}

impl ExecutedBlock {
    #[allow(clippy::too_many_arguments)]
    pub fn create(
        factories: Factories,
        conf: &BlockSysConfig,
        tracing: bool,
        block: OpenBlock,
        db: StateDB,
        state_root: H256,
        last_hashes: Arc<LastHashes>,
        eth_compatibility: bool,
    ) -> Result<Self, Error> {
        let mut state = State::from_existing(db, state_root, U256::default(), factories)?;
        state.super_admin_account = conf.super_admin_account;

        let r = ExecutedBlock {
            block,
            state,
            traces: if tracing { Some(Vec::new()) } else { None },
            last_hashes,
            account_gas_limit: conf.account_quota_limit.common_quota_limit.into(),
            account_gas: conf.account_quota_limit.specific_quota_limit.iter().fold(
                HashMap::new(),
                |mut acc, (key, value)| {
                    acc.insert(*key, (*value).into());
                    acc
                },
            ),
            current_quota_used: Default::default(),
            receipts: Default::default(),
            eth_compatibility,
        };

        Ok(r)
    }

    pub fn transactions(&self) -> &[SignedTransaction] {
        self.body.transactions()
    }

    /// Transaction execution env info.
    pub fn env_info(&self) -> EnvInfo {
        EnvInfo {
            number: self.number(),
            author: *self.proposer(),
            timestamp: if self.eth_compatibility {
                self.timestamp() / 1000
            } else {
                self.timestamp()
            },
            difficulty: U256::default(),
            last_hashes: Arc::clone(&self.last_hashes),
            gas_used: self.current_quota_used,
            gas_limit: *self.quota_limit(),
            account_gas_limit: 0.into(),
        }
    }

    #[allow(unknown_lints, clippy::too_many_arguments)] // TODO clippy
    pub fn apply_transaction(
        &mut self,
        engine: &Engine,
        t: &SignedTransaction,
        conf: &BlockSysConfig,
    ) {
        let mut env_info = self.env_info();
        self.account_gas
            .entry(*t.sender())
            .or_insert(self.account_gas_limit);
        env_info.account_gas_limit = *self
            .account_gas
            .get(t.sender())
            .expect("account should exist in account_gas_limit");

        let has_traces = self.traces.is_some();
        match self.state.apply(&env_info, engine, t, has_traces, conf) {
            Ok(outcome) => {
                trace!("apply signed transaction {} success", t.hash());
                if let Some(ref mut traces) = self.traces {
                    traces.push(outcome.trace);
                }
                let transaction_quota_used = outcome.receipt.quota_used - self.current_quota_used;
                self.current_quota_used = outcome.receipt.quota_used;
                if conf.check_options.quota {
                    if let Some(value) = self.account_gas.get_mut(t.sender()) {
                        *value = *value - transaction_quota_used;
                    }
                }
                self.receipts.push(outcome.receipt);
            }
            _ => panic!("apply_transaction: There must be something wrong!"),
        }
    }

    /// Turn this into a `ClosedBlock`.
    pub fn close(mut self, conf: &BlockSysConfig) -> ClosedBlock {
        let env_info = self.env_info();
        if conf.auto_exec {
            auto_exec(
                &mut self.state,
                conf.auto_exec_quota_limit,
                conf.economical_model,
                env_info,
                conf.chain_version,
            );
            self.state.commit().expect("commit trie error");
        }
        // Rebuild block
        let mut block = Block::new(self.block);
        let state_root = *self.state.root();
        block.set_state_root(state_root);
        let receipts_root = cita_merklehash::Tree::from_hashes(
            self.receipts
                .iter()
                .map(|r| r.rlp_bytes().to_vec().crypt_hash())
                .collect::<Vec<_>>(),
            cita_merklehash::merge,
        )
        .get_root_hash()
        .cloned()
        .unwrap_or(cita_merklehash::HASH_NULL);

        block.set_receipts_root(receipts_root);
        block.set_quota_used(self.current_quota_used);

        // blocks blooms
        let log_bloom = self
            .receipts
            .clone()
            .into_iter()
            .fold(LogBloom::zero(), |mut b, r| {
                b = b | r.log_bloom;
                b
            });

        block.set_log_bloom(log_bloom);
        block.rehash();

        ClosedBlock {
            block,
            receipts: self.receipts,
            state: self.state,
        }
    }
}

// Block that prepared to commit to db.
#[derive(Debug)]
pub struct ClosedBlock {
    /// Protobuf Block
    pub block: Block,
    pub receipts: Vec<Receipt>,
    pub state: State<StateDB>,
}

impl Drain for ClosedBlock {
    /// Drop this object and return the underlieing database.
    fn drain(self) -> StateDB {
        self.state.drop().1
    }
}

impl ClosedBlock {
    pub fn protobuf(&self) -> ExecutedInfo {
        let mut executed_info = ExecutedInfo::new();

        executed_info
            .mut_header()
            .set_prevhash(self.parent_hash().to_vec());
        executed_info.mut_header().set_timestamp(self.timestamp());
        executed_info.mut_header().set_height(self.number());
        executed_info
            .mut_header()
            .set_state_root(self.state_root().to_vec());
        executed_info
            .mut_header()
            .set_transactions_root(self.transactions_root().to_vec());
        executed_info
            .mut_header()
            .set_receipts_root(self.receipts_root().to_vec());
        executed_info
            .mut_header()
            .set_log_bloom(self.log_bloom().to_vec());
        executed_info
            .mut_header()
            .set_quota_used(u64::from(*self.quota_used()));
        executed_info
            .mut_header()
            .set_quota_limit(self.quota_limit().low_u64());

        executed_info.receipts = self
            .receipts
            .clone()
            .into_iter()
            .map(|receipt| {
                let mut receipt_proto_option = ReceiptWithOption::new();
                receipt_proto_option.set_receipt(receipt.protobuf());
                receipt_proto_option
            })
            .collect();
        executed_info
            .mut_header()
            .set_proposer(self.proposer().to_vec());
        executed_info
    }
}

impl Deref for ClosedBlock {
    type Target = Block;

    fn deref(&self) -> &Block {
        &self.block
    }
}

impl DerefMut for ClosedBlock {
    fn deref_mut(&mut self) -> &mut Block {
        &mut self.block
    }
}

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

    #[test]
    fn test_encode_and_decode() {
        let mut stx = SignedTransaction::default();
        stx.data = vec![1; 200];
        let transactions = vec![stx; 200];
        let body = BlockBody { transactions };
        let body_rlp = rlp::encode(&body);
        let body: BlockBody = rlp::decode(&body_rlp);
        let body_encoded = rlp::encode(&body).into_vec();

        assert_eq!(body_rlp, body_encoded);
    }
}
<commit_msg>feat(auto_exec): upgrade auto_exec<commit_after>// CITA
// Copyright 2016-2018 Cryptape Technologies LLC.

// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.

// This program 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 General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use basic_types::LogBloom;
use cita_merklehash;
use cita_types::{Address, H256, U256};
use engines::Engine;
use error::Error;
use evm::env_info::{EnvInfo, LastHashes};
use factory::Factories;
use hashable::Hashable;
use libexecutor::auto_exec::auto_exec;
use libexecutor::sys_config::BlockSysConfig;
use libproto::executor::{ExecutedInfo, ReceiptWithOption};
use receipt::Receipt;
use rlp::*;
use state::State;
use state_db::StateDB;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use trace::FlatTrace;
pub use types::block::{Block, BlockBody, OpenBlock};
use types::transaction::SignedTransaction;

lazy_static! {
    /// Block Reward
    /// HardFork if need to change block reward
    pub static ref BLOCK_REWARD: U256 = U256::from(5_000_000_000_000_000_000 as i64);
}

/// Trait for a object that has a state database.
pub trait Drain {
    /// Drop this object and return the underlieing database.
    fn drain(self) -> StateDB;
}

#[derive(Debug)]
pub struct ExecutedBlock {
    pub block: OpenBlock,
    pub receipts: Vec<Receipt>,
    pub state: State<StateDB>,
    pub current_quota_used: U256,
    traces: Option<Vec<Vec<FlatTrace>>>,
    last_hashes: Arc<LastHashes>,
    account_gas_limit: U256,
    account_gas: HashMap<Address, U256>,
    eth_compatibility: bool,
}

impl Deref for ExecutedBlock {
    type Target = OpenBlock;

    fn deref(&self) -> &OpenBlock {
        &self.block
    }
}

impl DerefMut for ExecutedBlock {
    fn deref_mut(&mut self) -> &mut OpenBlock {
        &mut self.block
    }
}

impl ExecutedBlock {
    #[allow(clippy::too_many_arguments)]
    pub fn create(
        factories: Factories,
        conf: &BlockSysConfig,
        tracing: bool,
        block: OpenBlock,
        db: StateDB,
        state_root: H256,
        last_hashes: Arc<LastHashes>,
        eth_compatibility: bool,
    ) -> Result<Self, Error> {
        let mut state = State::from_existing(db, state_root, U256::default(), factories)?;
        state.super_admin_account = conf.super_admin_account;

        let r = ExecutedBlock {
            block,
            state,
            traces: if tracing { Some(Vec::new()) } else { None },
            last_hashes,
            account_gas_limit: conf.account_quota_limit.common_quota_limit.into(),
            account_gas: conf.account_quota_limit.specific_quota_limit.iter().fold(
                HashMap::new(),
                |mut acc, (key, value)| {
                    acc.insert(*key, (*value).into());
                    acc
                },
            ),
            current_quota_used: Default::default(),
            receipts: Default::default(),
            eth_compatibility,
        };

        Ok(r)
    }

    pub fn transactions(&self) -> &[SignedTransaction] {
        self.body.transactions()
    }

    /// Transaction execution env info.
    pub fn env_info(&self) -> EnvInfo {
        EnvInfo {
            number: self.number(),
            author: *self.proposer(),
            timestamp: if self.eth_compatibility {
                self.timestamp() / 1000
            } else {
                self.timestamp()
            },
            difficulty: U256::default(),
            last_hashes: Arc::clone(&self.last_hashes),
            gas_used: self.current_quota_used,
            gas_limit: *self.quota_limit(),
            account_gas_limit: 0.into(),
        }
    }

    #[allow(unknown_lints, clippy::too_many_arguments)] // TODO clippy
    pub fn apply_transaction(
        &mut self,
        engine: &Engine,
        t: &SignedTransaction,
        conf: &BlockSysConfig,
    ) {
        let mut env_info = self.env_info();
        self.account_gas
            .entry(*t.sender())
            .or_insert(self.account_gas_limit);
        env_info.account_gas_limit = *self
            .account_gas
            .get(t.sender())
            .expect("account should exist in account_gas_limit");

        let has_traces = self.traces.is_some();
        match self.state.apply(&env_info, engine, t, has_traces, conf) {
            Ok(outcome) => {
                trace!("apply signed transaction {} success", t.hash());
                if let Some(ref mut traces) = self.traces {
                    traces.push(outcome.trace);
                }
                let transaction_quota_used = outcome.receipt.quota_used - self.current_quota_used;
                self.current_quota_used = outcome.receipt.quota_used;
                if conf.check_options.quota {
                    if let Some(value) = self.account_gas.get_mut(t.sender()) {
                        *value = *value - transaction_quota_used;
                    }
                }
                self.receipts.push(outcome.receipt);
            }
            _ => panic!("apply_transaction: There must be something wrong!"),
        }
    }

    /// Turn this into a `ClosedBlock`.
    pub fn close(mut self, conf: &BlockSysConfig) -> ClosedBlock {
        let mut env_info = self.env_info();
        // In protocol version 0, 1:
        // Auto Execution's env info author is default address
        // In protocol version > 1:
        // Auto Execution's env info author is block author
        if conf.chain_version < 2 {
            env_info.author = Address::default();
        }

        if conf.auto_exec {
            auto_exec(
                &mut self.state,
                conf.auto_exec_quota_limit,
                conf.economical_model,
                env_info,
                conf.chain_version,
            );
            self.state.commit().expect("commit trie error");
        }
        // Rebuild block
        let mut block = Block::new(self.block);
        let state_root = *self.state.root();
        block.set_state_root(state_root);
        let receipts_root = cita_merklehash::Tree::from_hashes(
            self.receipts
                .iter()
                .map(|r| r.rlp_bytes().to_vec().crypt_hash())
                .collect::<Vec<_>>(),
            cita_merklehash::merge,
        )
        .get_root_hash()
        .cloned()
        .unwrap_or(cita_merklehash::HASH_NULL);

        block.set_receipts_root(receipts_root);
        block.set_quota_used(self.current_quota_used);

        // blocks blooms
        let log_bloom = self
            .receipts
            .clone()
            .into_iter()
            .fold(LogBloom::zero(), |mut b, r| {
                b = b | r.log_bloom;
                b
            });

        block.set_log_bloom(log_bloom);
        block.rehash();

        ClosedBlock {
            block,
            receipts: self.receipts,
            state: self.state,
        }
    }
}

// Block that prepared to commit to db.
#[derive(Debug)]
pub struct ClosedBlock {
    /// Protobuf Block
    pub block: Block,
    pub receipts: Vec<Receipt>,
    pub state: State<StateDB>,
}

impl Drain for ClosedBlock {
    /// Drop this object and return the underlieing database.
    fn drain(self) -> StateDB {
        self.state.drop().1
    }
}

impl ClosedBlock {
    pub fn protobuf(&self) -> ExecutedInfo {
        let mut executed_info = ExecutedInfo::new();

        executed_info
            .mut_header()
            .set_prevhash(self.parent_hash().to_vec());
        executed_info.mut_header().set_timestamp(self.timestamp());
        executed_info.mut_header().set_height(self.number());
        executed_info
            .mut_header()
            .set_state_root(self.state_root().to_vec());
        executed_info
            .mut_header()
            .set_transactions_root(self.transactions_root().to_vec());
        executed_info
            .mut_header()
            .set_receipts_root(self.receipts_root().to_vec());
        executed_info
            .mut_header()
            .set_log_bloom(self.log_bloom().to_vec());
        executed_info
            .mut_header()
            .set_quota_used(u64::from(*self.quota_used()));
        executed_info
            .mut_header()
            .set_quota_limit(self.quota_limit().low_u64());

        executed_info.receipts = self
            .receipts
            .clone()
            .into_iter()
            .map(|receipt| {
                let mut receipt_proto_option = ReceiptWithOption::new();
                receipt_proto_option.set_receipt(receipt.protobuf());
                receipt_proto_option
            })
            .collect();
        executed_info
            .mut_header()
            .set_proposer(self.proposer().to_vec());
        executed_info
    }
}

impl Deref for ClosedBlock {
    type Target = Block;

    fn deref(&self) -> &Block {
        &self.block
    }
}

impl DerefMut for ClosedBlock {
    fn deref_mut(&mut self) -> &mut Block {
        &mut self.block
    }
}

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

    #[test]
    fn test_encode_and_decode() {
        let mut stx = SignedTransaction::default();
        stx.data = vec![1; 200];
        let transactions = vec![stx; 200];
        let body = BlockBody { transactions };
        let body_rlp = rlp::encode(&body);
        let body: BlockBody = rlp::decode(&body_rlp);
        let body_encoded = rlp::encode(&body).into_vec();

        assert_eq!(body_rlp, body_encoded);
    }
}
<|endoftext|>


<commit_before>
#![feature(globs)]

extern crate shader_version;
extern crate input;
extern crate ai_behavior;
extern crate sprite;
extern crate event;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;

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

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

use sdl2_window::Sdl2Window;
use opengl_graphics::{
    Gl,
    Texture,
};

fn main() {
    let (width, height) = (300, 300);
    let opengl = shader_version::OpenGL::_3_2;
    let window = Sdl2Window::new(
        opengl,
        WindowSettings {
            title: "Sprite".to_string(),
            size: [width, height],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

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

    let id = scene.add_child(sprite);

    // Run a sequence or animations.
    let seq = Sequence(vec![
        Action(Ease(EaseCubicOut, box ScaleTo(2.0, 0.5, 0.5))),
        Action(Ease(EaseBounceOut, box MoveBy(1.0, 0.0, 100.0))),
        Action(Ease(EaseElasticOut, box MoveBy(2.0, 0.0, -100.0))),
        Action(Ease(EaseBackInOut, box MoveBy(1.0, 0.0, -100.0))),
        Wait(0.5),
        Action(Ease(EaseExponentialInOut, box MoveBy(1.0, 0.0, 100.0))),
        Action(Blink(1.0, 5)),
        While(box WaitForever, vec![
            Action(Ease(EaseQuadraticIn, box FadeOut(1.0))),
            Action(Ease(EaseQuadraticOut, box FadeIn(1.0))),
        ]),
    ]);
    scene.run(id.clone(), &seq);

    // This animation and the one above can run in parallel.
    let rotate = Action(Ease(EaseExponentialInOut, box RotateTo(2.0, 360.0)));
    scene.run(id.clone(), &rotate);

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

    let ref mut gl = Gl::new(opengl);
    let window = RefCell::new(window);
    for e in Events::new(&window) {
        use event::{ PressEvent, RenderEvent };

        scene.event(&e);

        e.render(|args| {
            use graphics::*;
            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                graphics::clear([1.0, 1.0, 1.0, 1.0], gl);
                scene.draw(&c, gl);
            });
        });
        e.press(|_| {
            scene.toggle(id.clone(), &seq);
            scene.toggle(id.clone(), &rotate);
        });
    }
}
<commit_msg>Upgrade to latest Rust<commit_after>#![feature(default_type_params)]
#![feature(globs)]

extern crate shader_version;
extern crate input;
extern crate ai_behavior;
extern crate sprite;
extern crate event;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;

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

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

use sdl2_window::Sdl2Window;
use opengl_graphics::{
    Gl,
    Texture,
};

fn main() {
    let (width, height) = (300, 300);
    let opengl = shader_version::OpenGL::_3_2;
    let window = Sdl2Window::new(
        opengl,
        WindowSettings {
            title: "Sprite".to_string(),
            size: [width, height],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

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

    let id = scene.add_child(sprite);

    // Run a sequence or animations.
    let seq = Sequence(vec![
        Action(Ease(EaseCubicOut, box ScaleTo(2.0, 0.5, 0.5))),
        Action(Ease(EaseBounceOut, box MoveBy(1.0, 0.0, 100.0))),
        Action(Ease(EaseElasticOut, box MoveBy(2.0, 0.0, -100.0))),
        Action(Ease(EaseBackInOut, box MoveBy(1.0, 0.0, -100.0))),
        Wait(0.5),
        Action(Ease(EaseExponentialInOut, box MoveBy(1.0, 0.0, 100.0))),
        Action(Blink(1.0, 5)),
        While(box WaitForever, vec![
            Action(Ease(EaseQuadraticIn, box FadeOut(1.0))),
            Action(Ease(EaseQuadraticOut, box FadeIn(1.0))),
        ]),
    ]);
    scene.run(id.clone(), &seq);

    // This animation and the one above can run in parallel.
    let rotate = Action(Ease(EaseExponentialInOut, box RotateTo(2.0, 360.0)));
    scene.run(id.clone(), &rotate);

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

    let ref mut gl = Gl::new(opengl);
    let window = RefCell::new(window);
    for e in Events::new(&window) {
        use event::{ PressEvent, RenderEvent };

        let e: event::Event<input::Input> = e;
        scene.event(&e);

        e.render(|args| {
            use graphics::*;
            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                graphics::clear([1.0, 1.0, 1.0, 1.0], gl);
                scene.draw(&c, gl);
            });
        });
        e.press(|_| {
            scene.toggle(id.clone(), &seq);
            scene.toggle(id.clone(), &rotate);
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>Use FnvHashMap directly in std cmd pool<commit_after><|endoftext|>


<commit_before>// Find Cargo's source cache directory for a crate
use super::es;
use std::fs;
use es::traits::*;
use std::env;
use std::path;

pub fn rustup_lib() -> String {
    es::shell("rustc --print sysroot") + "/lib"
}
pub fn proper_crate_name(crate_name: &str) -> String {
    crate_name.replace('-',"_")
}

pub fn path_file_name(p: &path::Path) -> String {
    if let Some(file_name) = p.file_name() {
        file_name.to_string_lossy().to_string()
    } else
    if let Ok(full_path) = p.canonicalize() {
        path_file_name(&full_path)
    } else {
        p.to_string_lossy().to_string()
    }
}

// there's a Crate for This...
fn semver_i (s: &str) -> u64 {
    let v = s.split('.').filter_map(|s| s.parse::<u64>().ok()).to_vec();
    (((v[0] << 8) + v[1]) << 8) + v[2]
}

pub fn cargo_home() -> path::PathBuf {
	if let Ok(home) = env::var("CARGO_HOME") { // set in cargo runs
		home.into()
	} else {
		env::home_dir().or_die("no home!").join(".cargo")
    }
}

pub fn cache_path(crate_name: &str) -> path::PathBuf {
    let home = cargo_home();
    let crate_root = path::PathBuf::from(home.join("registry/src"));
    // actual crate source is in some fairly arbitrary subdirectory of this
    let mut crate_dir = crate_root.clone();
    crate_dir.push(es::files(&crate_root).next().or_die("no crate cache directory"));

    let mut crates = Vec::new();
    for (p,d) in es::paths(&crate_dir) {
        if ! d.is_dir() { continue; }
        let filename = path_file_name(&p);
        if let Some(endc) = filename.rfind('-') {
            if &filename[0..endc] == crate_name {
                crates.push((p,semver_i(&filename[endc+1..])));
            }
        }
    }
    // crate versions in ascending order by semver rules
    crates.sort_by(|a,b| a.1.cmp(&b.1));
    crates.pop().or_die(&format!("no such crate: {}",crate_name)).0
}

// Very hacky stuff - we want the ACTUAL crate name, not the project name
// So look just past [package] and scrape the name...
fn crate_name(cargo_toml: &path::Path) -> String {
    let name_line = es::lines(es::open(cargo_toml))
        .skip_while(|line| line.trim() != "[package]")
        .skip(1)
        .skip_while(|line| ! line.starts_with("name "))
        .next().or_die("totally fked Cargo.toml");
    let idx = name_line.find('"').or_die("no name?");
    (&name_line[(idx+1)..(name_line.len()-1)]).into()

}

pub fn crate_path(file: &path::Path, first_arg: &str) -> Result<(path::PathBuf,String),String> {
    if file.exists() {
        //let filename = path_file_name(file);
        if file.is_dir() { // assumed to be Cargo directory
            let cargo_toml = file.join("Cargo.toml");
            if ! cargo_toml.exists() {
                return Err(format!("not a Cargo project directory: {}",file.display()));
            }
            Ok((file.join("src/lib.rs"), crate_name(&cargo_toml)))
        } else { // should be just a Rust source file
            if file.extension().or_die("expecting extension") != "rs" {
                return Err("expecting Rust source file".into());
            }
            let name = path_file_name(&file.with_extension(""));
            Ok((file.to_path_buf(), name))
        }
    } else {
        let project_dir = cache_path(first_arg);
        let cargo_toml = project_dir.join("Cargo.toml");
        Ok((project_dir.join("src/lib.rs"), crate_name(&cargo_toml)))
    }
}

pub fn full_crate_name(deps: &path::Path, crate_name: &str) -> Option<String> {
    let mut res = Vec::new();
    let patt = format!("lib{}-",crate_name);
    for entry in fs::read_dir(deps).expect("cannot access dependencies dir") {
		let entry = entry.expect("cannot access deps entry");
		let path = entry.path();
        if let Some(f) = path.file_name() {
            let name = f.to_string_lossy();
            //println!("got {}",name);
            if name.starts_with(&patt) {
                let cname = &name[3..(name.len()-5) ];
                res.push(cname.to_string());
            }
        }
    }
    res.pop()
}
<commit_msg>tabs are evil and will be relentlessly chased down<commit_after>// Find Cargo's source cache directory for a crate
use super::es;
use std::fs;
use es::traits::*;
use std::env;
use std::path;

pub fn rustup_lib() -> String {
    es::shell("rustc --print sysroot") + "/lib"
}
pub fn proper_crate_name(crate_name: &str) -> String {
    crate_name.replace('-',"_")
}

pub fn path_file_name(p: &path::Path) -> String {
    if let Some(file_name) = p.file_name() {
        file_name.to_string_lossy().to_string()
    } else
    if let Ok(full_path) = p.canonicalize() {
        path_file_name(&full_path)
    } else {
        p.to_string_lossy().to_string()
    }
}

// there's a Crate for This...
fn semver_i (s: &str) -> u64 {
    let v = s.split('.').filter_map(|s| s.parse::<u64>().ok()).to_vec();
    (((v[0] << 8) + v[1]) << 8) + v[2]
}

pub fn cargo_home() -> path::PathBuf {
    if let Ok(home) = env::var("CARGO_HOME") { // set in cargo runs
        home.into()
    } else {
        env::home_dir().or_die("no home!").join(".cargo")
    }
}

pub fn cache_path(crate_name: &str) -> path::PathBuf {
    let home = cargo_home();
    let crate_root = path::PathBuf::from(home.join("registry/src"));
    // actual crate source is in some fairly arbitrary subdirectory of this
    let mut crate_dir = crate_root.clone();
    crate_dir.push(es::files(&crate_root).next().or_die("no crate cache directory"));

    let mut crates = Vec::new();
    for (p,d) in es::paths(&crate_dir) {
        if ! d.is_dir() { continue; }
        let filename = path_file_name(&p);
        if let Some(endc) = filename.rfind('-') {
            if &filename[0..endc] == crate_name {
                crates.push((p,semver_i(&filename[endc+1..])));
            }
        }
    }
    // crate versions in ascending order by semver rules
    crates.sort_by(|a,b| a.1.cmp(&b.1));
    crates.pop().or_die(&format!("no such crate: {}",crate_name)).0
}

// Very hacky stuff - we want the ACTUAL crate name, not the project name
// So look just past [package] and scrape the name...
fn crate_name(cargo_toml: &path::Path) -> String {
    let name_line = es::lines(es::open(cargo_toml))
        .skip_while(|line| line.trim() != "[package]")
        .skip(1)
        .skip_while(|line| ! line.starts_with("name "))
        .next().or_die("totally fked Cargo.toml");
    let idx = name_line.find('"').or_die("no name?");
    (&name_line[(idx+1)..(name_line.len()-1)]).into()

}

pub fn crate_path(file: &path::Path, first_arg: &str) -> Result<(path::PathBuf,String),String> {
    if file.exists() {
        if file.is_dir() { // assumed to be Cargo directory
            let cargo_toml = file.join("Cargo.toml");
            if ! cargo_toml.exists() {
                return Err(format!("not a Cargo project directory: {}",file.display()));
            }
            Ok((file.join("src").join("lib.rs"), crate_name(&cargo_toml)))
        } else { // should be just a Rust source file
            if file.extension().or_die("expecting extension") != "rs" {
                return Err("expecting Rust source file".into());
            }
            let name = path_file_name(&file.with_extension(""));
            Ok((file.to_path_buf(), name))
        }
    } else {
        let project_dir = cache_path(first_arg);
        let cargo_toml = project_dir.join("Cargo.toml");
        Ok((project_dir.join("src").join("lib.rs"), crate_name(&cargo_toml)))
    }
}

pub fn full_crate_name(deps: &path::Path, crate_name: &str) -> Option<String> {
    let mut res = Vec::new();
    let patt = format!("lib{}-",crate_name);
    for entry in fs::read_dir(deps).expect("cannot access dependencies dir") {
        let entry = entry.expect("cannot access deps entry");
        let path = entry.path();
        if let Some(f) = path.file_name() {
            let name = f.to_string_lossy();
            //println!("got {}",name);
            if name.starts_with(&patt) {
                let cname = &name[3..(name.len()-5) ];
                res.push(cname.to_string());
            }
        }
    }
    res.pop()
}
<|endoftext|>


<commit_before>#![feature(test)]
extern crate parallel_letter_frequency;
extern crate test;

use std::collections::HashMap;
use test::Bencher;

#[bench]
fn bench_tiny_parallel(b: &mut Bencher) {
    let tiny = &["a"];
    b.iter(|| parallel_letter_frequency::frequency(tiny, 3));
}

#[bench]
fn bench_tiny_sequential(b: &mut Bencher) {
    let tiny = &["a"];
    b.iter(|| frequency(tiny));
}

#[bench]
fn bench_small_parallel(b: &mut Bencher) {
    let texts = all_texts(1);
    b.iter(|| parallel_letter_frequency::frequency(&texts, 3));
}

#[bench]
fn bench_small_sequential(b: &mut Bencher) {
    let texts = all_texts(1);
    b.iter(|| frequency(&texts));
}

#[bench]
fn bench_large_parallel(b: &mut Bencher) {
    let texts = all_texts(30);
    b.iter(|| parallel_letter_frequency::frequency(&texts, 3));
}

#[bench]
fn bench_large_sequential(b: &mut Bencher) {
    let texts = all_texts(30);
    b.iter(|| frequency(&texts));
}

/// Simple sequential char frequency. Can it be beat?
pub fn frequency(texts: &[&str]) -> HashMap<char, usize> {
    let mut map = HashMap::new();

    for line in texts {
        for chr in line.chars().filter(|c| c.is_alphabetic()) {
            if let Some(c) = chr.to_lowercase().next() {
                (*map.entry(c).or_insert(0)) += 1;
            }
        }
    }

    map
}

fn all_texts(repeat: usize) -> Vec<&'static str> {
    [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER]
        .iter()
        .cycle()
        .take(3 * repeat)
        .flat_map(|anthem| anthem.iter().cloned())
        .collect()
}

// Poem by Friedrich Schiller. The corresponding music is the European Anthem.
pub const ODE_AN_DIE_FREUDE: [&'static str; 8] = [
    "Freude schöner Götterfunken",
    "Tochter aus Elysium,",
    "Wir betreten feuertrunken,",
    "Himmlische, dein Heiligtum!",
    "Deine Zauber binden wieder",
    "Was die Mode streng geteilt;",
    "Alle Menschen werden Brüder,",
    "Wo dein sanfter Flügel weilt.",
];

// Dutch national anthem
pub const WILHELMUS: [&'static str; 8] = [
    "Wilhelmus van Nassouwe",
    "ben ik, van Duitsen bloed,",
    "den vaderland getrouwe",
    "blijf ik tot in den dood.",
    "Een Prinse van Oranje",
    "ben ik, vrij, onverveerd,",
    "den Koning van Hispanje",
    "heb ik altijd geëerd.",
];

// American national anthem
pub const STAR_SPANGLED_BANNER: [&'static str; 8] = [
    "O say can you see by the dawn's early light,",
    "What so proudly we hailed at the twilight's last gleaming,",
    "Whose broad stripes and bright stars through the perilous fight,",
    "O'er the ramparts we watched, were so gallantly streaming?",
    "And the rockets' red glare, the bombs bursting in air,",
    "Gave proof through the night that our flag was still there;",
    "O say does that star-spangled banner yet wave,",
    "O'er the land of the free and the home of the brave?",
];
<commit_msg>Clippy says to remove this and all tests still pass (#997)<commit_after>#![feature(test)]
extern crate parallel_letter_frequency;
extern crate test;

use std::collections::HashMap;
use test::Bencher;

#[bench]
fn bench_tiny_parallel(b: &mut Bencher) {
    let tiny = &["a"];
    b.iter(|| parallel_letter_frequency::frequency(tiny, 3));
}

#[bench]
fn bench_tiny_sequential(b: &mut Bencher) {
    let tiny = &["a"];
    b.iter(|| frequency(tiny));
}

#[bench]
fn bench_small_parallel(b: &mut Bencher) {
    let texts = all_texts(1);
    b.iter(|| parallel_letter_frequency::frequency(&texts, 3));
}

#[bench]
fn bench_small_sequential(b: &mut Bencher) {
    let texts = all_texts(1);
    b.iter(|| frequency(&texts));
}

#[bench]
fn bench_large_parallel(b: &mut Bencher) {
    let texts = all_texts(30);
    b.iter(|| parallel_letter_frequency::frequency(&texts, 3));
}

#[bench]
fn bench_large_sequential(b: &mut Bencher) {
    let texts = all_texts(30);
    b.iter(|| frequency(&texts));
}

/// Simple sequential char frequency. Can it be beat?
pub fn frequency(texts: &[&str]) -> HashMap<char, usize> {
    let mut map = HashMap::new();

    for line in texts {
        for chr in line.chars().filter(|c| c.is_alphabetic()) {
            if let Some(c) = chr.to_lowercase().next() {
                (*map.entry(c).or_insert(0)) += 1;
            }
        }
    }

    map
}

fn all_texts(repeat: usize) -> Vec<&'static str> {
    [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER]
        .iter()
        .cycle()
        .take(3 * repeat)
        .flat_map(|anthem| anthem.iter().cloned())
        .collect()
}

// Poem by Friedrich Schiller. The corresponding music is the European Anthem.
pub const ODE_AN_DIE_FREUDE: [&str; 8] = [
    "Freude schöner Götterfunken",
    "Tochter aus Elysium,",
    "Wir betreten feuertrunken,",
    "Himmlische, dein Heiligtum!",
    "Deine Zauber binden wieder",
    "Was die Mode streng geteilt;",
    "Alle Menschen werden Brüder,",
    "Wo dein sanfter Flügel weilt.",
];

// Dutch national anthem
pub const WILHELMUS: [&str; 8] = [
    "Wilhelmus van Nassouwe",
    "ben ik, van Duitsen bloed,",
    "den vaderland getrouwe",
    "blijf ik tot in den dood.",
    "Een Prinse van Oranje",
    "ben ik, vrij, onverveerd,",
    "den Koning van Hispanje",
    "heb ik altijd geëerd.",
];

// American national anthem
pub const STAR_SPANGLED_BANNER: [&str; 8] = [
    "O say can you see by the dawn's early light,",
    "What so proudly we hailed at the twilight's last gleaming,",
    "Whose broad stripes and bright stars through the perilous fight,",
    "O'er the ramparts we watched, were so gallantly streaming?",
    "And the rockets' red glare, the bombs bursting in air,",
    "Gave proof through the night that our flag was still there;",
    "O say does that star-spangled banner yet wave,",
    "O'er the land of the free and the home of the brave?",
];
<|endoftext|>