<commit_before>#[derive(Copy, Clone, Debug)]
struct Tile
{
    population : f64,
    fertility : f64,
    gold : f64,
}

#[derive(Copy, Clone, Debug)]
struct Producer
{
    population : f64,
    gold: f64,

    happiness : f64,

    products : [f64; 2], // 0 food, 1 goods
    products_ratio : [f64; 2],
    product_usage: [f64; 2]
}

fn main() {

    println!("TYPE;ID;A;B;C;D;E;F;G");

    let mut producers = [Producer {population : 20_f64, gold: 1000_f64, products: [0_f64, 0_f64], products_ratio: [0.0, 0.0], product_usage: [1.0, 1.0], happiness: 0.1}; 5];
    let producer_count = producers.len();

    producers[1].products_ratio[0] = 1.1;
    producers[2].products_ratio[1] = 1.05;
    producers[3].products_ratio[0] = 1.05;
    producers[4].products_ratio[1] = 1.015;

    let mut prices : [f64; 2] = [1_f64, 1_f64];

    for _ in 0..200
    {
        let mut total_product = [0_f64, 0_f64];
        let mut total_gold = 0_f64;

        // produce goods
        for x in 0..producer_count {
            let mut producer = &mut producers[x];

            //let n1 = 1.1;
            //let produced_food = ((( producer.population + 1.0_f64).powf(1.0-n1) - 1.0)/(1.0-n1)) * producer.products_ratio[0];
            let produced_food = producer.population * producer.products_ratio[0];
            producer.products[0] += produced_food;

            //let n1 = 1.1;
            //let produced_goods = ((( producer.population + 1.0_f64).powf(1.0-n1) - 1.0)/(1.0-n1)) * producer.products_ratio[1];
            let produced_goods = producer.population * producer.products_ratio[1];
            producer.products[1] += produced_goods;

            println!("PRODUCERS_PRODUCE;{3};{0:.3};{1:.3};{2:.3};{4:.3};{5:.3};{6:.3}", producer.population, producer.products[0], producer.products[1], x, producer.gold, produced_food, produced_goods);
        }

        for _ in 0..4 {
            // calculate totals for trading
            for x in 0..producer_count {
                let producer = &producers[x];

                total_product[0] += producer.products[0];
                total_product[1] += producer.products[1];
                total_gold += producer.gold;
            }

            // trade between producers
            for product_id in 0..2 {

                let average_gold = total_gold / producer_count as f64;
                let needed_resources = total_product[product_id] / producer_count as f64;

                let (_, sellers_buyers) : (_, Vec<&mut Producer>) = producers.iter_mut().partition(|prod| prod.products[product_id] > needed_resources && prod.gold > average_gold);
                let (mut buyers, mut sellers) : (Vec<&mut Producer>, Vec<&mut Producer>) = sellers_buyers.into_iter().partition(|prod| prod.products[product_id] < needed_resources);

                if sellers.len() <= 0 || buyers.len() <= 0 {
                    continue;
                }

                let mut wanted_resources = 0_f64;
                let mut offered_gold = 0_f64;

                for buyer in &buyers {
                    wanted_resources += needed_resources - buyer.products[product_id];
                    offered_gold += buyer.gold;
                }

                let mut wanted_gold = 0_f64;
                let mut offered_resource = 0_f64;
                for seller in &sellers {
                    wanted_gold += average_gold - seller.gold;
                    offered_resource += seller.products[product_id] - needed_resources;
                }

                if offered_resource <= 0.1 { // if there is nothing to sell, no trading
                    continue;
                }

                let price = offered_gold / offered_resource;
                prices[product_id] = price;

                let mut total_bough = 0_f64;

                for buyer in &mut buyers {
                    let can_buy = buyer.gold / price;
                    let want = needed_resources - buyer.products[product_id];
                    let buys = can_buy.min(want);
                    buyer.products[product_id] += buys;
                    buyer.gold -= buys * price;
                    total_bough += buys;
                }

                let sold_ratio = total_bough / offered_resource;

                if sold_ratio > 1.0 {
                    println!("ERROR; sold more than is available");
                }

                for seller in &mut sellers {
                    let offered = seller.products[product_id] - needed_resources;
                    let seller_sold = offered * sold_ratio;

                    seller.products[product_id] -= seller_sold;
                    seller.gold += seller_sold * price;
                }

                println!("TRADING;{0:.10};{1:.10};{2:.10};{3:.10};{4:.10};{5:.10};{6:.10}", product_id, price, wanted_resources, offered_gold, offered_resource, wanted_gold, total_bough);
            }
        }
        println!("PRICES;0;{0:.10};{1:.10};", prices[0], prices[1]);

        // consume goods
        for x in 0..producer_count {
            let mut producer = &mut producers[x];

            println!("PRODUCERS_CONSUME_BEFORE;{3};{0:.3};{1:.3};{2:.3};{4:.3};{5:.3}", producer.population, producer.products[0], producer.products[1], x, producer.gold, producer.happiness);

            let needed_food = producer.population * producer.product_usage[0];
            let eaten_food = producer.products[0].min(needed_food);
            producer.products[0] -= eaten_food;

            let needed_goods = producer.population * producer.product_usage[1];
            let used_goods = producer.products[1].min(needed_goods);
            producer.products[1] -= used_goods;

            let food_ratio = eaten_food / needed_food;
            let goods_ratio = used_goods / needed_goods;

            producer.happiness = food_ratio + food_ratio * goods_ratio * 0.5;

            if x == 0 {
                producer.happiness *= 1.01;
            }

            println!("PRODUCERS_CONSUME_AFTER;{3};{0:.3};{1:.3};{2:.3};{4:.3};{5:.3};{6:.3};{7:.3}", producer.population, producer.products[0], producer.products[1], x, producer.gold, producer.happiness, eaten_food, used_goods);
        }

        // move people between producers
        {
            let mut producers_vec: Vec<&mut Producer> = producers.iter_mut().collect::<Vec<_>>();

            producers_vec.sort_by(|a, b| a.happiness.partial_cmp(&b.happiness).unwrap());

            for from in 0 .. producers_vec.len() {
                for to in from+1 .. producers_vec.len(){

                    let move_people = producers_vec[to].happiness - producers_vec[from].happiness;
                    let move_people = move_people * 0.1;
                    let target_population = 0.1_f64.max(producers_vec[from].population - move_people);
                    let move_people = producers_vec[from].population - target_population;

                    producers_vec[from].population -= move_people;
                    producers_vec[to].population += move_people;

                    println!("POPULATION_MOVE;{0:.3};{1:.3};{2:.3};{3:.3};{4:.3};{5:.3}", from, to, producers_vec[from].population, producers_vec[to].population, target_population, move_people);
                }
            }
        }

        // taxes (duh!)
        {
            let tax_rate = 0.2;

            let mut total_tax = 0.0;
            for x in 1..producer_count {
                let tax = producers[x].gold * tax_rate;
                producers[x].gold -= tax;
                total_tax += tax;
            }

            producers[0].gold += total_tax;
        }

        // sanity checks
        {
            for prod in &producers{
                for x in 0..2 {
                    if prod.products[x] < -0.0000001 {
                        println!("ERROR; product {0} is negative", x)
                    }
                }
                if prod.gold < -0.0000001 {
                    println!("ERROR; gold is negative:{0:.10}", prod.gold)
                }
            }
        }
    }
}
<commit_msg>Improved output<commit_after>use std::fs::File;
use std::io::Write;

#[derive(Copy, Clone, Debug)]
struct Tile
{
    population : f64,
    fertility : f64,
    gold : f64,
}

#[derive(Copy, Clone, Debug)]
struct Producer
{
    population : f64,
    gold: f64,

    happiness : f64,

    products : [f64; 2], // 0 food, 1 goods
    products_ratio : [f64; 2],
    product_usage: [f64; 2]
}

fn main() {

    println!("TYPE;ID;A;B;C;D;E;F;G");

    let mut producers = [Producer {population : 20_f64, gold: 1000_f64, products: [0_f64, 0_f64], products_ratio: [0.0, 0.0], product_usage: [1.0, 1.0], happiness: 0.1}; 5];
    let producer_count = producers.len();

    producers[1].products_ratio[0] = 1.1;
    producers[2].products_ratio[1] = 1.05;
    producers[3].products_ratio[0] = 1.05;
    producers[4].products_ratio[1] = 1.015;

    let mut prices : [f64; 2] = [1_f64, 1_f64];

    let mut prices_output : File = File::create("prices.csv").unwrap();
    writeln!(&mut prices_output, "Step;Price 1;Price 2").unwrap();

    let mut population_output : File = File::create("population.csv").unwrap();
    writeln!(&mut population_output, "Step;").unwrap();

    for step_id in 0..3000
    {
        let mut total_product = [0_f64, 0_f64];
        let mut total_gold = 0_f64;

        // produce goods
        for x in 0..producer_count {
            let mut producer = &mut producers[x];

            //let n1 = 1.1;
            //let produced_food = ((( producer.population + 1.0_f64).powf(1.0-n1) - 1.0)/(1.0-n1)) * producer.products_ratio[0];
            let produced_food = producer.population * producer.products_ratio[0];
            producer.products[0] += produced_food;

            //let n1 = 1.1;
            //let produced_goods = ((( producer.population + 1.0_f64).powf(1.0-n1) - 1.0)/(1.0-n1)) * producer.products_ratio[1];
            let produced_goods = producer.population * producer.products_ratio[1];
            producer.products[1] += produced_goods;

            println!("PRODUCERS_PRODUCE;{3};{0:.3};{1:.3};{2:.3};{4:.3};{5:.3};{6:.3}", producer.population, producer.products[0], producer.products[1], x, producer.gold, produced_food, produced_goods);
        }

        for _ in 0..4 {
            // calculate totals for trading
            for x in 0..producer_count {
                let producer = &producers[x];

                total_product[0] += producer.products[0];
                total_product[1] += producer.products[1];
                total_gold += producer.gold;
            }

            // trade between producers
            for product_id in 0..2 {

                let average_gold = total_gold / producer_count as f64;
                let needed_resources = total_product[product_id] / producer_count as f64;

                let (_, sellers_buyers) : (_, Vec<&mut Producer>) = producers.iter_mut().partition(|prod| prod.products[product_id] > needed_resources && prod.gold > average_gold);
                let (mut buyers, mut sellers) : (Vec<&mut Producer>, Vec<&mut Producer>) = sellers_buyers.into_iter().partition(|prod| prod.products[product_id] < needed_resources);

                if sellers.len() <= 0 || buyers.len() <= 0 {
                    continue;
                }

                let mut wanted_resources = 0_f64;
                let mut offered_gold = 0_f64;

                for buyer in &buyers {
                    wanted_resources += needed_resources - buyer.products[product_id];
                    offered_gold += buyer.gold;
                }

                let mut wanted_gold = 0_f64;
                let mut offered_resource = 0_f64;
                for seller in &sellers {
                    wanted_gold += average_gold - seller.gold;
                    offered_resource += seller.products[product_id] - needed_resources;
                }

                if offered_resource <= 0.1 { // if there is nothing to sell, no trading
                    continue;
                }

                let price = offered_gold / offered_resource;
                prices[product_id] = price;

                let mut total_bough = 0_f64;

                for buyer in &mut buyers {
                    let can_buy = buyer.gold / price;
                    let want = needed_resources - buyer.products[product_id];
                    let buys = can_buy.min(want);
                    buyer.products[product_id] += buys;
                    buyer.gold -= buys * price;
                    total_bough += buys;
                }

                let sold_ratio = total_bough / offered_resource;

                if sold_ratio > 1.0 {
                    println!("ERROR; sold more than is available");
                }

                for seller in &mut sellers {
                    let offered = seller.products[product_id] - needed_resources;
                    let seller_sold = offered * sold_ratio;

                    seller.products[product_id] -= seller_sold;
                    seller.gold += seller_sold * price;
                }

                println!("TRADING;{0:.10};{1:.10};{2:.10};{3:.10};{4:.10};{5:.10};{6:.10}", product_id, price, wanted_resources, offered_gold, offered_resource, wanted_gold, total_bough);
            }
        }
        println!("PRICES;0;{0:.10};{1:.10};", prices[0], prices[1]);

        // consume goods
        for x in 0..producer_count {
            let mut producer = &mut producers[x];

            println!("PRODUCERS_CONSUME_BEFORE;{3};{0:.3};{1:.3};{2:.3};{4:.3};{5:.3}", producer.population, producer.products[0], producer.products[1], x, producer.gold, producer.happiness);

            let needed_food = producer.population * producer.product_usage[0];
            let eaten_food = producer.products[0].min(needed_food);
            producer.products[0] -= eaten_food;

            let needed_goods = producer.population * producer.product_usage[1];
            let used_goods = producer.products[1].min(needed_goods);
            producer.products[1] -= used_goods;

            let food_ratio = eaten_food / needed_food;
            let goods_ratio = used_goods / needed_goods;

            producer.happiness = food_ratio + food_ratio * goods_ratio * 0.5;

            if x == 0 {
                producer.happiness *= 1.01;
            }

            println!("PRODUCERS_CONSUME_AFTER;{3};{0:.3};{1:.3};{2:.3};{4:.3};{5:.3};{6:.3};{7:.3}", producer.population, producer.products[0], producer.products[1], x, producer.gold, producer.happiness, eaten_food, used_goods);
        }

        // move people between producers
        {
            let mut producers_vec: Vec<&mut Producer> = producers.iter_mut().collect::<Vec<_>>();

            producers_vec.sort_by(|a, b| a.happiness.partial_cmp(&b.happiness).unwrap());

            for from in 0 .. producers_vec.len() {
                for to in from+1 .. producers_vec.len(){

                    let move_people = producers_vec[to].happiness - producers_vec[from].happiness;
                    let move_people = move_people * 0.1;
                    let target_population = 0.1_f64.max(producers_vec[from].population - move_people);
                    let move_people = producers_vec[from].population - target_population;

                    producers_vec[from].population -= move_people;
                    producers_vec[to].population += move_people;

                    println!("POPULATION_MOVE;{0:.3};{1:.3};{2:.3};{3:.3};{4:.3};{5:.3}", from, to, producers_vec[from].population, producers_vec[to].population, target_population, move_people);
                }
            }
        }

        // taxes (duh!)
        {
            let tax_rate = 0.2;

            let mut total_tax = 0.0;
            for x in 1..producer_count {
                let tax = producers[x].gold * tax_rate;
                producers[x].gold -= tax;
                total_tax += tax;
            }

            producers[0].gold += total_tax;
        }

        // sanity checks
        {
            for prod in &producers{
                for x in 0..2 {
                    if prod.products[x] < -0.0000001 {
                        println!("ERROR; product {0} is negative", x)
                    }
                }
                if prod.gold < -0.0000001 {
                    println!("ERROR; gold is negative:{0:.10}", prod.gold)
                }
            }
        }

        {
            let producers_population = producers.iter().map(|prod| prod.population.to_string()).collect::<Vec<_>>().join(";");
            writeln!(&mut population_output, "{0};{1}", step_id, producers_population).unwrap();
            writeln!(&mut prices_output, "{0};{1:.3};{2:.3}", step_id, prices[0], prices[1]).unwrap();
        }
    }
}
<|endoftext|>


<commit_before>#![warn(bad_style)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
// #![warn(missing_docs)]
#![warn(trivial_casts)]
#![warn(trivial_numeric_casts)]
#![warn(unused)]
#![warn(unused_extern_crates)]
#![warn(unused_import_braces)]
#![warn(unused_qualifications)]
#![warn(unused_results)]

extern crate board_game_geom as geom;
#[macro_use]
extern crate conrod;
extern crate find_folder;
extern crate piston_window;
extern crate vecmath;

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

use geom::{Point, Size};

use conrod::{Canvas, Circle, Frameable, LineStyle, Rectangle, Sizeable, Text, Theme, Widget,
             WidgetMatrix};
use conrod::color::{self, Color, Colorable};
use conrod::Positionable;

use piston_window::{Glyphs, PistonWindow, UpdateEvent, WindowSettings};

use board::Board;
use othello_disk::OthelloDisk;

type Ui = conrod::Ui<Glyphs>;

mod board;
mod othello_disk;

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Side {
    Black,
    White,
}

impl Side {
    fn flip(self) -> Side {
        match self {
            Side::Black => Side::White,
            Side::White => Side::Black,
        }
    }
}

#[derive(Clone, Debug)]
struct App {
    board: Board,

    frame_width: f64,
    cell_size: f64,
    disk_radius: f64,
    dot_radius: f64,
    board_margin: f64,
    indicator_text_width: f64,

    frame_color: Color,
    board_color: Color,
    white_color: Color,
    black_color: Color,
}

impl Default for App {
    fn default() -> App {
        App {
            board: Board::new(Size(8, 8)),

            frame_width: 1.0,
            cell_size: 80.0,
            disk_radius: 32.0,
            dot_radius: 6.0,
            board_margin: 40.0,
            indicator_text_width: 90.0,

            frame_color: color::black(),
            board_color: color::rgba(0.0, 0.5, 0.0, 1.0),
            white_color: color::white(),
            black_color: color::black(),
        }
    }
}

fn main() {
    let app_ref = Rc::new(RefCell::new(App::default()));

    let window: PistonWindow = {
        WindowSettings::new("Othello", (1024, 768))
            .exit_on_esc(true)
            .vsync(true)
            .build()
            .unwrap_or_else(|e| panic!("Failed to build PistonWindow: {}", e))
    };

    let mut ui = {
        let assets = find_folder::Search::KidsThenParents(3, 5)
                         .for_folder("assets")
                         .unwrap();
        let ref font_path = assets.join("FiraSans-Regular.ttf");
        let theme = Theme::default();
        let factory = window.factory.borrow().clone();
        let glyph_cache = Glyphs::new(font_path, factory).unwrap();
        Ui::new(glyph_cache, theme)
    };

    for event in window {
        ui.handle_event(&event);

        let _ = event.update(|_| ui.set_widgets(|ui| set_widgets(ui, app_ref.clone())));
        event.draw_2d(|c, g| ui.draw_if_changed(c, g));
    }
}

widget_ids! {
    CANVAS,
    OTHELLO_CANVAS,
    BOARD,
    DOT with 4,
    INDICATOR_LABEL_ICON with 2,
    INDICATOR_LABEL_TEXT with 2,
}

fn set_widgets(ui: &mut Ui, app_ref: Rc<RefCell<App>>) {
    let Size(rows, cols) = {
        let app = app_ref.deref().borrow();
        Canvas::new().color(app.board_color).scrolling(true).set(CANVAS, ui);
        app.board.size()
    };

    {
        let app = app_ref.deref().borrow();
        let board_width = app.cell_size * (app.board.size().1 as f64);
        let indicator_width = app.cell_size + app.indicator_text_width;
        let width = board_width + app.board_margin * 2.0 + indicator_width + app.board_margin;

        let board_height = app.cell_size * (app.board.size().0 as f64);
        let indicator_height = app.cell_size * 2.0;
        let height = app.board_margin * 2.0 + f64::max(board_height, indicator_height);

        let style = LineStyle::new().thickness(0.0);
        let rect = Rectangle::outline_styled([width, height], style);

        match (ui.win_w < board_width, ui.win_h < board_height) {
            (true, true) => rect.top_left_of(CANVAS),
            (false, true) => rect.mid_top_of(CANVAS),
            (true, false) => rect.mid_left_of(CANVAS),
            (false, false) => rect.middle_of(CANVAS),
        }
        .set(OTHELLO_CANVAS, ui);
    }

    let matrix = {
        let app = app_ref.deref().borrow();
        WidgetMatrix::new(cols as usize, rows as usize)
            .top_left_with_margins_on(OTHELLO_CANVAS, app.board_margin, app.board_margin)
            .w_h(app.cell_size * (cols as f64), app.cell_size * (rows as f64))
    };

    matrix.each_widget(|_n, col, row| {
              let pt = Point(row as i32, col as i32);
              let disk = {
                  let app_ref = app_ref.clone();
                  let app = app_ref.deref().borrow();
                  let mut disk = OthelloDisk::new()
                                     .background_color(app.board_color)
                                     .frame(app.frame_width)
                                     .frame_color(app.frame_color)
                                     .white_color(app.white_color)
                                     .black_color(app.black_color)
                                     .radius(app.disk_radius)
                                     .disk(app.board[pt]);
                  if let Some(turn) = app.board.turn() {
                      if app.board.can_locate(pt) {
                          disk = disk.flow_disk(Some(turn));
                      }
                  }
                  disk
              };

              let app_ref = app_ref.clone();
              disk.react(move || {
                  app_ref.borrow_mut().board.locate(pt);
              })
          })
          .set(BOARD, ui);

    {
        let app = app_ref.deref().borrow();
        let x = app.cell_size * ((cols / 4) as f64);
        let y = app.cell_size * ((rows / 4) as f64);
        let signs = &[(-1.0, 1.0), (1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)];
        for (i, &(sx, sy)) in signs.iter().enumerate() {
            Circle::fill(app.dot_radius)
                .x_y_relative_to(BOARD, sx * x, sy * y)
                .color(app.frame_color)
                .set(DOT + i, ui);
        }
    }

    for (i, &side) in [Side::Black, Side::White].iter().enumerate() {
        let app = app_ref.deref().borrow();
        if side == Side::Black {
            OthelloDisk::new().right_from(BOARD, app.board_margin)
        } else {
            OthelloDisk::new().down_from(INDICATOR_LABEL_ICON + (i - 1), 0.0)
        }
        .w_h(app.cell_size, app.cell_size)
        .background_color(app.board_color)
        .frame(0.0)
        .white_color(app.white_color)
        .black_color(app.black_color)
        .radius(app.disk_radius)
        .disk(Some(side))
        .react(|| {})
        .set(INDICATOR_LABEL_ICON + i, ui);

        let text = match side {
            Side::Black => app.board.num_black().to_string(),
            Side::White => app.board.num_white().to_string(),
        };
        Text::new(&text)
            .w(app.indicator_text_width)
            .right_from(INDICATOR_LABEL_ICON + i, 0.0)
            .font_size(60)
            .align_text_right()
            .set(INDICATOR_LABEL_TEXT + i, ui);
    }
}
<commit_msg>App splits into ViewConfig<commit_after>#![warn(bad_style)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
// #![warn(missing_docs)]
#![warn(trivial_casts)]
#![warn(trivial_numeric_casts)]
#![warn(unused)]
#![warn(unused_extern_crates)]
#![warn(unused_import_braces)]
#![warn(unused_qualifications)]
#![warn(unused_results)]

extern crate board_game_geom as geom;
#[macro_use]
extern crate conrod;
extern crate find_folder;
extern crate piston_window;
extern crate vecmath;

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

use geom::{Point, Size};

use conrod::{Canvas, Circle, Frameable, LineStyle, Rectangle, Sizeable, Text, Theme, Widget,
             WidgetMatrix};
use conrod::color::{self, Color, Colorable};
use conrod::Positionable;

use piston_window::{Glyphs, PistonWindow, UpdateEvent, WindowSettings};

use board::Board;
use othello_disk::OthelloDisk;

type Ui = conrod::Ui<Glyphs>;

mod board;
mod othello_disk;

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Side {
    Black,
    White,
}

impl Side {
    fn flip(self) -> Side {
        match self {
            Side::Black => Side::White,
            Side::White => Side::Black,
        }
    }
}

#[derive(Clone, Debug)]
struct App {
    board: Board,
    view_config: ViewConfig,
}

#[derive(Copy, Clone, Debug)]
struct ViewConfig {
    frame_width: f64,
    cell_size: f64,
    disk_radius: f64,
    dot_radius: f64,
    board_margin: f64,
    indicator_text_width: f64,

    frame_color: Color,
    board_color: Color,
    white_color: Color,
    black_color: Color,
}

impl Default for ViewConfig {
    fn default() -> ViewConfig {
        ViewConfig {
            frame_width: 1.0,
            cell_size: 80.0,
            disk_radius: 32.0,
            dot_radius: 6.0,
            board_margin: 40.0,
            indicator_text_width: 90.0,

            frame_color: color::black(),
            board_color: color::rgba(0.0, 0.5, 0.0, 1.0),
            white_color: color::white(),
            black_color: color::black(),
        }
    }
}

impl Default for App {
    fn default() -> App {
        App {
            board: Board::new(Size(8, 8)),
            view_config: ViewConfig::default(),
        }
    }
}

fn main() {
    let app_ref = Rc::new(RefCell::new(App::default()));

    let window: PistonWindow = {
        WindowSettings::new("Othello", (1024, 768))
            .exit_on_esc(true)
            .vsync(true)
            .build()
            .unwrap_or_else(|e| panic!("Failed to build PistonWindow: {}", e))
    };

    let mut ui = {
        let assets = find_folder::Search::KidsThenParents(3, 5)
                         .for_folder("assets")
                         .unwrap();
        let ref font_path = assets.join("FiraSans-Regular.ttf");
        let factory = window.factory.borrow().clone();
        let glyph_cache = Glyphs::new(font_path, factory).unwrap();
        let theme = Theme::default();
        Ui::new(glyph_cache, theme)
    };

    for event in window {
        ui.handle_event(&event);

        let _ = event.update(|_| ui.set_widgets(|ui| set_widgets(ui, app_ref.clone())));
        event.draw_2d(|c, g| ui.draw_if_changed(c, g));
    }
}

widget_ids! {
    CANVAS,
    OTHELLO_CANVAS,
    BOARD,
    DOT with 4,
    INDICATOR_LABEL_ICON with 2,
    INDICATOR_LABEL_TEXT with 2,
}

fn set_widgets(ui: &mut Ui, app_ref: Rc<RefCell<App>>) {
    let (Size(rows, cols), vc) = {
        let app = app_ref.deref().borrow();
        let size = app.board.size();
        (size, app.view_config)
    };

    Canvas::new().color(vc.board_color).scrolling(true).set(CANVAS, ui);

    let board_width = vc.cell_size * (cols as f64);
    let indicator_width = vc.cell_size + vc.indicator_text_width;
    let width = board_width + vc.board_margin * 2.0 + indicator_width + vc.board_margin;

    let board_height = vc.cell_size * (rows as f64);
    let indicator_height = vc.cell_size * 2.0;
    let height = vc.board_margin * 2.0 + f64::max(board_height, indicator_height);

    let style = LineStyle::new().thickness(0.0);
    let rect = Rectangle::outline_styled([width, height], style);

    match (ui.win_w < board_width, ui.win_h < board_height) {
        (true, true) => rect.top_left_of(CANVAS),
        (false, true) => rect.mid_top_of(CANVAS),
        (true, false) => rect.mid_left_of(CANVAS),
        (false, false) => rect.middle_of(CANVAS),
    }
    .set(OTHELLO_CANVAS, ui);

    WidgetMatrix::new(cols as usize, rows as usize)
        .top_left_with_margins_on(OTHELLO_CANVAS, vc.board_margin, vc.board_margin)
        .w_h(vc.cell_size * (cols as f64), vc.cell_size * (rows as f64))
        .each_widget(|_n, col, row| {
            let pt = Point(row as i32, col as i32);
            let disk = {
                let app_ref = app_ref.clone();
                let app = app_ref.deref().borrow();
                let mut disk = OthelloDisk::new()
                                   .background_color(vc.board_color)
                                   .frame(vc.frame_width)
                                   .frame_color(vc.frame_color)
                                   .white_color(vc.white_color)
                                   .black_color(vc.black_color)
                                   .radius(vc.disk_radius)
                                   .disk(app.board[pt]);
                if let Some(turn) = app.board.turn() {
                    if app.board.can_locate(pt) {
                        disk = disk.flow_disk(Some(turn));
                    }
                }
                disk
            };

            let app_ref = app_ref.clone();
            disk.react(move || {
                app_ref.borrow_mut().board.locate(pt);
            })
        })
        .set(BOARD, ui);

    let x = vc.cell_size * ((cols / 4) as f64);
    let y = vc.cell_size * ((rows / 4) as f64);
    let signs = &[(-1.0, 1.0), (1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)];
    for (i, &(sx, sy)) in signs.iter().enumerate() {
        Circle::fill(vc.dot_radius)
            .x_y_relative_to(BOARD, sx * x, sy * y)
            .color(vc.frame_color)
            .set(DOT + i, ui);
    }

    for (i, &side) in [Side::Black, Side::White].iter().enumerate() {
        let app = app_ref.deref().borrow();
        if side == Side::Black {
            OthelloDisk::new().right_from(BOARD, vc.board_margin)
        } else {
            OthelloDisk::new().down_from(INDICATOR_LABEL_ICON + (i - 1), 0.0)
        }
        .w_h(vc.cell_size, vc.cell_size)
        .background_color(vc.board_color)
        .frame(0.0)
        .white_color(vc.white_color)
        .black_color(vc.black_color)
        .radius(vc.disk_radius)
        .disk(Some(side))
        .react(|| {})
        .set(INDICATOR_LABEL_ICON + i, ui);

        let text = match side {
            Side::Black => app.board.num_black().to_string(),
            Side::White => app.board.num_white().to_string(),
        };
        Text::new(&text)
            .w(vc.indicator_text_width)
            .right_from(INDICATOR_LABEL_ICON + i, 0.0)
            .font_size(60)
            .align_text_right()
            .set(INDICATOR_LABEL_TEXT + i, ui);
    }
}
<|endoftext|>


<commit_before>struct Coordinates {
    x: i32,
    y: i32,
}

fn main() {
    let origin = Coordinates { x: 0, y: 0 };

    println!("X is {} and Y is {})", origin.x + 1, origin.y + 90);

    let mut v = vec![1, 2, 3, 4, 5];

    for i in &v {
        println!("A reference to {}", i);
    }

    for i in &mut v {
        println!("A mutable reference to {}", i);
    }

    for i in v {
        println!("Take ownership of the vector and its element {}", i);
    }
}
<commit_msg>trying to figure out how to change the cords for good<commit_after>struct Coordinates {
    x: i32,
    y: i32,
}

fn main() {
    let origin = Coordinates { x: 0, y: 0 };

    println!("X is {} and Y is {}", origin.x + 1, origin.y + 90);

    let mut v = vec![1, 2, 3, 4, 5];

    for i in &v {
        println!("A reference to {}", i);
    }

    for i in &mut v {
        println!("A mutable reference to {}", i);
    }

    for i in v {
        println!("Take ownership of the vector and its element {}", i);
    }

    println!("X is {} and Y is {}", move_right(origin.x), move_up(origin.y));
    println!("X is {} and Y is {}", move_right(origin.x), move_up(origin.y));
}

fn move_up(y_cord: i32) -> i32 {
    y_cord - 1
}

fn move_right(x_cord: i32) -> i32 {
    x_cord + 1
}
<|endoftext|>


<commit_before>#[macro_use] extern crate log;
extern crate toml;
extern crate rustc_serialize;

mod lockfile;

use std::fs::File;
use std::io::{self, Read, Write};
use std::process::{self, Command};
use std::fmt;
use std::env;
use std::error::Error;

#[cfg(feature = "logging")]
fn init_logging() {
    extern crate env_logger;
    env_logger::init().unwrap();
    info!("logging enabled");
}
#[cfg(not(feature = "logging"))]
fn init_logging() {}

/// "Stringly typed" error message
#[derive(Debug)]
struct StringError(String);

impl<T: Into<String>> From<T> for StringError {
    fn from(t: T) -> Self {
        StringError(t.into())
    }
}

impl fmt::Display for StringError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Error for StringError {
    fn description(&self) -> &str {
        &self.0
    }
}

#[derive(Debug)]
struct RunError(Box<Error>);

impl<T: Error + 'static> From<T> for RunError {
    fn from(t: T) -> Self {
        RunError(Box::new(t))
    }
}

impl fmt::Display for RunError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Main entry point.
///
/// Returns a `RunError` on error, which can carry any type that implements `Display`.
fn run() -> Result<(), RunError> {
    // First, validate cmd line arguments
    let mut args = env::args();
    // We can dispose of the first 2 arguments (the executable, and the subcommand passed by cargo)
    args.next().expect("exec name not passed as argument");
    if args.next() == None {
        return Err(StringError::from(
            "subcommand not passed as argument (not running with cargo?)"
        ).into());
    }
    // Then we expect at least one more argument to pass to cargo
    let cargo_cmd = match args.next() {
        Some(cmd) => cmd,
        None => return Err(StringError::from("no cargo command passed").into()),
    };
    // Any other arg is passed along to cargo
    let cargo_args: Vec<_> = args.collect();

    // Helper for running Cargo on a package
    let run_cargo = |pkg: &str| -> Result<(), RunError> {
        let mut cmd = Command::new("cargo");
        cmd.arg(&cargo_cmd).arg("-p").arg(pkg).args(&cargo_args);
        info!("running {:?}", cmd);
        let status = try!(cmd.status());

        if !status.success() {
            return Err(StringError::from(
                format!("cargo exited with error: {}", status)
            ).into());
        }

        Ok(())
    };

    let mut file = try!(File::open("Cargo.lock"));
    let mut string = String::new();
    try!(file.read_to_string(&mut string));
    let lockfile = try!(lockfile::parse(&string));
    debug!("parsed lockfile: {:#?}", lockfile);
    info!("root pkg: {}", &lockfile.root.name);

    // Run the subcommand on the main pkg. This isn't normally done via `-p`, but should work
    // regardless.
    info!("handling root pkg");
    try!(run_cargo(&lockfile.root.name));

    for dep in &lockfile.package {
        if dep.is_local() {
            info!("got local package '{}'", dep.name);
            try!(run_cargo(&dep.name));
        }
    }

    Ok(())
}

fn main() {
    init_logging();

    match run() {
        Ok(()) => {},
        Err(e) => {
            let mut stderr = io::stderr();
            writeln!(stderr, "An error occurred: {}", e).unwrap();
            process::exit(1);
        }
    }
}
<commit_msg>Make lock file errors more clear<commit_after>#[macro_use] extern crate log;
extern crate toml;
extern crate rustc_serialize;

mod lockfile;

use std::fs::File;
use std::io::{self, Read, Write, ErrorKind};
use std::process::{self, Command};
use std::fmt;
use std::env;
use std::error::Error;

#[cfg(feature = "logging")]
fn init_logging() {
    extern crate env_logger;
    env_logger::init().unwrap();
    info!("logging enabled");
}
#[cfg(not(feature = "logging"))]
fn init_logging() {}

/// "Stringly typed" error message
#[derive(Debug)]
struct StringError(String);

impl<T: Into<String>> From<T> for StringError {
    fn from(t: T) -> Self {
        StringError(t.into())
    }
}

impl fmt::Display for StringError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Error for StringError {
    fn description(&self) -> &str {
        &self.0
    }
}

#[derive(Debug)]
struct RunError(Box<Error>);

impl<T: Error + 'static> From<T> for RunError {
    fn from(t: T) -> Self {
        RunError(Box::new(t))
    }
}

impl fmt::Display for RunError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Main entry point.
///
/// Returns a `RunError` on error, which can carry any type that implements `Display`.
fn run() -> Result<(), RunError> {
    // First, validate cmd line arguments
    let mut args = env::args();
    // We can dispose of the first 2 arguments (the executable, and the subcommand passed by cargo)
    args.next().expect("exec name not passed as argument");
    if args.next() == None {
        return Err(StringError::from(
            "subcommand not passed as argument (not running with cargo?)"
        ).into());
    }
    // Then we expect at least one more argument to pass to cargo
    let cargo_cmd = match args.next() {
        Some(cmd) => cmd,
        None => return Err(StringError::from("no cargo command passed").into()),
    };
    // Any other arg is passed along to cargo
    let cargo_args: Vec<_> = args.collect();

    // Helper for running Cargo on a package
    let run_cargo = |pkg: &str| -> Result<(), RunError> {
        let mut cmd = Command::new("cargo");
        cmd.arg(&cargo_cmd).arg("-p").arg(pkg).args(&cargo_args);
        info!("running {:?}", cmd);
        let status = try!(cmd.status());

        if !status.success() {
            return Err(StringError::from(
                format!("cargo exited with error: {}", status)
            ).into());
        }

        Ok(())
    };

    let mut file = try!(File::open("Cargo.lock").map_err(|e| match e.kind() {
        ErrorKind::NotFound => {
            StringError::from("lock file 'Cargo.lock' not found (try running `cargo update` first)")
        }
        _ => {
            StringError::from(format!("error opening 'Cargo.lock': {}", e))
        }
    }));
    let mut string = String::new();
    try!(file.read_to_string(&mut string));
    let lockfile = try!(lockfile::parse(&string));
    debug!("parsed lockfile: {:#?}", lockfile);
    info!("root pkg: {}", &lockfile.root.name);

    // Run the subcommand on the main pkg. This isn't normally done via `-p`, but should work
    // regardless.
    info!("handling root pkg");
    try!(run_cargo(&lockfile.root.name));

    for dep in &lockfile.package {
        if dep.is_local() {
            info!("got local package '{}'", dep.name);
            try!(run_cargo(&dep.name));
        }
    }

    Ok(())
}

fn main() {
    init_logging();

    match run() {
        Ok(()) => {},
        Err(e) => {
            let mut stderr = io::stderr();
            writeln!(stderr, "An error occurred: {}", e).unwrap();
            process::exit(1);
        }
    }
}
<|endoftext|>


<commit_before>struct AddressSpace {
    data: [u8; 0xFFFF],
}

impl AddressSpace {

    fn new() -> AddressSpace {
        AddressSpace { data: [0; 0xFFFF] }
    }

    fn read(&self, addr: u16) -> u8 {
        self.data[addr as usize]
    }

    fn read_slice(&self, addr: u16, bytes: u16) -> &[u8] {
        self.data.slice(addr as usize, (addr + bytes) as usize)
    }

    fn write(&mut self, addr: u16, data: u8) {
        self.data[addr as usize] = data;
    }

}

struct Instr<'a> {
    opcode: u8,
    data: Option<&'a [u8]>,
    cycles: usize,
}

impl<'a> Instr<'a> {

    fn parse(reg: &mut RegData, rom: &'a AddressSpace) -> Instr<'a> {
        let opcode = rom.read(reg.advance_pc());
        Instr {
            opcode: opcode,
            data: None,
            cycles: 4,
        }
    }

    fn opcode(&self) -> u8 {
        self.opcode
    }

    fn cycles(&self) -> usize {
        self.cycles
    }

    fn param(&self, i: usize) -> u8 {
        self.data.expect("Instruction type does not carry parameters")[i]
    }

}

enum RegFlag {
    Zero,
    Subtract,
    HalfCarry,
    Carry,
}

enum Register {
    A,
    B,
    C,
    D,
    E,
    F,
    H,
    L,
    AF,
    BC,
    DE,
    HL,
    SP,
    PC,
    Flag,
}

struct RegData {
    a: u8,
    b: u8,
    c: u8,
    d: u8,
    e: u8,
    f: u8,
    h: u8,
    l: u8,
    sp: u16,
    pc: u16,
    flag: u8,
}

impl RegData {

    fn new() -> RegData {
        RegData {
            a: 0,
            b: 0,
            c: 0,
            d: 0,
            e: 0,
            f: 0,
            h: 0,
            l: 0,
            sp: 0xFFFE,
            pc: 0x100,
            flag: 0,
        }
    }

    fn read(&self, reg: Register) -> u8 {
        match reg {
            Register::A => self.a,
            Register::B => self.b,
            Register::C => self.c,
            Register::D => self.d,
            Register::E => self.e,
            Register::F => self.f,
            Register::H => self.h,
            Register::L => self.l,
            Register::Flag => self.flag,
            _ => panic!("Register not available for 8-bit read"),
        }
    }

    fn read_u16(&self, reg: Register) -> u16 {
        match reg {
            Register::AF => (self.a as u16) << 8 | self.f as u16,
            Register::BC => (self.b as u16) << 8 | self.c as u16,
            Register::DE => (self.d as u16) << 8 | self.e as u16,
            Register::HL => (self.h as u16) << 8 | self.l as u16,
            Register::SP => self.sp,
            Register::PC => self.pc,
            _ => panic!("Register not available for 16-bit read"),
        }
    }

    fn write(&mut self, reg: Register, data: u8) {
        match reg {
            Register::A => self.a = data,
            Register::B => self.b = data,
            Register::C => self.c = data,
            Register::D => self.d = data,
            Register::E => self.e = data,
            Register::F => self.f = data,
            Register::H => self.h = data,
            Register::L => self.l = data,
            _ => panic!("Register not available for 8-bit write"),
        }
    }

    fn write_u16(&mut self, reg: Register, data: u16) {
        let (hi, lo) = ((data & 0xFF00 >> 8) as u8, (data & 0xFF) as u8);
        match reg {
            Register::AF => {
                self.a = hi;
                self.f = lo;
            },
            Register::BC => {
                self.b = hi;
                self.c = lo;
            },
            Register::DE => {
                self.d = hi;
                self.c = lo;
            },
            Register::HL => {
                self.h = hi;
                self.l = lo;
            },
            Register::SP => self.sp = data,
            Register::PC => self.pc = data,
            _ => panic!("Register not available for 16-bit write"),
        }
    }

    fn set_flag(&mut self, flag: RegFlag, on: bool) {
        let bit = match flag {
            RegFlag::Zero => 0x80,
            RegFlag::Subtract => 0x40,
            RegFlag::HalfCarry => 0x20,
            RegFlag::Carry => 0x10,
        };
        if (on) {
            self.flag |= bit;
        } else {
            self.flag &= bit ^ 0xFF;
        }
    }

    fn advance_pc(&mut self) -> u16 {
        let pc = self.pc;
        self.pc += 1;
        pc
    }

}

static GB_FREQUENCY: u32 = 4194304;

struct Cpu {
    reg: RegData,
    ram: AddressSpace,
    freq: u32,
    clock: u64,
    cycle_block: u32,
}

impl Cpu {

    fn new() -> Cpu {
        Cpu::new_with_freq(GB_FREQUENCY)
    }

    fn new_with_freq(freq: u32) -> Cpu {
        Cpu {
            reg: RegData::new(),
            ram: AddressSpace::new(),
            freq: freq,
            clock: 0,
            cycle_block: 0,
        }
    }

    fn do_cycle(&mut self) {
        self.clock += 1;
        if self.cycle_block > 0 {
            self.cycle_block -= 1;
        } else {
            let instr = Instr::parse(&mut self.reg, &self.ram);
            match instr.opcode() {
                _ => panic!("Instruction not implemented!"),
            }
        }
    }

}

fn main() {
    println!("Hello, world!");
}
<commit_msg>Implement register copy<commit_after>struct AddressSpace {
    data: [u8; 0xFFFF],
}

impl AddressSpace {

    fn new() -> AddressSpace {
        AddressSpace { data: [0; 0xFFFF] }
    }

    fn read(&self, addr: u16) -> u8 {
        self.data[addr as usize]
    }

    fn read_slice(&self, addr: u16, bytes: u16) -> &[u8] {
        self.data.slice(addr as usize, (addr + bytes) as usize)
    }

    fn write(&mut self, addr: u16, data: u8) {
        self.data[addr as usize] = data;
    }

}

struct Instr<'a> {
    opcode: u8,
    data: Option<&'a [u8]>,
    cycles: usize,
}

impl<'a> Instr<'a> {

    fn parse(reg: &mut RegData, rom: &'a AddressSpace) -> Instr<'a> {
        let opcode = rom.read(reg.advance_pc());
        Instr {
            opcode: opcode,
            data: None,
            cycles: 4,
        }
    }

    fn opcode(&self) -> u8 {
        self.opcode
    }

    fn cycles(&self) -> usize {
        self.cycles
    }

    fn param(&self, i: usize) -> u8 {
        self.data.expect("Instruction type does not carry parameters")[i]
    }

}

enum RegFlag {
    Zero,
    Subtract,
    HalfCarry,
    Carry,
}

enum Register {
    A,
    B,
    C,
    D,
    E,
    F,
    H,
    L,
    AF,
    BC,
    DE,
    HL,
    SP,
    PC,
    Flag,
}

struct RegData {
    a: u8,
    b: u8,
    c: u8,
    d: u8,
    e: u8,
    f: u8,
    h: u8,
    l: u8,
    sp: u16,
    pc: u16,
    flag: u8,
}

impl RegData {

    fn new() -> RegData {
        RegData {
            a: 0,
            b: 0,
            c: 0,
            d: 0,
            e: 0,
            f: 0,
            h: 0,
            l: 0,
            sp: 0xFFFE,
            pc: 0x100,
            flag: 0,
        }
    }

    fn read(&self, reg: Register) -> u8 {
        match reg {
            Register::A => self.a,
            Register::B => self.b,
            Register::C => self.c,
            Register::D => self.d,
            Register::E => self.e,
            Register::F => self.f,
            Register::H => self.h,
            Register::L => self.l,
            Register::Flag => self.flag,
            _ => panic!("Register not available for 8-bit read"),
        }
    }

    fn read_u16(&self, reg: Register) -> u16 {
        match reg {
            Register::AF => (self.a as u16) << 8 | self.f as u16,
            Register::BC => (self.b as u16) << 8 | self.c as u16,
            Register::DE => (self.d as u16) << 8 | self.e as u16,
            Register::HL => (self.h as u16) << 8 | self.l as u16,
            Register::SP => self.sp,
            Register::PC => self.pc,
            _ => panic!("Register not available for 16-bit read"),
        }
    }

    fn write(&mut self, reg: Register, data: u8) {
        match reg {
            Register::A => self.a = data,
            Register::B => self.b = data,
            Register::C => self.c = data,
            Register::D => self.d = data,
            Register::E => self.e = data,
            Register::F => self.f = data,
            Register::H => self.h = data,
            Register::L => self.l = data,
            _ => panic!("Register not available for 8-bit write"),
        }
    }

    fn write_u16(&mut self, reg: Register, data: u16) {
        let (hi, lo) = ((data & 0xFF00 >> 8) as u8, (data & 0xFF) as u8);
        match reg {
            Register::AF => {
                self.a = hi;
                self.f = lo;
            },
            Register::BC => {
                self.b = hi;
                self.c = lo;
            },
            Register::DE => {
                self.d = hi;
                self.c = lo;
            },
            Register::HL => {
                self.h = hi;
                self.l = lo;
            },
            Register::SP => self.sp = data,
            Register::PC => self.pc = data,
            _ => panic!("Register not available for 16-bit write"),
        }
    }

    fn copy(&mut self, dst: Register, src: Register) {
        self.write(dst, self.read(src));
    }

    fn copy_u16(&mut self, dst: Register, src: Register) {
        self.write_u16(dst, self.read_u16(src));
    }

    fn set_flag(&mut self, flag: RegFlag, on: bool) {
        let bit = match flag {
            RegFlag::Zero => 0x80,
            RegFlag::Subtract => 0x40,
            RegFlag::HalfCarry => 0x20,
            RegFlag::Carry => 0x10,
        };
        if (on) {
            self.flag |= bit;
        } else {
            self.flag &= bit ^ 0xFF;
        }
    }

    fn advance_pc(&mut self) -> u16 {
        let pc = self.pc;
        self.pc += 1;
        pc
    }

}

static GB_FREQUENCY: u32 = 4194304;

struct Cpu {
    reg: RegData,
    ram: AddressSpace,
    freq: u32,
    clock: u64,
    cycle_block: u32,
}

impl Cpu {

    fn new() -> Cpu {
        Cpu::new_with_freq(GB_FREQUENCY)
    }

    fn new_with_freq(freq: u32) -> Cpu {
        Cpu {
            reg: RegData::new(),
            ram: AddressSpace::new(),
            freq: freq,
            clock: 0,
            cycle_block: 0,
        }
    }

    fn do_cycle(&mut self) {
        self.clock += 1;
        if self.cycle_block > 0 {
            self.cycle_block -= 1;
        } else {
            let instr = Instr::parse(&mut self.reg, &self.ram);
            match instr.opcode() {
                _ => panic!("Instruction not implemented!"),
            }
        }
    }

}

fn main() {
    println!("Hello, world!");
}
<|endoftext|>


<commit_before>#![recursion_limit = "256"]
#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[cfg(feature = "profile-index")]
#[macro_use]
extern crate flamer;

#[cfg(unix)]
use log::error;
#[cfg(unix)]
use sd_notify::{self, NotifyState};
#[cfg(unix)]
use std::fs::File;
#[cfg(unix)]
use std::io::prelude::*;
#[cfg(unix)]
use unix_daemonize::{daemonize_redirect, ChdirMode};

use anyhow::*;
use core::ops::Deref;
use getopts::Options;
use log::info;
use simplelog::{LevelFilter, SimpleLogger, TermLogger, TerminalMode};
use std::path::Path;
use std::sync::Arc;

mod api;
#[cfg(test)]
mod api_tests;
mod config;
mod db;
mod ddns;
mod index;
mod lastfm;
mod metadata;
mod playlist;
mod serve;
mod server;
mod swagger;
#[cfg(test)]
mod test;
mod thumbnails;
mod ui;
mod user;
mod utils;
mod vfs;
mod web;

fn log_config() -> simplelog::Config {
	simplelog::ConfigBuilder::new()
		.set_location_level(LevelFilter::Error)
		.build()
}

#[cfg(unix)]
fn daemonize(options: &getopts::Matches) -> Result<()> {
	if options.opt_present("f") {
		return Ok(());
	}
	let mut log_file = utils::get_data_root()?;
	log_file.push("polaris.log");
	let pid = daemonize_redirect(Some(&log_file), Some(&log_file), ChdirMode::NoChdir)?;
	let mut pid_path = utils::get_data_root()?;
	pid_path.push("polaris.pid");
	let mut file = File::create(pid_path)?;
	file.write_all(pid.to_string().as_bytes())?;
	Ok(())
}

#[cfg(unix)]
fn init_log(log_level: LevelFilter, options: &getopts::Matches) -> Result<()> {
	if options.opt_present("f") {
		if let Err(e) = TermLogger::init(log_level, log_config(), TerminalMode::Stdout) {
			println!("Error starting terminal logger: {}", e);
		} else {
			return Ok(());
		}
	}

	if let Err(e) = SimpleLogger::init(log_level, log_config()) {
		bail!("Error starting simple logger: {}", e);
	}
	Ok(())
}

#[cfg(windows)]
fn init_log(log_level: LevelFilter, _: &getopts::Matches) -> Result<()> {
	if TermLogger::init(log_level, log_config(), TerminalMode::Stdout).is_err() {
		if let Err(e) = SimpleLogger::init(log_level, log_config()) {
			bail!("Error starting simple logger: {}", e);
		}
	};
	Ok(())
}

#[cfg(unix)]
fn notify_ready() {
	if let Ok(true) = sd_notify::booted() {
		if let Err(e) = sd_notify::notify(true, &[NotifyState::Ready]) {
			error!("Unable to send ready notification: {}", e);
		}
	}
}

#[cfg(not(unix))]
fn notify_ready() {}

fn main() -> Result<()> {
	// Parse CLI options
	let args: Vec<String> = std::env::args().collect();
	let mut options = Options::new();
	options.optopt("c", "config", "set the configuration file", "FILE");
	options.optopt("p", "port", "set polaris to run on a custom port", "PORT");
	options.optopt("d", "database", "set the path to index database", "FILE");
	options.optopt("w", "web", "set the path to web client files", "DIRECTORY");
	options.optopt("s", "swagger", "set the path to swagger files", "DIRECTORY");
	options.optopt(
		"l",
		"log",
		"set the log level to a value between 0 (off) and 3 (debug)",
		"LEVEL",
	);

	#[cfg(unix)]
	options.optflag(
		"f",
		"foreground",
		"run polaris in the foreground instead of daemonizing",
	);

	options.optflag("h", "help", "print this help menu");

	let matches = options.parse(&args[1..])?;

	if matches.opt_present("h") {
		let program = args[0].clone();
		let brief = format!("Usage: {} [options]", program);
		print!("{}", options.usage(&brief));
		return Ok(());
	}

	let log_level = match matches.opt_str("l").as_ref().map(String::as_ref) {
		Some("0") => LevelFilter::Off,
		Some("1") => LevelFilter::Error,
		Some("2") => LevelFilter::Info,
		Some("3") => LevelFilter::Debug,
		_ => LevelFilter::Info,
	};

	init_log(log_level, &matches)?;

	#[cfg(unix)]
	daemonize(&matches)?;

	// Init DB
	info!("Starting up database");
	let db_path = matches.opt_str("d");
	let mut default_db_path = utils::get_data_root()?;
	default_db_path.push("db.sqlite");
	let db_path = db_path
		.map(|n| Path::new(n.as_str()).to_path_buf())
		.unwrap_or(default_db_path);
	let db = Arc::new(db::DB::new(&db_path)?);

	// Parse config
	info!("Parsing configuration");
	let config_file_name = matches.opt_str("c");
	let config_file_path = config_file_name.map(|p| Path::new(p.as_str()).to_path_buf());
	if let Some(path) = config_file_path {
		let config = config::parse_toml_file(&path)?;
		info!("Applying configuration");
		config::amend(db.deref(), &config)?;
	}
	let config = config::read(db.deref())?;
	let auth_secret = config::get_auth_secret(db.deref())?;

	// Init index
	info!("Initializing index");
	let command_sender = index::init(db.clone());

	// Trigger auto-indexing
	let db_auto_index = db.clone();
	let command_sender_auto_index = command_sender.clone();
	std::thread::spawn(move || {
		index::self_trigger(db_auto_index.deref(), &command_sender_auto_index);
	});

	// API mount target
	let prefix_url = config.prefix_url.unwrap_or_else(|| "".to_string());
	let api_url = format!("/{}api", &prefix_url);
	info!("Mounting API on {}", api_url);

	// Web client mount target
	let web_dir_name = matches.opt_str("w");
	let mut default_web_dir = utils::get_data_root()?;
	default_web_dir.push("web");
	let web_dir_path = web_dir_name
		.map(|n| Path::new(n.as_str()).to_path_buf())
		.unwrap_or(default_web_dir);
	info!("Static files location is {}", web_dir_path.display());
	let web_url = format!("/{}", &prefix_url);
	info!("Mounting web client files on {}", web_url);

	// Swagger files mount target
	let swagger_dir_name = matches.opt_str("s");
	let mut default_swagger_dir = utils::get_data_root()?;
	default_swagger_dir.push("swagger");
	let swagger_dir_path = swagger_dir_name
		.map(|n| Path::new(n.as_str()).to_path_buf())
		.unwrap_or(default_swagger_dir);
	info!("Swagger files location is {}", swagger_dir_path.display());
	let swagger_url = format!("/{}swagger", &prefix_url);
	info!("Mounting swagger files on {}", swagger_url);

	// Start server
	info!("Starting up server");
	let port: u16 = matches
		.opt_str("p")
		.unwrap_or_else(|| "5050".to_owned())
		.parse()
		.with_context(|| "Invalid port number")?;

	let server = server::get_server(
		port,
		Some(auth_secret.as_slice()),
		&api_url,
		&web_url,
		&web_dir_path,
		&swagger_url,
		&swagger_dir_path,
		db.clone(),
		command_sender,
	)?;
	std::thread::spawn(move || {
		server.launch();
	});

	// Start DDNS updates
	let db_ddns = db.clone();
	std::thread::spawn(move || {
		ddns::run(db_ddns.deref());
	});

	// Send readiness notification
	notify_ready();

	// Run UI
	ui::run();

	info!("Shutting down server");
	Ok(())
}
<commit_msg>More error fiddling<commit_after>#![recursion_limit = "256"]
#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[cfg(feature = "profile-index")]
#[macro_use]
extern crate flamer;

#[cfg(unix)]
use log::error;
#[cfg(unix)]
use sd_notify::{self, NotifyState};
#[cfg(unix)]
use std::fs::File;
#[cfg(unix)]
use std::io::prelude::*;
#[cfg(unix)]
use unix_daemonize::{daemonize_redirect, ChdirMode};

use anyhow::*;
use core::ops::Deref;
use getopts::Options;
use log::info;
use simplelog::{LevelFilter, SimpleLogger, TermLogger, TerminalMode};
use std::path::Path;
use std::sync::Arc;

mod api;
#[cfg(test)]
mod api_tests;
mod config;
mod db;
mod ddns;
mod index;
mod lastfm;
mod metadata;
mod playlist;
mod serve;
mod server;
mod swagger;
#[cfg(test)]
mod test;
mod thumbnails;
mod ui;
mod user;
mod utils;
mod vfs;
mod web;

fn log_config() -> simplelog::Config {
	simplelog::ConfigBuilder::new()
		.set_location_level(LevelFilter::Error)
		.build()
}

#[cfg(unix)]
fn daemonize(options: &getopts::Matches) -> Result<()> {
	if options.opt_present("f") {
		return Ok(());
	}
	let mut log_file = utils::get_data_root()?;
	log_file.push("polaris.log");
	let pid = match daemonize_redirect(Some(&log_file), Some(&log_file), ChdirMode::NoChdir) {
		Ok(p) => p,
		Err(e) => bail!("Daemonize error: {#?}", e),
	};
	let mut pid_path = utils::get_data_root()?;
	pid_path.push("polaris.pid");
	let mut file = File::create(pid_path)?;
	file.write_all(pid.to_string().as_bytes())?;
	Ok(())
}

#[cfg(unix)]
fn init_log(log_level: LevelFilter, options: &getopts::Matches) -> Result<()> {
	if options.opt_present("f") {
		if let Err(e) = TermLogger::init(log_level, log_config(), TerminalMode::Stdout) {
			println!("Error starting terminal logger: {}", e);
		} else {
			return Ok(());
		}
	}

	if let Err(e) = SimpleLogger::init(log_level, log_config()) {
		bail!("Error starting simple logger: {}", e);
	}
	Ok(())
}

#[cfg(windows)]
fn init_log(log_level: LevelFilter, _: &getopts::Matches) -> Result<()> {
	if TermLogger::init(log_level, log_config(), TerminalMode::Stdout).is_err() {
		if let Err(e) = SimpleLogger::init(log_level, log_config()) {
			bail!("Error starting simple logger: {}", e);
		}
	};
	Ok(())
}

#[cfg(unix)]
fn notify_ready() {
	if let Ok(true) = sd_notify::booted() {
		if let Err(e) = sd_notify::notify(true, &[NotifyState::Ready]) {
			error!("Unable to send ready notification: {}", e);
		}
	}
}

#[cfg(not(unix))]
fn notify_ready() {}

fn main() -> Result<()> {
	// Parse CLI options
	let args: Vec<String> = std::env::args().collect();
	let mut options = Options::new();
	options.optopt("c", "config", "set the configuration file", "FILE");
	options.optopt("p", "port", "set polaris to run on a custom port", "PORT");
	options.optopt("d", "database", "set the path to index database", "FILE");
	options.optopt("w", "web", "set the path to web client files", "DIRECTORY");
	options.optopt("s", "swagger", "set the path to swagger files", "DIRECTORY");
	options.optopt(
		"l",
		"log",
		"set the log level to a value between 0 (off) and 3 (debug)",
		"LEVEL",
	);

	#[cfg(unix)]
	options.optflag(
		"f",
		"foreground",
		"run polaris in the foreground instead of daemonizing",
	);

	options.optflag("h", "help", "print this help menu");

	let matches = options.parse(&args[1..])?;

	if matches.opt_present("h") {
		let program = args[0].clone();
		let brief = format!("Usage: {} [options]", program);
		print!("{}", options.usage(&brief));
		return Ok(());
	}

	let log_level = match matches.opt_str("l").as_ref().map(String::as_ref) {
		Some("0") => LevelFilter::Off,
		Some("1") => LevelFilter::Error,
		Some("2") => LevelFilter::Info,
		Some("3") => LevelFilter::Debug,
		_ => LevelFilter::Info,
	};

	init_log(log_level, &matches)?;

	#[cfg(unix)]
	daemonize(&matches)?;

	// Init DB
	info!("Starting up database");
	let db_path = matches.opt_str("d");
	let mut default_db_path = utils::get_data_root()?;
	default_db_path.push("db.sqlite");
	let db_path = db_path
		.map(|n| Path::new(n.as_str()).to_path_buf())
		.unwrap_or(default_db_path);
	let db = Arc::new(db::DB::new(&db_path)?);

	// Parse config
	info!("Parsing configuration");
	let config_file_name = matches.opt_str("c");
	let config_file_path = config_file_name.map(|p| Path::new(p.as_str()).to_path_buf());
	if let Some(path) = config_file_path {
		let config = config::parse_toml_file(&path)?;
		info!("Applying configuration");
		config::amend(db.deref(), &config)?;
	}
	let config = config::read(db.deref())?;
	let auth_secret = config::get_auth_secret(db.deref())?;

	// Init index
	info!("Initializing index");
	let command_sender = index::init(db.clone());

	// Trigger auto-indexing
	let db_auto_index = db.clone();
	let command_sender_auto_index = command_sender.clone();
	std::thread::spawn(move || {
		index::self_trigger(db_auto_index.deref(), &command_sender_auto_index);
	});

	// API mount target
	let prefix_url = config.prefix_url.unwrap_or_else(|| "".to_string());
	let api_url = format!("/{}api", &prefix_url);
	info!("Mounting API on {}", api_url);

	// Web client mount target
	let web_dir_name = matches.opt_str("w");
	let mut default_web_dir = utils::get_data_root()?;
	default_web_dir.push("web");
	let web_dir_path = web_dir_name
		.map(|n| Path::new(n.as_str()).to_path_buf())
		.unwrap_or(default_web_dir);
	info!("Static files location is {}", web_dir_path.display());
	let web_url = format!("/{}", &prefix_url);
	info!("Mounting web client files on {}", web_url);

	// Swagger files mount target
	let swagger_dir_name = matches.opt_str("s");
	let mut default_swagger_dir = utils::get_data_root()?;
	default_swagger_dir.push("swagger");
	let swagger_dir_path = swagger_dir_name
		.map(|n| Path::new(n.as_str()).to_path_buf())
		.unwrap_or(default_swagger_dir);
	info!("Swagger files location is {}", swagger_dir_path.display());
	let swagger_url = format!("/{}swagger", &prefix_url);
	info!("Mounting swagger files on {}", swagger_url);

	// Start server
	info!("Starting up server");
	let port: u16 = matches
		.opt_str("p")
		.unwrap_or_else(|| "5050".to_owned())
		.parse()
		.with_context(|| "Invalid port number")?;

	let server = server::get_server(
		port,
		Some(auth_secret.as_slice()),
		&api_url,
		&web_url,
		&web_dir_path,
		&swagger_url,
		&swagger_dir_path,
		db.clone(),
		command_sender,
	)?;
	std::thread::spawn(move || {
		server.launch();
	});

	// Start DDNS updates
	let db_ddns = db.clone();
	std::thread::spawn(move || {
		ddns::run(db_ddns.deref());
	});

	// Send readiness notification
	notify_ready();

	// Run UI
	ui::run();

	info!("Shutting down server");
	Ok(())
}
<|endoftext|>


<commit_before>extern crate rustyard;

fn main() {
    let shunting_yard = rustyard::ShuntingYard::new("2 + 4 * 3");

    println!("{}", shunting_yard.to_string());
}
<commit_msg>Added some extra output to StdOut<commit_after>extern crate rustyard;

fn main() {
    let shunting_yard = rustyard::ShuntingYard::new("2 + 4 * 3");

    println!("Input is: 2 + 4 * 3");
    println!("Shunting Yard result: {}", shunting_yard.to_string());
}
<|endoftext|>


<commit_before>#![feature(slicing_syntax)]
#![feature(phase)]

extern crate hyper;
extern crate puppetfile;
extern crate semver;
extern crate serialize;
extern crate term;

#[phase(plugin, link)] extern crate log;

use std::os;
use std::str;
use std::io::File;
use std::sync::Future;
use dependency::{ComposerDependency, Dependency, NpmDependency, PuppetDependency};
use semver::Version;

mod dependency;

fn get_published_versions<Dep: Dependency>(dependencies_to_check: &Vec<Dep>)
    -> Vec<(String, Version)>
{
    let mut version_ftrs = dependencies_to_check.iter().map(|d| {
        let dependency = d.clone();

        Future::spawn(move || {
            (dependency.name().clone(), dependency.registry_version())
        })
    }).collect::<Vec<Future<(String, Option<Version>)>>>();

    version_ftrs.iter_mut().map(
        |ftr| ftr.get()
    ).filter_map(
        |tpl| match tpl {
            (name, Some(version)) => Some((name, version)),
            (_, None) => None
        }
    ).collect()
}

fn filter_dependencies<Dep: Dependency>(dependencies_to_check: &Vec<Dep>, published_versions: Vec<(String, Version)>)
    -> (Vec<(&Dep, &Version)>, Vec<(&Dep, &Version)>)
{
    let mut outdated_dependencies = dependencies_to_check.iter()
        .filter(|d| d.version_req().is_some())
        .filter_map(|d| match published_versions.iter().find(|&&(ref name, _)| d.name() == name) {
            Some(&(_, ref version)) if !d.version_req().unwrap().matches(version) => Some((d, version)),
            _ => None
        })
        .collect::<Vec<(&Dep, &Version)>>();

    let mut up_to_date_dependencies = dependencies_to_check.iter()
        .filter(|d| d.version_req().is_some())
        .filter_map(|d| match published_versions.iter().find(|&&(ref name, _)| d.name() == name) {
            Some(&(_, ref version)) if d.version_req().unwrap().matches(version) => Some((d, version)),
            _ => None
        })
        .collect::<Vec<(&Dep, &Version)>>();

    outdated_dependencies.sort_by(|&(ref d1, _), &(ref d2, _)| d1.name().cmp(d2.name()));
    for &(ref dep, ref version) in outdated_dependencies.iter() {
        debug!("Name: {}", dep.name());
        debug!("Version: {}", version);
    }
    up_to_date_dependencies.sort_by(|&(ref d1, _), &(ref d2, _)| d1.name().cmp(d2.name()));
    for &(ref dep, ref version) in up_to_date_dependencies.iter() {
        debug!("Name: {}", dep.name());
        debug!("Version: {}", version);
    }

    (outdated_dependencies, up_to_date_dependencies)
}

fn out<Dep: Dependency>(dependencies: (Vec<(&Dep, &Version)>, Vec<(&Dep, &Version)>)) {
    let mut t = term::stdout().unwrap();

    println!("");

    let (outdated_dependencies, up_to_date_dependencies) = dependencies;

    t.fg(term::color::GREEN).unwrap();
    for &(dependency, version) in up_to_date_dependencies.iter() {
        debug!("{}", dependency.name());
        let version_string = version.to_string();
        (writeln!(t, "{}: {} matches {}", dependency.name(), "test", "test")).unwrap();
    }

    //println!("");

    //t.fg(term::color::RED).unwrap();
    //for &(dependency, version) in outdated_dependencies.iter() {
        //(writeln!(t, "{}: {} doesn't match {}", dependency.name(), version, dependency.version_req().unwrap())).unwrap();
    //}
}

fn main() {
    let args = os::args();
    let path = &Path::new(args[1][]);
    let file_raw_bytes = match File::open(path).read_to_end() {
        Ok(bytes) => bytes,
        Err(err)  => {
            println!("{}", err);
            return;
        }
    };
    let dependency_file_contents = str::from_utf8(file_raw_bytes[]).unwrap();

    match path.filename() {
        Some(name) if name == "composer.json".as_bytes() => {
            let composer_dependencies_to_check: Vec<ComposerDependency> = Dependency::to_check(dependency_file_contents);
            let published_versions = get_published_versions(&composer_dependencies_to_check);
            out(filter_dependencies(&composer_dependencies_to_check, published_versions))
        }
        Some(name) if name == "Puppetfile".as_bytes() => {
            let puppet_dependencies_to_check: Vec<PuppetDependency> = Dependency::to_check(dependency_file_contents);
            let published_versions = get_published_versions(&puppet_dependencies_to_check);
            out(filter_dependencies(&puppet_dependencies_to_check, published_versions))
        }
        Some(name) if name == "package.json".as_bytes() => {
            let npm_dependencies_to_check: Vec<NpmDependency> = Dependency::to_check(dependency_file_contents);
            let published_versions = get_published_versions(&npm_dependencies_to_check);
            out(filter_dependencies(&npm_dependencies_to_check, published_versions))
        }
        _ => {
            println!("File type not recognized");
            return
        }
    };
}
<commit_msg>cleanup and re-enable some code<commit_after>#![feature(slicing_syntax)]
#![feature(phase)]

extern crate hyper;
extern crate puppetfile;
extern crate semver;
extern crate serialize;
extern crate term;

#[phase(plugin, link)] extern crate log;

use std::os;
use std::str;
use std::io::File;
use std::sync::Future;
use dependency::{ComposerDependency, Dependency, NpmDependency, PuppetDependency};
use semver::Version;

mod dependency;

fn get_published_versions<Dep: Dependency>(dependencies_to_check: &Vec<Dep>)
    -> Vec<(String, Version)>
{
    let mut version_ftrs = dependencies_to_check.iter().map(|d| {
        let dependency = d.clone();

        Future::spawn(move || {
            (dependency.name().clone(), dependency.registry_version())
        })
    }).collect::<Vec<Future<(String, Option<Version>)>>>();

    version_ftrs.iter_mut().map(
        |ftr| ftr.get()
    ).filter_map(
        |tpl| match tpl {
            (name, Some(version)) => Some((name, version)),
            (_, None) => None
        }
    ).collect()
}

fn filter_dependencies<Dep: Dependency>(dependencies_to_check: &Vec<Dep>, published_versions: Vec<(String, Version)>)
    -> (Vec<(&Dep, &Version)>, Vec<(&Dep, &Version)>)
{
    let mut outdated_dependencies = dependencies_to_check.iter()
        .filter(|d| d.version_req().is_some())
        .filter_map(|d| match published_versions.iter().find(|&&(ref name, _)| d.name() == name) {
            Some(&(_, ref version)) if !d.version_req().unwrap().matches(version) => Some((d, version)),
            _ => None
        })
        .collect::<Vec<(&Dep, &Version)>>();

    let mut up_to_date_dependencies = dependencies_to_check.iter()
        .filter(|d| d.version_req().is_some())
        .filter_map(|d| match published_versions.iter().find(|&&(ref name, _)| d.name() == name) {
            Some(&(_, ref version)) if d.version_req().unwrap().matches(version) => Some((d, version)),
            _ => None
        })
        .collect::<Vec<(&Dep, &Version)>>();

    outdated_dependencies.sort_by(|&(ref d1, _), &(ref d2, _)| d1.name().cmp(d2.name()));
    for &(ref dep, ref version) in outdated_dependencies.iter() {
        debug!("Name: {}", dep.name());
        debug!("Version: {}", version);
    }
    up_to_date_dependencies.sort_by(|&(ref d1, _), &(ref d2, _)| d1.name().cmp(d2.name()));
    for &(ref dep, ref version) in up_to_date_dependencies.iter() {
        debug!("Name: {}", dep.name());
        debug!("Version: {}", version);
    }

    (outdated_dependencies, up_to_date_dependencies)
}

fn out<Dep: Dependency>(dependencies: (Vec<(&Dep, &Version)>, Vec<(&Dep, &Version)>)) {
    let mut t = term::stdout().unwrap();

    println!("");

    let (outdated_dependencies, up_to_date_dependencies) = dependencies;

    t.fg(term::color::GREEN).unwrap();
    for &(dependency, version) in up_to_date_dependencies.iter() {
        debug!("{}", dependency.name());
        writeln!(t, "{}: {} matches {}", dependency.name(), version, dependency.version_req().unwrap()).unwrap();
    }

    println!("");

    t.fg(term::color::RED).unwrap();
    for &(dependency, version) in outdated_dependencies.iter() {
        writeln!(t, "{}: {} doesn't match {}", dependency.name(), version, dependency.version_req().unwrap()).unwrap();
    }
}

fn main() {
    let args = os::args();
    let path = &Path::new(args[1][]);
    let file_raw_bytes = match File::open(path).read_to_end() {
        Ok(bytes) => bytes,
        Err(err)  => {
            println!("{}", err);
            return;
        }
    };
    let dependency_file_contents = str::from_utf8(file_raw_bytes[]).unwrap();

    match path.filename() {
        Some(name) if name == "composer.json".as_bytes() => {
            let composer_dependencies_to_check: Vec<ComposerDependency> = Dependency::to_check(dependency_file_contents);
            let published_versions = get_published_versions(&composer_dependencies_to_check);
            out(filter_dependencies(&composer_dependencies_to_check, published_versions))
        }
        Some(name) if name == "Puppetfile".as_bytes() => {
            let puppet_dependencies_to_check: Vec<PuppetDependency> = Dependency::to_check(dependency_file_contents);
            let published_versions = get_published_versions(&puppet_dependencies_to_check);
            out(filter_dependencies(&puppet_dependencies_to_check, published_versions))
        }
        Some(name) if name == "package.json".as_bytes() => {
            let npm_dependencies_to_check: Vec<NpmDependency> = Dependency::to_check(dependency_file_contents);
            let published_versions = get_published_versions(&npm_dependencies_to_check);
            out(filter_dependencies(&npm_dependencies_to_check, published_versions))
        }
        _ => {
            println!("File type not recognized");
            return
        }
    };
}
<|endoftext|>